From b0c1d245c2ec75459579f422fbf5ca6f39829789 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 10:48:35 +0200 Subject: [PATCH 001/233] Pin loop-claude's behaviour in black-box tests --- bin/test_loop_claude_black_box.py | 445 ++++++++++++++++++++++++++++++ todo.md | 1 - 2 files changed, 445 insertions(+), 1 deletion(-) create mode 100644 bin/test_loop_claude_black_box.py diff --git a/bin/test_loop_claude_black_box.py b/bin/test_loop_claude_black_box.py new file mode 100644 index 00000000..c98d30d3 --- /dev/null +++ b/bin/test_loop_claude_black_box.py @@ -0,0 +1,445 @@ +import dataclasses +import json +import os +import pathlib +import pty +import select +import shutil +import stat +import subprocess +import sys +import tempfile +import time +import unittest + +BIN = pathlib.Path(__file__).resolve().parent +TASK = "Do the next chunk." + +# Plays claude from FAKE_CLAUDE_SCENARIO, one step per call, logging each call; a step for another role, +# or none left, is Ctrl-C to loop-claude, which otherwise loops forever. +FAKE_CLAUDE = """#!{python} +import json, os, pathlib, signal, sys, time + +argv = sys.argv[1:] +role = "judge" if "--json-schema" in argv else "worker" if "-p" in argv else "interrupt" +scenario = pathlib.Path(os.environ["FAKE_CLAUDE_SCENARIO"]) +steps = json.loads(scenario.read_text()) +call = {{"argv": argv, "role": role}} +if role == "judge": + call["stdin"] = sys.stdin.read() +with open(os.environ["FAKE_CLAUDE_LOG"], "a") as log: + log.write(json.dumps(call) + "\\n") +if not steps or steps[0]["role"] != role: + parent = os.getppid() + os.kill(parent, signal.SIGINT) + while os.getppid() == parent: + time.sleep(0.05) + sys.exit(0) +step = steps.pop(0) +scenario.write_text(json.dumps(steps)) + + +def session(): + flag = "--session-id" if "--session-id" in argv else "--resume" + return argv[argv.index(flag) + 1] + + +def append(*entries): + path = pathlib.Path.home() / ".claude" / "projects" / "-fake" / f"{{session()}}.jsonl" + path.parent.mkdir(parents=True, exist_ok=True) + with open(path, "a") as transcript: + transcript.writelines(json.dumps(entry) + "\\n" for entry in entries) + + +if role == "worker": + said = {{"type": "assistant", "message": {{"content": [{{"type": "text", "text": step.get("say", "working")}}]}}}} + if step.get("transcript", True): + append({{"type": "user", "promptSource": "sdk", "message": {{"content": argv[argv.index("-p") + 1]}}}}, said) + if "append" in step: + with open(os.environ["FAKE_CLAUDE_EDIT"], "a") as script: + script.write(step["append"]) + if "replace" in step: + script = pathlib.Path(os.environ["FAKE_CLAUDE_EDIT"]) + script.write_text(script.read_text().replace(*step["replace"])) + print(json.dumps(said)) + if step.get("result", True): + print(json.dumps({{"type": "result"}})) + if "signal" in step: + os.kill(os.getpid(), step["signal"]) +elif role == "judge": + print(step["stdout"] if "stdout" in step else json.dumps({{"structured_output": step["verdict"]}})) + print(step.get("stderr", ""), file=sys.stderr) +elif "type" in step: + append({{"type": "user", "message": {{"content": step["type"]}}}}) +sys.exit(step.get("exit", 0)) +""" + +# Records every start of loop-claude and turns its retry waits into log lines. +SITECUSTOMIZE = """import json, os, sys, time + +if os.path.basename(sys.argv[0]) == "loop-claude": + def record(event): + with open(os.environ["LOOP_TEST_LOG"], "a") as log: + log.write(json.dumps(event) + "\\n") + record({"argv": sys.argv[1:]}) + pause = time.sleep + time.sleep = lambda seconds: record({"sleep": seconds}) if seconds >= 1 else pause(seconds) +""" + +PREMISES = "# Project\n\n## Goals\n\n1. Work.\n\n## Audience\n\nMe.\n" + + +def worker(**step): + return {"role": "worker", **step} + + +def judge(interrupt=False, finished=False, evidence="", question="", **step): + verdict = {"evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question} + return {"role": "judge", "verdict": verdict, **step} + + +def interrupt(**step): + return {"role": "interrupt", **step} + + +def lines(path): + return [json.loads(line) for line in path.read_text().splitlines()] if path.exists() else [] + + +@dataclasses.dataclass +class Run: + calls: list + code: int + sleeps: list + starts: list + stderr: str + stdout: str + + def roles(self): + return [call["role"] for call in self.calls] + + +class Checkout: + """A temporary HOME with a git checkout at ~/code/proj, where loop-claude runs against the fake claude.""" + + def __init__(self, test): + self.test = test + temp = tempfile.TemporaryDirectory() + test.addCleanup(temp.cleanup) + self.temp = pathlib.Path(os.path.realpath(temp.name)) + self.home = self.temp / "home" + self.root = self.home / "code" / "proj" + self.root.mkdir(parents=True) + (self.root / "README.md").write_text(PREMISES) + self.script = BIN / "loop-claude" + self.env = {name: value for name, value in os.environ.items() if not name.startswith(("GIT_", "LOOP_CLAUDE_", "PYTHON"))} + fake = self.temp / "fake-bin" + fake.mkdir() + (fake / "claude").write_text(FAKE_CLAUDE.format(python=sys.executable)) + (fake / "claude").chmod(0o755) + site = self.temp / "site" + site.mkdir() + (site / "sitecustomize.py").write_text(SITECUSTOMIZE) + self.env.update({ + "FAKE_CLAUDE_LOG": str(self.temp / "calls.jsonl"), + "FAKE_CLAUDE_SCENARIO": str(self.temp / "scenario.json"), + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_CONFIG_NOSYSTEM": "1", + "HOME": str(self.home), + "LOOP_CLAUDE_JUDGE_MODEL": "judge-model", + "LOOP_CLAUDE_WORKER_MODEL": "worker-model", + "LOOP_TEST_LOG": str(self.temp / "starts.jsonl"), + "PATH": f"{fake}{os.pathsep}{os.environ['PATH']}", + "PYTHONPATH": str(site), + }) + self.git("init", "--quiet") + + def git(self, *args): + subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@example.com", *args], capture_output=True, check=True, cwd=self.root, env=self.env) + + def run(self, steps, argv=(TASK,), cwd=None, terminal_input=None, stdout_on_terminal=True): + for name in ("FAKE_CLAUDE_LOG", "LOOP_TEST_LOG"): + pathlib.Path(self.env[name]).unlink(missing_ok=True) + pathlib.Path(self.env["FAKE_CLAUDE_SCENARIO"]).write_text(json.dumps(steps)) + command = [sys.executable, str(self.script), *argv] + cwd = cwd or self.root + if terminal_input is None: + done = subprocess.run(command, capture_output=True, cwd=cwd, env=self.env, stdin=subprocess.DEVNULL, text=True, timeout=60) + code, stdout, stderr = done.returncode, done.stdout, done.stderr + else: + code, stdout, stderr = self.run_on_terminal(command, cwd, terminal_input, stdout_on_terminal) + started = lines(pathlib.Path(self.env["LOOP_TEST_LOG"])) + return Run( + calls=lines(pathlib.Path(self.env["FAKE_CLAUDE_LOG"])), + code=code, + sleeps=[event["sleep"] for event in started if "sleep" in event], + starts=[event["argv"] for event in started if "argv" in event], + stderr=stderr, + stdout=stdout, + ) + + def run_on_terminal(self, command, cwd, typed, stdout_on_terminal): + controller, terminal = pty.openpty() + with tempfile.TemporaryFile() as stderr, tempfile.TemporaryFile() as stdout: + try: + proc = subprocess.Popen(command, cwd=cwd, env=self.env, stderr=stderr, stdin=terminal, stdout=terminal if stdout_on_terminal else stdout) + finally: + os.close(terminal) + try: + os.write(controller, typed.encode()) + output, deadline = b"", time.monotonic() + 60 + while time.monotonic() < deadline: + if select.select([controller], [], [], 1)[0]: + try: + chunk = os.read(controller, 4096) + except OSError: + break + if not chunk: + break + output += chunk + code = proc.wait(timeout=10) + finally: + os.close(controller) + proc.kill() + proc.wait() + stderr.seek(0) + stdout.seek(0) + output += stdout.read() + return code, output.decode(errors="replace").replace("\r\n", "\n"), stderr.read().decode() + + def claude_json(self): + return self.home / ".claude.json" + + def models_file(self): + return self.home / ".claude" / "loop-claude-models.json" + + def transcripts(self): + return sorted((self.home / ".claude" / "projects").glob("*/*.jsonl")) + + def archived(self): + return sorted((self.home / ".claude" / "loop-claude-transcripts" / "proj").glob("*")) + + +def argument(call, flag): + return call["argv"][call["argv"].index(flag) + 1] if flag in call["argv"] else None + + +class Premises(unittest.TestCase): + def test_refuses_to_start_without_a_task_a_checkout_or_premises(self): + checkout = Checkout(self) + for argv, code, said in (([], 1, "usage: loop-claude "), (["--help"], 0, "usage: loop-claude "), (["-h"], 0, "usage: loop-claude ")): + with self.subTest(argv=argv): + run = checkout.run([], argv=argv) + self.assertEqual(run.code, code) + self.assertIn(said, run.stdout if code == 0 else run.stderr) + outside = checkout.temp / "outside" + outside.mkdir() + run = checkout.run([], cwd=outside) + self.assertEqual((run.code, run.calls), (1, [])) + self.assertIn("not a git repository", run.stderr) + readmes = { + None: "README.md in {root}: No such file or directory - no premises.", + b"# P\n## Goals\n1. g\xff\n## Audience\nme\n": "README.md is not UTF-8 on line 3 - no premises.", + b"# P\n## Audience\nme\n": "README.md has no ## Goals heading - no premises.", + b"# P\n## Goals\n1. g\n": "README.md has no ## Audience heading - no premises.", + b"# P\n## Goals\n\n## Audience\nme\n": "README.md has nothing under ## Goals - no premises.", + b"# P\n## Goals\n1. g\n## Audience\nme\n## Audience\nyou\n": "README.md has ## Audience more than once - no premises.", + } + (checkout.root / "sub").mkdir() + for text, said in readmes.items(): + with self.subTest(said=said): + readme = checkout.root / "README.md" + readme.unlink(missing_ok=True) + if text is not None: + readme.write_bytes(text) + run = checkout.run([worker()], cwd=checkout.root / "sub") + self.assertEqual((run.code, run.calls), (1, [])) + self.assertEqual(run.stderr.strip(), said.format(root=checkout.root)) + + +class Cycles(unittest.TestCase): + def test_resumes_the_session_while_unfinished_and_starts_it_fresh_after_finishing(self): + checkout = Checkout(self) + run = checkout.run([ + worker(say="started"), judge(), + worker(say="landed-it"), judge(finished=True), + worker(say="next chunk"), + ]) + self.assertEqual(run.code, 130) + self.assertEqual(run.roles(), ["worker", "judge", "worker", "judge", "worker", "judge"]) + workers = [call for call in run.calls if call["role"] == "worker"] + session = argument(workers[0], "--session-id") + self.assertEqual(argument(workers[0], "--name"), "A proj loop-claude") + self.assertEqual(argument(workers[1], "--resume"), session) + self.assertIsNone(argument(workers[1], "--session-id")) + self.assertEqual(argument(workers[2], "--session-id"), session) + self.assertTrue(argument(workers[0], "-p").startswith(TASK)) + self.assertEqual({argument(call, "--model") for call in workers}, {"worker-model"}) + self.assertEqual({argument(call, "--model") for call in run.calls if call["role"] == "judge"}, {"judge-model"}) + self.assertIn("landed-it", run.calls[3]["stdin"]) + self.assertNotIn("landed-it", run.calls[5]["stdin"]) + self.assertIn("=== cycle 3 ===", run.stdout) + self.assertTrue(checkout.archived()) + for archived in checkout.archived(): + self.assertEqual(stat.S_IMODE(archived.stat().st_mode), 0o600) + + def test_stops_after_three_failures_running_retrying_a_minute_apart(self): + checkout = Checkout(self) + run = checkout.run([worker(exit=1), worker(result=False), worker(signal=9)]) + self.assertEqual(run.code, 1) + self.assertEqual(run.roles(), ["worker"] * 3) + self.assertEqual(run.sleeps, [60, 60]) + self.assertIn("retrying the worker in a minute: claude exited 1", run.stderr) + self.assertIn("claude exited 0 without a result event", run.stderr) + self.assertEqual(run.stderr.strip().splitlines()[-1], "the worker failed three times running: claude killed by signal 9") + + run = checkout.run([worker(exit=1), worker(exit=1), worker(), judge(), worker(exit=1), worker(exit=1)]) + self.assertEqual(run.code, 130) + self.assertEqual(run.sleeps, [60, 60, 60, 60]) + + run = checkout.run([worker(), judge(exit=1, stderr="judge down"), judge(stdout="{}"), judge(verdict={"interrupt": False})]) + self.assertEqual(run.code, 1) + self.assertEqual(run.roles(), ["worker", "judge", "judge", "judge"]) + self.assertEqual(run.sleeps, [60, 60]) + self.assertIn("retrying the judge in a minute: judge down", run.stderr) + self.assertEqual(run.stderr.strip().splitlines()[-1], "the judge failed three times running: the judge returned no verdict") + + def test_retries_the_judge_alone_when_its_interrupt_quotes_nothing_in_the_transcript(self): + checkout = Checkout(self) + run = checkout.run([worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="never said", question="A or B?"), judge()]) + self.assertEqual(run.code, 130) + self.assertEqual(run.roles(), ["worker", "judge", "judge", "worker"]) + self.assertIn("the judge quoted 'never said', nothing in the transcript, for the question: A or B?", run.stderr) + + def test_exits_1_when_claude_leaves_no_transcript(self): + checkout = Checkout(self) + run = checkout.run([worker(transcript=False)]) + self.assertEqual((run.code, run.roles()), (1, ["worker"])) + self.assertIn("claude left no transcript for session", run.stderr) + + +class Interrupt(unittest.TestCase): + def test_exits_2_off_a_terminal_and_resumes_on_the_next_run(self): + checkout = Checkout(self) + steps = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")] + run = checkout.run(steps) + self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"])) + self.assertEqual(run.stderr.strip().splitlines()[-2:], ["A or B?", "stdin or stdout is not a terminal"]) + self.assertTrue(checkout.archived()) + session = argument(run.calls[0], "--session-id") + run = checkout.run(steps, terminal_input="", stdout_on_terminal=False) + self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"])) + self.assertEqual(argument(run.calls[0], "--resume"), session) + self.assertEqual(run.stderr.strip().splitlines()[-1], "stdin or stdout is not a terminal") + + def test_hands_the_terminal_over_and_exits_2_when_nothing_is_typed(self): + checkout = Checkout(self) + checkout.git("commit", "--allow-empty", "--quiet", "-m", "start") + checkout.git("worktree", "add", "--quiet", str(checkout.home / "code" / "proj-wt")) + checkout.claude_json().write_text(json.dumps({"other": 1, "projects": {str(checkout.root): {"kept": True}}})) + checkout.claude_json().chmod(0o644) + asked = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")] + run = checkout.run([*asked, interrupt(type="B"), judge(), worker()], terminal_input="") + self.assertEqual(run.code, 130) + self.assertEqual(run.roles(), ["worker", "judge", "interrupt", "judge", "worker", "judge"]) + handed = run.calls[2]["argv"] + self.assertEqual(argument(run.calls[2], "--resume"), argument(run.calls[0], "--session-id")) + self.assertEqual(argument(run.calls[2], "--model"), "worker-model") + self.assertNotIn("-p", handed) + self.assertIn("[human] B", run.calls[3]["stdin"]) + trusted = json.loads(checkout.claude_json().read_text()) + self.assertEqual(trusted["other"], 1) + self.assertEqual(trusted["projects"][str(checkout.root)], {"hasTrustDialogAccepted": True, "kept": True}) + self.assertEqual(trusted["projects"][str(checkout.home / "code" / "proj-wt")], {"hasTrustDialogAccepted": True}) + self.assertEqual(stat.S_IMODE(checkout.claude_json().stat().st_mode), 0o644) + + for transcript in checkout.transcripts(): + transcript.unlink() + run = checkout.run([*asked, interrupt()], terminal_input="") + self.assertEqual((run.code, run.roles()), (2, ["worker", "judge", "interrupt"])) + self.assertEqual(run.stderr.strip().splitlines()[-1], "the interrupt ended without the human typing anything") + + +class Models(unittest.TestCase): + def catalog(self, checkout): + folder = checkout.home / ".claude" / "cache" / "model-catalog" + folder.mkdir(parents=True) + (folder / "old.json").write_text(json.dumps({"catalog": {"config": {"models": [{"id": "old-model"}]}}, "fetchedAt": 1})) + (folder / "new.json").write_text(json.dumps({"catalog": {"config": {"models": [{"id": "model-a", "name": "A"}, {"id": "model-b", "name": "B"}]}}, "fetchedAt": 2})) + + def test_asks_a_project_without_a_model_on_the_terminal_and_saves_the_answer(self): + checkout = Checkout(self) + del checkout.env["LOOP_CLAUDE_JUDGE_MODEL"], checkout.env["LOOP_CLAUDE_WORKER_MODEL"] + self.catalog(checkout) + run = checkout.run([worker()]) + self.assertEqual((run.code, run.calls), (2, [])) + self.assertIn(f"proj has no model in {checkout.models_file()}", run.stderr) + + run = checkout.run([worker(), judge()], terminal_input="9\n2\n") + self.assertEqual(run.code, 130) + self.assertIn("1. A (model-a)", run.stderr) + self.assertNotIn("old-model", run.stderr) + self.assertIn("pick 1 to 2", run.stderr) + self.assertEqual({argument(call, "--model") for call in run.calls}, {"model-b"}) + self.assertEqual(json.loads(checkout.models_file().read_text()), {"proj": "model-b"}) + self.assertEqual(stat.S_IMODE(checkout.models_file().stat().st_mode), 0o600) + + checkout.env["LOOP_CLAUDE_JUDGE_MODEL"] = "judge-model" + run = checkout.run([worker(), judge()]) + self.assertEqual([argument(call, "--model") for call in run.calls], ["model-b", "judge-model", "model-b"]) + + def test_keeps_the_models_file_mode_and_other_projects_when_saving(self): + checkout = Checkout(self) + del checkout.env["LOOP_CLAUDE_JUDGE_MODEL"], checkout.env["LOOP_CLAUDE_WORKER_MODEL"] + checkout.models_file().parent.mkdir(parents=True) + checkout.models_file().write_text(json.dumps({"other": "model-x"})) + checkout.models_file().chmod(0o640) + run = checkout.run([worker()], terminal_input="custom-model\n") + self.assertEqual(run.code, 130) + self.assertIn("no model catalog cached", run.stderr) + self.assertEqual(json.loads(checkout.models_file().read_text()), {"other": "model-x", "proj": "custom-model"}) + self.assertEqual(stat.S_IMODE(checkout.models_file().stat().st_mode), 0o640) + + checkout.models_file().write_text("[]") + run = checkout.run([worker()]) + self.assertEqual((run.code, run.calls), (1, [])) + self.assertIn(f"could not read {checkout.models_file()}", run.stderr) + + @unittest.skipIf(os.geteuid() == 0, "root writes into a read-only directory") + def test_exits_1_when_the_models_file_cannot_be_written(self): + checkout = Checkout(self) + del checkout.env["LOOP_CLAUDE_JUDGE_MODEL"], checkout.env["LOOP_CLAUDE_WORKER_MODEL"] + checkout.models_file().parent.mkdir(parents=True, mode=0o500) + self.addCleanup(checkout.models_file().parent.chmod, 0o700) + run = checkout.run([worker()], terminal_input="custom-model\n") + self.assertEqual((run.code, run.calls), (1, [])) + self.assertIn(f"could not save the model in {checkout.models_file()}: Permission denied", run.stderr) + + +class Reload(unittest.TestCase): + def test_an_edit_takes_effect_at_the_next_cycle_boundary_once_it_answers_help(self): + checkout = Checkout(self) + copy = checkout.temp / "bin" + shutil.copytree(BIN, copy, ignore=shutil.ignore_patterns("__pycache__", "test_*")) + checkout.script = copy / "loop-claude" + checkout.env["FAKE_CLAUDE_EDIT"] = str(checkout.script) + run = checkout.run([ + worker(append="\ndef\n"), judge(), + worker(replace=["\ndef\n", "\n# edited\n"]), judge(), + worker(), + ]) + self.assertEqual(run.code, 130) + self.assertEqual(run.roles(), ["worker", "judge"] * 3) + self.assertIn("keeping the running script", run.stderr) + reloads = [argv for argv in run.starts if argv[:1] == ["--reloaded"]] + self.assertEqual(len(reloads), 1) + self.assertEqual(json.loads(reloads[0][1]), {"cycle_number": 2, "failures": 0, "root": str(checkout.root), "task": TASK}) + self.assertIn("=== cycle 3 ===", run.stdout) + + run = checkout.run([], argv=["--reloaded", "{}"]) + self.assertEqual((run.code, run.calls), (1, [])) + self.assertIn("rerun loop-claude ", run.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/todo.md b/todo.md index 243d819b..ea907421 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,6 @@ Ships when a four-seat scoring run puts every dimension and the overall at 7.0 or above (`docs/decisions.md`). The rebuild lifts every dimension: each item below is one chunk on a worktree based on `origin/rebuild`, its PR into `rebuild`, until the last item merges `rebuild` into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -- **Pin loop-claude's behaviour in black-box tests that pass against main's script.** Run `bin/loop-claude` as a subprocess with a fake `claude` on `PATH` and temporary `HOME` and checkout: premises refusals, exit codes, the worker's and the judge's three strikes, an ungrounded verdict, the interrupt off a terminal, the session resumed while unfinished and fresh after finishing, the models file and `~/.claude.json` rewritten with their modes, the reload at a cycle boundary. - **Lay out `bin/loop-claude` as a launcher over a `bin/loop_claude/` package, with the loop, checkout and premises moved in.** The launcher resolves its own symlink, injects `Paths` and the environment, and is the only thing that exits; `main` owns the loop state, carries it across a reload on argv, and maps `Stop | Retry | Continue`. The black-box tests pass unchanged. - **Move the transcript, the session and the worker into their own modules.** `UserEntryKind` names each entry Claude Code writes; a malformed line is skipped; an unreadable transcript is its own error, never "typed nothing"; `session` states the lifecycle once, where the id is made. - **Move the judge, the interrupt, trust and model resolution into their own modules.** The judge is retried alone and checks evidence on every verdict against the rendered transcript; `models` owns the whole resolution, env overrides included, with no sentinel; `trust` names a `projects` entry that is not an object; `input()` at end of file is exit 2. -- 2.52.0 From e5d1d0dd7fe685e9c040fa0f0976665a3963389d Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 10:54:39 +0200 Subject: [PATCH 002/233] Keep main's --reloaded state across the rebuild --- AGENTS.md | 1 + docs/decisions.md | 4 ++++ todo.md | 2 +- 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 9ce5a71c..1f7171a9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -24,3 +24,4 @@ Decisions live in `docs/decisions.md`: - loop-claude: the judge is retried alone, on its own counter - loop-claude: the judge loads `CLAUDE.md` - loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop +- loop-claude: the rebuild keeps main's `--reloaded` state diff --git a/docs/decisions.md b/docs/decisions.md index 494e3e8f..c9fa0a0e 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -79,3 +79,7 @@ ## loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop 2026-09-28, lilleman, for the rebuild. Serves goal 2. A copy of the `.jsonl`, deduplicated by content hash, with the verdict beside it; a rendering drops tool results, and a second-resolution stamp collapses two states. A failed archive exits 1, since a loop that loses its record silently fails the backup goal. Valid while transcripts stay small enough to copy whole. + +## loop-claude: the rebuild keeps main's `--reloaded` state + +2026-09-28, lilleman, for the rebuild. Serves goal 4. A loop running main's script reloads into the rebuilt one at its next cycle boundary and carries on; the state keeps main's four fields, `cycle_number`, `failures`, `root` and `task`, so no code exists only for the cut-over. Valid until the rebuild merges. diff --git a/todo.md b/todo.md index ea907421..b6fc7eb9 100644 --- a/todo.md +++ b/todo.md @@ -15,4 +15,4 @@ Ships when a four-seat scoring run puts every dimension and the overall at 7.0 o - **Rewrite larv-review around one pass table and one re-entry rule.** A trigger per pass, each stated only there; the re-entry paragraph classifies a fix by the widest thing it touches; forge neutrality, the draft PR, CI watched in the foreground, the comprehension floor, the auto-reviewer's waits and the goal-alignment check carried over. - **Make the three reviewer agents pure reporters in the findings document's vocabulary.** Keep their names and checklists; remove every README- and decision-writing duty and every private severity or verdict scale. - **Bring `CLAUDE.md` → "Vocabulary", the README and `docs/decisions.md` in line with the rebuild.** Trigger covers every pass, round cap counts per chunk, "looping reviewer" goes if the rule no longer needs it; superseded decisions leave the log. -- **Score `rebuild` with the four-seat panel at 7.0 or above on every dimension and the overall, none below the 2026-09-28 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. Before merging, a loop running main's script reloads into the new one at its next cycle boundary: accept main's `--reloaded` state, or say in the changelog that running loops stop once. +- **Score `rebuild` with the four-seat panel at 7.0 or above on every dimension and the overall, none below the 2026-09-28 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. A loop running main's script reloads into the new one and carries on (`docs/decisions.md`). -- 2.52.0 From 2ffeb5b4c083f2cc8be48b9b6562330e68b5e056 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 10:58:46 +0200 Subject: [PATCH 003/233] Plan the contributor as a standing audience for 0.2.0 --- todo.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/todo.md b/todo.md index b6fc7eb9..2b4ab42d 100644 --- a/todo.md +++ b/todo.md @@ -16,3 +16,7 @@ Ships when a four-seat scoring run puts every dimension and the overall at 7.0 o - **Make the three reviewer agents pure reporters in the findings document's vocabulary.** Keep their names and checklists; remove every README- and decision-writing duty and every private severity or verdict scale. - **Bring `CLAUDE.md` → "Vocabulary", the README and `docs/decisions.md` in line with the rebuild.** Trigger covers every pass, round cap counts per chunk, "looping reviewer" goes if the rule no longer needs it; superseded decisions leave the log. - **Score `rebuild` with the four-seat panel at 7.0 or above on every dimension and the overall, none below the 2026-09-28 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. A loop running main's script reloads into the new one and carries on (`docs/decisions.md`). + +## 0.2.0 + +- **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. -- 2.52.0 From 5a681948beb01bf65c6ee08da5f00fa1bbe72b5a Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 11:03:01 +0200 Subject: [PATCH 004/233] Lay out loop-claude as a launcher over the loop_claude package --- .gitignore | 1 + bin/loop-claude | 576 +----------------------------------- bin/loop_claude/checkout.py | 22 ++ bin/loop_claude/cycle.py | 399 +++++++++++++++++++++++++ bin/loop_claude/main.py | 141 +++++++++ bin/loop_claude/outcome.py | 17 ++ bin/loop_claude/paths.py | 24 ++ bin/loop_claude/premises.py | 36 +++ bin/test_loop_claude.py | 237 +++++++-------- todo.md | 1 - 10 files changed, 752 insertions(+), 702 deletions(-) create mode 100644 bin/loop_claude/checkout.py create mode 100644 bin/loop_claude/cycle.py create mode 100644 bin/loop_claude/main.py create mode 100644 bin/loop_claude/outcome.py create mode 100644 bin/loop_claude/paths.py create mode 100644 bin/loop_claude/premises.py diff --git a/.gitignore b/.gitignore index 01dedfeb..abba4dcf 100644 --- a/.gitignore +++ b/.gitignore @@ -19,6 +19,7 @@ !agents/*.md !bin/ !bin/* +!bin/loop_claude/*.py !docs/ !docs/*.md !principles/ diff --git a/bin/loop-claude b/bin/loop-claude index f4d4d6e2..f783e143 100755 --- a/bin/loop-claude +++ b/bin/loop-claude @@ -1,579 +1,11 @@ #!/usr/bin/env python3 -"""Run a task as headless claude cycles; a judge interrupts only when a decision is the human's. - -usage: loop-claude - -Run it anywhere inside a project checkout whose README.md has ## Goals and ## Audience, the -premises; the task runs at the checkout root. Each cycle a worker runs the task; a judge then reads -the transcript against them and rules whether the chunk, the smallest PR-able change, is finished. -A question only the human can answer, or a release ready to cut, is an interrupt: `claude --resume` -on the terminal, every worktree first marked trusted in ~/.claude.json. An unfinished chunk resumes -its session next cycle; the next chunk starts a fresh session. -Cycles continue until that interrupt or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary". - -Exit 1: no task, not inside a checkout, no premises, a models file it cannot read or write, claude -leaves no transcript, a reload with unreadable state, or the worker or the judge fails three times -running. A worker fails when claude exits non-zero, is killed, or ends without a result event; a -judge when its verdict misses a field or quotes nothing in the transcript. -Exit 2: the human is needed, to pick the model or answer an interrupt, and stdin or stdout is not a -terminal, or the interrupt ended without them typing anything. Rerunning resumes any open session. - -Each project has one session, "A loop-claude", being the checkout relative to ~/code, -or to / outside it, deleted when the chunk finishes. Its transcript is archived under -$LOOP_CLAUDE_TRANSCRIPTS// (default ~/.claude/loop-claude-transcripts) at every interrupt and -when the chunk finishes. - -Every claude it starts runs the project's model, saved per in ~/.claude/loop-claude-models.json -and read each cycle; a project without an entry, as on its first run, is asked for one. -LOOP_CLAUDE_JUDGE_MODEL overrides it for the judge, LOOP_CLAUDE_WORKER_MODEL for the worker and the -interrupt; with both set, nothing is asked. - -A change to this script takes effect at the next cycle boundary, once the new script answers --help. - -Claude Code internals this rests on, observed on 2.1.282, the model catalog on 2.1.283: -- The transcript is ~/.claude/projects/*/.jsonl, one JSON object per line. A / - folder and .superseded-*/ and .orphaned-*.jsonl siblings belong to the same session. -- Claude Code writes "user" entries of its own into the transcript, and a `claude -p` prompt lands as one - with promptSource "sdk"; typed() tells a human's from them. -- An "assistant" entry, in the transcript and in --output-format stream-json, carries message.content - parts of type "text" (text) and "tool_use" (name, input); stream-json ends with a "result" event. -- `claude -p --output-format json --json-schema` returns the verdict under "structured_output". -- `claude -p` without --bare loads the project's and ~/.claude's CLAUDE.md, so the judge reads the words. -- ~/.claude.json holds projects..hasTrustDialogAccepted per checkout. -- ~/.claude/cache/model-catalog/*.json holds catalog.config.models, each with an id and a name; the newest - file has the highest fetchedAt. -""" -import dataclasses -import glob -import itertools -import json import os import pathlib -import shutil -import subprocess import sys -import time -import uuid -ARCHIVE = os.path.expanduser(os.environ.get("LOOP_CLAUDE_TRANSCRIPTS", "~/.claude/loop-claude-transcripts")) -RELOAD_BASELINE = pathlib.Path(__file__).read_text(encoding="utf-8") -RELOAD_FLAG = "--reloaded" -SESSION_NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec") +LAUNCHER = pathlib.Path(__file__).resolve() +sys.path.insert(0, str(LAUNCHER.parent)) -JUDGE_RULES = ( - "Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n" - "- the agent asks the human anything, seeks approval, or says a decision is the human's\n" - "- it carried on under an assumption that decides the deliverable and that the human could " - "reasonably reject; a caveat about transient state it then handled is not one\n" - "- it is blocked on something only the human can supply: a credential, a version bump, a release " - "ready to cut, a choice outside the repo\n" - "- it flags that the goals, the plan or the task itself is unclear, missing or in need of change\n" - "- it chose between alternatives the README text does not discriminate between - it does not " - "rule the rejected one out - and the choice materially changes the deliverable\n" - "interrupt=false otherwise. Bookkeeping the agent settled silently - what to document, wording, " - "where a note goes - is not on its own a reason to interrupt. The human may have replied inside the transcript, on a [human] line: judge only what " - "is still open, never a question they already answered there.\n" - "Where the agent asked or flagged something itself, the question is that one, in the agent's own " - "wording; never construct another from facts it stated.\n" - "finished=true when the chunk is complete: merged, or nothing remains that the agent could do on " - "its own. finished=false when work remains that a further run can continue: an open PR, a review " - "not yet run, CI not yet reported." -) +from loop_claude import main, paths -JUDGE_SCHEMA = { - "properties": { - "evidence": {"description": "A verbatim quote of the transcript line that triggers the interrupt. Empty when interrupt is false.", "type": "string"}, - "finished": {"type": "boolean"}, - "interrupt": {"type": "boolean"}, - "question": {"description": "The single question to put to the human. Empty when interrupt is false.", "type": "string"}, - }, - "required": ["evidence", "finished", "interrupt", "question"], - "type": "object", -} - - -@dataclasses.dataclass(frozen=True) -class Stop: - code: int - reason: str - - -def main(): - try: - stop = run_loop(sys.argv[1:]) - except KeyboardInterrupt: - stop = Stop(130, "") - if stop.reason: - print(stop.reason, file=sys.stderr if stop.code else sys.stdout) - sys.exit(stop.code) - - -def run_loop(argv): - state = loop_state(argv) - if isinstance(state, Stop): - return state - while True: - reload_if_edited(state) - state = dataclasses.replace(state, cycle_number=state.cycle_number + 1) - premises = read_premises(state.root) - if isinstance(premises, Stop): - return premises - chosen = project_model(state.root) - if isinstance(chosen, Stop): - return chosen - name = session_name(state.root) - print(f"\n=== cycle {state.cycle_number} ===", flush=True) - failure = run_cycle(state.root, state.task, premises, name, uuid.uuid5(SESSION_NAMESPACE, name), chosen) - if isinstance(failure, Stop): - return failure - state = dataclasses.replace(state, failures=state.failures + 1 if failure else 0) - if failure and (stop := strike("worker", state.failures, failure)): - return stop - - -def strike(who, failures, failure): - if failures == 3: - return Stop(1, f"the {who} failed three times running: {failure}") - print(f"retrying the {who} in a minute: {failure}", file=sys.stderr) - time.sleep(60) - - -def run_cycle(root, task, premises, name, session_id, chosen): - if failure := run_worker(root, worker_args(task, name, session_id, chosen, resuming=session_open(session_id))): - return failure - path = session_file(session_id) - if not path: - return Stop(1, f"claude left no transcript for session {session_id}") - # The interrupt appends to this transcript, so each pass judges and archives it anew; archive skips a stamp it already wrote. - while True: - verdict = judge(root, task, premises, render(entries(path)), chosen) - if isinstance(verdict, Stop): - return verdict - if not verdict["interrupt"]: - break - archive(root, path, f"Task: {task}\n\nVerdict: interrupt\n\n{verdict['question']}") - if failure := interrupt(root, session_id, chosen, path, verdict["question"]): - return Stop(2, failure) - if verdict["finished"]: - archive(root, path, f"Task: {task}\n\nVerdict: finished") - delete_transcript_files(path) - return "" - - -def checkout_root(): - found = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True) - if found.returncode != 0: - return Stop(1, found.stderr.strip()) - return found.stdout.strip() - - -def read_premises(root): - try: - found = sections(pathlib.Path(root, "README.md").read_text(encoding="utf-8")) - except OSError as failure: - return Stop(1, f"README.md in {root}: {failure.strerror} - no premises.") - except UnicodeDecodeError as failure: - line = failure.object.count(b"\n", 0, failure.start) + 1 - return Stop(1, f"README.md is not UTF-8 on line {line} - no premises.") - for name in ("Goals", "Audience"): - bodies = found.get(name, []) - if not bodies: - return Stop(1, f"README.md has no ## {name} heading - no premises.") - if len(bodies) > 1: - return Stop(1, f"README.md has ## {name} more than once - no premises.") - if not bodies[0]: - return Stop(1, f"README.md has nothing under ## {name} - no premises.") - return f"## Goals\n{found['Goals'][0]}\n\n## Audience\n{found['Audience'][0]}" - - -def sections(text): - found, current, fenced = {}, None, False - for line in text.splitlines(): - fenced ^= line.startswith("```") - if not fenced and line.startswith("## "): - current = [] - found.setdefault(line.strip()[3:], []).append(current) - elif not fenced and line.startswith("# "): - current = None - elif current is not None and line.strip(): - current.append(line) - return {name: ["\n".join(body) for body in bodies] for name, bodies in found.items()} - - -def session_name(root): - # "A " is the human's cue in the session picker that the session is the loop's. - return f"A {project_name(root)} loop-claude" - - -def archive(root, path, note): - # Stamped by mtime, so a transcript unchanged since its last archive maps to the file already written. - folder = os.path.join(ARCHIVE, project_name(root)) - try: - stamp = time.strftime("%Y-%m-%dT%H-%M-%SZ", time.gmtime(os.path.getmtime(path))) - make_private(folder) - dest = os.path.join(folder, f"{stamp}.md") - if not os.path.exists(dest): - with open(os.open(dest, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as copy: - copy.write(f"# {stamp} {project_name(root)}\n\n{note}\n\n{render(entries(path))}\n") - print(f"transcript: {dest}", file=sys.stderr) - except OSError as failure: - print(f"could not archive the transcript: {failure}", file=sys.stderr) - - -def make_private(folder): - mask = os.umask(0o077) - try: - os.makedirs(folder, exist_ok=True) - finally: - os.umask(mask) - - -def replace_json(path, data, **dump): - staged = f"{path}.{os.getpid()}" - try: - mode = os.stat(path).st_mode & 0o7777 if os.path.exists(path) else 0o600 - with open(os.open(staged, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as handle: - os.fchmod(handle.fileno(), mode) - json.dump(data, handle, **dump) - os.replace(staged, path) - except OSError as failure: - if os.path.exists(staged): - os.remove(staged) - return failure - return None - - -def model_args(variable, chosen): - return ["--model", os.environ.get(variable) or chosen] - - -def project_name(root): - return root.removeprefix(os.path.expanduser("~/code/")).lstrip("/") - - -# The reload - - -@dataclasses.dataclass(frozen=True) -class LoopState: - cycle_number: int - failures: int - root: str - task: str - - -def loop_state(argv): - if argv[:1] != [RELOAD_FLAG]: - task = " ".join(argv) - if task in ("", "-h", "--help"): - return Stop(0 if task else 1, __doc__.strip()) - root = checkout_root() - return root if isinstance(root, Stop) else LoopState(0, 0, root, task) - handed = parse(argv[1]) if len(argv) == 2 else None - shape = {field.name: field.type for field in dataclasses.fields(LoopState)} - if not handed or handed.keys() != shape.keys() or any(type(handed[name]) is not kind for name, kind in shape.items()) or not (handed["root"] and handed["task"]): - return Stop(1, f"the reload cannot read the loop's state from {argv[1:]}; rerun loop-claude ") - return LoopState(**handed) - - -def reload_if_edited(state): - try: - source = pathlib.Path(__file__).read_text(encoding="utf-8") - except OSError as failure: - print(f"keeping the running script: {failure}", file=sys.stderr) - return - if source == RELOAD_BASELINE: - return - trial = subprocess.run([sys.executable, __file__, "--help"], capture_output=True, text=True) - if trial.returncode != 0: - print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr) - return - os.execv(sys.executable, [sys.executable, __file__, RELOAD_FLAG, json.dumps(dataclasses.asdict(state))]) - - -# ~/.claude/loop-claude-models.json - - -def project_model(root): - if os.environ.get("LOOP_CLAUDE_JUDGE_MODEL") and os.environ.get("LOOP_CLAUDE_WORKER_MODEL"): - return "" - saved = os.path.expanduser("~/.claude/loop-claude-models.json") - name = project_name(root) - models = read_models(saved) - if isinstance(models, Stop): - return models - if chosen := models.get(name): - return chosen - chosen = ask_model(name, saved) - if isinstance(chosen, Stop): - return chosen - # Reread: another loop may have saved its project while this one waited on the human. - models = read_models(saved) - if isinstance(models, Stop): - return models - if failure := replace_json(saved, {**models, name: chosen}, indent="\t", sort_keys=True): - return Stop(1, f"could not save the model in {saved}: {failure.strerror}") - print(f"{name} runs on {chosen}", file=sys.stderr) - return chosen - - -def read_models(saved): - try: - with open(saved, encoding="utf-8") as handle: - models = json.load(handle) - except FileNotFoundError: - return {} - except (OSError, ValueError) as failure: - return Stop(1, f"could not read {saved}: {getattr(failure, 'strerror', None) or failure}") - if not isinstance(models, dict) or not all(isinstance(chosen, str) and chosen for chosen in models.values()): - return Stop(1, f"could not read {saved}: not an object mapping projects to model names") - return models - - -def ask_model(name, saved): - if not (sys.stdin.isatty() and sys.stdout.isatty()): - return Stop(2, f"{name} has no model in {saved}, and stdin or stdout is not a terminal to ask on; run it on a terminal or merge {{\"{name}\": \"\"}} into {saved}") - offered = catalog() - print(f"\nThe model to run {name} on, saved in {saved}:", file=sys.stderr) - for number, (model_id, label) in enumerate(offered, 1): - print(f" {number}. {label} ({model_id})", file=sys.stderr) - if not offered: - print(" no model catalog cached in ~/.claude/cache/model-catalog", file=sys.stderr) - while True: - try: - answer = input(f"{'A number, or any' if offered else 'A'} name claude --model takes: ").strip() - except EOFError: - print(file=sys.stderr) - return Stop(2, "no model picked") - if not answer: - continue - if not (offered and answer.isdecimal()): - return answer - if 1 <= int(answer) <= len(offered): - return offered[int(answer) - 1][0] - print(f"pick 1 to {len(offered)}", file=sys.stderr) - - -def catalog(): - newest = {} - for path in glob.glob(os.path.expanduser("~/.claude/cache/model-catalog/*.json")): - try: - with open(path, encoding="utf-8") as handle: - data = json.load(handle) - except (OSError, ValueError): - continue - if isinstance(data, dict) and isinstance(data.get("fetchedAt"), (int, float)) and data["fetchedAt"] > newest.get("fetchedAt", -1): - newest = data - models = 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 [] - - -# The transcript file - - -def session_open(session_id): - return bool(session_file(session_id)) - - -def session_file(session_id): - hit = glob.glob(os.path.expanduser(f"~/.claude/projects/*/{session_id}.jsonl")) - return hit[0] if hit else "" - - -def delete_transcript_files(path): - for sibling in glob.glob(glob.escape(path.removesuffix(".jsonl")) + "*"): - try: - shutil.rmtree(sibling) if os.path.isdir(sibling) else os.remove(sibling) - except OSError as failure: - print(f"could not remove {sibling}: {failure}", file=sys.stderr) - - -def entries(path): - with open(path, encoding="utf-8") as handle: - for raw in handle: - if entry := parse(raw): - yield entry - - -def parse(raw): - try: - entry = json.loads(raw) - except ValueError: - return None - return entry if isinstance(entry, dict) else None - - -# "user" entries - - -def human_turns(entries): - return sum(1 for entry in entries if typed(entry)) - - -def typed(entry): - if entry.get("type") != "user": - return False - content = entry.get("message", {}).get("content") - parts = content if isinstance(content, list) else [] - meta = entry.get("isMeta") - loop_prompt = entry.get("promptSource") == "sdk" - command = isinstance(content, str) and content.startswith("<") - no_content = not isinstance(content, str) and not parts - non_text = any(not isinstance(part, dict) or part.get("type") != "text" for part in parts) - interruption = not non_text and any(part.get("text", "").startswith("[Request interrupted") for part in parts) - return not (meta or loop_prompt or command or no_content or non_text or interruption) - - -# "assistant" entries and stream-json - - -def run_worker(root, args): - with subprocess.Popen(["claude", *args], cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, text=True) as proc: - done = False - for raw in proc.stdout: - event = parse(raw) or {} - if event.get("type") == "result": - done = True - elif event.get("type") == "assistant": - for part in event.get("message", {}).get("content", []): - if line := said(part, 160): - print(line, flush=True) - code = proc.wait() - if code < 0: - return f"claude killed by signal {-code}" - if code: - return f"claude exited {code}" - return "" if done else "claude exited 0 without a result event" - - -def worker_args(task, name, session_id, chosen, resuming): - if resuming: - start = ["-p", "Continue the task; the previous run stopped before it was finished.", "--resume", str(session_id)] - else: - start = ["-p", f"{task}\n\nContinue any open draft PR or worktree for the item before creating a new one.", "--name", name, "--session-id", str(session_id)] - return [ - *start, - "--output-format", "stream-json", - "--permission-mode", "bypassPermissions", - "--verbose", - *model_args("LOOP_CLAUDE_WORKER_MODEL", chosen), - ] - - -def render(entries): - lines = [] - for entry in entries: - if entry.get("type") == "assistant": - lines += [line for part in entry.get("message", {}).get("content", []) if (line := said(part))] - elif typed(entry): - content = entry["message"]["content"] - lines.append("[human] " + (content if isinstance(content, str) else "".join(part.get("text", "") for part in content))) - return "\n\n".join(lines) - - -def said(part, limit=400): - kind = part.get("type") if isinstance(part, dict) else None - if kind == "text" and part.get("text", "").strip(): - return part["text"] - if kind == "tool_use": - return f"[tool {part.get('name')}] {json.dumps(part.get('input'))[:limit]}" - return "" - - -# --json-schema verdicts - - -def judge(root, task, premises, transcript, chosen): - # 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", - "--json-schema", json.dumps(JUDGE_SCHEMA), - *model_args("LOOP_CLAUDE_JUDGE_MODEL", chosen), - "--no-session-persistence", - "--output-format", "json", - "--permission-mode", "bypassPermissions", - "--tools", "", - ] - prompt = judge_prompt(task, premises, transcript) - for failures in itertools.count(1): - proc = subprocess.run(["claude", *args], capture_output=True, cwd=root, input=prompt, text=True) - verdict = (parse(proc.stdout) or {}).get("structured_output") if proc.returncode == 0 else None - if not complete(verdict): - failure = proc.stderr.strip() or "the judge returned no verdict" - elif not grounded(verdict, transcript): - failure = f"the judge quoted {verdict['evidence']!r}, nothing in the transcript, for the question: {verdict['question']}" - else: - return verdict - if stop := strike("judge", failures, failure): - return stop - - -def judge_prompt(task, premises, transcript): - return ( - f"From README.md:\n{premises}\n\n" - f"The task an agent was given:\n{task}\n\n" - # The tail, where an interrupt or a finish lands; the session's transcript grows cycle over cycle. - f"What the agent did and said, and what the human typed on [human] lines, latest last:\n{transcript[-40000:]}\n\n" - f"{JUDGE_RULES}" - ) - - -def complete(verdict): - return isinstance(verdict, dict) and set(JUDGE_SCHEMA["required"]) <= verdict.keys() - - -def grounded(verdict, transcript): - if not verdict["interrupt"]: - return True - evidence = verdict["evidence"] - return evidence.strip() != "" and evidence in transcript - - -# ~/.claude.json - - -def interrupt(root, session_id, chosen, path, question): - print(f"\n{question}", file=sys.stderr) - if not (sys.stdin.isatty() and sys.stdout.isatty()): - return "stdin or stdout is not a terminal" - trust(checkouts(root)) - before = human_turns(entries(path)) - subprocess.run(["claude", *model_args("LOOP_CLAUDE_WORKER_MODEL", chosen), "--permission-mode", "bypassPermissions", "--resume", str(session_id)], cwd=root) - return "" if human_turns(entries(path)) > before else "the interrupt ended without the human typing anything" - - -def checkouts(root): - found = [root] - listing = subprocess.run(["git", "worktree", "list", "--porcelain"], capture_output=True, cwd=root, text=True) - if listing.returncode == 0: - found += [line.split(" ", 1)[1] for line in listing.stdout.splitlines() if line.startswith("worktree ")] - return sorted(set(found)) - - -def trust(paths): - config = os.path.expanduser("~/.claude.json") - try: - with open(config, encoding="utf-8") as handle: - data = json.load(handle) - except (OSError, ValueError) as failure: - print(f"could not read {config}: {getattr(failure, 'strerror', failure)}", file=sys.stderr) - return - projects = data.setdefault("projects", {}) if isinstance(data, dict) else None - if not isinstance(projects, dict) or not all(isinstance(record, dict) for record in projects.values()): - print(f"could not read {config}: not an object whose \"projects\" maps paths to objects", file=sys.stderr) - return - untrusted = [path for path in paths if not projects.get(path, {}).get("hasTrustDialogAccepted")] - if not untrusted: - return - for path in untrusted: - projects.setdefault(path, {})["hasTrustDialogAccepted"] = True - if failure := replace_json(config, data, indent=2): - print(f"could not write {config}: {failure.strerror}", file=sys.stderr) - return - print("trusted for the interrupt: " + ", ".join(untrusted), file=sys.stderr) - - -if __name__ == "__main__": - main() +sys.exit(main.main(sys.argv[1:], os.environ, paths.paths_from(pathlib.Path.home(), os.environ), LAUNCHER)) diff --git a/bin/loop_claude/checkout.py b/bin/loop_claude/checkout.py new file mode 100644 index 00000000..7ad42d79 --- /dev/null +++ b/bin/loop_claude/checkout.py @@ -0,0 +1,22 @@ +import subprocess + +from loop_claude.outcome import Stop + + +def checkout_root(): + found = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True) + if found.returncode != 0: + return Stop(1, found.stderr.strip()) + return found.stdout.strip() + + +def checkouts(root): + found = [root] + listing = subprocess.run(["git", "worktree", "list", "--porcelain"], capture_output=True, cwd=root, text=True) + if listing.returncode == 0: + found += [line.split(" ", 1)[1] for line in listing.stdout.splitlines() if line.startswith("worktree ")] + return sorted(set(found)) + + +def project_name(root, code): + return root.removeprefix(f"{code}/").lstrip("/") diff --git a/bin/loop_claude/cycle.py b/bin/loop_claude/cycle.py new file mode 100644 index 00000000..6633101f --- /dev/null +++ b/bin/loop_claude/cycle.py @@ -0,0 +1,399 @@ +import glob +import itertools +import json +import os +import shutil +import subprocess +import sys +import time +import uuid + +from loop_claude.checkout import checkouts, project_name +from loop_claude.outcome import Continue, Retry, Stop + +SESSION_NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec") + +JUDGE_RULES = ( + "Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n" + "- the agent asks the human anything, seeks approval, or says a decision is the human's\n" + "- it carried on under an assumption that decides the deliverable and that the human could " + "reasonably reject; a caveat about transient state it then handled is not one\n" + "- it is blocked on something only the human can supply: a credential, a version bump, a release " + "ready to cut, a choice outside the repo\n" + "- it flags that the goals, the plan or the task itself is unclear, missing or in need of change\n" + "- it chose between alternatives the README text does not discriminate between - it does not " + "rule the rejected one out - and the choice materially changes the deliverable\n" + "interrupt=false otherwise. Bookkeeping the agent settled silently - what to document, wording, " + "where a note goes - is not on its own a reason to interrupt. The human may have replied inside the transcript, on a [human] line: judge only what " + "is still open, never a question they already answered there.\n" + "Where the agent asked or flagged something itself, the question is that one, in the agent's own " + "wording; never construct another from facts it stated.\n" + "finished=true when the chunk is complete: merged, or nothing remains that the agent could do on " + "its own. finished=false when work remains that a further run can continue: an open PR, a review " + "not yet run, CI not yet reported." +) + +JUDGE_SCHEMA = { + "properties": { + "evidence": {"description": "A verbatim quote of the transcript line that triggers the interrupt. Empty when interrupt is false.", "type": "string"}, + "finished": {"type": "boolean"}, + "interrupt": {"type": "boolean"}, + "question": {"description": "The single question to put to the human. Empty when interrupt is false.", "type": "string"}, + }, + "required": ["evidence", "finished", "interrupt", "question"], + "type": "object", +} + + +def strike(who, failures, failure): + if failures == 3: + return Stop(1, f"the {who} failed three times running: {failure}") + print(f"retrying the {who} in a minute: {failure}", file=sys.stderr) + time.sleep(60) + + +def run_cycle(root, task, premises, chosen, paths, env): + name = session_name(root, paths.code) + session_id = uuid.uuid5(SESSION_NAMESPACE, name) + if failure := run_worker(root, worker_args(task, name, session_id, chosen, env, resuming=session_open(paths.projects, session_id))): + return Retry(failure) + path = session_file(paths.projects, session_id) + if not path: + return Stop(1, f"claude left no transcript for session {session_id}") + # The interrupt appends to this transcript, so each pass judges and archives it anew; archive skips a stamp it already wrote. + while True: + verdict = judge(root, task, premises, render(entries(path)), chosen, env) + if isinstance(verdict, Stop): + return verdict + if not verdict["interrupt"]: + break + archive(root, path, f"Task: {task}\n\nVerdict: interrupt\n\n{verdict['question']}", paths) + if failure := interrupt(root, session_id, chosen, path, verdict["question"], paths, env): + return Stop(2, failure) + if verdict["finished"]: + archive(root, path, f"Task: {task}\n\nVerdict: finished", paths) + delete_transcript_files(path) + return Continue() + + +def session_name(root, code): + # "A " is the human's cue in the session picker that the session is the loop's. + return f"A {project_name(root, code)} loop-claude" + + +def archive(root, path, note, paths): + # Stamped by mtime, so a transcript unchanged since its last archive maps to the file already written. + name = project_name(root, paths.code) + folder = paths.archive / name + try: + stamp = time.strftime("%Y-%m-%dT%H-%M-%SZ", time.gmtime(os.path.getmtime(path))) + make_private(folder) + dest = folder / f"{stamp}.md" + if not os.path.exists(dest): + with open(os.open(dest, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as copy: + copy.write(f"# {stamp} {name}\n\n{note}\n\n{render(entries(path))}\n") + print(f"transcript: {dest}", file=sys.stderr) + except OSError as failure: + print(f"could not archive the transcript: {failure}", file=sys.stderr) + + +def make_private(folder): + mask = os.umask(0o077) + try: + os.makedirs(folder, exist_ok=True) + finally: + os.umask(mask) + + +def replace_json(path, data, **dump): + staged = f"{path}.{os.getpid()}" + try: + mode = os.stat(path).st_mode & 0o7777 if os.path.exists(path) else 0o600 + with open(os.open(staged, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as handle: + os.fchmod(handle.fileno(), mode) + json.dump(data, handle, **dump) + os.replace(staged, path) + except OSError as failure: + if os.path.exists(staged): + os.remove(staged) + return failure + return None + + +def model_args(env, variable, chosen): + return ["--model", env.get(variable) or chosen] + + +# ~/.claude/loop-claude-models.json + + +def project_model(root, paths, env): + if env.get("LOOP_CLAUDE_JUDGE_MODEL") and env.get("LOOP_CLAUDE_WORKER_MODEL"): + return "" + saved = paths.models_file + name = project_name(root, paths.code) + models = read_models(saved) + if isinstance(models, Stop): + return models + if chosen := models.get(name): + return chosen + chosen = ask_model(name, saved, paths.model_catalog) + if isinstance(chosen, Stop): + return chosen + # Reread: another loop may have saved its project while this one waited on the human. + models = read_models(saved) + if isinstance(models, Stop): + return models + if failure := replace_json(saved, {**models, name: chosen}, indent="\t", sort_keys=True): + return Stop(1, f"could not save the model in {saved}: {failure.strerror}") + print(f"{name} runs on {chosen}", file=sys.stderr) + return chosen + + +def read_models(saved): + try: + with open(saved, encoding="utf-8") as handle: + models = json.load(handle) + except FileNotFoundError: + return {} + except (OSError, ValueError) as failure: + return Stop(1, f"could not read {saved}: {getattr(failure, 'strerror', None) or failure}") + if not isinstance(models, dict) or not all(isinstance(chosen, str) and chosen for chosen in models.values()): + return Stop(1, f"could not read {saved}: not an object mapping projects to model names") + return models + + +def ask_model(name, saved, folder): + if not (sys.stdin.isatty() and sys.stdout.isatty()): + return Stop(2, f"{name} has no model in {saved}, and stdin or stdout is not a terminal to ask on; run it on a terminal or merge {{\"{name}\": \"\"}} into {saved}") + offered = catalog(folder) + print(f"\nThe model to run {name} on, saved in {saved}:", file=sys.stderr) + for number, (model_id, label) in enumerate(offered, 1): + print(f" {number}. {label} ({model_id})", file=sys.stderr) + if not offered: + print(f" no model catalog cached in {folder}", file=sys.stderr) + while True: + try: + answer = input(f"{'A number, or any' if offered else 'A'} name claude --model takes: ").strip() + except EOFError: + print(file=sys.stderr) + return Stop(2, "no model picked") + if not answer: + continue + if not (offered and answer.isdecimal()): + return answer + if 1 <= int(answer) <= len(offered): + return offered[int(answer) - 1][0] + print(f"pick 1 to {len(offered)}", file=sys.stderr) + + +def catalog(folder): + newest = {} + for path in folder.glob("*.json"): + try: + with open(path, encoding="utf-8") as handle: + data = json.load(handle) + except (OSError, ValueError): + continue + if isinstance(data, dict) and isinstance(data.get("fetchedAt"), (int, float)) and data["fetchedAt"] > newest.get("fetchedAt", -1): + newest = data + models = 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 [] + + +# The transcript file + + +def session_open(projects, session_id): + return bool(session_file(projects, session_id)) + + +def session_file(projects, session_id): + hit = glob.glob(os.path.join(glob.escape(str(projects)), "*", f"{session_id}.jsonl")) + return hit[0] if hit else "" + + +def delete_transcript_files(path): + for sibling in glob.glob(glob.escape(path.removesuffix(".jsonl")) + "*"): + try: + shutil.rmtree(sibling) if os.path.isdir(sibling) else os.remove(sibling) + except OSError as failure: + print(f"could not remove {sibling}: {failure}", file=sys.stderr) + + +def entries(path): + with open(path, encoding="utf-8") as handle: + for raw in handle: + if entry := parse(raw): + yield entry + + +def parse(raw): + try: + entry = json.loads(raw) + except ValueError: + return None + return entry if isinstance(entry, dict) else None + + +# "user" entries + + +def human_turns(entries): + return sum(1 for entry in entries if typed(entry)) + + +def typed(entry): + if entry.get("type") != "user": + return False + content = entry.get("message", {}).get("content") + parts = content if isinstance(content, list) else [] + meta = entry.get("isMeta") + loop_prompt = entry.get("promptSource") == "sdk" + command = isinstance(content, str) and content.startswith("<") + no_content = not isinstance(content, str) and not parts + non_text = any(not isinstance(part, dict) or part.get("type") != "text" for part in parts) + interruption = not non_text and any(part.get("text", "").startswith("[Request interrupted") for part in parts) + return not (meta or loop_prompt or command or no_content or non_text or interruption) + + +# "assistant" entries and stream-json + + +def run_worker(root, args): + with subprocess.Popen(["claude", *args], cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, text=True) as proc: + done = False + for raw in proc.stdout: + event = parse(raw) or {} + if event.get("type") == "result": + done = True + elif event.get("type") == "assistant": + for part in event.get("message", {}).get("content", []): + if line := said(part, 160): + print(line, flush=True) + code = proc.wait() + if code < 0: + return f"claude killed by signal {-code}" + if code: + return f"claude exited {code}" + return "" if done else "claude exited 0 without a result event" + + +def worker_args(task, name, session_id, chosen, env, resuming): + if resuming: + start = ["-p", "Continue the task; the previous run stopped before it was finished.", "--resume", str(session_id)] + else: + start = ["-p", f"{task}\n\nContinue any open draft PR or worktree for the item before creating a new one.", "--name", name, "--session-id", str(session_id)] + return [ + *start, + "--output-format", "stream-json", + "--permission-mode", "bypassPermissions", + "--verbose", + *model_args(env, "LOOP_CLAUDE_WORKER_MODEL", chosen), + ] + + +def render(entries): + lines = [] + for entry in entries: + if entry.get("type") == "assistant": + lines += [line for part in entry.get("message", {}).get("content", []) if (line := said(part))] + elif typed(entry): + content = entry["message"]["content"] + lines.append("[human] " + (content if isinstance(content, str) else "".join(part.get("text", "") for part in content))) + return "\n\n".join(lines) + + +def said(part, limit=400): + kind = part.get("type") if isinstance(part, dict) else None + if kind == "text" and part.get("text", "").strip(): + return part["text"] + if kind == "tool_use": + return f"[tool {part.get('name')}] {json.dumps(part.get('input'))[:limit]}" + return "" + + +# --json-schema verdicts + + +def judge(root, task, premises, transcript, chosen, env): + # 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", + "--json-schema", json.dumps(JUDGE_SCHEMA), + *model_args(env, "LOOP_CLAUDE_JUDGE_MODEL", chosen), + "--no-session-persistence", + "--output-format", "json", + "--permission-mode", "bypassPermissions", + "--tools", "", + ] + prompt = judge_prompt(task, premises, transcript) + for failures in itertools.count(1): + proc = subprocess.run(["claude", *args], capture_output=True, cwd=root, input=prompt, text=True) + verdict = (parse(proc.stdout) or {}).get("structured_output") if proc.returncode == 0 else None + if not complete(verdict): + failure = proc.stderr.strip() or "the judge returned no verdict" + elif not grounded(verdict, transcript): + failure = f"the judge quoted {verdict['evidence']!r}, nothing in the transcript, for the question: {verdict['question']}" + else: + return verdict + if stop := strike("judge", failures, failure): + return stop + + +def judge_prompt(task, premises, transcript): + return ( + f"From README.md:\n{premises}\n\n" + f"The task an agent was given:\n{task}\n\n" + # The tail, where an interrupt or a finish lands; the session's transcript grows cycle over cycle. + f"What the agent did and said, and what the human typed on [human] lines, latest last:\n{transcript[-40000:]}\n\n" + f"{JUDGE_RULES}" + ) + + +def complete(verdict): + return isinstance(verdict, dict) and set(JUDGE_SCHEMA["required"]) <= verdict.keys() + + +def grounded(verdict, transcript): + if not verdict["interrupt"]: + return True + evidence = verdict["evidence"] + return evidence.strip() != "" and evidence in transcript + + +# ~/.claude.json + + +def interrupt(root, session_id, chosen, path, question, paths, env): + print(f"\n{question}", file=sys.stderr) + if not (sys.stdin.isatty() and sys.stdout.isatty()): + return "stdin or stdout is not a terminal" + trust(paths.claude_json, checkouts(root)) + before = human_turns(entries(path)) + subprocess.run(["claude", *model_args(env, "LOOP_CLAUDE_WORKER_MODEL", chosen), "--permission-mode", "bypassPermissions", "--resume", str(session_id)], cwd=root) + return "" if human_turns(entries(path)) > before else "the interrupt ended without the human typing anything" + + +def trust(config, roots): + try: + with open(config, encoding="utf-8") as handle: + data = json.load(handle) + except (OSError, ValueError) as failure: + print(f"could not read {config}: {getattr(failure, 'strerror', failure)}", file=sys.stderr) + return + projects = data.setdefault("projects", {}) if isinstance(data, dict) else None + if not isinstance(projects, dict) or not all(isinstance(record, dict) for record in projects.values()): + print(f"could not read {config}: not an object whose \"projects\" maps paths to objects", file=sys.stderr) + return + untrusted = [path for path in roots if not projects.get(path, {}).get("hasTrustDialogAccepted")] + if not untrusted: + return + for path in untrusted: + projects.setdefault(path, {})["hasTrustDialogAccepted"] = True + if failure := replace_json(config, data, indent=2): + print(f"could not write {config}: {failure.strerror}", file=sys.stderr) + return + print("trusted for the interrupt: " + ", ".join(untrusted), file=sys.stderr) diff --git a/bin/loop_claude/main.py b/bin/loop_claude/main.py new file mode 100644 index 00000000..2488ecbf --- /dev/null +++ b/bin/loop_claude/main.py @@ -0,0 +1,141 @@ +"""Run a task as headless claude cycles; a judge interrupts only when a decision is the human's. + +usage: loop-claude + +Run it anywhere inside a project checkout whose README.md has ## Goals and ## Audience, the +premises; the task runs at the checkout root. Each cycle a worker runs the task; a judge then reads +the transcript against them and rules whether the chunk, the smallest PR-able change, is finished. +A question only the human can answer, or a release ready to cut, is an interrupt: `claude --resume` +on the terminal, every worktree first marked trusted in ~/.claude.json. An unfinished chunk resumes +its session next cycle; the next chunk starts a fresh session. +Cycles continue until that interrupt or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary". + +Exit 1: no task, not inside a checkout, no premises, a models file it cannot read or write, claude +leaves no transcript, a reload with unreadable state, or the worker or the judge fails three times +running. A worker fails when claude exits non-zero, is killed, or ends without a result event; a +judge when its verdict misses a field or quotes nothing in the transcript. +Exit 2: the human is needed, to pick the model or answer an interrupt, and stdin or stdout is not a +terminal, or the interrupt ended without them typing anything. Rerunning resumes any open session. + +Each project has one session, "A loop-claude", being the checkout relative to ~/code, +or to / outside it, deleted when the chunk finishes. Its transcript is archived under +$LOOP_CLAUDE_TRANSCRIPTS// (default ~/.claude/loop-claude-transcripts) at every interrupt and +when the chunk finishes. + +Every claude it starts runs the project's model, saved per in ~/.claude/loop-claude-models.json +and read each cycle; a project without an entry, as on its first run, is asked for one. +LOOP_CLAUDE_JUDGE_MODEL overrides it for the judge, LOOP_CLAUDE_WORKER_MODEL for the worker and the +interrupt; with both set, nothing is asked. + +A change to loop-claude's files takes effect at the next cycle boundary, once they answer --help. + +Claude Code internals this rests on, observed on 2.1.282, the model catalog on 2.1.283: +- The transcript is ~/.claude/projects/*/.jsonl, one JSON object per line. A / + folder and .superseded-*/ and .orphaned-*.jsonl siblings belong to the same session. +- Claude Code writes "user" entries of its own into the transcript, and a `claude -p` prompt lands as one + with promptSource "sdk"; typed() tells a human's from them. +- An "assistant" entry, in the transcript and in --output-format stream-json, carries message.content + parts of type "text" (text) and "tool_use" (name, input); stream-json ends with a "result" event. +- `claude -p --output-format json --json-schema` returns the verdict under "structured_output". +- `claude -p` without --bare loads the project's and ~/.claude's CLAUDE.md, so the judge reads the words. +- ~/.claude.json holds projects..hasTrustDialogAccepted per checkout. +- ~/.claude/cache/model-catalog/*.json holds catalog.config.models, each with an id and a name; the newest + file has the highest fetchedAt. +""" +import dataclasses +import hashlib +import json +import os +import pathlib +import subprocess +import sys + +from loop_claude.checkout import checkout_root +from loop_claude.cycle import parse, project_model, run_cycle, strike +from loop_claude.outcome import Continue, Retry, Stop +from loop_claude.premises import read_premises + +RELOAD_FLAG = "--reloaded" + + +@dataclasses.dataclass(frozen=True) +class LoopState: + cycle_number: int + failures: int + root: str + task: str + + +def main(argv, env, paths, launcher): + try: + stop = run_loop(argv, env, paths, launcher) + except KeyboardInterrupt: + stop = Stop(130, "") + if stop.reason: + print(stop.reason, file=sys.stderr if stop.code else sys.stdout) + return stop.code + + +def run_loop(argv, env, paths, launcher): + state = loop_state(argv) + if isinstance(state, Stop): + return state + baseline = fingerprint(launcher) + while True: + reload_if_edited(launcher, baseline, state) + state = dataclasses.replace(state, cycle_number=state.cycle_number + 1) + premises = read_premises(state.root) + if isinstance(premises, Stop): + return premises + chosen = project_model(state.root, paths, env) + if isinstance(chosen, Stop): + return chosen + print(f"\n=== cycle {state.cycle_number} ===", flush=True) + match run_cycle(state.root, state.task, premises, chosen, paths, env): + case Stop() as stop: + return stop + case Retry(failure): + state = dataclasses.replace(state, failures=state.failures + 1) + if stop := strike("worker", state.failures, failure): + return stop + case Continue(): + state = dataclasses.replace(state, failures=0) + + +# The reload + + +def loop_state(argv): + if argv[:1] != [RELOAD_FLAG]: + task = " ".join(argv) + if task in ("", "-h", "--help"): + return Stop(0 if task else 1, __doc__.strip()) + root = checkout_root() + return root if isinstance(root, Stop) else LoopState(0, 0, root, task) + handed = parse(argv[1]) if len(argv) == 2 else None + shape = {field.name: field.type for field in dataclasses.fields(LoopState)} + if not handed or handed.keys() != shape.keys() or any(type(handed[name]) is not kind for name, kind in shape.items()) or not (handed["root"] and handed["task"]): + return Stop(1, f"the reload cannot read the loop's state from {argv[1:]}; rerun loop-claude ") + return LoopState(**handed) + + +def fingerprint(launcher): + # An unreadable file hashes its error, and the --help trial judges it. + digest = hashlib.sha256() + for path in [launcher, *sorted(pathlib.Path(__file__).parent.glob("*.py"))]: + try: + content = path.read_bytes() + except OSError as failure: + content = str(failure).encode() + digest.update(f"{path.name}\0{len(content)}\0".encode() + content) + return digest.hexdigest() + + +def reload_if_edited(launcher, baseline, state): + if fingerprint(launcher) == baseline: + return + trial = subprocess.run([sys.executable, launcher, "--help"], capture_output=True, text=True) + if trial.returncode != 0: + print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr) + return + os.execv(sys.executable, [sys.executable, str(launcher), RELOAD_FLAG, json.dumps(dataclasses.asdict(state))]) diff --git a/bin/loop_claude/outcome.py b/bin/loop_claude/outcome.py new file mode 100644 index 00000000..acd5df0b --- /dev/null +++ b/bin/loop_claude/outcome.py @@ -0,0 +1,17 @@ +import dataclasses + + +@dataclasses.dataclass(frozen=True) +class Continue: + pass + + +@dataclasses.dataclass(frozen=True) +class Retry: + failure: str + + +@dataclasses.dataclass(frozen=True) +class Stop: + code: int + reason: str diff --git a/bin/loop_claude/paths.py b/bin/loop_claude/paths.py new file mode 100644 index 00000000..cdf05a48 --- /dev/null +++ b/bin/loop_claude/paths.py @@ -0,0 +1,24 @@ +import dataclasses +import pathlib + + +@dataclasses.dataclass(frozen=True) +class Paths: + archive: pathlib.Path + claude_json: pathlib.Path + code: pathlib.Path + model_catalog: pathlib.Path + models_file: pathlib.Path + projects: pathlib.Path + + +def paths_from(home, env): + claude = home / ".claude" + return Paths( + archive=pathlib.Path(env["LOOP_CLAUDE_TRANSCRIPTS"]).expanduser() if env.get("LOOP_CLAUDE_TRANSCRIPTS") else claude / "loop-claude-transcripts", + claude_json=home / ".claude.json", + code=home / "code", + model_catalog=claude / "cache" / "model-catalog", + models_file=claude / "loop-claude-models.json", + projects=claude / "projects", + ) diff --git a/bin/loop_claude/premises.py b/bin/loop_claude/premises.py new file mode 100644 index 00000000..a23fc24f --- /dev/null +++ b/bin/loop_claude/premises.py @@ -0,0 +1,36 @@ +import pathlib + +from loop_claude.outcome import Stop + + +def read_premises(root): + try: + found = sections(pathlib.Path(root, "README.md").read_text(encoding="utf-8")) + except OSError as failure: + return Stop(1, f"README.md in {root}: {failure.strerror} - no premises.") + except UnicodeDecodeError as failure: + line = failure.object.count(b"\n", 0, failure.start) + 1 + return Stop(1, f"README.md is not UTF-8 on line {line} - no premises.") + for name in ("Goals", "Audience"): + bodies = found.get(name, []) + if not bodies: + return Stop(1, f"README.md has no ## {name} heading - no premises.") + if len(bodies) > 1: + return Stop(1, f"README.md has ## {name} more than once - no premises.") + if not bodies[0]: + return Stop(1, f"README.md has nothing under ## {name} - no premises.") + return f"## Goals\n{found['Goals'][0]}\n\n## Audience\n{found['Audience'][0]}" + + +def sections(text): + found, current, fenced = {}, None, False + for line in text.splitlines(): + fenced ^= line.startswith("```") + if not fenced and line.startswith("## "): + current = [] + found.setdefault(line.strip()[3:], []).append(current) + elif not fenced and line.startswith("# "): + current = None + elif current is not None and line.strip(): + current.append(line) + return {name: ["\n".join(body) for body in bodies] for name, bodies in found.items()} diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index c031435d..607f7499 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -1,7 +1,5 @@ import contextlib import errno -import importlib.machinery -import importlib.util import io import json import os @@ -14,12 +12,15 @@ import unittest import unittest.mock import uuid -SESSION_ID = str(getattr(uuid, "uuid7", uuid.uuid4)()) +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -LOADER = importlib.machinery.SourceFileLoader("loop_claude", str(pathlib.Path(__file__).with_name("loop-claude"))) -SPEC = importlib.util.spec_from_loader("loop_claude", LOADER) -loop = importlib.util.module_from_spec(SPEC) -LOADER.exec_module(loop) +from loop_claude import checkout, cycle, main, premises +from loop_claude.outcome import Continue, Retry, Stop +from loop_claude.paths import paths_from + +LAUNCHER = pathlib.Path(__file__).resolve().with_name("loop-claude") +PATHS = paths_from(pathlib.Path("/h"), {}) +SESSION_ID = str(getattr(uuid, "uuid7", uuid.uuid4)()) def assistant(*parts): @@ -42,12 +43,12 @@ def umask(mask): class Sections(unittest.TestCase): def test_keeps_every_headed_section_with_its_bodies(self): text = "# Title\n\nintro\n\n## Goals\n\n1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority\n\n## Empty\n\n## Audience\nme\n## Audience\nagain\n# Appendix\nnot audience\n" - self.assertEqual(loop.sections(text), {"Goals": ["1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority"], "Empty": [""], "Audience": ["me", "again"]}) + self.assertEqual(premises.sections(text), {"Goals": ["1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority"], "Empty": [""], "Audience": ["me", "again"]}) class ReadPremises(unittest.TestCase): def exit_message(self, root): - stop = loop.read_premises(root) + stop = premises.read_premises(root) self.assertEqual(stop.code, 1) self.assertTrue(stop.reason.endswith("no premises.")) return stop.reason @@ -73,12 +74,12 @@ class ReadPremises(unittest.TestCase): pathlib.Path(readme).write_text(text) self.assertIn(missing, self.exit_message(root)) pathlib.Path(readme).write_text("# T\n## Goals\n1. g\n## Audience\nme\n") - self.assertEqual(loop.read_premises(root), "## Goals\n1. g\n\n## Audience\nme") + self.assertEqual(premises.read_premises(root), "## Goals\n1. g\n\n## Audience\nme") class Render(unittest.TestCase): def test_joins_assistant_text_and_tool_calls_and_human_turns_and_skips_the_rest(self): - said = loop.render([ + said = cycle.render([ human("do it"), assistant({"type": "text", "text": "Starting."}, {"type": "tool_use", "name": "Bash", "input": {"command": "ls"}}), assistant({"type": "text", "text": " "}), @@ -92,7 +93,7 @@ class Render(unittest.TestCase): class HumanTurns(unittest.TestCase): def test_counts_typed_turns_and_not_tool_results(self): - self.assertEqual(loop.human_turns([ + self.assertEqual(cycle.human_turns([ human("typed"), human([{"type": "text", "text": "typed as a block"}]), human([{"type": "tool_result", "content": "not typed"}]), @@ -109,74 +110,69 @@ class CheckoutRoot(unittest.TestCase): def test_is_the_checkout_from_any_directory_inside_it_and_exits_outside_one(self): with tempfile.TemporaryDirectory() as tmp, contextlib.chdir(tmp): root = os.getcwd() - self.assertEqual(loop.checkout_root().code, 1) + self.assertEqual(checkout.checkout_root().code, 1) subprocess.run(["git", "init", "-q"], check=True) os.makedirs("a/b") with contextlib.chdir("a/b"): - self.assertEqual(loop.checkout_root(), root) + self.assertEqual(checkout.checkout_root(), root) subprocess.run(["git", "init", "-q", "other"], check=True) with contextlib.chdir("other"): - self.assertEqual(loop.checkouts(root), [root]) + self.assertEqual(checkout.checkouts(root), [root]) class ProjectName(unittest.TestCase): def test_names_a_checkout_relative_to_code_and_any_other_relative_to_root(self): - with unittest.mock.patch.dict(os.environ, {"HOME": "/h"}): - self.assertEqual(loop.project_name("/h/code/a/b"), "a/b") - self.assertEqual(loop.session_name("/h/code/a/b"), "A a/b loop-claude") - self.assertEqual(loop.project_name("/h/code"), "h/code") - self.assertEqual(loop.project_name("/srv/x"), "srv/x") - self.assertEqual(loop.session_name("/srv/x"), "A srv/x loop-claude") + code = pathlib.Path("/h/code") + self.assertEqual(checkout.project_name("/h/code/a/b", code), "a/b") + self.assertEqual(cycle.session_name("/h/code/a/b", code), "A a/b loop-claude") + self.assertEqual(checkout.project_name("/h/code", code), "h/code") + self.assertEqual(checkout.project_name("/srv/x", code), "srv/x") + self.assertEqual(cycle.session_name("/srv/x", code), "A srv/x loop-claude") class WorkerArgs(unittest.TestCase): def test_a_fresh_cycle_names_the_session_and_asks_to_continue_open_work(self): - args = loop.worker_args("the task", "A name", SESSION_ID, "m", resuming=False) + args = cycle.worker_args("the task", "A name", SESSION_ID, "m", {}, resuming=False) self.assertIn("--session-id", args) self.assertEqual(args[args.index("--name") + 1], "A name") self.assertTrue(args[1].startswith("the task\n\nContinue any open draft PR")) def test_a_resumed_cycle_reuses_the_session(self): - args = loop.worker_args("paint the fence", "A name", SESSION_ID, "m", resuming=True) + args = cycle.worker_args("paint the fence", "A name", SESSION_ID, "m", {}, resuming=True) self.assertEqual(args[args.index("--resume") + 1], SESSION_ID) self.assertNotIn("--name", args) self.assertNotIn("paint the fence", args[1]) def test_the_project_model_runs_unless_the_environment_names_one(self): - with unittest.mock.patch.dict(os.environ): - os.environ.pop("LOOP_CLAUDE_WORKER_MODEL", None) - args = loop.worker_args("t", "n", SESSION_ID, "claude-opus-5-5", resuming=False) + args = cycle.worker_args("t", "n", SESSION_ID, "claude-opus-5-5", {}, resuming=False) self.assertEqual(args[args.index("--model") + 1], "claude-opus-5-5") - with unittest.mock.patch.dict(os.environ, {"LOOP_CLAUDE_WORKER_MODEL": "claude-fable-5-1"}): - args = loop.worker_args("t", "n", SESSION_ID, "claude-opus-5-5", resuming=False) + args = cycle.worker_args("t", "n", SESSION_ID, "claude-opus-5-5", {"LOOP_CLAUDE_WORKER_MODEL": "claude-fable-5-1"}, resuming=False) self.assertEqual(args[args.index("--model") + 1], "claude-fable-5-1") class ProjectModel(unittest.TestCase): def test_asks_once_per_project_from_the_newest_catalog_and_saves_the_answer(self): - with tempfile.TemporaryDirectory() as home, unittest.mock.patch.dict(os.environ, {"HOME": home}), unittest.mock.patch.object(sys, "stderr", io.StringIO()), umask(0o022): - for variable in ("LOOP_CLAUDE_JUDGE_MODEL", "LOOP_CLAUDE_WORKER_MODEL"): - os.environ.pop(variable, None) + with tempfile.TemporaryDirectory() as home, unittest.mock.patch.object(sys, "stderr", io.StringIO()), umask(0o022): + paths = paths_from(pathlib.Path(home), {}) saved = pathlib.Path(home, ".claude", "loop-claude-models.json") catalog = pathlib.Path(home, ".claude", "cache", "model-catalog") catalog.mkdir(parents=True) for name, fetched, ids in (("old.json", 1, ["claude-opus-5"]), ("new.json", 2, ["claude-opus-5-5", "claude-sonnet-5"])): catalog.joinpath(name).write_text(json.dumps({"fetchedAt": fetched, "catalog": {"config": {"models": [{"id": id, "name": id.upper()} for id in ids]}}})) with unittest.mock.patch("sys.stdin.isatty", return_value=False): - stop = loop.project_model("/srv/a") + stop = cycle.project_model("/srv/a", paths, {}) self.assertEqual(stop.code, 2) self.assertIn(f'merge {{"srv/a": ""}} into {saved}', stop.reason) self.assertFalse(saved.exists()) - with unittest.mock.patch.dict(os.environ, {"LOOP_CLAUDE_JUDGE_MODEL": "j", "LOOP_CLAUDE_WORKER_MODEL": "w"}), unittest.mock.patch("sys.stdin.isatty", return_value=False): - self.assertEqual(loop.project_model("/srv/a"), "") - with unittest.mock.patch.dict(os.environ, {"LOOP_CLAUDE_JUDGE_MODEL": "j"}), unittest.mock.patch("sys.stdin.isatty", return_value=False): - self.assertEqual(loop.project_model("/srv/a").code, 2) + with unittest.mock.patch("sys.stdin.isatty", return_value=False): + self.assertEqual(cycle.project_model("/srv/a", paths, {"LOOP_CLAUDE_JUDGE_MODEL": "j", "LOOP_CLAUDE_WORKER_MODEL": "w"}), "") + self.assertEqual(cycle.project_model("/srv/a", paths, {"LOOP_CLAUDE_JUDGE_MODEL": "j"}).code, 2) with ( unittest.mock.patch("sys.stdin.isatty", return_value=True), unittest.mock.patch("sys.stdout.isatty", return_value=True), unittest.mock.patch("builtins.input", side_effect=["", "3", "2"]) as typed, ): - self.assertEqual(loop.project_model("/srv/a"), "claude-sonnet-5") + self.assertEqual(cycle.project_model("/srv/a", paths, {}), "claude-sonnet-5") self.assertEqual(typed.call_count, 3) self.assertIn("2. CLAUDE-SONNET-5 (claude-sonnet-5)", sys.stderr.getvalue()) self.assertIn("pick 1 to 2", sys.stderr.getvalue()) @@ -188,33 +184,33 @@ class ProjectModel(unittest.TestCase): saved.write_text(json.dumps({**json.loads(saved.read_text()), "srv/d": "haiku"})) return "opus[1m]" typed.side_effect = saved_elsewhere_while_asking - self.assertEqual(loop.project_model("/srv/b"), "opus[1m]") - self.assertEqual(loop.project_model("/srv/a"), "claude-sonnet-5") + self.assertEqual(cycle.project_model("/srv/b", paths, {}), "opus[1m]") + self.assertEqual(cycle.project_model("/srv/a", paths, {}), "claude-sonnet-5") self.assertEqual(typed.call_count, 4) typed.side_effect = EOFError - self.assertEqual(loop.project_model("/srv/c"), loop.Stop(2, "no model picked")) + self.assertEqual(cycle.project_model("/srv/c", paths, {}), Stop(2, "no model picked")) typed.side_effect = ["sonnet"] with unittest.mock.patch("os.replace", side_effect=OSError(errno.EACCES, "Permission denied")): - self.assertEqual(loop.project_model("/srv/c"), loop.Stop(1, f"could not save the model in {saved}: Permission denied")) + self.assertEqual(cycle.project_model("/srv/c", paths, {}), Stop(1, f"could not save the model in {saved}: Permission denied")) self.assertEqual(json.loads(saved.read_text()), {"srv/a": "claude-sonnet-5", "srv/b": "opus[1m]", "srv/d": "haiku"}) self.assertEqual(stat.S_IMODE(saved.stat().st_mode), 0o640) self.assertEqual(sorted(os.listdir(saved.parent)), ["cache", "loop-claude-models.json"]) for shape in ({"fetchedAt": 3, "catalog": {"config": {"models": []}}}, {"fetchedAt": 3, "catalog": None}, {"fetchedAt": 3, "catalog": {"config": []}}, {"fetchedAt": 3, "catalog": {"config": {"models": "x"}}}): catalog.joinpath("new.json").write_text(json.dumps(shape)) with self.subTest(shape=shape): - self.assertEqual(loop.catalog(), []) + self.assertEqual(cycle.catalog(catalog), []) with ( unittest.mock.patch("sys.stdin.isatty", return_value=True), unittest.mock.patch("sys.stdout.isatty", return_value=True), unittest.mock.patch("builtins.input", side_effect=["1"]) as typed, ): - self.assertEqual(loop.project_model("/srv/e"), "1") + self.assertEqual(cycle.project_model("/srv/e", paths, {}), "1") self.assertEqual(typed.call_args.args[0], "A name claude --model takes: ") self.assertIn("no model catalog cached", sys.stderr.getvalue()) for broken in ("{", "[]", '{"srv/a": 1}'): saved.write_text(broken) with self.subTest(broken=broken): - stop = loop.project_model("/srv/a") + stop = cycle.project_model("/srv/a", paths, {}) self.assertEqual(stop.code, 1) self.assertTrue(stop.reason.startswith(f"could not read {saved}: ")) self.assertEqual(saved.read_text(), broken) @@ -222,10 +218,10 @@ class ProjectModel(unittest.TestCase): class JudgePrompt(unittest.TestCase): def test_hands_the_judge_the_tail_of_a_long_transcript(self): - prompt = loop.judge_prompt("task", "## Goals\n1. g", "early " * 20000 + "LATE") + prompt = cycle.judge_prompt("task", "## Goals\n1. g", "early " * 20000 + "LATE") self.assertIn("LATE", prompt) self.assertLess(prompt.count("early"), 20000) - self.assertTrue(prompt.endswith(loop.JUDGE_RULES)) + self.assertTrue(prompt.endswith(cycle.JUDGE_RULES)) class Archive(unittest.TestCase): @@ -233,9 +229,9 @@ class Archive(unittest.TestCase): with tempfile.TemporaryDirectory() as root: transcript = os.path.join(root, "session.jsonl") pathlib.Path(transcript).write_text(json.dumps(assistant({"type": "text", "text": "said"})) + "\n") - loop.ARCHIVE = os.path.join(root, "deep", "archive") - loop.archive("/srv/a/b", transcript, "note") - [copy] = [os.path.join(folder, name) for folder, _, names in os.walk(loop.ARCHIVE) for name in names] + paths = paths_from(pathlib.Path(root), {"LOOP_CLAUDE_TRANSCRIPTS": os.path.join(root, "deep", "archive")}) + cycle.archive("/srv/a/b", transcript, "note", paths) + [copy] = [os.path.join(folder, name) for folder, _, names in os.walk(paths.archive) for name in names] self.assertEqual(stat.S_IMODE(os.stat(copy).st_mode), 0o600) folder = os.path.dirname(copy) while folder != root: @@ -246,26 +242,27 @@ class Archive(unittest.TestCase): class Said(unittest.TestCase): def test_renders_text_and_tool_calls_and_nothing_else(self): - self.assertEqual(loop.said({"type": "text", "text": "hi"}), "hi") - self.assertEqual(loop.said({"type": "text", "text": " \n"}), "") - self.assertEqual(loop.said({"type": "tool_use", "name": "Bash", "input": {"command": "x" * 500}}, 20), '[tool Bash] {"command": "xxxxxxx') - self.assertEqual(loop.said("not a part"), "") + self.assertEqual(cycle.said({"type": "text", "text": "hi"}), "hi") + self.assertEqual(cycle.said({"type": "text", "text": " \n"}), "") + self.assertEqual(cycle.said({"type": "tool_use", "name": "Bash", "input": {"command": "x" * 500}}, 20), '[tool Bash] {"command": "xxxxxxx') + self.assertEqual(cycle.said("not a part"), "") class DeleteTranscriptFiles(unittest.TestCase): def test_deletes_the_transcript_and_its_siblings_so_the_session_is_gone(self): - with tempfile.TemporaryDirectory() as home, unittest.mock.patch.dict(os.environ, {"HOME": home}): - root = os.path.join(home, ".claude", "projects", "p") + with tempfile.TemporaryDirectory() as home: + projects = paths_from(pathlib.Path(home), {}).projects + root = os.path.join(projects, "p") os.makedirs(root) transcript = os.path.join(root, f"{SESSION_ID}.jsonl") pathlib.Path(transcript).write_text("{}\n") os.makedirs(os.path.join(root, SESSION_ID, "subagents")) os.makedirs(os.path.join(root, f"{SESSION_ID}.superseded-1", "tool-results")) pathlib.Path(root, f"{SESSION_ID}.orphaned-1-ab.jsonl").write_text("{}\n") - self.assertTrue(loop.session_open(SESSION_ID)) - loop.delete_transcript_files(transcript) + self.assertTrue(cycle.session_open(projects, SESSION_ID)) + cycle.delete_transcript_files(transcript) self.assertEqual(os.listdir(root), []) - self.assertFalse(loop.session_open(SESSION_ID)) + self.assertFalse(cycle.session_open(projects, SESSION_ID)) class Interrupt(unittest.TestCase): @@ -274,14 +271,14 @@ class Interrupt(unittest.TestCase): transcript = os.path.join(root, "session.jsonl") pathlib.Path(transcript).write_text("{}\n") with unittest.mock.patch("sys.stdin.isatty", return_value=False): - self.assertEqual(loop.interrupt(root, SESSION_ID, "m", transcript, "q?"), "stdin or stdout is not a terminal") + self.assertEqual(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {}), "stdin or stdout is not a terminal") with ( unittest.mock.patch("sys.stdin.isatty", return_value=True), unittest.mock.patch("sys.stdout.isatty", return_value=True), - unittest.mock.patch.multiple(loop, checkouts=unittest.mock.DEFAULT, trust=unittest.mock.DEFAULT) as mocks, + unittest.mock.patch.multiple(cycle, checkouts=unittest.mock.DEFAULT, trust=unittest.mock.DEFAULT) as mocks, unittest.mock.patch("subprocess.run") as run, ): - self.assertEqual(loop.interrupt(root, SESSION_ID, "m", transcript, "q?"), "the interrupt ended without the human typing anything") + self.assertEqual(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {}), "the interrupt ended without the human typing anything") mocks["checkouts"].assert_called_with(root) self.assertEqual(run.call_args.kwargs["cwd"], root) self.assertEqual(run.call_args.args[0][run.call_args.args[0].index("--model") + 1], "m") @@ -290,35 +287,35 @@ class Interrupt(unittest.TestCase): handle.write(json.dumps(human("typed")) + "\n") run.side_effect = type_a_turn - self.assertEqual(loop.interrupt(root, SESSION_ID, "m", transcript, "q?"), "") + self.assertEqual(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {}), "") class Trust(unittest.TestCase): def test_says_why_the_config_cannot_be_read_and_records_only_what_is_new(self): - with tempfile.TemporaryDirectory() as home, unittest.mock.patch.dict(os.environ, {"HOME": home}), umask(0o022): + with tempfile.TemporaryDirectory() as home, umask(0o022): config = pathlib.Path(home, ".claude.json") with contextlib.redirect_stderr(io.StringIO()) as err: - loop.trust(["/a"]) + cycle.trust(config, ["/a"]) self.assertEqual(err.getvalue(), f"could not read {config}: No such file or directory\n") config.write_text("{") with contextlib.redirect_stderr(io.StringIO()) as err: - loop.trust(["/a"]) + cycle.trust(config, ["/a"]) self.assertIn(f"could not read {config}: ", err.getvalue()) for shape in ([], {"projects": []}, {"projects": {"/a": 1}}): config.write_text(json.dumps(shape)) with contextlib.redirect_stderr(io.StringIO()) as err: - loop.trust(["/a"]) + cycle.trust(config, ["/a"]) self.assertEqual(err.getvalue(), f"could not read {config}: not an object whose \"projects\" maps paths to objects\n") self.assertEqual(json.loads(config.read_text()), shape) data = {"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True, "kept": 2}}} config.write_text(json.dumps(data)) config.chmod(0o600) with contextlib.redirect_stderr(io.StringIO()) as err: - loop.trust(["/a"]) + cycle.trust(config, ["/a"]) self.assertEqual(err.getvalue(), "") self.assertEqual(json.loads(config.read_text()), data) with contextlib.redirect_stderr(io.StringIO()) as err: - loop.trust(["/a", "/b"]) + cycle.trust(config, ["/a", "/b"]) self.assertEqual(err.getvalue(), "trusted for the interrupt: /b\n") data["projects"]["/b"] = {"hasTrustDialogAccepted": True} self.assertEqual(json.loads(config.read_text()), data) @@ -326,7 +323,7 @@ class Trust(unittest.TestCase): contextlib.redirect_stderr(io.StringIO()) as err, unittest.mock.patch("os.replace", side_effect=OSError(errno.EACCES, "Permission denied")), ): - loop.trust(["/c"]) + cycle.trust(config, ["/c"]) self.assertEqual(err.getvalue(), f"could not write {config}: Permission denied\n") self.assertEqual(json.loads(config.read_text()), data) self.assertEqual(stat.S_IMODE(config.stat().st_mode), 0o600) @@ -335,25 +332,25 @@ class Trust(unittest.TestCase): class Parse(unittest.TestCase): def test_yields_only_json_objects(self): - self.assertEqual(loop.parse('{"type": "user"}'), {"type": "user"}) - self.assertIsNone(loop.parse("not json")) - self.assertIsNone(loop.parse("[1, 2]")) + self.assertEqual(cycle.parse('{"type": "user"}'), {"type": "user"}) + self.assertIsNone(cycle.parse("not json")) + self.assertIsNone(cycle.parse("[1, 2]")) class Grounded(unittest.TestCase): def test_an_interrupt_must_quote_the_transcript(self): - self.assertTrue(loop.grounded({"interrupt": False, "evidence": ""}, "anything")) - self.assertTrue(loop.grounded({"interrupt": True, "evidence": "Needs you: x"}, "so.\n\nNeeds you: x\n")) - self.assertFalse(loop.grounded({"interrupt": True, "evidence": "invented"}, "the transcript")) - self.assertFalse(loop.grounded({"interrupt": True, "evidence": ""}, "the transcript")) - self.assertFalse(loop.grounded({"interrupt": True, "evidence": " "}, "the transcript")) + self.assertTrue(cycle.grounded({"interrupt": False, "evidence": ""}, "anything")) + self.assertTrue(cycle.grounded({"interrupt": True, "evidence": "Needs you: x"}, "so.\n\nNeeds you: x\n")) + self.assertFalse(cycle.grounded({"interrupt": True, "evidence": "invented"}, "the transcript")) + self.assertFalse(cycle.grounded({"interrupt": True, "evidence": ""}, "the transcript")) + self.assertFalse(cycle.grounded({"interrupt": True, "evidence": " "}, "the transcript")) class Verdict(unittest.TestCase): def test_needs_every_field_the_schema_requires(self): - self.assertTrue(loop.complete({"interrupt": False, "evidence": "", "finished": True, "question": ""})) - self.assertFalse(loop.complete({"interrupt": False})) - self.assertFalse(loop.complete(None)) + self.assertTrue(cycle.complete({"interrupt": False, "evidence": "", "finished": True, "question": ""})) + self.assertFalse(cycle.complete({"interrupt": False})) + self.assertFalse(cycle.complete(None)) STUB_CLAUDE = """#!/usr/bin/env python3 @@ -392,7 +389,7 @@ class RunWorker(unittest.TestCase): for failure, script in scripts.items(): pathlib.Path(stub).write_text(f"#!/usr/bin/env python3\nimport json\nimport os\nimport sys\n{script}\n") os.chmod(stub, 0o700) - self.assertEqual(loop.run_worker(bin, []), failure) + self.assertEqual(cycle.run_worker(bin, []), failure) class RunCycle(unittest.TestCase): @@ -402,24 +399,25 @@ class RunCycle(unittest.TestCase): pathlib.Path(stub).write_text(STUB_CLAUDE) os.chmod(stub, 0o700) calls, verdicts = os.path.join(home, "calls"), os.path.join(home, "verdicts") + session_id = cycle.uuid.uuid5(cycle.SESSION_NAMESPACE, cycle.session_name(home, paths_from(pathlib.Path(home), {}).code)) pathlib.Path(verdicts).write_text("fail continue finished unquoted continue") - loop.ARCHIVE = os.path.join(home, "archive") + paths = paths_from(pathlib.Path(home), {"LOOP_CLAUDE_TRANSCRIPTS": os.path.join(home, "archive")}) environment = {"HOME": home, "PATH": f"{home}:{os.environ['PATH']}", "STUB_CALLS": calls, "STUB_VERDICTS": verdicts} with unittest.mock.patch.dict(os.environ, environment), unittest.mock.patch("time.sleep") as sleep, unittest.mock.patch("sys.stdin.isatty", return_value=False): for _ in range(3): - self.assertEqual(loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5"), "") + self.assertEqual(cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}), Continue()) pathlib.Path(verdicts).write_text("interrupt") with unittest.mock.patch("sys.stderr") as stderr: - self.assertEqual(loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5"), loop.Stop(2, "stdin or stdout is not a terminal")) - self.assertIn(f"transcript: {loop.ARCHIVE}", "".join(str(call.args[0]) for call in stderr.write.call_args_list)) + self.assertEqual(cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}), Stop(2, "stdin or stdout is not a terminal")) + self.assertIn(f"transcript: {paths.archive}", "".join(str(call.args[0]) for call in stderr.write.call_args_list)) pathlib.Path(verdicts).write_text("interrupt fail fail fail") - with unittest.mock.patch("sys.stderr"), unittest.mock.patch.object(loop, "interrupt", return_value=""): - self.assertEqual(loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5").code, 1) - with unittest.mock.patch.object(loop, "session_file", return_value=""): - self.assertEqual(loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5"), loop.Stop(1, f"claude left no transcript for session {SESSION_ID}")) + with unittest.mock.patch("sys.stderr"), unittest.mock.patch.object(cycle, "interrupt", return_value=""): + self.assertEqual(cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}).code, 1) + with unittest.mock.patch.object(cycle, "session_file", return_value=""): + self.assertEqual(cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}), Stop(1, f"claude left no transcript for session {session_id}")) for plan in ("fail fail fail", "unquoted unquoted unquoted"): pathlib.Path(verdicts).write_text(plan) - stop = loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5") + stop = cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}) self.assertEqual(stop.code, 1) self.assertTrue(stop.reason.startswith("the judge ")) if plan.startswith("unquoted"): @@ -428,74 +426,55 @@ class RunCycle(unittest.TestCase): self.assertEqual({json.loads(line)[0] for line in pathlib.Path(calls).read_text().splitlines()}, {home}) starts = [args[args.index("-p") + 1:][:3] for args in map(json.loads, pathlib.Path(calls).read_text().splitlines()) if "--json-schema" not in args] self.assertEqual([start[1] for start in starts], ["--name", "--resume", "--name", "--resume", "--resume", "--name", "--resume", "--resume"]) - self.assertEqual(starts[1][2], SESSION_ID) + self.assertEqual(starts[1][2], str(session_id)) self.assertEqual(sleep.call_count, 8) self.assertEqual({args[args.index("--model") + 1] for args in map(json.loads, pathlib.Path(calls).read_text().splitlines())}, {"claude-opus-5-5"}) -class Reload(unittest.TestCase): - def test_runs_the_edited_file_before_trusting_it_and_hands_it_the_state_as_one_json_argument(self): - with tempfile.TemporaryDirectory() as root: - script = os.path.join(root, "loop-claude") - pathlib.Path(script).write_text(loop.RELOAD_BASELINE.replace("import glob\n", "import glob\nimport no_such_module\n")) - with unittest.mock.patch.object(loop, "__file__", script), unittest.mock.patch("os.execv") as execv: - loop.reload_if_edited(loop.LoopState(1, 0, "/r", "do it")) - execv.assert_not_called() - pathlib.Path(script).write_text(loop.RELOAD_BASELINE.replace("RELOAD_FLAG = ", "RELOAD_FLAG = \"x\" or ")) - environment = dict(os.environ) - with unittest.mock.patch.object(loop, "__file__", script), unittest.mock.patch("os.execv") as execv: - loop.reload_if_edited(loop.LoopState(1, 2, "/r", "do it")) - execv.assert_called_once_with(sys.executable, [sys.executable, script, loop.RELOAD_FLAG, json.dumps({"cycle_number": 1, "failures": 2, "root": "/r", "task": "do it"})]) - self.assertEqual(dict(os.environ), environment) - - class Main(unittest.TestCase): - def test_exits_only_here_with_the_stop_the_loop_returned(self): - for argv, code, stream in ((["--help"], 0, "stdout"), ([], 1, "stderr"), ([loop.RELOAD_FLAG, "3"], 1, "stderr")): - with self.subTest(argv=argv), unittest.mock.patch.object(sys, "argv", ["loop-claude", *argv]), contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as err, self.assertRaises(SystemExit) as stopped: - loop.main() - self.assertEqual(stopped.exception.code, code) - self.assertEqual({"stdout": out, "stderr": err}[stream].getvalue(), loop.run_loop(argv).reason + "\n") - with unittest.mock.patch.object(loop, "run_loop", side_effect=KeyboardInterrupt), self.assertRaises(SystemExit) as stopped: - loop.main() - self.assertEqual(stopped.exception.code, 130) + def test_returns_the_exit_code_of_the_stop_the_loop_returned(self): + for argv, code, stream in ((["--help"], 0, "stdout"), ([], 1, "stderr"), ([main.RELOAD_FLAG, "3"], 1, "stderr")): + with self.subTest(argv=argv), contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as err: + self.assertEqual(main.main(argv, {}, PATHS, LAUNCHER), code) + self.assertEqual({"stdout": out, "stderr": err}[stream].getvalue(), main.loop_state(argv).reason + "\n") + with unittest.mock.patch.object(main, "run_loop", side_effect=KeyboardInterrupt): + self.assertEqual(main.main(["t"], {}, PATHS, LAUNCHER), 130) class RunLoop(unittest.TestCase): def test_stops_naming_the_reload_when_it_hands_over_anything_but_the_state_with_a_task(self): for handed in (["3", "2", "/r", "do it"], ["3"], ["[1]"], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": ""})], [json.dumps({"cycle_number": "3", "failures": 0, "root": "/r", "task": "do it"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "", "task": "do it"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it", "turns": 1})]): with self.subTest(handed=handed): - self.assertEqual(loop.run_loop([loop.RELOAD_FLAG, *handed]), loop.Stop(1, f"the reload cannot read the loop's state from {handed}; rerun loop-claude ")) + self.assertEqual(main.loop_state([main.RELOAD_FLAG, *handed]), Stop(1, f"the reload cannot read the loop's state from {handed}; rerun loop-claude ")) def test_resumes_the_root_and_counters_a_reload_handed_over(self): - patches = [unittest.mock.patch.object(loop, name) for name in ("checkout_root", "read_premises", "reload_if_edited", "run_cycle", "project_model")] - stopped = loop.Stop(1, "stopped") + patches = [unittest.mock.patch.object(main, name) for name in ("checkout_root", "read_premises", "reload_if_edited", "run_cycle", "project_model")] + stopped = Stop(1, "stopped") with contextlib.ExitStack() as stack: mocks = [stack.enter_context(patch) for patch in patches] stack.enter_context(unittest.mock.patch.object(sys, "stdout", io.StringIO())) mocks[3].return_value = stopped - self.assertEqual(loop.run_loop([loop.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 2, "root": "/r", "task": "do it"})]), stopped) + self.assertEqual(main.run_loop([main.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 2, "root": "/r", "task": "do it"})], {}, PATHS, LAUNCHER), stopped) mocks[0].assert_not_called() mocks[1].assert_called_once_with("/r") - mocks[2].assert_called_once_with(loop.LoopState(3, 2, "/r", "do it")) + self.assertEqual(mocks[2].call_args.args[2], main.LoopState(3, 2, "/r", "do it")) self.assertEqual(mocks[3].call_args.args[0], "/r") - mocks[4].assert_called_once_with("/r") - self.assertEqual(mocks[3].call_args.args[-1], mocks[4].return_value) + mocks[4].assert_called_once_with("/r", PATHS, {}) + self.assertEqual(mocks[3].call_args.args[3], mocks[4].return_value) mocks[0].return_value = "/s" - self.assertEqual(loop.run_loop(["do", "it"]), stopped) + self.assertEqual(main.run_loop(["do", "it"], {}, PATHS, LAUNCHER), stopped) mocks[0].assert_called_once_with() mocks[1].assert_called_with("/s") self.assertIn("=== cycle 4 ===", sys.stdout.getvalue()) for leaf in (0, 1, 4): with self.subTest(leaf=leaf): - mocks[leaf].return_value = loop.Stop(2, f"leaf {leaf}") - self.assertEqual(loop.run_loop(["do it"]), mocks[leaf].return_value) + mocks[leaf].return_value = Stop(2, f"leaf {leaf}") + self.assertEqual(main.run_loop(["do it"], {}, PATHS, LAUNCHER), mocks[leaf].return_value) mocks[leaf].return_value = "/s" - mocks[3].return_value = None - mocks[3].side_effect = ["claude exited 3"] * 3 + mocks[3].side_effect = [Retry("claude exited 3")] * 3 stack.enter_context(unittest.mock.patch.object(sys, "stderr", io.StringIO())) sleep = stack.enter_context(unittest.mock.patch("time.sleep")) - self.assertEqual(loop.run_loop([loop.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it"})]), loop.Stop(1, "the worker failed three times running: claude exited 3")) + self.assertEqual(main.run_loop([main.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it"})], {}, PATHS, LAUNCHER), Stop(1, "the worker failed three times running: claude exited 3")) self.assertIn("retrying the worker in a minute: claude exited 3", sys.stderr.getvalue()) self.assertEqual(sleep.call_count, 2) diff --git a/todo.md b/todo.md index 2b4ab42d..6244c9e8 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,6 @@ Ships when a four-seat scoring run puts every dimension and the overall at 7.0 or above (`docs/decisions.md`). The rebuild lifts every dimension: each item below is one chunk on a worktree based on `origin/rebuild`, its PR into `rebuild`, until the last item merges `rebuild` into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -- **Lay out `bin/loop-claude` as a launcher over a `bin/loop_claude/` package, with the loop, checkout and premises moved in.** The launcher resolves its own symlink, injects `Paths` and the environment, and is the only thing that exits; `main` owns the loop state, carries it across a reload on argv, and maps `Stop | Retry | Continue`. The black-box tests pass unchanged. - **Move the transcript, the session and the worker into their own modules.** `UserEntryKind` names each entry Claude Code writes; a malformed line is skipped; an unreadable transcript is its own error, never "typed nothing"; `session` states the lifecycle once, where the id is made. - **Move the judge, the interrupt, trust and model resolution into their own modules.** The judge is retried alone and checks evidence on every verdict against the rendered transcript; `models` owns the whole resolution, env overrides included, with no sentinel; `trust` names a `projects` entry that is not an object; `input()` at end of file is exit 2. - **Archive the raw transcript, deduplicated by content hash, with the verdict beside it, and stop on a failed archive.** Tests first; the changelog line says what the archive now holds. -- 2.52.0 From 5de7e0fc9c97583206d6603df97344c2fc18e172 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 11:07:40 +0200 Subject: [PATCH 005/233] Pin that an edited package file reloads the loop --- bin/loop_claude/main.py | 2 +- bin/test_loop_claude.py | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/bin/loop_claude/main.py b/bin/loop_claude/main.py index 2488ecbf..6cb7cd92 100644 --- a/bin/loop_claude/main.py +++ b/bin/loop_claude/main.py @@ -27,7 +27,7 @@ and read each cycle; a project without an entry, as on its first run, is asked f LOOP_CLAUDE_JUDGE_MODEL overrides it for the judge, LOOP_CLAUDE_WORKER_MODEL for the worker and the interrupt; with both set, nothing is asked. -A change to loop-claude's files takes effect at the next cycle boundary, once they answer --help. +A change to loop-claude's files takes effect at the next cycle boundary, once the launcher answers --help. Claude Code internals this rests on, observed on 2.1.282, the model catalog on 2.1.283: - The transcript is ~/.claude/projects/*/.jsonl, one JSON object per line. A / diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 607f7499..456c31ad 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -4,6 +4,7 @@ import io import json import os import pathlib +import shutil import stat import subprocess import sys @@ -431,6 +432,24 @@ class RunCycle(unittest.TestCase): self.assertEqual({args[args.index("--model") + 1] for args in map(json.loads, pathlib.Path(calls).read_text().splitlines())}, {"claude-opus-5-5"}) +class Reload(unittest.TestCase): + def test_an_edited_package_file_reloads_once_the_launcher_answers_help(self): + with tempfile.TemporaryDirectory() as root: + copy = pathlib.Path(root, "bin") + shutil.copytree(LAUNCHER.parent, copy, ignore=shutil.ignore_patterns("__pycache__", "test_*")) + launcher, edited = copy / "loop-claude", copy / "loop_claude" / "cycle.py" + state = main.LoopState(1, 2, "/r", "do it") + with unittest.mock.patch.object(main, "__file__", str(copy / "loop_claude" / "main.py")), unittest.mock.patch("os.execv") as execv, contextlib.redirect_stderr(io.StringIO()) as err: + baseline = main.fingerprint(launcher) + edited.write_text(edited.read_text() + "\ndef\n") + main.reload_if_edited(launcher, baseline, state) + execv.assert_not_called() + self.assertIn("keeping the running script", err.getvalue()) + edited.write_text(edited.read_text().replace("\ndef\n", "\n# edited\n")) + main.reload_if_edited(launcher, baseline, state) + execv.assert_called_once_with(sys.executable, [sys.executable, str(launcher), main.RELOAD_FLAG, json.dumps({"cycle_number": 1, "failures": 2, "root": "/r", "task": "do it"})]) + + class Main(unittest.TestCase): def test_returns_the_exit_code_of_the_stop_the_loop_returned(self): for argv, code, stream in ((["--help"], 0, "stdout"), ([], 1, "stderr"), ([main.RELOAD_FLAG, "3"], 1, "stderr")): -- 2.52.0 From 4171a1ecbebddf07fea076fef85e46895aacfdab Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 11:11:23 +0200 Subject: [PATCH 006/233] Give the reload and the strike their own modules --- bin/loop-claude | 2 +- bin/loop_claude/__init__.py | 0 bin/loop_claude/checkout.py | 4 +-- bin/loop_claude/cycle.py | 8 +----- bin/loop_claude/main.py | 54 +++++++++---------------------------- bin/loop_claude/reload.py | 43 +++++++++++++++++++++++++++++ bin/loop_claude/strike.py | 11 ++++++++ bin/test_loop_claude.py | 33 ++++++++++++----------- todo.md | 2 +- 9 files changed, 88 insertions(+), 69 deletions(-) create mode 100644 bin/loop_claude/__init__.py create mode 100644 bin/loop_claude/reload.py create mode 100644 bin/loop_claude/strike.py diff --git a/bin/loop-claude b/bin/loop-claude index f783e143..faeda406 100755 --- a/bin/loop-claude +++ b/bin/loop-claude @@ -8,4 +8,4 @@ sys.path.insert(0, str(LAUNCHER.parent)) from loop_claude import main, paths -sys.exit(main.main(sys.argv[1:], os.environ, paths.paths_from(pathlib.Path.home(), os.environ), LAUNCHER)) +sys.exit(main.main(sys.argv[1:], os.environ, paths.paths_from(pathlib.Path.home(), os.environ), LAUNCHER, pathlib.Path.cwd())) diff --git a/bin/loop_claude/__init__.py b/bin/loop_claude/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/bin/loop_claude/checkout.py b/bin/loop_claude/checkout.py index 7ad42d79..8d56d06d 100644 --- a/bin/loop_claude/checkout.py +++ b/bin/loop_claude/checkout.py @@ -3,8 +3,8 @@ import subprocess from loop_claude.outcome import Stop -def checkout_root(): - found = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True) +def checkout_root(cwd): + 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() diff --git a/bin/loop_claude/cycle.py b/bin/loop_claude/cycle.py index 6633101f..e0284026 100644 --- a/bin/loop_claude/cycle.py +++ b/bin/loop_claude/cycle.py @@ -10,6 +10,7 @@ import uuid from loop_claude.checkout import checkouts, project_name from loop_claude.outcome import Continue, Retry, Stop +from loop_claude.strike import strike SESSION_NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec") @@ -45,13 +46,6 @@ JUDGE_SCHEMA = { } -def strike(who, failures, failure): - if failures == 3: - return Stop(1, f"the {who} failed three times running: {failure}") - print(f"retrying the {who} in a minute: {failure}", file=sys.stderr) - time.sleep(60) - - def run_cycle(root, task, premises, chosen, paths, env): name = session_name(root, paths.code) session_id = uuid.uuid5(SESSION_NAMESPACE, name) diff --git a/bin/loop_claude/main.py b/bin/loop_claude/main.py index 6cb7cd92..8c3f5c86 100644 --- a/bin/loop_claude/main.py +++ b/bin/loop_claude/main.py @@ -43,19 +43,14 @@ Claude Code internals this rests on, observed on 2.1.282, the model catalog on 2 file has the highest fetchedAt. """ import dataclasses -import hashlib -import json -import os -import pathlib -import subprocess import sys from loop_claude.checkout import checkout_root -from loop_claude.cycle import parse, project_model, run_cycle, strike +from loop_claude.cycle import project_model, run_cycle from loop_claude.outcome import Continue, Retry, Stop from loop_claude.premises import read_premises - -RELOAD_FLAG = "--reloaded" +from loop_claude.reload import RELOAD_FLAG, decode_state, fingerprint, reload_if_edited +from loop_claude.strike import strike @dataclasses.dataclass(frozen=True) @@ -66,9 +61,9 @@ class LoopState: task: str -def main(argv, env, paths, launcher): +def main(argv, env, paths, launcher, cwd): try: - stop = run_loop(argv, env, paths, launcher) + stop = run_loop(argv, env, paths, launcher, cwd) except KeyboardInterrupt: stop = Stop(130, "") if stop.reason: @@ -76,8 +71,8 @@ def main(argv, env, paths, launcher): return stop.code -def run_loop(argv, env, paths, launcher): - state = loop_state(argv) +def run_loop(argv, env, paths, launcher, cwd): + state = loop_state(argv, cwd) if isinstance(state, Stop): return state baseline = fingerprint(launcher) @@ -102,40 +97,15 @@ def run_loop(argv, env, paths, launcher): state = dataclasses.replace(state, failures=0) -# The reload - -def loop_state(argv): +def loop_state(argv, cwd): if argv[:1] != [RELOAD_FLAG]: task = " ".join(argv) if task in ("", "-h", "--help"): return Stop(0 if task else 1, __doc__.strip()) - root = checkout_root() + root = checkout_root(cwd) return root if isinstance(root, Stop) else LoopState(0, 0, root, task) - handed = parse(argv[1]) if len(argv) == 2 else None - shape = {field.name: field.type for field in dataclasses.fields(LoopState)} - if not handed or handed.keys() != shape.keys() or any(type(handed[name]) is not kind for name, kind in shape.items()) or not (handed["root"] and handed["task"]): + state = decode_state(argv[1], LoopState) if len(argv) == 2 else None + if not (state and state.root and state.task): return Stop(1, f"the reload cannot read the loop's state from {argv[1:]}; rerun loop-claude ") - return LoopState(**handed) - - -def fingerprint(launcher): - # An unreadable file hashes its error, and the --help trial judges it. - digest = hashlib.sha256() - for path in [launcher, *sorted(pathlib.Path(__file__).parent.glob("*.py"))]: - try: - content = path.read_bytes() - except OSError as failure: - content = str(failure).encode() - digest.update(f"{path.name}\0{len(content)}\0".encode() + content) - return digest.hexdigest() - - -def reload_if_edited(launcher, baseline, state): - if fingerprint(launcher) == baseline: - return - trial = subprocess.run([sys.executable, launcher, "--help"], capture_output=True, text=True) - if trial.returncode != 0: - print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr) - return - os.execv(sys.executable, [sys.executable, str(launcher), RELOAD_FLAG, json.dumps(dataclasses.asdict(state))]) + return state diff --git a/bin/loop_claude/reload.py b/bin/loop_claude/reload.py new file mode 100644 index 00000000..788445b7 --- /dev/null +++ b/bin/loop_claude/reload.py @@ -0,0 +1,43 @@ +import dataclasses +import hashlib +import json +import os +import subprocess +import sys + +RELOAD_FLAG = "--reloaded" + + +def decode_state(handed, kind): + try: + fields = json.loads(handed) + except ValueError: + return None + shape = {field.name: field.type for field in dataclasses.fields(kind)} + if not isinstance(fields, dict) or fields.keys() != shape.keys(): + return None + if any(type(fields[name]) is not type_ for name, type_ in shape.items()): + return None + return kind(**fields) + + +def fingerprint(launcher): + # An unreadable file hashes its error, and the --help trial judges it. + digest = hashlib.sha256() + for path in [launcher, *sorted((launcher.parent / "loop_claude").glob("*.py"))]: + try: + content = path.read_bytes() + except OSError as failure: + content = str(failure).encode() + digest.update(f"{path.name}\0{len(content)}\0".encode() + content) + return digest.hexdigest() + + +def reload_if_edited(launcher, baseline, state): + if fingerprint(launcher) == baseline: + return + trial = subprocess.run([sys.executable, launcher, "--help"], capture_output=True, text=True) + if trial.returncode != 0: + print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr) + return + os.execv(sys.executable, [sys.executable, str(launcher), RELOAD_FLAG, json.dumps(dataclasses.asdict(state))]) diff --git a/bin/loop_claude/strike.py b/bin/loop_claude/strike.py new file mode 100644 index 00000000..72105153 --- /dev/null +++ b/bin/loop_claude/strike.py @@ -0,0 +1,11 @@ +import sys +import time + +from loop_claude.outcome import Stop + + +def strike(who, failures, failure): + if failures == 3: + return Stop(1, f"the {who} failed three times running: {failure}") + print(f"retrying the {who} in a minute: {failure}", file=sys.stderr) + time.sleep(60) diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 456c31ad..3d532a24 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -15,10 +15,11 @@ import uuid sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -from loop_claude import checkout, cycle, main, premises +from loop_claude import checkout, cycle, main, premises, reload from loop_claude.outcome import Continue, Retry, Stop from loop_claude.paths import paths_from +CWD = pathlib.Path("/c") LAUNCHER = pathlib.Path(__file__).resolve().with_name("loop-claude") PATHS = paths_from(pathlib.Path("/h"), {}) SESSION_ID = str(getattr(uuid, "uuid7", uuid.uuid4)()) @@ -111,11 +112,11 @@ class CheckoutRoot(unittest.TestCase): def test_is_the_checkout_from_any_directory_inside_it_and_exits_outside_one(self): with tempfile.TemporaryDirectory() as tmp, contextlib.chdir(tmp): root = os.getcwd() - self.assertEqual(checkout.checkout_root().code, 1) + self.assertEqual(checkout.checkout_root(os.getcwd()).code, 1) subprocess.run(["git", "init", "-q"], check=True) os.makedirs("a/b") with contextlib.chdir("a/b"): - self.assertEqual(checkout.checkout_root(), root) + self.assertEqual(checkout.checkout_root(os.getcwd()), root) subprocess.run(["git", "init", "-q", "other"], check=True) with contextlib.chdir("other"): self.assertEqual(checkout.checkouts(root), [root]) @@ -439,14 +440,14 @@ class Reload(unittest.TestCase): shutil.copytree(LAUNCHER.parent, copy, ignore=shutil.ignore_patterns("__pycache__", "test_*")) launcher, edited = copy / "loop-claude", copy / "loop_claude" / "cycle.py" state = main.LoopState(1, 2, "/r", "do it") - with unittest.mock.patch.object(main, "__file__", str(copy / "loop_claude" / "main.py")), unittest.mock.patch("os.execv") as execv, contextlib.redirect_stderr(io.StringIO()) as err: - baseline = main.fingerprint(launcher) + with unittest.mock.patch("os.execv") as execv, contextlib.redirect_stderr(io.StringIO()) as err: + baseline = reload.fingerprint(launcher) edited.write_text(edited.read_text() + "\ndef\n") - main.reload_if_edited(launcher, baseline, state) + reload.reload_if_edited(launcher, baseline, state) execv.assert_not_called() self.assertIn("keeping the running script", err.getvalue()) edited.write_text(edited.read_text().replace("\ndef\n", "\n# edited\n")) - main.reload_if_edited(launcher, baseline, state) + reload.reload_if_edited(launcher, baseline, state) execv.assert_called_once_with(sys.executable, [sys.executable, str(launcher), main.RELOAD_FLAG, json.dumps({"cycle_number": 1, "failures": 2, "root": "/r", "task": "do it"})]) @@ -454,17 +455,17 @@ class Main(unittest.TestCase): def test_returns_the_exit_code_of_the_stop_the_loop_returned(self): for argv, code, stream in ((["--help"], 0, "stdout"), ([], 1, "stderr"), ([main.RELOAD_FLAG, "3"], 1, "stderr")): with self.subTest(argv=argv), contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as err: - self.assertEqual(main.main(argv, {}, PATHS, LAUNCHER), code) - self.assertEqual({"stdout": out, "stderr": err}[stream].getvalue(), main.loop_state(argv).reason + "\n") + self.assertEqual(main.main(argv, {}, PATHS, LAUNCHER, CWD), code) + self.assertEqual({"stdout": out, "stderr": err}[stream].getvalue(), main.loop_state(argv, CWD).reason + "\n") with unittest.mock.patch.object(main, "run_loop", side_effect=KeyboardInterrupt): - self.assertEqual(main.main(["t"], {}, PATHS, LAUNCHER), 130) + self.assertEqual(main.main(["t"], {}, PATHS, LAUNCHER, CWD), 130) class RunLoop(unittest.TestCase): def test_stops_naming_the_reload_when_it_hands_over_anything_but_the_state_with_a_task(self): for handed in (["3", "2", "/r", "do it"], ["3"], ["[1]"], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": ""})], [json.dumps({"cycle_number": "3", "failures": 0, "root": "/r", "task": "do it"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "", "task": "do it"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it", "turns": 1})]): with self.subTest(handed=handed): - self.assertEqual(main.loop_state([main.RELOAD_FLAG, *handed]), Stop(1, f"the reload cannot read the loop's state from {handed}; rerun loop-claude ")) + self.assertEqual(main.loop_state([main.RELOAD_FLAG, *handed], CWD), Stop(1, f"the reload cannot read the loop's state from {handed}; rerun loop-claude ")) def test_resumes_the_root_and_counters_a_reload_handed_over(self): patches = [unittest.mock.patch.object(main, name) for name in ("checkout_root", "read_premises", "reload_if_edited", "run_cycle", "project_model")] @@ -473,7 +474,7 @@ class RunLoop(unittest.TestCase): mocks = [stack.enter_context(patch) for patch in patches] stack.enter_context(unittest.mock.patch.object(sys, "stdout", io.StringIO())) mocks[3].return_value = stopped - self.assertEqual(main.run_loop([main.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 2, "root": "/r", "task": "do it"})], {}, PATHS, LAUNCHER), stopped) + self.assertEqual(main.run_loop([main.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 2, "root": "/r", "task": "do it"})], {}, PATHS, LAUNCHER, CWD), stopped) mocks[0].assert_not_called() mocks[1].assert_called_once_with("/r") self.assertEqual(mocks[2].call_args.args[2], main.LoopState(3, 2, "/r", "do it")) @@ -481,19 +482,19 @@ class RunLoop(unittest.TestCase): mocks[4].assert_called_once_with("/r", PATHS, {}) self.assertEqual(mocks[3].call_args.args[3], mocks[4].return_value) mocks[0].return_value = "/s" - self.assertEqual(main.run_loop(["do", "it"], {}, PATHS, LAUNCHER), stopped) - mocks[0].assert_called_once_with() + self.assertEqual(main.run_loop(["do", "it"], {}, PATHS, LAUNCHER, CWD), stopped) + mocks[0].assert_called_once_with(CWD) mocks[1].assert_called_with("/s") self.assertIn("=== cycle 4 ===", sys.stdout.getvalue()) for leaf in (0, 1, 4): with self.subTest(leaf=leaf): mocks[leaf].return_value = Stop(2, f"leaf {leaf}") - self.assertEqual(main.run_loop(["do it"], {}, PATHS, LAUNCHER), mocks[leaf].return_value) + self.assertEqual(main.run_loop(["do it"], {}, PATHS, LAUNCHER, CWD), mocks[leaf].return_value) mocks[leaf].return_value = "/s" mocks[3].side_effect = [Retry("claude exited 3")] * 3 stack.enter_context(unittest.mock.patch.object(sys, "stderr", io.StringIO())) sleep = stack.enter_context(unittest.mock.patch("time.sleep")) - self.assertEqual(main.run_loop([main.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it"})], {}, PATHS, LAUNCHER), Stop(1, "the worker failed three times running: claude exited 3")) + self.assertEqual(main.run_loop([main.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it"})], {}, PATHS, LAUNCHER, CWD), Stop(1, "the worker failed three times running: claude exited 3")) self.assertIn("retrying the worker in a minute: claude exited 3", sys.stderr.getvalue()) self.assertEqual(sleep.call_count, 2) diff --git a/todo.md b/todo.md index 6244c9e8..59ba94a5 100644 --- a/todo.md +++ b/todo.md @@ -7,7 +7,7 @@ Ships when a four-seat scoring run puts every dimension and the overall at 7.0 or above (`docs/decisions.md`). The rebuild lifts every dimension: each item below is one chunk on a worktree based on `origin/rebuild`, its PR into `rebuild`, until the last item merges `rebuild` into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. - **Move the transcript, the session and the worker into their own modules.** `UserEntryKind` names each entry Claude Code writes; a malformed line is skipped; an unreadable transcript is its own error, never "typed nothing"; `session` states the lifecycle once, where the id is made. -- **Move the judge, the interrupt, trust and model resolution into their own modules.** The judge is retried alone and checks evidence on every verdict against the rendered transcript; `models` owns the whole resolution, env overrides included, with no sentinel; `trust` names a `projects` entry that is not an object; `input()` at end of file is exit 2. +- **Move the judge, the interrupt, trust and model resolution into their own modules.** The judge is retried alone and checks evidence on every verdict against the rendered transcript; `models` owns the whole resolution, env overrides included, with no sentinel; `trust` names a `projects` entry that is not an object; `input()` at end of file is exit 2. Every leaf spells failure one way — `Stop` where it ends the loop, else a failure its caller maps — so `ask_model`'s `Stop(2)`, `interrupt`'s string and `run_worker`'s `""` for success become one spelling; `replace_json` and `make_private` get one module shared by `models`, `trust` and the archive; each Claude Code internal `--help` lists sits beside the module relying on it, or `docs/decisions.md` says why `--help` keeps it, and "the five section headers stay" is rechecked against the module names. - **Archive the raw transcript, deduplicated by content hash, with the verdict beside it, and stop on a failed archive.** Tests first; the changelog line says what the archive now holds. - **Replace `bin/test_loop_claude.py`'s internal-function tests with the black-box tests plus unit tests of the pure parsers.** - **Hold every reviewer to one findings document, `principles/review-findings.md`.** Severity, verdict, rounds with round 2 verifying each earlier finding, the per-chunk round cap, declining, and `/security-review`'s HIGH/MEDIUM/LOW mapped onto the scale; it replaces `principles/review-protocol.md`. -- 2.52.0 From 018c7d95c31fecd8e07ec5a87610281e711a2ffb Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 11:15:54 +0200 Subject: [PATCH 007/233] Drop a stray blank line --- bin/loop_claude/main.py | 1 - 1 file changed, 1 deletion(-) diff --git a/bin/loop_claude/main.py b/bin/loop_claude/main.py index 8c3f5c86..6b8da299 100644 --- a/bin/loop_claude/main.py +++ b/bin/loop_claude/main.py @@ -97,7 +97,6 @@ def run_loop(argv, env, paths, launcher, cwd): state = dataclasses.replace(state, failures=0) - def loop_state(argv, cwd): if argv[:1] != [RELOAD_FLAG]: task = " ".join(argv) -- 2.52.0 From 7e65d070b800464062db05305c50ee713e2bd40e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 11:17:01 +0200 Subject: [PATCH 008/233] Name the files a reload watches in --help --- bin/loop_claude/main.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/bin/loop_claude/main.py b/bin/loop_claude/main.py index 6b8da299..66d646be 100644 --- a/bin/loop_claude/main.py +++ b/bin/loop_claude/main.py @@ -27,7 +27,8 @@ and read each cycle; a project without an entry, as on its first run, is asked f LOOP_CLAUDE_JUDGE_MODEL overrides it for the judge, LOOP_CLAUDE_WORKER_MODEL for the worker and the interrupt; with both set, nothing is asked. -A change to loop-claude's files takes effect at the next cycle boundary, once the launcher answers --help. +A change to bin/loop-claude or bin/loop_claude/*.py takes effect at the next cycle boundary, once +loop-claude --help succeeds. Claude Code internals this rests on, observed on 2.1.282, the model catalog on 2.1.283: - The transcript is ~/.claude/projects/*/.jsonl, one JSON object per line. A / -- 2.52.0 From d8331d5c3436518524239d6268866f6d8b5e605d Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 11:19:35 +0200 Subject: [PATCH 009/233] Bring the decisions and the plan in line with the package --- AGENTS.md | 3 ++- bin/loop_claude/reload.py | 1 - docs/decisions.md | 12 ++++++++---- todo.md | 9 +++++---- 4 files changed, 15 insertions(+), 10 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 1f7171a9..9f231cdd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,7 +13,7 @@ Decisions live in `docs/decisions.md`: - bin/: the Python floor is README's Install prerequisite - bin/: host python, no container - comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it -- loop-claude: the five section headers stay +- loop-claude: the section headers stay - vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link - larv-review: a re-entered loop takes a fresh round cap - loop-claude: a reload into an older file is unsupported @@ -25,3 +25,4 @@ Decisions live in `docs/decisions.md`: - loop-claude: the judge loads `CLAUDE.md` - loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop - loop-claude: the rebuild keeps main's `--reloaded` state +- rebuild: a chunk into `rebuild` takes no comprehension scoring run diff --git a/bin/loop_claude/reload.py b/bin/loop_claude/reload.py index 788445b7..a3c75177 100644 --- a/bin/loop_claude/reload.py +++ b/bin/loop_claude/reload.py @@ -22,7 +22,6 @@ def decode_state(handed, kind): def fingerprint(launcher): - # An unreadable file hashes its error, and the --help trial judges it. digest = hashlib.sha256() for path in [launcher, *sorted((launcher.parent / "loop_claude").glob("*.py"))]: try: diff --git a/docs/decisions.md b/docs/decisions.md index c9fa0a0e..d1e1fcec 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -10,7 +10,7 @@ ## loop-claude: one session per project, at a fixed id -2026-09-21, lilleman; the rename and mirrored-path costs accepted 2026-09-25 by larv-review. Serves goal 4. One fixed id per project keeps the session picker at one entry per project and makes any transcript under that id the script's own to delete. The id derives from the session name, so moving the checkout or changing that name orphans open sessions: they stay in the picker until the human deletes them, migration code not being worth a one-human audience. A checkout outside `~/code` mirroring a path inside it would share its id. Valid while claude takes `--session-id` and resumes by it, and no checkout outside `~/code` mirrors a path inside it. +2026-09-21, lilleman; the rename and mirrored-path costs accepted 2026-09-25 by larv-review. Serves goal 4. One fixed id per project keeps the session picker at one entry per project and makes any transcript under that id loop-claude's own to delete. The id derives from the session name, so moving the checkout or changing that name orphans open sessions: they stay in the picker until the human deletes them, migration code not being worth a one-human audience. A checkout outside `~/code` mirroring a path inside it would share its id. Valid while claude takes `--session-id` and resumes by it, and no checkout outside `~/code` mirrors a path inside it. ## loop-claude: the trust file is rewritten before an interrupt @@ -36,9 +36,9 @@ 2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The rebuild planned in `todo.md` under 0.1.0 answers the places named, and a later chunk may not lower any dimension. Valid until the next scoring run, which uses the same four seats. -## loop-claude: the five section headers stay +## loop-claude: the section headers stay -2026-09-26, larv-review, declining a prose-pass deletion under `CLAUDE.md` → "Comments and documentation". Serves goal 4. Two seats of the 2026-09-26 panel credit Navigation 8 to `# The transcript file` and its four siblings indexing the script by the Claude Code internal each group touches. Valid until a scoring run scores Navigation without them. +2026-09-26, larv-review, declining a prose-pass deletion under `CLAUDE.md` → "Comments and documentation". Serves goal 4. Two seats of the 2026-09-26 panel credit Navigation 8 to `# The transcript file` and its siblings, now in `bin/loop_claude/cycle.py`, indexing it by the file or format each group touches. Valid until the modules the rebuild splits out of `cycle.py` take over that index. ## vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link @@ -50,7 +50,7 @@ ## loop-claude: a reload into an older file is unsupported -2026-09-26, lilleman. Serves goal 4. A running loop whose `bin/loop-claude` on disk is rolled back to a version with an older handover fails in that older file, or, older than the handover itself, runs `--reloaded ` as its task; this version cannot change either; the human who rolled it back reruns `loop-claude `. Valid while nobody but the developer runs it: other team members running it while it is still developed reopens this. +2026-09-26, lilleman. Serves goal 4. A running loop whose `bin/loop-claude` or `bin/loop_claude/` on disk is rolled back to a version with an older handover fails in that older file, or, older than the handover itself, runs `--reloaded ` as its task; this version cannot change either; the human who rolled it back reruns `loop-claude `. Valid while nobody but the developer runs it: other team members running it while it is still developed reopens this. ## loop-claude: a CR-only README.md is reported at line 1 @@ -83,3 +83,7 @@ ## loop-claude: the rebuild keeps main's `--reloaded` state 2026-09-28, lilleman, for the rebuild. Serves goal 4. A loop running main's script reloads into the rebuilt one at its next cycle boundary and carries on; the state keeps main's four fields, `cycle_number`, `failures`, `root` and `task`, so no code exists only for the cut-over. Valid until the rebuild merges. + +## rebuild: a chunk into `rebuild` takes no comprehension scoring run + +2026-09-28, larv-review, reading the rebuild decision above. Serves goal 4. The floor and its ratchet gate `rebuild` into main, scored by the plan's last item; the chunks before it pass through half-moved states a per-chunk run would block. Valid until the rebuild merges. diff --git a/todo.md b/todo.md index 59ba94a5..1980f442 100644 --- a/todo.md +++ b/todo.md @@ -2,12 +2,13 @@ ## 0.1.0 -**⚠️ THE REBUILD NEVER MERGES INTO MAIN WITHOUT THE HUMAN'S EXPLICIT APPROVAL.** Every rebuild chunk is a worktree based on `origin/rebuild` with its PR into `rebuild`, never into main. What remains of the rebuild is `rebuild`'s `todo.md` (`git show origin/rebuild:todo.md`), where each chunk ticks its item off; this copy stays as planned until the merge. Other sessions run on `~/.claude` main throughout; only the human merges `rebuild` into main, once they have approved the finished whole. +**⚠️ THE REBUILD NEVER MERGES INTO MAIN WITHOUT THE HUMAN'S EXPLICIT APPROVAL.** Every rebuild chunk is a worktree based on `origin/rebuild` with its PR into `rebuild`, never into main. Other sessions run on `~/.claude` main throughout; only the human merges `rebuild` into main, once they have approved the finished whole. -Ships when a four-seat scoring run puts every dimension and the overall at 7.0 or above (`docs/decisions.md`). The rebuild lifts every dimension: each item below is one chunk on a worktree based on `origin/rebuild`, its PR into `rebuild`, until the last item merges `rebuild` into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. +The rebuild lifts every dimension: each item below is one chunk on a worktree based on `origin/rebuild`, its PR into `rebuild`, until the last item merges `rebuild` into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -- **Move the transcript, the session and the worker into their own modules.** `UserEntryKind` names each entry Claude Code writes; a malformed line is skipped; an unreadable transcript is its own error, never "typed nothing"; `session` states the lifecycle once, where the id is made. -- **Move the judge, the interrupt, trust and model resolution into their own modules.** The judge is retried alone and checks evidence on every verdict against the rendered transcript; `models` owns the whole resolution, env overrides included, with no sentinel; `trust` names a `projects` entry that is not an object; `input()` at end of file is exit 2. Every leaf spells failure one way — `Stop` where it ends the loop, else a failure its caller maps — so `ask_model`'s `Stop(2)`, `interrupt`'s string and `run_worker`'s `""` for success become one spelling; `replace_json` and `make_private` get one module shared by `models`, `trust` and the archive; each Claude Code internal `--help` lists sits beside the module relying on it, or `docs/decisions.md` says why `--help` keeps it, and "the five section headers stay" is rechecked against the module names. +- **Move the transcript, the session and the worker into their own modules.** `UserEntryKind` names each entry Claude Code writes; a malformed line is skipped; an unreadable transcript is its own error, never "typed nothing"; `session` states the lifecycle once, where the id is made; `run_worker` returns a failure its caller maps, never `""` for success. +- **Move the judge, the interrupt, trust and model resolution into their own modules.** The judge is retried alone and checks evidence on every verdict against the rendered transcript; `models` owns the whole resolution, env overrides included, with no sentinel; `trust` names a `projects` entry that is not an object; `input()` at end of file is exit 2. `ask_model` and `interrupt` spell "the human is needed" one way; `replace_json` and `make_private` get one module shared by `models`, `trust` and the archive. +- **Move each Claude Code internal `--help` lists beside the module relying on it.** Or `docs/decisions.md` says why `--help` keeps it. - **Archive the raw transcript, deduplicated by content hash, with the verdict beside it, and stop on a failed archive.** Tests first; the changelog line says what the archive now holds. - **Replace `bin/test_loop_claude.py`'s internal-function tests with the black-box tests plus unit tests of the pure parsers.** - **Hold every reviewer to one findings document, `principles/review-findings.md`.** Severity, verdict, rounds with round 2 verifying each earlier finding, the per-chunk round cap, declining, and `/security-review`'s HIGH/MEDIUM/LOW mapped onto the scale; it replaces `principles/review-protocol.md`. -- 2.52.0 From a7da17c9b68d7931bfb49ec9108d58d6e78b4101 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 16:19:23 +0200 Subject: [PATCH 010/233] Record the human's approval of skipping per-chunk scoring during the rebuild --- docs/decisions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/decisions.md b/docs/decisions.md index d1e1fcec..7ad9efb7 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -86,4 +86,4 @@ ## rebuild: a chunk into `rebuild` takes no comprehension scoring run -2026-09-28, larv-review, reading the rebuild decision above. Serves goal 4. The floor and its ratchet gate `rebuild` into main, scored by the plan's last item; the chunks before it pass through half-moved states a per-chunk run would block. Valid until the rebuild merges. +2026-09-28, lilleman, confirming larv-review's reading of the rebuild decision above. Serves goal 4. The floor and its ratchet gate `rebuild` into main, scored by the plan's last item; the chunks before it pass through half-moved states a per-chunk run would block. Valid until the rebuild merges. -- 2.52.0 From 60c949b7329d6582a87ecf13e78a335961cf1513 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 16:21:50 +0200 Subject: [PATCH 011/233] Pin the transcript's malformed lines, an unreadable transcript and a worker claude cannot start --- bin/test_loop_claude_black_box.py | 50 +++++++++++++++++++++++++++---- 1 file changed, 45 insertions(+), 5 deletions(-) diff --git a/bin/test_loop_claude_black_box.py b/bin/test_loop_claude_black_box.py index c98d30d3..66410f87 100644 --- a/bin/test_loop_claude_black_box.py +++ b/bin/test_loop_claude_black_box.py @@ -44,17 +44,23 @@ def session(): return argv[argv.index(flag) + 1] +def transcript(): + return pathlib.Path.home() / ".claude" / "projects" / "-fake" / f"{{session()}}.jsonl" + + def append(*entries): - path = pathlib.Path.home() / ".claude" / "projects" / "-fake" / f"{{session()}}.jsonl" - path.parent.mkdir(parents=True, exist_ok=True) - with open(path, "a") as transcript: - transcript.writelines(json.dumps(entry) + "\\n" for entry in entries) + transcript().parent.mkdir(parents=True, exist_ok=True) + with open(transcript(), "a") as handle: + handle.writelines(json.dumps(entry) + "\\n" for entry in entries) if role == "worker": said = {{"type": "assistant", "message": {{"content": [{{"type": "text", "text": step.get("say", "working")}}]}}}} if step.get("transcript", True): - append({{"type": "user", "promptSource": "sdk", "message": {{"content": argv[argv.index("-p") + 1]}}}}, said) + append({{"type": "user", "promptSource": "sdk", "message": {{"content": argv[argv.index("-p") + 1]}}}}) + with open(transcript(), "ab") as handle: + handle.write(step.get("raw", "").encode("latin-1")) + append(said) if "append" in step: with open(os.environ["FAKE_CLAUDE_EDIT"], "a") as script: script.write(step["append"]) @@ -71,6 +77,8 @@ elif role == "judge": print(step.get("stderr", ""), file=sys.stderr) elif "type" in step: append({{"type": "user", "message": {{"content": step["type"]}}}}) +if step.get("unreadable"): + transcript().chmod(0) sys.exit(step.get("exit", 0)) """ @@ -311,6 +319,31 @@ class Cycles(unittest.TestCase): self.assertEqual(run.roles(), ["worker", "judge", "judge", "worker"]) self.assertIn("the judge quoted 'never said', nothing in the transcript, for the question: A or B?", run.stderr) + def test_skips_a_malformed_transcript_line(self): + checkout = Checkout(self) + raw = "\xff not UTF-8\nnot JSON\n[1]\n" + json.dumps({"type": "assistant", "message": "not an object"}) + "\n" + json.dumps({"type": "user", "message": None}) + "\n" + run = checkout.run([worker(raw=raw, say="past the noise"), judge()]) + self.assertEqual((run.code, run.roles()), (130, ["worker", "judge", "worker"])) + self.assertIn("past the noise", run.calls[1]["stdin"]) + + @unittest.skipIf(os.geteuid() == 0, "root reads an unreadable file") + def test_exits_1_when_the_transcript_cannot_be_read(self): + checkout = Checkout(self) + run = checkout.run([worker(unreadable=True)]) + self.assertEqual((run.code, run.roles()), (1, ["worker"])) + self.assertRegex(run.stderr.strip().splitlines()[-1], r"^could not read the transcript .*\.jsonl: Permission denied$") + + def test_retries_a_worker_claude_cannot_start(self): + checkout = Checkout(self) + only_git = checkout.temp / "only-git" + only_git.mkdir() + (only_git / "git").symlink_to(shutil.which("git")) + checkout.env["PATH"] = str(only_git) + run = checkout.run([]) + self.assertEqual((run.code, run.calls), (1, [])) + self.assertEqual(run.sleeps, [60, 60]) + self.assertEqual(run.stderr.strip().splitlines()[-1], "the worker failed three times running: could not start claude: No such file or directory") + def test_exits_1_when_claude_leaves_no_transcript(self): checkout = Checkout(self) run = checkout.run([worker(transcript=False)]) @@ -359,6 +392,13 @@ class Interrupt(unittest.TestCase): self.assertEqual((run.code, run.roles()), (2, ["worker", "judge", "interrupt"])) self.assertEqual(run.stderr.strip().splitlines()[-1], "the interrupt ended without the human typing anything") + @unittest.skipIf(os.geteuid() == 0, "root reads an unreadable file") + def test_exits_1_when_the_transcript_cannot_be_read_after_the_interrupt(self): + checkout = Checkout(self) + run = checkout.run([worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?"), interrupt(type="B", unreadable=True)], terminal_input="") + self.assertEqual((run.code, run.roles()), (1, ["worker", "judge", "interrupt"])) + self.assertRegex(run.stderr.strip().splitlines()[-1], r"^could not tell whether you typed anything: could not read the transcript .*\.jsonl: Permission denied$") + class Models(unittest.TestCase): def catalog(self, checkout): -- 2.52.0 From dfb7ae294cd26c5d3f5f84e9002d3db974d0962e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 16:24:26 +0200 Subject: [PATCH 012/233] Move the transcript, the session and the worker into their own modules --- CHANGELOG.md | 1 + bin/loop_claude/cycle.py | 177 +++++++--------------------------- bin/loop_claude/main.py | 9 +- bin/loop_claude/outcome.py | 5 + bin/loop_claude/session.py | 39 ++++++++ bin/loop_claude/transcript.py | 86 +++++++++++++++++ bin/loop_claude/worker.py | 41 ++++++++ bin/test_loop_claude.py | 62 ++++++------ docs/decisions.md | 2 +- todo.md | 1 - 10 files changed, 245 insertions(+), 178 deletions(-) create mode 100644 bin/loop_claude/session.py create mode 100644 bin/loop_claude/transcript.py create mode 100644 bin/loop_claude/worker.py diff --git a/CHANGELOG.md b/CHANGELOG.md index f0722177..360bafc3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,4 +6,5 @@ - `settings.json`, the agents and the status line run on any machine unedited; the status line shows reset times in the machine's own time zone. - `loop-claude`'s no-premises exit names what is wrong: `README.md` unopenable or not UTF-8, a `## Goals` or `## Audience` heading missing or repeated, or nothing under one. - `loop-claude` says why when it cannot read or write `~/.claude.json` before an interrupt, and the interrupt then lands in Claude Code's trust dialog. +- `loop-claude` skips a transcript line it cannot parse, exits 1 naming a transcript it cannot read, and counts a `claude` it cannot start as a failed worker run. - `loop-claude` keeps the mode of `~/.claude.json` and of its models file when it rewrites them, and creates the models file 0600. diff --git a/bin/loop_claude/cycle.py b/bin/loop_claude/cycle.py index e0284026..e3ed6fa7 100644 --- a/bin/loop_claude/cycle.py +++ b/bin/loop_claude/cycle.py @@ -1,18 +1,16 @@ -import glob import itertools import json import os -import shutil import subprocess import sys import time -import uuid from loop_claude.checkout import checkouts, project_name -from loop_claude.outcome import Continue, Retry, Stop +from loop_claude.outcome import Continue, Failure, Retry, Stop +from loop_claude.session import delete_session, session_for, transcript_file from loop_claude.strike import strike - -SESSION_NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec") +from loop_claude.transcript import human_turns, parse, read, render +from loop_claude.worker import run_worker, worker_args JUDGE_RULES = ( "Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n" @@ -47,34 +45,32 @@ JUDGE_SCHEMA = { def run_cycle(root, task, premises, chosen, paths, env): - name = session_name(root, paths.code) - session_id = uuid.uuid5(SESSION_NAMESPACE, name) - if failure := run_worker(root, worker_args(task, name, session_id, chosen, env, resuming=session_open(paths.projects, session_id))): - return Retry(failure) - path = session_file(paths.projects, session_id) + session = session_for(root, paths) + resuming = bool(transcript_file(session)) + if failure := run_worker(root, worker_args(task, session, model_for(env, "LOOP_CLAUDE_WORKER_MODEL", chosen), resuming)): + return Retry(failure.reason) + path = transcript_file(session) if not path: - return Stop(1, f"claude left no transcript for session {session_id}") + return Stop(1, f"claude left no transcript for session {session.id}") # The interrupt appends to this transcript, so each pass judges and archives it anew; archive skips a stamp it already wrote. while True: - verdict = judge(root, task, premises, render(entries(path)), chosen, env) + entries = read(path) + if isinstance(entries, Failure): + return Stop(1, entries.reason) + verdict = judge(root, task, premises, render(entries), chosen, env) if isinstance(verdict, Stop): return verdict if not verdict["interrupt"]: break archive(root, path, f"Task: {task}\n\nVerdict: interrupt\n\n{verdict['question']}", paths) - if failure := interrupt(root, session_id, chosen, path, verdict["question"], paths, env): - return Stop(2, failure) + if stop := interrupt(root, session.id, chosen, path, verdict["question"], paths, env): + return stop if verdict["finished"]: archive(root, path, f"Task: {task}\n\nVerdict: finished", paths) - delete_transcript_files(path) + delete_session(path) return Continue() -def session_name(root, code): - # "A " is the human's cue in the session picker that the session is the loop's. - return f"A {project_name(root, code)} loop-claude" - - def archive(root, path, note, paths): # Stamped by mtime, so a transcript unchanged since its last archive maps to the file already written. name = project_name(root, paths.code) @@ -84,8 +80,12 @@ def archive(root, path, note, paths): make_private(folder) dest = folder / f"{stamp}.md" if not os.path.exists(dest): + entries = read(path) + if isinstance(entries, Failure): + print(f"could not archive the transcript: {entries.reason}", file=sys.stderr) + return with open(os.open(dest, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as copy: - copy.write(f"# {stamp} {name}\n\n{note}\n\n{render(entries(path))}\n") + copy.write(f"# {stamp} {name}\n\n{note}\n\n{render(entries)}\n") print(f"transcript: {dest}", file=sys.stderr) except OSError as failure: print(f"could not archive the transcript: {failure}", file=sys.stderr) @@ -114,8 +114,8 @@ def replace_json(path, data, **dump): return None -def model_args(env, variable, chosen): - return ["--model", env.get(variable) or chosen] +def model_for(env, variable, chosen): + return env.get(variable) or chosen # ~/.claude/loop-claude-models.json @@ -197,118 +197,6 @@ def catalog(folder): 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 [] -# The transcript file - - -def session_open(projects, session_id): - return bool(session_file(projects, session_id)) - - -def session_file(projects, session_id): - hit = glob.glob(os.path.join(glob.escape(str(projects)), "*", f"{session_id}.jsonl")) - return hit[0] if hit else "" - - -def delete_transcript_files(path): - for sibling in glob.glob(glob.escape(path.removesuffix(".jsonl")) + "*"): - try: - shutil.rmtree(sibling) if os.path.isdir(sibling) else os.remove(sibling) - except OSError as failure: - print(f"could not remove {sibling}: {failure}", file=sys.stderr) - - -def entries(path): - with open(path, encoding="utf-8") as handle: - for raw in handle: - if entry := parse(raw): - yield entry - - -def parse(raw): - try: - entry = json.loads(raw) - except ValueError: - return None - return entry if isinstance(entry, dict) else None - - -# "user" entries - - -def human_turns(entries): - return sum(1 for entry in entries if typed(entry)) - - -def typed(entry): - if entry.get("type") != "user": - return False - content = entry.get("message", {}).get("content") - parts = content if isinstance(content, list) else [] - meta = entry.get("isMeta") - loop_prompt = entry.get("promptSource") == "sdk" - command = isinstance(content, str) and content.startswith("<") - no_content = not isinstance(content, str) and not parts - non_text = any(not isinstance(part, dict) or part.get("type") != "text" for part in parts) - interruption = not non_text and any(part.get("text", "").startswith("[Request interrupted") for part in parts) - return not (meta or loop_prompt or command or no_content or non_text or interruption) - - -# "assistant" entries and stream-json - - -def run_worker(root, args): - with subprocess.Popen(["claude", *args], cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, text=True) as proc: - done = False - for raw in proc.stdout: - event = parse(raw) or {} - if event.get("type") == "result": - done = True - elif event.get("type") == "assistant": - for part in event.get("message", {}).get("content", []): - if line := said(part, 160): - print(line, flush=True) - code = proc.wait() - if code < 0: - return f"claude killed by signal {-code}" - if code: - return f"claude exited {code}" - return "" if done else "claude exited 0 without a result event" - - -def worker_args(task, name, session_id, chosen, env, resuming): - if resuming: - start = ["-p", "Continue the task; the previous run stopped before it was finished.", "--resume", str(session_id)] - else: - start = ["-p", f"{task}\n\nContinue any open draft PR or worktree for the item before creating a new one.", "--name", name, "--session-id", str(session_id)] - return [ - *start, - "--output-format", "stream-json", - "--permission-mode", "bypassPermissions", - "--verbose", - *model_args(env, "LOOP_CLAUDE_WORKER_MODEL", chosen), - ] - - -def render(entries): - lines = [] - for entry in entries: - if entry.get("type") == "assistant": - lines += [line for part in entry.get("message", {}).get("content", []) if (line := said(part))] - elif typed(entry): - content = entry["message"]["content"] - lines.append("[human] " + (content if isinstance(content, str) else "".join(part.get("text", "") for part in content))) - return "\n\n".join(lines) - - -def said(part, limit=400): - kind = part.get("type") if isinstance(part, dict) else None - if kind == "text" and part.get("text", "").strip(): - return part["text"] - if kind == "tool_use": - return f"[tool {part.get('name')}] {json.dumps(part.get('input'))[:limit]}" - return "" - - # --json-schema verdicts @@ -317,7 +205,7 @@ def judge(root, task, premises, transcript, chosen, env): args = [ "-p", "--json-schema", json.dumps(JUDGE_SCHEMA), - *model_args(env, "LOOP_CLAUDE_JUDGE_MODEL", chosen), + "--model", model_for(env, "LOOP_CLAUDE_JUDGE_MODEL", chosen), "--no-session-persistence", "--output-format", "json", "--permission-mode", "bypassPermissions", @@ -364,11 +252,18 @@ def grounded(verdict, transcript): def interrupt(root, session_id, chosen, path, question, paths, env): print(f"\n{question}", file=sys.stderr) if not (sys.stdin.isatty() and sys.stdout.isatty()): - return "stdin or stdout is not a terminal" + return Stop(2, "stdin or stdout is not a terminal") trust(paths.claude_json, checkouts(root)) - before = human_turns(entries(path)) - subprocess.run(["claude", *model_args(env, "LOOP_CLAUDE_WORKER_MODEL", chosen), "--permission-mode", "bypassPermissions", "--resume", str(session_id)], cwd=root) - return "" if human_turns(entries(path)) > before else "the interrupt ended without the human typing anything" + before = read(path) + if isinstance(before, Failure): + return Stop(1, before.reason) + subprocess.run(["claude", "--model", model_for(env, "LOOP_CLAUDE_WORKER_MODEL", chosen), "--permission-mode", "bypassPermissions", "--resume", str(session_id)], cwd=root) + after = read(path) + if isinstance(after, Failure): + return Stop(1, f"could not tell whether you typed anything: {after.reason}") + if human_turns(after) <= human_turns(before): + return Stop(2, "the interrupt ended without the human typing anything") + return None def trust(config, roots): diff --git a/bin/loop_claude/main.py b/bin/loop_claude/main.py index 66d646be..0789bc58 100644 --- a/bin/loop_claude/main.py +++ b/bin/loop_claude/main.py @@ -11,9 +11,10 @@ its session next cycle; the next chunk starts a fresh session. Cycles continue until that interrupt or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary". Exit 1: no task, not inside a checkout, no premises, a models file it cannot read or write, claude -leaves no transcript, a reload with unreadable state, or the worker or the judge fails three times -running. A worker fails when claude exits non-zero, is killed, or ends without a result event; a -judge when its verdict misses a field or quotes nothing in the transcript. +leaves no transcript or one it cannot read, a reload with unreadable state, or the worker or the +judge fails three times running. A worker fails when claude cannot start, exits non-zero, is killed, +or ends without a result event; a judge when its verdict misses a field or quotes nothing in the +transcript. Exit 2: the human is needed, to pick the model or answer an interrupt, and stdin or stdout is not a terminal, or the interrupt ended without them typing anything. Rerunning resumes any open session. @@ -34,7 +35,7 @@ Claude Code internals this rests on, observed on 2.1.282, the model catalog on 2 - The transcript is ~/.claude/projects/*/.jsonl, one JSON object per line. A / folder and .superseded-*/ and .orphaned-*.jsonl siblings belong to the same session. - Claude Code writes "user" entries of its own into the transcript, and a `claude -p` prompt lands as one - with promptSource "sdk"; typed() tells a human's from them. + with promptSource "sdk"; UserEntryKind in transcript.py tells a human's from them. - An "assistant" entry, in the transcript and in --output-format stream-json, carries message.content parts of type "text" (text) and "tool_use" (name, input); stream-json ends with a "result" event. - `claude -p --output-format json --json-schema` returns the verdict under "structured_output". diff --git a/bin/loop_claude/outcome.py b/bin/loop_claude/outcome.py index acd5df0b..25395bf1 100644 --- a/bin/loop_claude/outcome.py +++ b/bin/loop_claude/outcome.py @@ -6,6 +6,11 @@ class Continue: pass +@dataclasses.dataclass(frozen=True) +class Failure: + reason: str + + @dataclasses.dataclass(frozen=True) class Retry: failure: str diff --git a/bin/loop_claude/session.py b/bin/loop_claude/session.py new file mode 100644 index 00000000..f1b8a009 --- /dev/null +++ b/bin/loop_claude/session.py @@ -0,0 +1,39 @@ +import dataclasses +import glob +import os +import pathlib +import shutil +import sys +import uuid + +from loop_claude.checkout import project_name + +NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec") + + +@dataclasses.dataclass(frozen=True) +class Session: + id: uuid.UUID + name: str + projects: pathlib.Path + + +def session_for(root, paths): + """The project's one session, at an id fixed by its name. It exists while its transcript does: a chunk's first + cycle starts it, each later cycle of the chunk resumes it, and the finished chunk deletes it.""" + # "A " is the human's cue in the session picker that the session is the loop's. + name = f"A {project_name(root, paths.code)} loop-claude" + return Session(uuid.uuid5(NAMESPACE, name), name, paths.projects) + + +def transcript_file(session): + hit = glob.glob(os.path.join(glob.escape(str(session.projects)), "*", f"{session.id}.jsonl")) + return hit[0] if hit else "" + + +def delete_session(path): + for sibling in glob.glob(glob.escape(path.removesuffix(".jsonl")) + "*"): + try: + shutil.rmtree(sibling) if os.path.isdir(sibling) else os.remove(sibling) + except OSError as failure: + print(f"could not remove {sibling}: {failure}", file=sys.stderr) diff --git a/bin/loop_claude/transcript.py b/bin/loop_claude/transcript.py new file mode 100644 index 00000000..ed1e4346 --- /dev/null +++ b/bin/loop_claude/transcript.py @@ -0,0 +1,86 @@ +import enum +import json + +from loop_claude.outcome import Failure + + +class UserEntryKind(enum.Enum): + """Who wrote a "user" entry: the human wrote HUMAN, Claude Code every other kind; the value is the tell.""" + + COMMAND = "string content starting with <" + CTRL_C = "a text part starting with [Request interrupted" + EMPTY = "no content" + HUMAN = "typed by the human" + META = "isMeta" + NON_TEXT = "a part that is not text, such as a tool result" + SDK_PROMPT = "promptSource sdk: the claude -p prompt" + + +def read(path): + try: + with open(path, "rb") as handle: + return [entry for raw in handle if (entry := parse(raw))] + except OSError as failure: + return Failure(f"could not read the transcript {path}: {failure.strerror}") + + +def parse(raw): + try: + entry = json.loads(raw) + except ValueError: + return None + return entry if isinstance(entry, dict) else None + + +def content(entry): + message = entry.get("message") + return message.get("content") if isinstance(message, dict) else None + + +def parts(entry): + found = content(entry) + return found if isinstance(found, list) else [] + + +def user_entry_kind(entry): + if entry.get("isMeta"): + return UserEntryKind.META + if entry.get("promptSource") == "sdk": + return UserEntryKind.SDK_PROMPT + if isinstance(text := content(entry), str): + return UserEntryKind.COMMAND if text.startswith("<") else UserEntryKind.HUMAN + if not parts(entry): + return UserEntryKind.EMPTY + if any(not isinstance(part, dict) or part.get("type") != "text" or not isinstance(part.get("text"), str) for part in parts(entry)): + return UserEntryKind.NON_TEXT + if any(part["text"].startswith("[Request interrupted") for part in parts(entry)): + return UserEntryKind.CTRL_C + return UserEntryKind.HUMAN + + +def typed(entry): + return entry.get("type") == "user" and user_entry_kind(entry) is UserEntryKind.HUMAN + + +def human_turns(entries): + return sum(1 for entry in entries if typed(entry)) + + +def render(entries): + lines = [] + for entry in entries: + if entry.get("type") == "assistant": + lines += [line for part in parts(entry) if (line := said(part))] + elif typed(entry): + text = content(entry) + lines.append("[human] " + (text if isinstance(text, str) else "".join(part["text"] for part in text))) + return "\n\n".join(lines) + + +def said(part, limit=400): + kind = part.get("type") if isinstance(part, dict) else None + if kind == "text" and isinstance(part.get("text"), str) and part["text"].strip(): + return part["text"] + if kind == "tool_use": + return f"[tool {part.get('name')}] {json.dumps(part.get('input'))[:limit]}" + return "" diff --git a/bin/loop_claude/worker.py b/bin/loop_claude/worker.py new file mode 100644 index 00000000..971af16a --- /dev/null +++ b/bin/loop_claude/worker.py @@ -0,0 +1,41 @@ +import subprocess + +from loop_claude.outcome import Failure +from loop_claude.transcript import parse, parts, said + + +def run_worker(root, args): + try: + proc = subprocess.Popen(["claude", *args], cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, text=True) + except OSError as failure: + return Failure(f"could not start claude: {failure.strerror}") + with proc: + done = False + for raw in proc.stdout: + event = parse(raw) or {} + if event.get("type") == "result": + done = True + elif event.get("type") == "assistant": + for part in parts(event): + if line := said(part, 160): + print(line, flush=True) + code = proc.wait() + if code < 0: + return Failure(f"claude killed by signal {-code}") + if code: + return Failure(f"claude exited {code}") + return None if done else Failure("claude exited 0 without a result event") + + +def worker_args(task, session, model, resuming): + if resuming: + start = ["-p", "Continue the task; the previous run stopped before it was finished.", "--resume", str(session.id)] + else: + start = ["-p", f"{task}\n\nContinue any open draft PR or worktree for the item before creating a new one.", "--name", session.name, "--session-id", str(session.id)] + return [ + *start, + "--output-format", "stream-json", + "--permission-mode", "bypassPermissions", + "--verbose", + "--model", model, + ] diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 3d532a24..cf247d76 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -15,14 +15,15 @@ import uuid sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -from loop_claude import checkout, cycle, main, premises, reload -from loop_claude.outcome import Continue, Retry, Stop +from loop_claude import checkout, cycle, main, premises, reload, session, transcript, worker +from loop_claude.outcome import Continue, Failure, Retry, Stop from loop_claude.paths import paths_from CWD = pathlib.Path("/c") LAUNCHER = pathlib.Path(__file__).resolve().with_name("loop-claude") PATHS = paths_from(pathlib.Path("/h"), {}) SESSION_ID = str(getattr(uuid, "uuid7", uuid.uuid4)()) +SESSION = session.Session(uuid.UUID(SESSION_ID), "A name", PATHS.projects) def assistant(*parts): @@ -81,7 +82,7 @@ class ReadPremises(unittest.TestCase): class Render(unittest.TestCase): def test_joins_assistant_text_and_tool_calls_and_human_turns_and_skips_the_rest(self): - said = cycle.render([ + said = transcript.render([ human("do it"), assistant({"type": "text", "text": "Starting."}, {"type": "tool_use", "name": "Bash", "input": {"command": "ls"}}), assistant({"type": "text", "text": " "}), @@ -95,7 +96,7 @@ class Render(unittest.TestCase): class HumanTurns(unittest.TestCase): def test_counts_typed_turns_and_not_tool_results(self): - self.assertEqual(cycle.human_turns([ + self.assertEqual(transcript.human_turns([ human("typed"), human([{"type": "text", "text": "typed as a block"}]), human([{"type": "tool_result", "content": "not typed"}]), @@ -126,30 +127,28 @@ class ProjectName(unittest.TestCase): def test_names_a_checkout_relative_to_code_and_any_other_relative_to_root(self): code = pathlib.Path("/h/code") self.assertEqual(checkout.project_name("/h/code/a/b", code), "a/b") - self.assertEqual(cycle.session_name("/h/code/a/b", code), "A a/b loop-claude") + self.assertEqual(session.session_for("/h/code/a/b", PATHS).name, "A a/b loop-claude") self.assertEqual(checkout.project_name("/h/code", code), "h/code") self.assertEqual(checkout.project_name("/srv/x", code), "srv/x") - self.assertEqual(cycle.session_name("/srv/x", code), "A srv/x loop-claude") + self.assertEqual(session.session_for("/srv/x", PATHS).name, "A srv/x loop-claude") class WorkerArgs(unittest.TestCase): def test_a_fresh_cycle_names_the_session_and_asks_to_continue_open_work(self): - args = cycle.worker_args("the task", "A name", SESSION_ID, "m", {}, resuming=False) + args = worker.worker_args("the task", SESSION, "m", resuming=False) self.assertIn("--session-id", args) self.assertEqual(args[args.index("--name") + 1], "A name") self.assertTrue(args[1].startswith("the task\n\nContinue any open draft PR")) def test_a_resumed_cycle_reuses_the_session(self): - args = cycle.worker_args("paint the fence", "A name", SESSION_ID, "m", {}, resuming=True) - self.assertEqual(args[args.index("--resume") + 1], SESSION_ID) + args = worker.worker_args("paint the fence", SESSION, "m", resuming=True) + self.assertEqual(args[args.index("--resume") + 1], str(SESSION.id)) self.assertNotIn("--name", args) self.assertNotIn("paint the fence", args[1]) def test_the_project_model_runs_unless_the_environment_names_one(self): - args = cycle.worker_args("t", "n", SESSION_ID, "claude-opus-5-5", {}, resuming=False) - self.assertEqual(args[args.index("--model") + 1], "claude-opus-5-5") - args = cycle.worker_args("t", "n", SESSION_ID, "claude-opus-5-5", {"LOOP_CLAUDE_WORKER_MODEL": "claude-fable-5-1"}, resuming=False) - self.assertEqual(args[args.index("--model") + 1], "claude-fable-5-1") + self.assertEqual(cycle.model_for({}, "LOOP_CLAUDE_WORKER_MODEL", "claude-opus-5-5"), "claude-opus-5-5") + self.assertEqual(cycle.model_for({"LOOP_CLAUDE_WORKER_MODEL": "claude-fable-5-1"}, "LOOP_CLAUDE_WORKER_MODEL", "claude-opus-5-5"), "claude-fable-5-1") class ProjectModel(unittest.TestCase): @@ -244,10 +243,10 @@ class Archive(unittest.TestCase): class Said(unittest.TestCase): def test_renders_text_and_tool_calls_and_nothing_else(self): - self.assertEqual(cycle.said({"type": "text", "text": "hi"}), "hi") - self.assertEqual(cycle.said({"type": "text", "text": " \n"}), "") - self.assertEqual(cycle.said({"type": "tool_use", "name": "Bash", "input": {"command": "x" * 500}}, 20), '[tool Bash] {"command": "xxxxxxx') - self.assertEqual(cycle.said("not a part"), "") + self.assertEqual(transcript.said({"type": "text", "text": "hi"}), "hi") + self.assertEqual(transcript.said({"type": "text", "text": " \n"}), "") + self.assertEqual(transcript.said({"type": "tool_use", "name": "Bash", "input": {"command": "x" * 500}}, 20), '[tool Bash] {"command": "xxxxxxx') + self.assertEqual(transcript.said("not a part"), "") class DeleteTranscriptFiles(unittest.TestCase): @@ -261,10 +260,11 @@ class DeleteTranscriptFiles(unittest.TestCase): os.makedirs(os.path.join(root, SESSION_ID, "subagents")) os.makedirs(os.path.join(root, f"{SESSION_ID}.superseded-1", "tool-results")) pathlib.Path(root, f"{SESSION_ID}.orphaned-1-ab.jsonl").write_text("{}\n") - self.assertTrue(cycle.session_open(projects, SESSION_ID)) - cycle.delete_transcript_files(transcript) + located = session.Session(uuid.UUID(SESSION_ID), "A name", projects) + self.assertEqual(session.transcript_file(located), transcript) + session.delete_session(transcript) self.assertEqual(os.listdir(root), []) - self.assertFalse(cycle.session_open(projects, SESSION_ID)) + self.assertEqual(session.transcript_file(located), "") class Interrupt(unittest.TestCase): @@ -273,14 +273,14 @@ class Interrupt(unittest.TestCase): transcript = os.path.join(root, "session.jsonl") pathlib.Path(transcript).write_text("{}\n") with unittest.mock.patch("sys.stdin.isatty", return_value=False): - self.assertEqual(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {}), "stdin or stdout is not a terminal") + self.assertEqual(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {}), Stop(2, "stdin or stdout is not a terminal")) with ( unittest.mock.patch("sys.stdin.isatty", return_value=True), unittest.mock.patch("sys.stdout.isatty", return_value=True), unittest.mock.patch.multiple(cycle, checkouts=unittest.mock.DEFAULT, trust=unittest.mock.DEFAULT) as mocks, unittest.mock.patch("subprocess.run") as run, ): - self.assertEqual(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {}), "the interrupt ended without the human typing anything") + self.assertEqual(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {}), Stop(2, "the interrupt ended without the human typing anything")) mocks["checkouts"].assert_called_with(root) self.assertEqual(run.call_args.kwargs["cwd"], root) self.assertEqual(run.call_args.args[0][run.call_args.args[0].index("--model") + 1], "m") @@ -289,7 +289,7 @@ class Interrupt(unittest.TestCase): handle.write(json.dumps(human("typed")) + "\n") run.side_effect = type_a_turn - self.assertEqual(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {}), "") + self.assertIsNone(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {})) class Trust(unittest.TestCase): @@ -334,9 +334,9 @@ class Trust(unittest.TestCase): class Parse(unittest.TestCase): def test_yields_only_json_objects(self): - self.assertEqual(cycle.parse('{"type": "user"}'), {"type": "user"}) - self.assertIsNone(cycle.parse("not json")) - self.assertIsNone(cycle.parse("[1, 2]")) + self.assertEqual(transcript.parse('{"type": "user"}'), {"type": "user"}) + self.assertIsNone(transcript.parse("not json")) + self.assertIsNone(transcript.parse("[1, 2]")) class Grounded(unittest.TestCase): @@ -382,7 +382,7 @@ class RunWorker(unittest.TestCase): with tempfile.TemporaryDirectory() as bin: stub = os.path.join(bin, "claude") scripts = { - "": 'print(json.dumps({"type": "result"}))', + None: 'print(json.dumps({"type": "result"}))', "claude exited 0 without a result event": 'print(json.dumps({"type": "assistant", "message": {"content": [{"type": "text", "text": "worked"}]}}))', "claude exited 3": "sys.exit(3)", "claude killed by signal 9": "os.kill(os.getpid(), 9)", @@ -391,7 +391,7 @@ class RunWorker(unittest.TestCase): for failure, script in scripts.items(): pathlib.Path(stub).write_text(f"#!/usr/bin/env python3\nimport json\nimport os\nimport sys\n{script}\n") os.chmod(stub, 0o700) - self.assertEqual(cycle.run_worker(bin, []), failure) + self.assertEqual(worker.run_worker(bin, []), failure and Failure(failure)) class RunCycle(unittest.TestCase): @@ -401,7 +401,7 @@ class RunCycle(unittest.TestCase): pathlib.Path(stub).write_text(STUB_CLAUDE) os.chmod(stub, 0o700) calls, verdicts = os.path.join(home, "calls"), os.path.join(home, "verdicts") - session_id = cycle.uuid.uuid5(cycle.SESSION_NAMESPACE, cycle.session_name(home, paths_from(pathlib.Path(home), {}).code)) + session_id = session.session_for(home, paths_from(pathlib.Path(home), {})).id pathlib.Path(verdicts).write_text("fail continue finished unquoted continue") paths = paths_from(pathlib.Path(home), {"LOOP_CLAUDE_TRANSCRIPTS": os.path.join(home, "archive")}) environment = {"HOME": home, "PATH": f"{home}:{os.environ['PATH']}", "STUB_CALLS": calls, "STUB_VERDICTS": verdicts} @@ -413,9 +413,9 @@ class RunCycle(unittest.TestCase): self.assertEqual(cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}), Stop(2, "stdin or stdout is not a terminal")) self.assertIn(f"transcript: {paths.archive}", "".join(str(call.args[0]) for call in stderr.write.call_args_list)) pathlib.Path(verdicts).write_text("interrupt fail fail fail") - with unittest.mock.patch("sys.stderr"), unittest.mock.patch.object(cycle, "interrupt", return_value=""): + with unittest.mock.patch("sys.stderr"), unittest.mock.patch.object(cycle, "interrupt", return_value=None): self.assertEqual(cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}).code, 1) - with unittest.mock.patch.object(cycle, "session_file", return_value=""): + with unittest.mock.patch.object(cycle, "transcript_file", return_value=""): self.assertEqual(cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}), Stop(1, f"claude left no transcript for session {session_id}")) for plan in ("fail fail fail", "unquoted unquoted unquoted"): pathlib.Path(verdicts).write_text(plan) diff --git a/docs/decisions.md b/docs/decisions.md index 7ad9efb7..2510f3bf 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -38,7 +38,7 @@ ## loop-claude: the section headers stay -2026-09-26, larv-review, declining a prose-pass deletion under `CLAUDE.md` → "Comments and documentation". Serves goal 4. Two seats of the 2026-09-26 panel credit Navigation 8 to `# The transcript file` and its siblings, now in `bin/loop_claude/cycle.py`, indexing it by the file or format each group touches. Valid until the modules the rebuild splits out of `cycle.py` take over that index. +2026-09-26, larv-review, declining a prose-pass deletion under `CLAUDE.md` → "Comments and documentation". Serves goal 4. Two seats of the 2026-09-26 panel credit Navigation 8 to `# ~/.claude.json` and its siblings, now in `bin/loop_claude/cycle.py`, indexing it by the file or format each group touches. Valid until the modules the rebuild splits out of `cycle.py` take over that index. ## vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link diff --git a/todo.md b/todo.md index 1980f442..9cf5980f 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,6 @@ The rebuild lifts every dimension: each item below is one chunk on a worktree based on `origin/rebuild`, its PR into `rebuild`, until the last item merges `rebuild` into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -- **Move the transcript, the session and the worker into their own modules.** `UserEntryKind` names each entry Claude Code writes; a malformed line is skipped; an unreadable transcript is its own error, never "typed nothing"; `session` states the lifecycle once, where the id is made; `run_worker` returns a failure its caller maps, never `""` for success. - **Move the judge, the interrupt, trust and model resolution into their own modules.** The judge is retried alone and checks evidence on every verdict against the rendered transcript; `models` owns the whole resolution, env overrides included, with no sentinel; `trust` names a `projects` entry that is not an object; `input()` at end of file is exit 2. `ask_model` and `interrupt` spell "the human is needed" one way; `replace_json` and `make_private` get one module shared by `models`, `trust` and the archive. - **Move each Claude Code internal `--help` lists beside the module relying on it.** Or `docs/decisions.md` says why `--help` keeps it. - **Archive the raw transcript, deduplicated by content hash, with the verdict beside it, and stop on a failed archive.** Tests first; the changelog line says what the archive now holds. -- 2.52.0 From 72d04227f9f8a46116d0b5a632491d2b6d5f70fb Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 16:27:55 +0200 Subject: [PATCH 013/233] Pin that a non-UTF-8 byte in the worker's stream is skipped --- bin/test_loop_claude_black_box.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/bin/test_loop_claude_black_box.py b/bin/test_loop_claude_black_box.py index 66410f87..56a5ccf8 100644 --- a/bin/test_loop_claude_black_box.py +++ b/bin/test_loop_claude_black_box.py @@ -67,6 +67,8 @@ if role == "worker": if "replace" in step: script = pathlib.Path(os.environ["FAKE_CLAUDE_EDIT"]) script.write_text(script.read_text().replace(*step["replace"])) + sys.stdout.flush() + sys.stdout.buffer.write(step.get("stream", "").encode("latin-1")) print(json.dumps(said)) if step.get("result", True): print(json.dumps({{"type": "result"}})) @@ -319,11 +321,12 @@ class Cycles(unittest.TestCase): self.assertEqual(run.roles(), ["worker", "judge", "judge", "worker"]) self.assertIn("the judge quoted 'never said', nothing in the transcript, for the question: A or B?", run.stderr) - def test_skips_a_malformed_transcript_line(self): + def test_skips_a_malformed_transcript_or_stream_line(self): checkout = Checkout(self) raw = "\xff not UTF-8\nnot JSON\n[1]\n" + json.dumps({"type": "assistant", "message": "not an object"}) + "\n" + json.dumps({"type": "user", "message": None}) + "\n" - run = checkout.run([worker(raw=raw, say="past the noise"), judge()]) + run = checkout.run([worker(raw=raw, say="past the noise", stream="\xff not UTF-8\n"), judge()]) self.assertEqual((run.code, run.roles()), (130, ["worker", "judge", "worker"])) + self.assertIn("past the noise", run.stdout) self.assertIn("past the noise", run.calls[1]["stdin"]) @unittest.skipIf(os.geteuid() == 0, "root reads an unreadable file") -- 2.52.0 From 9659f70efd0f29b7c8ce6c55a1af243de2023c31 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 16:28:43 +0200 Subject: [PATCH 014/233] Decode the worker's stream leniently, name UserEntryKind's members only, and restore the section-headers decision's citation --- bin/loop_claude/cycle.py | 17 +++++++++-------- bin/loop_claude/session.py | 5 ++++- bin/loop_claude/transcript.py | 16 ++++++++-------- bin/loop_claude/worker.py | 2 +- bin/test_loop_claude.py | 2 +- docs/decisions.md | 2 +- 6 files changed, 24 insertions(+), 20 deletions(-) diff --git a/bin/loop_claude/cycle.py b/bin/loop_claude/cycle.py index e3ed6fa7..1f4e368b 100644 --- a/bin/loop_claude/cycle.py +++ b/bin/loop_claude/cycle.py @@ -67,7 +67,7 @@ def run_cycle(root, task, premises, chosen, paths, env): return stop if verdict["finished"]: archive(root, path, f"Task: {task}\n\nVerdict: finished", paths) - delete_session(path) + delete_session(session) return Continue() @@ -254,14 +254,15 @@ def interrupt(root, session_id, chosen, path, question, paths, env): if not (sys.stdin.isatty() and sys.stdout.isatty()): return Stop(2, "stdin or stdout is not a terminal") trust(paths.claude_json, checkouts(root)) - before = read(path) - if isinstance(before, Failure): - return Stop(1, before.reason) + entries = read(path) + if isinstance(entries, Failure): + return Stop(1, entries.reason) + before = human_turns(entries) subprocess.run(["claude", "--model", model_for(env, "LOOP_CLAUDE_WORKER_MODEL", chosen), "--permission-mode", "bypassPermissions", "--resume", str(session_id)], cwd=root) - after = read(path) - if isinstance(after, Failure): - return Stop(1, f"could not tell whether you typed anything: {after.reason}") - if human_turns(after) <= human_turns(before): + entries = read(path) + if isinstance(entries, Failure): + return Stop(1, f"could not tell whether you typed anything: {entries.reason}") + if human_turns(entries) <= before: return Stop(2, "the interrupt ended without the human typing anything") return None diff --git a/bin/loop_claude/session.py b/bin/loop_claude/session.py index f1b8a009..aa44e9bf 100644 --- a/bin/loop_claude/session.py +++ b/bin/loop_claude/session.py @@ -31,7 +31,10 @@ def transcript_file(session): return hit[0] if hit else "" -def delete_session(path): +def delete_session(session): + path = transcript_file(session) + if not path: + return for sibling in glob.glob(glob.escape(path.removesuffix(".jsonl")) + "*"): try: shutil.rmtree(sibling) if os.path.isdir(sibling) else os.remove(sibling) diff --git a/bin/loop_claude/transcript.py b/bin/loop_claude/transcript.py index ed1e4346..ad987f71 100644 --- a/bin/loop_claude/transcript.py +++ b/bin/loop_claude/transcript.py @@ -5,15 +5,15 @@ from loop_claude.outcome import Failure class UserEntryKind(enum.Enum): - """Who wrote a "user" entry: the human wrote HUMAN, Claude Code every other kind; the value is the tell.""" + """Who wrote a "user" entry: the human wrote HUMAN, Claude Code every other kind.""" - COMMAND = "string content starting with <" - CTRL_C = "a text part starting with [Request interrupted" - EMPTY = "no content" - HUMAN = "typed by the human" - META = "isMeta" - NON_TEXT = "a part that is not text, such as a tool result" - SDK_PROMPT = "promptSource sdk: the claude -p prompt" + COMMAND = enum.auto() + CTRL_C = enum.auto() + EMPTY = enum.auto() + HUMAN = enum.auto() + META = enum.auto() + NON_TEXT = enum.auto() + SDK_PROMPT = enum.auto() def read(path): diff --git a/bin/loop_claude/worker.py b/bin/loop_claude/worker.py index 971af16a..c6029849 100644 --- a/bin/loop_claude/worker.py +++ b/bin/loop_claude/worker.py @@ -6,7 +6,7 @@ from loop_claude.transcript import parse, parts, said def run_worker(root, args): try: - proc = subprocess.Popen(["claude", *args], cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, text=True) + proc = subprocess.Popen(["claude", *args], cwd=root, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, stdout=subprocess.PIPE) except OSError as failure: return Failure(f"could not start claude: {failure.strerror}") with proc: diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index cf247d76..1d478b00 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -262,7 +262,7 @@ class DeleteTranscriptFiles(unittest.TestCase): pathlib.Path(root, f"{SESSION_ID}.orphaned-1-ab.jsonl").write_text("{}\n") located = session.Session(uuid.UUID(SESSION_ID), "A name", projects) self.assertEqual(session.transcript_file(located), transcript) - session.delete_session(transcript) + session.delete_session(located) self.assertEqual(os.listdir(root), []) self.assertEqual(session.transcript_file(located), "") diff --git a/docs/decisions.md b/docs/decisions.md index 2510f3bf..4ba7c53e 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -38,7 +38,7 @@ ## loop-claude: the section headers stay -2026-09-26, larv-review, declining a prose-pass deletion under `CLAUDE.md` → "Comments and documentation". Serves goal 4. Two seats of the 2026-09-26 panel credit Navigation 8 to `# ~/.claude.json` and its siblings, now in `bin/loop_claude/cycle.py`, indexing it by the file or format each group touches. Valid until the modules the rebuild splits out of `cycle.py` take over that index. +2026-09-26, larv-review, declining a prose-pass deletion under `CLAUDE.md` → "Comments and documentation". Serves goal 4. Two seats of the 2026-09-26 panel credit Navigation 8 to `# The transcript file` and its siblings, indexing what is now `bin/loop_claude/cycle.py` by the file or format each group touches. Valid until the modules the rebuild splits out of `cycle.py` take over that index; a header stays in it until its group moves. ## vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link -- 2.52.0 From b99906495eb66cb2cf27b371a1a3f7ce7ea2e5c5 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 16:29:16 +0200 Subject: [PATCH 015/233] Name the section headers the decision still covers --- docs/decisions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/decisions.md b/docs/decisions.md index 4ba7c53e..556e92a5 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -38,7 +38,7 @@ ## loop-claude: the section headers stay -2026-09-26, larv-review, declining a prose-pass deletion under `CLAUDE.md` → "Comments and documentation". Serves goal 4. Two seats of the 2026-09-26 panel credit Navigation 8 to `# The transcript file` and its siblings, indexing what is now `bin/loop_claude/cycle.py` by the file or format each group touches. Valid until the modules the rebuild splits out of `cycle.py` take over that index; a header stays in it until its group moves. +2026-09-26, larv-review, declining a prose-pass deletion under `CLAUDE.md` → "Comments and documentation". Serves goal 4. Two seats of the 2026-09-26 panel credit Navigation 8 to the headers in `bin/loop_claude/cycle.py`, which index it by the file or format each group touches. Valid while `cycle.py` holds more than one group; a header leaves with its group, as `# The transcript file` did into `transcript.py`. ## vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link -- 2.52.0 From 07b08c6a574510277884cb244910074dccfa055d Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 16:30:25 +0200 Subject: [PATCH 016/233] Record retrying a claude that cannot start, and date the headers' citation --- AGENTS.md | 1 + docs/decisions.md | 6 +++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 9f231cdd..ddcdcb39 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -26,3 +26,4 @@ Decisions live in `docs/decisions.md`: - loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop - loop-claude: the rebuild keeps main's `--reloaded` state - rebuild: a chunk into `rebuild` takes no comprehension scoring run +- loop-claude: a `claude` that cannot start is a failed worker run, retried diff --git a/docs/decisions.md b/docs/decisions.md index 556e92a5..2ca8c5a4 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -38,7 +38,7 @@ ## loop-claude: the section headers stay -2026-09-26, larv-review, declining a prose-pass deletion under `CLAUDE.md` → "Comments and documentation". Serves goal 4. Two seats of the 2026-09-26 panel credit Navigation 8 to the headers in `bin/loop_claude/cycle.py`, which index it by the file or format each group touches. Valid while `cycle.py` holds more than one group; a header leaves with its group, as `# The transcript file` did into `transcript.py`. +2026-09-26, larv-review, declining a prose-pass deletion under `CLAUDE.md` → "Comments and documentation". Serves goal 4. Two seats of the 2026-09-26 panel credit Navigation 8 to the headers in what is now `bin/loop_claude/cycle.py`, which index it by the file or format each group touches. Valid while `cycle.py` holds more than one group; a header leaves with its group, as `# The transcript file` did into `transcript.py`. ## vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link @@ -87,3 +87,7 @@ ## rebuild: a chunk into `rebuild` takes no comprehension scoring run 2026-09-28, lilleman, confirming larv-review's reading of the rebuild decision above. Serves goal 4. The floor and its ratchet gate `rebuild` into main, scored by the plan's last item; the chunks before it pass through half-moved states a per-chunk run would block. Valid until the rebuild merges. + +## 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 auto-updater replaces the `claude` binary in place, so a start can fail for a moment; exiting would end an unattended loop on it. Valid while Claude Code updates its binary in place. -- 2.52.0 From 8b5569519c2c7e55c65115c602b44f9f346d200e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 16:30:38 +0200 Subject: [PATCH 017/233] State how Claude Code updates its binary in the retry decision --- docs/decisions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/decisions.md b/docs/decisions.md index 2ca8c5a4..b99a1749 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -90,4 +90,4 @@ ## 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 auto-updater replaces the `claude` binary in place, so a start can fail for a moment; exiting would end an unattended loop on it. Valid while Claude Code updates its binary in place. +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. -- 2.52.0 From a1c5e8a16b05a95cb6e224a55fd10b0e5d3d4843 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 16:37:55 +0200 Subject: [PATCH 018/233] Pin evidence on every verdict, a named non-object trust entry, one spelling of the human being needed, and a claude the judge or interrupt cannot start --- bin/test_loop_claude.py | 92 +++++++++++++++---------------- bin/test_loop_claude_black_box.py | 49 ++++++++++++---- 2 files changed, 83 insertions(+), 58 deletions(-) diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 1d478b00..a25565ea 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -15,7 +15,7 @@ import uuid sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -from loop_claude import checkout, cycle, main, premises, reload, session, transcript, worker +from loop_claude import checkout, cycle, interrupt, judge, main, models, premises, reload, session, transcript, trust, worker from loop_claude.outcome import Continue, Failure, Retry, Stop from loop_claude.paths import paths_from @@ -24,6 +24,7 @@ LAUNCHER = pathlib.Path(__file__).resolve().with_name("loop-claude") PATHS = paths_from(pathlib.Path("/h"), {}) SESSION_ID = str(getattr(uuid, "uuid7", uuid.uuid4)()) SESSION = session.Session(uuid.UUID(SESSION_ID), "A name", PATHS.projects) +OPUS = models.Models("claude-opus-5-5", "claude-opus-5-5") def assistant(*parts): @@ -146,10 +147,6 @@ class WorkerArgs(unittest.TestCase): self.assertNotIn("--name", args) self.assertNotIn("paint the fence", args[1]) - def test_the_project_model_runs_unless_the_environment_names_one(self): - self.assertEqual(cycle.model_for({}, "LOOP_CLAUDE_WORKER_MODEL", "claude-opus-5-5"), "claude-opus-5-5") - self.assertEqual(cycle.model_for({"LOOP_CLAUDE_WORKER_MODEL": "claude-fable-5-1"}, "LOOP_CLAUDE_WORKER_MODEL", "claude-opus-5-5"), "claude-fable-5-1") - class ProjectModel(unittest.TestCase): def test_asks_once_per_project_from_the_newest_catalog_and_saves_the_answer(self): @@ -161,19 +158,19 @@ class ProjectModel(unittest.TestCase): for name, fetched, ids in (("old.json", 1, ["claude-opus-5"]), ("new.json", 2, ["claude-opus-5-5", "claude-sonnet-5"])): catalog.joinpath(name).write_text(json.dumps({"fetchedAt": fetched, "catalog": {"config": {"models": [{"id": id, "name": id.upper()} for id in ids]}}})) with unittest.mock.patch("sys.stdin.isatty", return_value=False): - stop = cycle.project_model("/srv/a", paths, {}) + stop = models.project_models("/srv/a", paths, {}) self.assertEqual(stop.code, 2) self.assertIn(f'merge {{"srv/a": ""}} into {saved}', stop.reason) self.assertFalse(saved.exists()) with unittest.mock.patch("sys.stdin.isatty", return_value=False): - self.assertEqual(cycle.project_model("/srv/a", paths, {"LOOP_CLAUDE_JUDGE_MODEL": "j", "LOOP_CLAUDE_WORKER_MODEL": "w"}), "") - self.assertEqual(cycle.project_model("/srv/a", paths, {"LOOP_CLAUDE_JUDGE_MODEL": "j"}).code, 2) + self.assertEqual(models.project_models("/srv/a", paths, {"LOOP_CLAUDE_JUDGE_MODEL": "j", "LOOP_CLAUDE_WORKER_MODEL": "w"}), models.Models("j", "w")) + self.assertEqual(models.project_models("/srv/a", paths, {"LOOP_CLAUDE_JUDGE_MODEL": "j"}).code, 2) with ( unittest.mock.patch("sys.stdin.isatty", return_value=True), unittest.mock.patch("sys.stdout.isatty", return_value=True), unittest.mock.patch("builtins.input", side_effect=["", "3", "2"]) as typed, ): - self.assertEqual(cycle.project_model("/srv/a", paths, {}), "claude-sonnet-5") + self.assertEqual(models.project_models("/srv/a", paths, {}), models.Models("claude-sonnet-5", "claude-sonnet-5")) self.assertEqual(typed.call_count, 3) self.assertIn("2. CLAUDE-SONNET-5 (claude-sonnet-5)", sys.stderr.getvalue()) self.assertIn("pick 1 to 2", sys.stderr.getvalue()) @@ -185,33 +182,34 @@ class ProjectModel(unittest.TestCase): saved.write_text(json.dumps({**json.loads(saved.read_text()), "srv/d": "haiku"})) return "opus[1m]" typed.side_effect = saved_elsewhere_while_asking - self.assertEqual(cycle.project_model("/srv/b", paths, {}), "opus[1m]") - self.assertEqual(cycle.project_model("/srv/a", paths, {}), "claude-sonnet-5") + self.assertEqual(models.project_models("/srv/b", paths, {}), models.Models("opus[1m]", "opus[1m]")) + self.assertEqual(models.project_models("/srv/a", paths, {}), models.Models("claude-sonnet-5", "claude-sonnet-5")) + self.assertEqual(models.project_models("/srv/a", paths, {"LOOP_CLAUDE_WORKER_MODEL": "w"}), models.Models("claude-sonnet-5", "w")) self.assertEqual(typed.call_count, 4) typed.side_effect = EOFError - self.assertEqual(cycle.project_model("/srv/c", paths, {}), Stop(2, "no model picked")) + self.assertEqual(models.project_models("/srv/c", paths, {}), Stop(2, "the human is needed to pick srv/c's model, but the input ended")) typed.side_effect = ["sonnet"] with unittest.mock.patch("os.replace", side_effect=OSError(errno.EACCES, "Permission denied")): - self.assertEqual(cycle.project_model("/srv/c", paths, {}), Stop(1, f"could not save the model in {saved}: Permission denied")) + self.assertEqual(models.project_models("/srv/c", paths, {}), Stop(1, f"could not save the model in {saved}: Permission denied")) self.assertEqual(json.loads(saved.read_text()), {"srv/a": "claude-sonnet-5", "srv/b": "opus[1m]", "srv/d": "haiku"}) self.assertEqual(stat.S_IMODE(saved.stat().st_mode), 0o640) self.assertEqual(sorted(os.listdir(saved.parent)), ["cache", "loop-claude-models.json"]) for shape in ({"fetchedAt": 3, "catalog": {"config": {"models": []}}}, {"fetchedAt": 3, "catalog": None}, {"fetchedAt": 3, "catalog": {"config": []}}, {"fetchedAt": 3, "catalog": {"config": {"models": "x"}}}): catalog.joinpath("new.json").write_text(json.dumps(shape)) with self.subTest(shape=shape): - self.assertEqual(cycle.catalog(catalog), []) + self.assertEqual(models.catalog(catalog), []) with ( unittest.mock.patch("sys.stdin.isatty", return_value=True), unittest.mock.patch("sys.stdout.isatty", return_value=True), unittest.mock.patch("builtins.input", side_effect=["1"]) as typed, ): - self.assertEqual(cycle.project_model("/srv/e", paths, {}), "1") + self.assertEqual(models.project_models("/srv/e", paths, {}), models.Models("1", "1")) self.assertEqual(typed.call_args.args[0], "A name claude --model takes: ") self.assertIn("no model catalog cached", sys.stderr.getvalue()) for broken in ("{", "[]", '{"srv/a": 1}'): saved.write_text(broken) with self.subTest(broken=broken): - stop = cycle.project_model("/srv/a", paths, {}) + stop = models.project_models("/srv/a", paths, {}) self.assertEqual(stop.code, 1) self.assertTrue(stop.reason.startswith(f"could not read {saved}: ")) self.assertEqual(saved.read_text(), broken) @@ -219,10 +217,10 @@ class ProjectModel(unittest.TestCase): class JudgePrompt(unittest.TestCase): def test_hands_the_judge_the_tail_of_a_long_transcript(self): - prompt = cycle.judge_prompt("task", "## Goals\n1. g", "early " * 20000 + "LATE") + prompt = judge.judge_prompt("task", "## Goals\n1. g", "early " * 20000 + "LATE") self.assertIn("LATE", prompt) self.assertLess(prompt.count("early"), 20000) - self.assertTrue(prompt.endswith(cycle.JUDGE_RULES)) + self.assertTrue(prompt.endswith(judge.JUDGE_RULES)) class Archive(unittest.TestCase): @@ -273,14 +271,14 @@ class Interrupt(unittest.TestCase): transcript = os.path.join(root, "session.jsonl") pathlib.Path(transcript).write_text("{}\n") with unittest.mock.patch("sys.stdin.isatty", return_value=False): - self.assertEqual(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {}), Stop(2, "stdin or stdout is not a terminal")) + self.assertEqual(interrupt.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {})), Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal")) with ( unittest.mock.patch("sys.stdin.isatty", return_value=True), unittest.mock.patch("sys.stdout.isatty", return_value=True), - unittest.mock.patch.multiple(cycle, checkouts=unittest.mock.DEFAULT, trust=unittest.mock.DEFAULT) as mocks, + unittest.mock.patch.multiple(interrupt, checkouts=unittest.mock.DEFAULT, trust=unittest.mock.DEFAULT) as mocks, unittest.mock.patch("subprocess.run") as run, ): - self.assertEqual(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {}), Stop(2, "the interrupt ended without the human typing anything")) + self.assertEqual(interrupt.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {})), Stop(2, "the human is needed to answer the question above, but the interrupt ended without you typing anything")) mocks["checkouts"].assert_called_with(root) self.assertEqual(run.call_args.kwargs["cwd"], root) self.assertEqual(run.call_args.args[0][run.call_args.args[0].index("--model") + 1], "m") @@ -289,7 +287,7 @@ class Interrupt(unittest.TestCase): handle.write(json.dumps(human("typed")) + "\n") run.side_effect = type_a_turn - self.assertIsNone(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {})) + self.assertIsNone(interrupt.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}))) class Trust(unittest.TestCase): @@ -297,27 +295,27 @@ class Trust(unittest.TestCase): with tempfile.TemporaryDirectory() as home, umask(0o022): config = pathlib.Path(home, ".claude.json") with contextlib.redirect_stderr(io.StringIO()) as err: - cycle.trust(config, ["/a"]) + trust.trust(config, ["/a"]) self.assertEqual(err.getvalue(), f"could not read {config}: No such file or directory\n") config.write_text("{") with contextlib.redirect_stderr(io.StringIO()) as err: - cycle.trust(config, ["/a"]) + trust.trust(config, ["/a"]) self.assertIn(f"could not read {config}: ", err.getvalue()) - for shape in ([], {"projects": []}, {"projects": {"/a": 1}}): + for shape, said in (([], 'not an object whose "projects" is an object'), ({"projects": []}, 'not an object whose "projects" is an object'), ({"projects": {"/a": 1}}, 'projects["/a"] is not an object')): config.write_text(json.dumps(shape)) with contextlib.redirect_stderr(io.StringIO()) as err: - cycle.trust(config, ["/a"]) - self.assertEqual(err.getvalue(), f"could not read {config}: not an object whose \"projects\" maps paths to objects\n") + trust.trust(config, ["/a"]) + self.assertEqual(err.getvalue(), f"could not read {config}: {said}\n") self.assertEqual(json.loads(config.read_text()), shape) data = {"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True, "kept": 2}}} config.write_text(json.dumps(data)) config.chmod(0o600) with contextlib.redirect_stderr(io.StringIO()) as err: - cycle.trust(config, ["/a"]) + trust.trust(config, ["/a"]) self.assertEqual(err.getvalue(), "") self.assertEqual(json.loads(config.read_text()), data) with contextlib.redirect_stderr(io.StringIO()) as err: - cycle.trust(config, ["/a", "/b"]) + trust.trust(config, ["/a", "/b"]) self.assertEqual(err.getvalue(), "trusted for the interrupt: /b\n") data["projects"]["/b"] = {"hasTrustDialogAccepted": True} self.assertEqual(json.loads(config.read_text()), data) @@ -325,7 +323,7 @@ class Trust(unittest.TestCase): contextlib.redirect_stderr(io.StringIO()) as err, unittest.mock.patch("os.replace", side_effect=OSError(errno.EACCES, "Permission denied")), ): - cycle.trust(config, ["/c"]) + trust.trust(config, ["/c"]) self.assertEqual(err.getvalue(), f"could not write {config}: Permission denied\n") self.assertEqual(json.loads(config.read_text()), data) self.assertEqual(stat.S_IMODE(config.stat().st_mode), 0o600) @@ -340,19 +338,21 @@ class Parse(unittest.TestCase): class Grounded(unittest.TestCase): - def test_an_interrupt_must_quote_the_transcript(self): - self.assertTrue(cycle.grounded({"interrupt": False, "evidence": ""}, "anything")) - self.assertTrue(cycle.grounded({"interrupt": True, "evidence": "Needs you: x"}, "so.\n\nNeeds you: x\n")) - self.assertFalse(cycle.grounded({"interrupt": True, "evidence": "invented"}, "the transcript")) - self.assertFalse(cycle.grounded({"interrupt": True, "evidence": ""}, "the transcript")) - self.assertFalse(cycle.grounded({"interrupt": True, "evidence": " "}, "the transcript")) + def test_every_verdict_must_quote_the_transcript(self): + for interrupting in (False, True): + self.assertTrue(judge.grounded({"interrupt": interrupting, "evidence": "Needs you: x"}, "so.\n\nNeeds you: x\n")) + self.assertFalse(judge.grounded({"interrupt": interrupting, "evidence": "invented"}, "the transcript")) + self.assertFalse(judge.grounded({"interrupt": interrupting, "evidence": ""}, "the transcript")) + self.assertFalse(judge.grounded({"interrupt": interrupting, "evidence": " "}, "the transcript")) class Verdict(unittest.TestCase): def test_needs_every_field_the_schema_requires(self): - self.assertTrue(cycle.complete({"interrupt": False, "evidence": "", "finished": True, "question": ""})) - self.assertFalse(cycle.complete({"interrupt": False})) - self.assertFalse(cycle.complete(None)) + self.assertTrue(judge.complete({"interrupt": False, "evidence": "", "finished": True, "question": ""})) + self.assertFalse(judge.complete({"interrupt": "no", "evidence": "", "finished": True, "question": ""})) + self.assertFalse(judge.complete({"interrupt": False, "evidence": None, "finished": True, "question": ""})) + self.assertFalse(judge.complete({"interrupt": False})) + self.assertFalse(judge.complete(None)) STUB_CLAUDE = """#!/usr/bin/env python3 @@ -366,7 +366,7 @@ if "--json-schema" in args: if plan[0] == "fail": sys.exit(1) interrupt = plan[0] in ("interrupt", "unquoted") - print(json.dumps({"structured_output": {"interrupt": interrupt, "evidence": {"interrupt": "worked", "unquoted": "invented"}.get(plan[0], ""), "finished": plan[0] == "finished", "question": "q?" if interrupt else ""}})) + print(json.dumps({"structured_output": {"interrupt": interrupt, "evidence": {"interrupt": "worked", "unquoted": "invented"}.get(plan[0], "worked"), "finished": plan[0] == "finished", "question": "q?" if interrupt else ""}})) else: flag = "--session-id" if "--session-id" in args else "--resume" folder = os.path.expanduser("~/.claude/projects/p") @@ -407,19 +407,19 @@ class RunCycle(unittest.TestCase): environment = {"HOME": home, "PATH": f"{home}:{os.environ['PATH']}", "STUB_CALLS": calls, "STUB_VERDICTS": verdicts} with unittest.mock.patch.dict(os.environ, environment), unittest.mock.patch("time.sleep") as sleep, unittest.mock.patch("sys.stdin.isatty", return_value=False): for _ in range(3): - self.assertEqual(cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}), Continue()) + self.assertEqual(cycle.run_cycle(home, "task", "premises", OPUS, paths), Continue()) pathlib.Path(verdicts).write_text("interrupt") with unittest.mock.patch("sys.stderr") as stderr: - self.assertEqual(cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}), Stop(2, "stdin or stdout is not a terminal")) + self.assertEqual(cycle.run_cycle(home, "task", "premises", OPUS, paths), Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal")) self.assertIn(f"transcript: {paths.archive}", "".join(str(call.args[0]) for call in stderr.write.call_args_list)) pathlib.Path(verdicts).write_text("interrupt fail fail fail") with unittest.mock.patch("sys.stderr"), unittest.mock.patch.object(cycle, "interrupt", return_value=None): - self.assertEqual(cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}).code, 1) + self.assertEqual(cycle.run_cycle(home, "task", "premises", OPUS, paths).code, 1) with unittest.mock.patch.object(cycle, "transcript_file", return_value=""): - self.assertEqual(cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}), Stop(1, f"claude left no transcript for session {session_id}")) + self.assertEqual(cycle.run_cycle(home, "task", "premises", OPUS, paths), Stop(1, f"claude left no transcript for session {session_id}")) for plan in ("fail fail fail", "unquoted unquoted unquoted"): pathlib.Path(verdicts).write_text(plan) - stop = cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}) + stop = cycle.run_cycle(home, "task", "premises", OPUS, paths) self.assertEqual(stop.code, 1) self.assertTrue(stop.reason.startswith("the judge ")) if plan.startswith("unquoted"): @@ -468,7 +468,7 @@ class RunLoop(unittest.TestCase): self.assertEqual(main.loop_state([main.RELOAD_FLAG, *handed], CWD), Stop(1, f"the reload cannot read the loop's state from {handed}; rerun loop-claude ")) def test_resumes_the_root_and_counters_a_reload_handed_over(self): - patches = [unittest.mock.patch.object(main, name) for name in ("checkout_root", "read_premises", "reload_if_edited", "run_cycle", "project_model")] + patches = [unittest.mock.patch.object(main, name) for name in ("checkout_root", "read_premises", "reload_if_edited", "run_cycle", "project_models")] stopped = Stop(1, "stopped") with contextlib.ExitStack() as stack: mocks = [stack.enter_context(patch) for patch in patches] diff --git a/bin/test_loop_claude_black_box.py b/bin/test_loop_claude_black_box.py index 56a5ccf8..6f26acf5 100644 --- a/bin/test_loop_claude_black_box.py +++ b/bin/test_loop_claude_black_box.py @@ -81,6 +81,8 @@ elif "type" in step: append({{"type": "user", "message": {{"content": step["type"]}}}}) if step.get("unreadable"): transcript().chmod(0) +if step.get("vanish"): + os.remove(__file__) sys.exit(step.get("exit", 0)) """ @@ -103,7 +105,7 @@ def worker(**step): return {"role": "worker", **step} -def judge(interrupt=False, finished=False, evidence="", question="", **step): +def judge(interrupt=False, finished=False, evidence="working", question="", **step): verdict = {"evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question} return {"role": "judge", "verdict": verdict, **step} @@ -271,8 +273,8 @@ class Cycles(unittest.TestCase): def test_resumes_the_session_while_unfinished_and_starts_it_fresh_after_finishing(self): checkout = Checkout(self) run = checkout.run([ - worker(say="started"), judge(), - worker(say="landed-it"), judge(finished=True), + worker(say="started"), judge(evidence="started"), + worker(say="landed-it"), judge(finished=True, evidence="landed-it"), worker(say="next chunk"), ]) self.assertEqual(run.code, 130) @@ -314,17 +316,32 @@ class Cycles(unittest.TestCase): self.assertIn("retrying the judge in a minute: judge down", run.stderr) self.assertEqual(run.stderr.strip().splitlines()[-1], "the judge failed three times running: the judge returned no verdict") - def test_retries_the_judge_alone_when_its_interrupt_quotes_nothing_in_the_transcript(self): + def test_retries_the_judge_alone_when_its_verdict_quotes_nothing_in_the_transcript(self): checkout = Checkout(self) - run = checkout.run([worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="never said", question="A or B?"), judge()]) + run = checkout.run([ + worker(say="Shall I use A or B?"), + judge(interrupt=True, evidence="never said", question="A or B?"), + judge(finished=True, evidence=""), + judge(evidence="A or B"), + worker(), + ]) self.assertEqual(run.code, 130) - self.assertEqual(run.roles(), ["worker", "judge", "judge", "worker"]) + self.assertEqual(run.roles(), ["worker", "judge", "judge", "judge", "worker", "judge"]) + self.assertEqual(run.sleeps, [60, 60]) self.assertIn("the judge quoted 'never said', nothing in the transcript, for the question: A or B?", run.stderr) + self.assertIn("retrying the judge in a minute: the judge quoted '', nothing in the transcript\n", run.stderr) + + def test_retries_a_judge_claude_cannot_start(self): + checkout = Checkout(self) + run = checkout.run([worker(vanish=True)]) + self.assertEqual((run.code, run.roles()), (1, ["worker"])) + self.assertEqual(run.sleeps, [60, 60]) + self.assertEqual(run.stderr.strip().splitlines()[-1], "the judge failed three times running: could not start claude: No such file or directory") def test_skips_a_malformed_transcript_or_stream_line(self): checkout = Checkout(self) raw = "\xff not UTF-8\nnot JSON\n[1]\n" + json.dumps({"type": "assistant", "message": "not an object"}) + "\n" + json.dumps({"type": "user", "message": None}) + "\n" - run = checkout.run([worker(raw=raw, say="past the noise", stream="\xff not UTF-8\n"), judge()]) + run = checkout.run([worker(raw=raw, say="past the noise", stream="\xff not UTF-8\n"), judge(evidence="past the noise")]) self.assertEqual((run.code, run.roles()), (130, ["worker", "judge", "worker"])) self.assertIn("past the noise", run.stdout) self.assertIn("past the noise", run.calls[1]["stdin"]) @@ -360,13 +377,13 @@ class Interrupt(unittest.TestCase): steps = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")] run = checkout.run(steps) self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"])) - self.assertEqual(run.stderr.strip().splitlines()[-2:], ["A or B?", "stdin or stdout is not a terminal"]) + self.assertEqual(run.stderr.strip().splitlines()[-2:], ["A or B?", "the human is needed to answer the question above, but stdin or stdout is not a terminal"]) self.assertTrue(checkout.archived()) session = argument(run.calls[0], "--session-id") run = checkout.run(steps, terminal_input="", stdout_on_terminal=False) self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"])) self.assertEqual(argument(run.calls[0], "--resume"), session) - self.assertEqual(run.stderr.strip().splitlines()[-1], "stdin or stdout is not a terminal") + self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to answer the question above, but stdin or stdout is not a terminal") def test_hands_the_terminal_over_and_exits_2_when_nothing_is_typed(self): checkout = Checkout(self) @@ -375,7 +392,7 @@ class Interrupt(unittest.TestCase): checkout.claude_json().write_text(json.dumps({"other": 1, "projects": {str(checkout.root): {"kept": True}}})) checkout.claude_json().chmod(0o644) asked = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")] - run = checkout.run([*asked, interrupt(type="B"), judge(), worker()], terminal_input="") + run = checkout.run([*asked, interrupt(type="B"), judge(evidence="B"), worker()], terminal_input="") self.assertEqual(run.code, 130) self.assertEqual(run.roles(), ["worker", "judge", "interrupt", "judge", "worker", "judge"]) handed = run.calls[2]["argv"] @@ -393,7 +410,11 @@ class Interrupt(unittest.TestCase): transcript.unlink() run = checkout.run([*asked, interrupt()], terminal_input="") self.assertEqual((run.code, run.roles()), (2, ["worker", "judge", "interrupt"])) - self.assertEqual(run.stderr.strip().splitlines()[-1], "the interrupt ended without the human typing anything") + self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to answer the question above, but the interrupt ended without you typing anything") + + run = checkout.run([worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?", vanish=True)], terminal_input="") + self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"])) + self.assertEqual(run.stderr.strip().splitlines()[-1], "could not start claude: No such file or directory") @unittest.skipIf(os.geteuid() == 0, "root reads an unreadable file") def test_exits_1_when_the_transcript_cannot_be_read_after_the_interrupt(self): @@ -416,7 +437,11 @@ class Models(unittest.TestCase): self.catalog(checkout) run = checkout.run([worker()]) self.assertEqual((run.code, run.calls), (2, [])) - self.assertIn(f"proj has no model in {checkout.models_file()}", run.stderr) + self.assertEqual(run.stderr.strip(), f'the human is needed to pick proj\'s model, or merge {{"proj": ""}} into {checkout.models_file()}, but stdin or stdout is not a terminal') + + run = checkout.run([worker()], terminal_input="\x04") + self.assertEqual((run.code, run.calls), (2, [])) + self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to pick proj's model, but the input ended") run = checkout.run([worker(), judge()], terminal_input="9\n2\n") self.assertEqual(run.code, 130) -- 2.52.0 From 5e773f8460aa543d9c27cfe18ccefd4e61900b92 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 16:42:32 +0200 Subject: [PATCH 019/233] Keep the host's claude off the black-box tests' PATH --- bin/test_loop_claude_black_box.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/bin/test_loop_claude_black_box.py b/bin/test_loop_claude_black_box.py index 6f26acf5..67e52a00 100644 --- a/bin/test_loop_claude_black_box.py +++ b/bin/test_loop_claude_black_box.py @@ -149,6 +149,7 @@ class Checkout: fake.mkdir() (fake / "claude").write_text(FAKE_CLAUDE.format(python=sys.executable)) (fake / "claude").chmod(0o755) + (fake / "git").symlink_to(shutil.which("git")) site = self.temp / "site" site.mkdir() (site / "sitecustomize.py").write_text(SITECUSTOMIZE) @@ -161,7 +162,7 @@ class Checkout: "LOOP_CLAUDE_JUDGE_MODEL": "judge-model", "LOOP_CLAUDE_WORKER_MODEL": "worker-model", "LOOP_TEST_LOG": str(self.temp / "starts.jsonl"), - "PATH": f"{fake}{os.pathsep}{os.environ['PATH']}", + "PATH": str(fake), "PYTHONPATH": str(site), }) self.git("init", "--quiet") @@ -355,10 +356,7 @@ class Cycles(unittest.TestCase): def test_retries_a_worker_claude_cannot_start(self): checkout = Checkout(self) - only_git = checkout.temp / "only-git" - only_git.mkdir() - (only_git / "git").symlink_to(shutil.which("git")) - checkout.env["PATH"] = str(only_git) + (checkout.temp / "fake-bin" / "claude").unlink() run = checkout.run([]) self.assertEqual((run.code, run.calls), (1, [])) self.assertEqual(run.sleeps, [60, 60]) -- 2.52.0 From b0afcfab57214362146235a9f81cdcfa1a4c4512 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 16:42:32 +0200 Subject: [PATCH 020/233] Move the judge, the interrupt, trust and model resolution into their own modules --- AGENTS.md | 1 - CHANGELOG.md | 4 +- bin/loop_claude/cycle.py | 248 ++------------------------------ bin/loop_claude/human.py | 13 ++ bin/loop_claude/interrupt.py | 31 ++++ bin/loop_claude/judge.py | 95 ++++++++++++ bin/loop_claude/main.py | 22 +-- bin/loop_claude/models.py | 98 +++++++++++++ bin/loop_claude/private_file.py | 25 ++++ bin/loop_claude/trust.py | 29 ++++ docs/decisions.md | 4 - todo.md | 1 - 12 files changed, 315 insertions(+), 256 deletions(-) create mode 100644 bin/loop_claude/human.py create mode 100644 bin/loop_claude/interrupt.py create mode 100644 bin/loop_claude/judge.py create mode 100644 bin/loop_claude/models.py create mode 100644 bin/loop_claude/private_file.py create mode 100644 bin/loop_claude/trust.py diff --git a/AGENTS.md b/AGENTS.md index ddcdcb39..4f7aa2eb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,7 +9,6 @@ Decisions live in `docs/decisions.md`: - loop-claude: one session per project, at a fixed id - loop-claude: the trust file is rewritten before an interrupt - loop-claude: every worktree of the checkout is trusted before an interrupt -- loop-claude: a wrong-shape trust file gets one message, naming the shape - bin/: the Python floor is README's Install prerequisite - bin/: host python, no container - comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it diff --git a/CHANGELOG.md b/CHANGELOG.md index 360bafc3..c2b87599 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ - First release: `README.md` states what the checkout holds and needs, `loop-claude --help` what `loop-claude` does. - `settings.json`, the agents and the status line run on any machine unedited; the status line shows reset times in the machine's own time zone. - `loop-claude`'s no-premises exit names what is wrong: `README.md` unopenable or not UTF-8, a `## Goals` or `## Audience` heading missing or repeated, or nothing under one. -- `loop-claude` says why when it cannot read or write `~/.claude.json` before an interrupt, and the interrupt then lands in Claude Code's trust dialog. +- `loop-claude` says why when it cannot read or write `~/.claude.json` before an interrupt, naming a `projects` entry that is not an object, and the interrupt then lands in Claude Code's trust dialog. - `loop-claude` skips a transcript line it cannot parse, exits 1 naming a transcript it cannot read, and counts a `claude` it cannot start as a failed worker run. +- `loop-claude`'s judge quotes the transcript for every verdict, and a verdict quoting nothing, or a `claude` the judge cannot start, is a failed judge run; a `claude` that cannot start for an interrupt exits 1. +- `loop-claude`'s exit-2 message says what the human is needed for. - `loop-claude` keeps the mode of `~/.claude.json` and of its models file when it rewrites them, and creates the models file 0600. diff --git a/bin/loop_claude/cycle.py b/bin/loop_claude/cycle.py index 1f4e368b..b9d11697 100644 --- a/bin/loop_claude/cycle.py +++ b/bin/loop_claude/cycle.py @@ -1,53 +1,21 @@ -import itertools -import json import os -import subprocess import sys import time -from loop_claude.checkout import checkouts, project_name +from loop_claude.checkout import project_name +from loop_claude.interrupt import interrupt +from loop_claude.judge import judge from loop_claude.outcome import Continue, Failure, Retry, Stop +from loop_claude.private_file import make_private from loop_claude.session import delete_session, session_for, transcript_file -from loop_claude.strike import strike -from loop_claude.transcript import human_turns, parse, read, render +from loop_claude.transcript import read, render from loop_claude.worker import run_worker, worker_args -JUDGE_RULES = ( - "Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n" - "- the agent asks the human anything, seeks approval, or says a decision is the human's\n" - "- it carried on under an assumption that decides the deliverable and that the human could " - "reasonably reject; a caveat about transient state it then handled is not one\n" - "- it is blocked on something only the human can supply: a credential, a version bump, a release " - "ready to cut, a choice outside the repo\n" - "- it flags that the goals, the plan or the task itself is unclear, missing or in need of change\n" - "- it chose between alternatives the README text does not discriminate between - it does not " - "rule the rejected one out - and the choice materially changes the deliverable\n" - "interrupt=false otherwise. Bookkeeping the agent settled silently - what to document, wording, " - "where a note goes - is not on its own a reason to interrupt. The human may have replied inside the transcript, on a [human] line: judge only what " - "is still open, never a question they already answered there.\n" - "Where the agent asked or flagged something itself, the question is that one, in the agent's own " - "wording; never construct another from facts it stated.\n" - "finished=true when the chunk is complete: merged, or nothing remains that the agent could do on " - "its own. finished=false when work remains that a further run can continue: an open PR, a review " - "not yet run, CI not yet reported." -) -JUDGE_SCHEMA = { - "properties": { - "evidence": {"description": "A verbatim quote of the transcript line that triggers the interrupt. Empty when interrupt is false.", "type": "string"}, - "finished": {"type": "boolean"}, - "interrupt": {"type": "boolean"}, - "question": {"description": "The single question to put to the human. Empty when interrupt is false.", "type": "string"}, - }, - "required": ["evidence", "finished", "interrupt", "question"], - "type": "object", -} - - -def run_cycle(root, task, premises, chosen, paths, env): +def run_cycle(root, task, premises, models, paths): session = session_for(root, paths) resuming = bool(transcript_file(session)) - if failure := run_worker(root, worker_args(task, session, model_for(env, "LOOP_CLAUDE_WORKER_MODEL", chosen), resuming)): + if failure := run_worker(root, worker_args(task, session, models.worker, resuming)): return Retry(failure.reason) path = transcript_file(session) if not path: @@ -57,13 +25,13 @@ def run_cycle(root, task, premises, chosen, paths, env): entries = read(path) if isinstance(entries, Failure): return Stop(1, entries.reason) - verdict = judge(root, task, premises, render(entries), chosen, env) + verdict = judge(root, task, premises, render(entries), models.judge) if isinstance(verdict, Stop): return verdict if not verdict["interrupt"]: break archive(root, path, f"Task: {task}\n\nVerdict: interrupt\n\n{verdict['question']}", paths) - if stop := interrupt(root, session.id, chosen, path, verdict["question"], paths, env): + if stop := interrupt(root, session.id, models.worker, path, verdict["question"], paths): return stop if verdict["finished"]: archive(root, path, f"Task: {task}\n\nVerdict: finished", paths) @@ -89,201 +57,3 @@ def archive(root, path, note, paths): print(f"transcript: {dest}", file=sys.stderr) except OSError as failure: print(f"could not archive the transcript: {failure}", file=sys.stderr) - - -def make_private(folder): - mask = os.umask(0o077) - try: - os.makedirs(folder, exist_ok=True) - finally: - os.umask(mask) - - -def replace_json(path, data, **dump): - staged = f"{path}.{os.getpid()}" - try: - mode = os.stat(path).st_mode & 0o7777 if os.path.exists(path) else 0o600 - with open(os.open(staged, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as handle: - os.fchmod(handle.fileno(), mode) - json.dump(data, handle, **dump) - os.replace(staged, path) - except OSError as failure: - if os.path.exists(staged): - os.remove(staged) - return failure - return None - - -def model_for(env, variable, chosen): - return env.get(variable) or chosen - - -# ~/.claude/loop-claude-models.json - - -def project_model(root, paths, env): - if env.get("LOOP_CLAUDE_JUDGE_MODEL") and env.get("LOOP_CLAUDE_WORKER_MODEL"): - return "" - saved = paths.models_file - name = project_name(root, paths.code) - models = read_models(saved) - if isinstance(models, Stop): - return models - if chosen := models.get(name): - return chosen - chosen = ask_model(name, saved, paths.model_catalog) - if isinstance(chosen, Stop): - return chosen - # Reread: another loop may have saved its project while this one waited on the human. - models = read_models(saved) - if isinstance(models, Stop): - return models - if failure := replace_json(saved, {**models, name: chosen}, indent="\t", sort_keys=True): - return Stop(1, f"could not save the model in {saved}: {failure.strerror}") - print(f"{name} runs on {chosen}", file=sys.stderr) - return chosen - - -def read_models(saved): - try: - with open(saved, encoding="utf-8") as handle: - models = json.load(handle) - except FileNotFoundError: - return {} - except (OSError, ValueError) as failure: - return Stop(1, f"could not read {saved}: {getattr(failure, 'strerror', None) or failure}") - if not isinstance(models, dict) or not all(isinstance(chosen, str) and chosen for chosen in models.values()): - return Stop(1, f"could not read {saved}: not an object mapping projects to model names") - return models - - -def ask_model(name, saved, folder): - if not (sys.stdin.isatty() and sys.stdout.isatty()): - return Stop(2, f"{name} has no model in {saved}, and stdin or stdout is not a terminal to ask on; run it on a terminal or merge {{\"{name}\": \"\"}} into {saved}") - offered = catalog(folder) - print(f"\nThe model to run {name} on, saved in {saved}:", file=sys.stderr) - for number, (model_id, label) in enumerate(offered, 1): - print(f" {number}. {label} ({model_id})", file=sys.stderr) - if not offered: - print(f" no model catalog cached in {folder}", file=sys.stderr) - while True: - try: - answer = input(f"{'A number, or any' if offered else 'A'} name claude --model takes: ").strip() - except EOFError: - print(file=sys.stderr) - return Stop(2, "no model picked") - if not answer: - continue - if not (offered and answer.isdecimal()): - return answer - if 1 <= int(answer) <= len(offered): - return offered[int(answer) - 1][0] - print(f"pick 1 to {len(offered)}", file=sys.stderr) - - -def catalog(folder): - newest = {} - for path in folder.glob("*.json"): - try: - with open(path, encoding="utf-8") as handle: - data = json.load(handle) - except (OSError, ValueError): - continue - if isinstance(data, dict) and isinstance(data.get("fetchedAt"), (int, float)) and data["fetchedAt"] > newest.get("fetchedAt", -1): - newest = data - models = 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 [] - - -# --json-schema verdicts - - -def judge(root, task, premises, transcript, chosen, env): - # 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", - "--json-schema", json.dumps(JUDGE_SCHEMA), - "--model", model_for(env, "LOOP_CLAUDE_JUDGE_MODEL", chosen), - "--no-session-persistence", - "--output-format", "json", - "--permission-mode", "bypassPermissions", - "--tools", "", - ] - prompt = judge_prompt(task, premises, transcript) - for failures in itertools.count(1): - proc = subprocess.run(["claude", *args], capture_output=True, cwd=root, input=prompt, text=True) - verdict = (parse(proc.stdout) or {}).get("structured_output") if proc.returncode == 0 else None - if not complete(verdict): - failure = proc.stderr.strip() or "the judge returned no verdict" - elif not grounded(verdict, transcript): - failure = f"the judge quoted {verdict['evidence']!r}, nothing in the transcript, for the question: {verdict['question']}" - else: - return verdict - if stop := strike("judge", failures, failure): - return stop - - -def judge_prompt(task, premises, transcript): - return ( - f"From README.md:\n{premises}\n\n" - f"The task an agent was given:\n{task}\n\n" - # The tail, where an interrupt or a finish lands; the session's transcript grows cycle over cycle. - f"What the agent did and said, and what the human typed on [human] lines, latest last:\n{transcript[-40000:]}\n\n" - f"{JUDGE_RULES}" - ) - - -def complete(verdict): - return isinstance(verdict, dict) and set(JUDGE_SCHEMA["required"]) <= verdict.keys() - - -def grounded(verdict, transcript): - if not verdict["interrupt"]: - return True - evidence = verdict["evidence"] - return evidence.strip() != "" and evidence in transcript - - -# ~/.claude.json - - -def interrupt(root, session_id, chosen, path, question, paths, env): - print(f"\n{question}", file=sys.stderr) - if not (sys.stdin.isatty() and sys.stdout.isatty()): - return Stop(2, "stdin or stdout is not a terminal") - trust(paths.claude_json, checkouts(root)) - entries = read(path) - if isinstance(entries, Failure): - return Stop(1, entries.reason) - before = human_turns(entries) - subprocess.run(["claude", "--model", model_for(env, "LOOP_CLAUDE_WORKER_MODEL", chosen), "--permission-mode", "bypassPermissions", "--resume", str(session_id)], cwd=root) - entries = read(path) - if isinstance(entries, Failure): - return Stop(1, f"could not tell whether you typed anything: {entries.reason}") - if human_turns(entries) <= before: - return Stop(2, "the interrupt ended without the human typing anything") - return None - - -def trust(config, roots): - try: - with open(config, encoding="utf-8") as handle: - data = json.load(handle) - except (OSError, ValueError) as failure: - print(f"could not read {config}: {getattr(failure, 'strerror', failure)}", file=sys.stderr) - return - projects = data.setdefault("projects", {}) if isinstance(data, dict) else None - if not isinstance(projects, dict) or not all(isinstance(record, dict) for record in projects.values()): - print(f"could not read {config}: not an object whose \"projects\" maps paths to objects", file=sys.stderr) - return - untrusted = [path for path in roots if not projects.get(path, {}).get("hasTrustDialogAccepted")] - if not untrusted: - return - for path in untrusted: - projects.setdefault(path, {})["hasTrustDialogAccepted"] = True - if failure := replace_json(config, data, indent=2): - print(f"could not write {config}: {failure.strerror}", file=sys.stderr) - return - print("trusted for the interrupt: " + ", ".join(untrusted), file=sys.stderr) diff --git a/bin/loop_claude/human.py b/bin/loop_claude/human.py new file mode 100644 index 00000000..0850fc90 --- /dev/null +++ b/bin/loop_claude/human.py @@ -0,0 +1,13 @@ +import sys + +from loop_claude.outcome import Stop + + +def needed(to, but): + return Stop(2, f"the human is needed to {to}, but {but}") + + +def off_terminal(to): + if sys.stdin.isatty() and sys.stdout.isatty(): + return None + return needed(to, "stdin or stdout is not a terminal") diff --git a/bin/loop_claude/interrupt.py b/bin/loop_claude/interrupt.py new file mode 100644 index 00000000..fbe7e7d3 --- /dev/null +++ b/bin/loop_claude/interrupt.py @@ -0,0 +1,31 @@ +import subprocess +import sys + +from loop_claude import human +from loop_claude.checkout import checkouts +from loop_claude.outcome import Failure, Stop +from loop_claude.transcript import human_turns, read +from loop_claude.trust import trust + +TO = "answer the question above" + + +def interrupt(root, session_id, model, path, question, paths): + print(f"\n{question}", file=sys.stderr) + if stop := human.off_terminal(TO): + return stop + trust(paths.claude_json, checkouts(root)) + entries = read(path) + if isinstance(entries, Failure): + return Stop(1, entries.reason) + before = human_turns(entries) + try: + subprocess.run(["claude", "--model", model, "--permission-mode", "bypassPermissions", "--resume", str(session_id)], cwd=root) + except OSError as failure: + return Stop(1, f"could not start claude: {failure.strerror}") + entries = read(path) + if isinstance(entries, Failure): + return Stop(1, f"could not tell whether you typed anything: {entries.reason}") + if human_turns(entries) <= before: + return human.needed(TO, "the interrupt ended without you typing anything") + return None diff --git a/bin/loop_claude/judge.py b/bin/loop_claude/judge.py new file mode 100644 index 00000000..4140ccda --- /dev/null +++ b/bin/loop_claude/judge.py @@ -0,0 +1,95 @@ +import itertools +import json +import subprocess + +from loop_claude.outcome import Failure +from loop_claude.strike import strike +from loop_claude.transcript import parse + +JUDGE_RULES = ( + "Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n" + "- the agent asks the human anything, seeks approval, or says a decision is the human's\n" + "- it carried on under an assumption that decides the deliverable and that the human could " + "reasonably reject; a caveat about transient state it then handled is not one\n" + "- it is blocked on something only the human can supply: a credential, a version bump, a release " + "ready to cut, a choice outside the repo\n" + "- it flags that the goals, the plan or the task itself is unclear, missing or in need of change\n" + "- it chose between alternatives the README text does not discriminate between - it does not " + "rule the rejected one out - and the choice materially changes the deliverable\n" + "interrupt=false otherwise. Bookkeeping the agent settled silently - what to document, wording, " + "where a note goes - is not on its own a reason to interrupt. The human may have replied inside the transcript, on a [human] line: judge only what " + "is still open, never a question they already answered there.\n" + "Where the agent asked or flagged something itself, the question is that one, in the agent's own " + "wording; never construct another from facts it stated.\n" + "finished=true when the chunk is complete: merged, or nothing remains that the agent could do on " + "its own. finished=false when work remains that a further run can continue: an open PR, a review " + "not yet run, CI not yet reported." +) + +JUDGE_SCHEMA = { + "properties": { + "evidence": {"description": "A verbatim quote of the transcript line the verdict rests on: what triggers the interrupt, else what shows the chunk finished or the work remaining.", "type": "string"}, + "finished": {"type": "boolean"}, + "interrupt": {"type": "boolean"}, + "question": {"description": "The single question to put to the human. Empty when interrupt is false.", "type": "string"}, + }, + "required": ["evidence", "finished", "interrupt", "question"], + "type": "object", +} + + +def judge(root, task, premises, transcript, model): + # 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", + "--json-schema", json.dumps(JUDGE_SCHEMA), + "--model", model, + "--no-session-persistence", + "--output-format", "json", + "--permission-mode", "bypassPermissions", + "--tools", "", + ] + prompt = judge_prompt(task, premises, transcript) + for failures in itertools.count(1): + verdict = run_judge(root, args, prompt) + if isinstance(verdict, Failure): + failure = verdict.reason + elif not complete(verdict): + failure = "the judge returned no verdict" + elif not grounded(verdict, transcript): + failure = f"the judge quoted {verdict['evidence']!r}, nothing in the transcript" + (f", for the question: {verdict['question']}" if verdict["interrupt"] else "") + else: + return verdict + if stop := strike("judge", failures, failure): + return stop + + +def run_judge(root, args, prompt): + try: + proc = subprocess.run(["claude", *args], capture_output=True, cwd=root, input=prompt, text=True) + except OSError as failure: + return Failure(f"could not start claude: {failure.strerror}") + if proc.returncode != 0: + return Failure(proc.stderr.strip() or f"the judge exited {proc.returncode}") + return (parse(proc.stdout) or {}).get("structured_output") + + +def judge_prompt(task, premises, transcript): + return ( + f"From README.md:\n{premises}\n\n" + f"The task an agent was given:\n{task}\n\n" + # The tail, where an interrupt or a finish lands; the session's transcript grows cycle over cycle. + f"What the agent did and said, and what the human typed on [human] lines, latest last:\n{transcript[-40000:]}\n\n" + f"{JUDGE_RULES}" + ) + + +def complete(verdict): + return isinstance(verdict, dict) and all( + isinstance(verdict.get(name), bool if JUDGE_SCHEMA["properties"][name]["type"] == "boolean" else str) for name in JUDGE_SCHEMA["required"] + ) + + +def grounded(verdict, transcript): + evidence = verdict["evidence"] + return evidence.strip() != "" and evidence in transcript diff --git a/bin/loop_claude/main.py b/bin/loop_claude/main.py index 0789bc58..432d208c 100644 --- a/bin/loop_claude/main.py +++ b/bin/loop_claude/main.py @@ -11,12 +11,13 @@ its session next cycle; the next chunk starts a fresh session. Cycles continue until that interrupt or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary". Exit 1: no task, not inside a checkout, no premises, a models file it cannot read or write, claude -leaves no transcript or one it cannot read, a reload with unreadable state, or the worker or the -judge fails three times running. A worker fails when claude cannot start, exits non-zero, is killed, -or ends without a result event; a judge when its verdict misses a field or quotes nothing in the -transcript. +leaves no transcript or one it cannot read, claude cannot start for an interrupt, a reload with +unreadable state, or the worker or the judge fails three times running. A worker fails when claude +cannot start, exits non-zero, is killed, or ends without a result event; a judge when claude cannot +start or exits non-zero, or its verdict misses a field or quotes nothing in the transcript. Exit 2: the human is needed, to pick the model or answer an interrupt, and stdin or stdout is not a -terminal, or the interrupt ended without them typing anything. Rerunning resumes any open session. +terminal, the input ends, or the interrupt ended without them typing anything. Rerunning resumes any +open session. Each project has one session, "A loop-claude", being the checkout relative to ~/code, or to / outside it, deleted when the chunk finishes. Its transcript is archived under @@ -48,7 +49,8 @@ import dataclasses import sys from loop_claude.checkout import checkout_root -from loop_claude.cycle import project_model, run_cycle +from loop_claude.cycle import run_cycle +from loop_claude.models import project_models from loop_claude.outcome import Continue, Retry, Stop from loop_claude.premises import read_premises from loop_claude.reload import RELOAD_FLAG, decode_state, fingerprint, reload_if_edited @@ -84,11 +86,11 @@ def run_loop(argv, env, paths, launcher, cwd): premises = read_premises(state.root) if isinstance(premises, Stop): return premises - chosen = project_model(state.root, paths, env) - if isinstance(chosen, Stop): - return chosen + models = project_models(state.root, paths, env) + if isinstance(models, Stop): + return models print(f"\n=== cycle {state.cycle_number} ===", flush=True) - match run_cycle(state.root, state.task, premises, chosen, paths, env): + match run_cycle(state.root, state.task, premises, models, paths): case Stop() as stop: return stop case Retry(failure): diff --git a/bin/loop_claude/models.py b/bin/loop_claude/models.py new file mode 100644 index 00000000..851bd0ba --- /dev/null +++ b/bin/loop_claude/models.py @@ -0,0 +1,98 @@ +import dataclasses +import json +import sys + +from loop_claude import human +from loop_claude.checkout import project_name +from loop_claude.outcome import Stop +from loop_claude.private_file import replace_json + + +@dataclasses.dataclass(frozen=True) +class Models: + judge: str + worker: str + + +def project_models(root, paths, env): + """LOOP_CLAUDE_JUDGE_MODEL and LOOP_CLAUDE_WORKER_MODEL, each falling back to the project's saved model.""" + judge, worker = env.get("LOOP_CLAUDE_JUDGE_MODEL"), env.get("LOOP_CLAUDE_WORKER_MODEL") + if judge and worker: + return Models(judge, worker) + chosen = project_model(project_name(root, paths.code), paths) + if isinstance(chosen, Stop): + return chosen + return Models(judge or chosen, worker or chosen) + + +def project_model(name, paths): + saved = paths.models_file + models = read_models(saved) + if isinstance(models, Stop): + return models + if chosen := models.get(name): + return chosen + chosen = ask_model(name, saved, paths.model_catalog) + if isinstance(chosen, Stop): + return chosen + # Reread: another loop may have saved its project while this one waited on the human. + models = read_models(saved) + if isinstance(models, Stop): + return models + if failure := replace_json(saved, {**models, name: chosen}, indent="\t", sort_keys=True): + return Stop(1, f"could not save the model in {saved}: {failure.strerror}") + print(f"{name} runs on {chosen}", file=sys.stderr) + return chosen + + +def read_models(saved): + try: + with open(saved, encoding="utf-8") as handle: + models = json.load(handle) + except FileNotFoundError: + return {} + except (OSError, ValueError) as failure: + return Stop(1, f"could not read {saved}: {getattr(failure, 'strerror', None) or failure}") + if not isinstance(models, dict) or not all(isinstance(chosen, str) and chosen for chosen in models.values()): + return Stop(1, f"could not read {saved}: not an object mapping projects to model names") + return models + + +def ask_model(name, saved, folder): + if stop := human.off_terminal(f"pick {name}'s model, or merge {{\"{name}\": \"\"}} into {saved}"): + return stop + offered = catalog(folder) + print(f"\nThe model to run {name} on, saved in {saved}:", file=sys.stderr) + for number, (model_id, label) in enumerate(offered, 1): + print(f" {number}. {label} ({model_id})", file=sys.stderr) + if not offered: + print(f" no model catalog cached in {folder}", file=sys.stderr) + while True: + try: + answer = input(f"{'A number, or any' if offered else 'A'} name claude --model takes: ").strip() + except EOFError: + print(file=sys.stderr) + return human.needed(f"pick {name}'s model", "the input ended") + if not answer: + continue + if not (offered and answer.isdecimal()): + return answer + if 1 <= int(answer) <= len(offered): + return offered[int(answer) - 1][0] + print(f"pick 1 to {len(offered)}", file=sys.stderr) + + +def catalog(folder): + newest = {} + for path in folder.glob("*.json"): + try: + with open(path, encoding="utf-8") as handle: + data = json.load(handle) + except (OSError, ValueError): + continue + if isinstance(data, dict) and isinstance(data.get("fetchedAt"), (int, float)) and data["fetchedAt"] > newest.get("fetchedAt", -1): + newest = data + models = 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 [] diff --git a/bin/loop_claude/private_file.py b/bin/loop_claude/private_file.py new file mode 100644 index 00000000..44cf070e --- /dev/null +++ b/bin/loop_claude/private_file.py @@ -0,0 +1,25 @@ +import json +import os + + +def make_private(folder): + mask = os.umask(0o077) + try: + os.makedirs(folder, exist_ok=True) + finally: + os.umask(mask) + + +def replace_json(path, data, **dump): + staged = f"{path}.{os.getpid()}" + try: + mode = os.stat(path).st_mode & 0o7777 if os.path.exists(path) else 0o600 + with open(os.open(staged, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as handle: + os.fchmod(handle.fileno(), mode) + json.dump(data, handle, **dump) + os.replace(staged, path) + except OSError as failure: + if os.path.exists(staged): + os.remove(staged) + return failure + return None diff --git a/bin/loop_claude/trust.py b/bin/loop_claude/trust.py new file mode 100644 index 00000000..299201cb --- /dev/null +++ b/bin/loop_claude/trust.py @@ -0,0 +1,29 @@ +import json +import sys + +from loop_claude.private_file import replace_json + + +def trust(config, roots): + try: + with open(config, encoding="utf-8") as handle: + data = json.load(handle) + except (OSError, ValueError) as failure: + print(f"could not read {config}: {getattr(failure, 'strerror', failure)}", file=sys.stderr) + return + projects = data.setdefault("projects", {}) if isinstance(data, dict) else None + if not isinstance(projects, dict): + print(f"could not read {config}: not an object whose \"projects\" is an object", file=sys.stderr) + return + if wrong := next((path for path, record in projects.items() if not isinstance(record, dict)), None): + print(f"could not read {config}: projects[{json.dumps(wrong)}] is not an object", file=sys.stderr) + return + untrusted = [path for path in roots if not projects.get(path, {}).get("hasTrustDialogAccepted")] + if not untrusted: + return + for path in untrusted: + projects.setdefault(path, {})["hasTrustDialogAccepted"] = True + if failure := replace_json(config, data, indent=2): + print(f"could not write {config}: {failure.strerror}", file=sys.stderr) + return + print("trusted for the interrupt: " + ", ".join(untrusted), file=sys.stderr) diff --git a/docs/decisions.md b/docs/decisions.md index b99a1749..148c4a48 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -20,10 +20,6 @@ 2026-09-24, lilleman. Serves goal 4. `claude --resume` re-enters the worktree the worker last entered, recorded in the transcript's `worktree-state` entry, and Claude Code asks trust per path, so trusting the checkout alone still lands the human in the dialog; trusting every worktree `git worktree list` names spares reading which one from the transcript. Valid while resume re-enters a recorded worktree and trust is kept per path. -## loop-claude: a wrong-shape trust file gets one message, naming the shape - -2026-09-26, larv-review, declining a product-owner nit. Serves goal 4. `trust` says `not an object whose "projects" maps paths to objects` for every wrong shape; naming the failing path would add a branch to `trust`, and the interrupt still lands in Claude Code's own dialog, which shows the path. The 2026-09-25 panel's `trust` as the unit least wanted to modify was the first reason; the 2026-09-26 panel named `typed`, so the entry rests on the dialog. Valid while the interrupt lands in that dialog. - ## bin/: the Python floor is README's Install prerequisite 2026-09-26, larv-review, carrying the floor the 2026-09-26 stability round assumed and verified its f-string fix under. Serves goal 1. The suite reruns itself on a `uv`-fetched interpreter of the version Install names: `ast.parse(feature_version=)` on the host's Python accepts the nested f-string 186181a fixed, a compile check passes a 3.11-only call like `contextlib.chdir`, and a `python3.N` on `PATH` is installed by hand on every machine and again at each bump. Valid while no machine taking the checkout ships an older Python. diff --git a/todo.md b/todo.md index 9cf5980f..81b4af98 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,6 @@ The rebuild lifts every dimension: each item below is one chunk on a worktree based on `origin/rebuild`, its PR into `rebuild`, until the last item merges `rebuild` into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -- **Move the judge, the interrupt, trust and model resolution into their own modules.** The judge is retried alone and checks evidence on every verdict against the rendered transcript; `models` owns the whole resolution, env overrides included, with no sentinel; `trust` names a `projects` entry that is not an object; `input()` at end of file is exit 2. `ask_model` and `interrupt` spell "the human is needed" one way; `replace_json` and `make_private` get one module shared by `models`, `trust` and the archive. - **Move each Claude Code internal `--help` lists beside the module relying on it.** Or `docs/decisions.md` says why `--help` keeps it. - **Archive the raw transcript, deduplicated by content hash, with the verdict beside it, and stop on a failed archive.** Tests first; the changelog line says what the archive now holds. - **Replace `bin/test_loop_claude.py`'s internal-function tests with the black-box tests plus unit tests of the pure parsers.** -- 2.52.0 From 9bfb2fe173b6fb71421413cbc3c8b43bb0b20290 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 16:45:46 +0200 Subject: [PATCH 021/233] Pin an interrupt verdict without a question as incomplete, and one person in the empty-interrupt message --- bin/test_loop_claude.py | 3 ++- bin/test_loop_claude_black_box.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index a25565ea..a42fc5b1 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -278,7 +278,7 @@ class Interrupt(unittest.TestCase): unittest.mock.patch.multiple(interrupt, checkouts=unittest.mock.DEFAULT, trust=unittest.mock.DEFAULT) as mocks, unittest.mock.patch("subprocess.run") as run, ): - self.assertEqual(interrupt.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {})), Stop(2, "the human is needed to answer the question above, but the interrupt ended without you typing anything")) + self.assertEqual(interrupt.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {})), Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed")) mocks["checkouts"].assert_called_with(root) self.assertEqual(run.call_args.kwargs["cwd"], root) self.assertEqual(run.call_args.args[0][run.call_args.args[0].index("--model") + 1], "m") @@ -352,6 +352,7 @@ class Verdict(unittest.TestCase): self.assertFalse(judge.complete({"interrupt": "no", "evidence": "", "finished": True, "question": ""})) self.assertFalse(judge.complete({"interrupt": False, "evidence": None, "finished": True, "question": ""})) self.assertFalse(judge.complete({"interrupt": False})) + self.assertFalse(judge.complete({"interrupt": True, "evidence": "x", "finished": False, "question": " "})) self.assertFalse(judge.complete(None)) diff --git a/bin/test_loop_claude_black_box.py b/bin/test_loop_claude_black_box.py index 67e52a00..c46572a0 100644 --- a/bin/test_loop_claude_black_box.py +++ b/bin/test_loop_claude_black_box.py @@ -408,7 +408,7 @@ class Interrupt(unittest.TestCase): transcript.unlink() run = checkout.run([*asked, interrupt()], terminal_input="") self.assertEqual((run.code, run.roles()), (2, ["worker", "judge", "interrupt"])) - self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to answer the question above, but the interrupt ended without you typing anything") + self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to answer the question above, but the interrupt ended with nothing typed") run = checkout.run([worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?", vanish=True)], terminal_input="") self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"])) -- 2.52.0 From b40893bc70742b84e5118b963ddadaaeec5c7713 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 16:46:18 +0200 Subject: [PATCH 022/233] Retire the section-headers decision, reject an interrupt without a question, and name file_writes by what it does --- AGENTS.md | 1 - bin/loop_claude/cycle.py | 2 +- bin/loop_claude/{private_file.py => file_writes.py} | 0 bin/loop_claude/interrupt.py | 2 +- bin/loop_claude/judge.py | 3 ++- bin/loop_claude/main.py | 5 +++-- bin/loop_claude/models.py | 2 +- bin/loop_claude/trust.py | 4 ++-- docs/decisions.md | 4 ---- 9 files changed, 10 insertions(+), 13 deletions(-) rename bin/loop_claude/{private_file.py => file_writes.py} (100%) diff --git a/AGENTS.md b/AGENTS.md index 4f7aa2eb..e6eb6094 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,7 +12,6 @@ Decisions live in `docs/decisions.md`: - bin/: the Python floor is README's Install prerequisite - bin/: host python, no container - comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it -- loop-claude: the section headers stay - vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link - larv-review: a re-entered loop takes a fresh round cap - loop-claude: a reload into an older file is unsupported diff --git a/bin/loop_claude/cycle.py b/bin/loop_claude/cycle.py index b9d11697..247c8011 100644 --- a/bin/loop_claude/cycle.py +++ b/bin/loop_claude/cycle.py @@ -6,7 +6,7 @@ from loop_claude.checkout import project_name from loop_claude.interrupt import interrupt from loop_claude.judge import judge from loop_claude.outcome import Continue, Failure, Retry, Stop -from loop_claude.private_file import make_private +from loop_claude.file_writes import make_private from loop_claude.session import delete_session, session_for, transcript_file from loop_claude.transcript import read, render from loop_claude.worker import run_worker, worker_args diff --git a/bin/loop_claude/private_file.py b/bin/loop_claude/file_writes.py similarity index 100% rename from bin/loop_claude/private_file.py rename to bin/loop_claude/file_writes.py diff --git a/bin/loop_claude/interrupt.py b/bin/loop_claude/interrupt.py index fbe7e7d3..31145aad 100644 --- a/bin/loop_claude/interrupt.py +++ b/bin/loop_claude/interrupt.py @@ -27,5 +27,5 @@ def interrupt(root, session_id, model, path, question, paths): if isinstance(entries, Failure): return Stop(1, f"could not tell whether you typed anything: {entries.reason}") if human_turns(entries) <= before: - return human.needed(TO, "the interrupt ended without you typing anything") + return human.needed(TO, "the interrupt ended with nothing typed") return None diff --git a/bin/loop_claude/judge.py b/bin/loop_claude/judge.py index 4140ccda..39617957 100644 --- a/bin/loop_claude/judge.py +++ b/bin/loop_claude/judge.py @@ -85,9 +85,10 @@ def judge_prompt(task, premises, transcript): def complete(verdict): - return isinstance(verdict, dict) and all( + typed = isinstance(verdict, dict) and all( isinstance(verdict.get(name), bool if JUDGE_SCHEMA["properties"][name]["type"] == "boolean" else str) for name in JUDGE_SCHEMA["required"] ) + return typed and not (verdict["interrupt"] and not verdict["question"].strip()) def grounded(verdict, transcript): diff --git a/bin/loop_claude/main.py b/bin/loop_claude/main.py index 432d208c..3802c6ba 100644 --- a/bin/loop_claude/main.py +++ b/bin/loop_claude/main.py @@ -14,9 +14,10 @@ Exit 1: no task, not inside a checkout, no premises, a models file it cannot rea leaves no transcript or one it cannot read, claude cannot start for an interrupt, a reload with unreadable state, or the worker or the judge fails three times running. A worker fails when claude cannot start, exits non-zero, is killed, or ends without a result event; a judge when claude cannot -start or exits non-zero, or its verdict misses a field or quotes nothing in the transcript. +start or exits non-zero, or its verdict misses or mistypes a field, interrupts without a question, +or quotes nothing in the transcript. Exit 2: the human is needed, to pick the model or answer an interrupt, and stdin or stdout is not a -terminal, the input ends, or the interrupt ended without them typing anything. Rerunning resumes any +terminal, the input ends, or the interrupt ended with nothing typed. Rerunning resumes any open session. Each project has one session, "A loop-claude", being the checkout relative to ~/code, diff --git a/bin/loop_claude/models.py b/bin/loop_claude/models.py index 851bd0ba..ae1bb6f7 100644 --- a/bin/loop_claude/models.py +++ b/bin/loop_claude/models.py @@ -5,7 +5,7 @@ import sys from loop_claude import human from loop_claude.checkout import project_name from loop_claude.outcome import Stop -from loop_claude.private_file import replace_json +from loop_claude.file_writes import replace_json @dataclasses.dataclass(frozen=True) diff --git a/bin/loop_claude/trust.py b/bin/loop_claude/trust.py index 299201cb..ab73f25b 100644 --- a/bin/loop_claude/trust.py +++ b/bin/loop_claude/trust.py @@ -1,7 +1,7 @@ import json import sys -from loop_claude.private_file import replace_json +from loop_claude.file_writes import replace_json def trust(config, roots): @@ -15,7 +15,7 @@ def trust(config, roots): if not isinstance(projects, dict): print(f"could not read {config}: not an object whose \"projects\" is an object", file=sys.stderr) return - if wrong := next((path for path, record in projects.items() if not isinstance(record, dict)), None): + if (wrong := next((path for path, record in projects.items() if not isinstance(record, dict)), None)) is not None: print(f"could not read {config}: projects[{json.dumps(wrong)}] is not an object", file=sys.stderr) return untrusted = [path for path in roots if not projects.get(path, {}).get("hasTrustDialogAccepted")] diff --git a/docs/decisions.md b/docs/decisions.md index 148c4a48..598eb123 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -32,10 +32,6 @@ 2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The rebuild planned in `todo.md` under 0.1.0 answers the places named, and a later chunk may not lower any dimension. Valid until the next scoring run, which uses the same four seats. -## loop-claude: the section headers stay - -2026-09-26, larv-review, declining a prose-pass deletion under `CLAUDE.md` → "Comments and documentation". Serves goal 4. Two seats of the 2026-09-26 panel credit Navigation 8 to the headers in what is now `bin/loop_claude/cycle.py`, which index it by the file or format each group touches. Valid while `cycle.py` holds more than one group; a header leaves with its group, as `# The transcript file` did into `transcript.py`. - ## vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link 2026-09-24, larv-review. Serves goal 4. Three seats of the 2026-09-24 panel found the words only in the changelog; a definition at each rule lands one reader and misses the next, so the section is the one landing place and each file using the words links it once, and `bin/test_citations.py` fails on a citation no heading or bold lead answers, so the pointer's rot is visible. `loop-claude --help` restates chunk, cycle, interrupt and premises, since a terminal reader has no link to follow. Valid until the next scoring run. -- 2.52.0 From cd9c0fe4a6acf197cfe3287272a32aa90c9672fd Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 16:47:36 +0200 Subject: [PATCH 023/233] Sort the file_writes imports and drop a docstring restating project_models --- bin/loop_claude/cycle.py | 2 +- bin/loop_claude/models.py | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/bin/loop_claude/cycle.py b/bin/loop_claude/cycle.py index 247c8011..c5b5e163 100644 --- a/bin/loop_claude/cycle.py +++ b/bin/loop_claude/cycle.py @@ -3,10 +3,10 @@ import sys import time from loop_claude.checkout import project_name +from loop_claude.file_writes import make_private from loop_claude.interrupt import interrupt from loop_claude.judge import judge from loop_claude.outcome import Continue, Failure, Retry, Stop -from loop_claude.file_writes import make_private from loop_claude.session import delete_session, session_for, transcript_file from loop_claude.transcript import read, render from loop_claude.worker import run_worker, worker_args diff --git a/bin/loop_claude/models.py b/bin/loop_claude/models.py index ae1bb6f7..808ad18d 100644 --- a/bin/loop_claude/models.py +++ b/bin/loop_claude/models.py @@ -4,8 +4,8 @@ import sys from loop_claude import human from loop_claude.checkout import project_name -from loop_claude.outcome import Stop from loop_claude.file_writes import replace_json +from loop_claude.outcome import Stop @dataclasses.dataclass(frozen=True) @@ -15,7 +15,6 @@ class Models: def project_models(root, paths, env): - """LOOP_CLAUDE_JUDGE_MODEL and LOOP_CLAUDE_WORKER_MODEL, each falling back to the project's saved model.""" judge, worker = env.get("LOOP_CLAUDE_JUDGE_MODEL"), env.get("LOOP_CLAUDE_WORKER_MODEL") if judge and worker: return Models(judge, worker) -- 2.52.0 From 7b1ee20c7c3b3d5be23bd2f9af338ab55f3e4ae6 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 16:48:46 +0200 Subject: [PATCH 024/233] Pin a reason per incomplete verdict, the rerun hint off a terminal, and which claude could not start --- bin/test_loop_claude.py | 15 +++++++-------- bin/test_loop_claude_black_box.py | 11 ++++++----- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index a42fc5b1..432645f9 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -271,7 +271,7 @@ class Interrupt(unittest.TestCase): transcript = os.path.join(root, "session.jsonl") pathlib.Path(transcript).write_text("{}\n") with unittest.mock.patch("sys.stdin.isatty", return_value=False): - self.assertEqual(interrupt.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {})), Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal")) + self.assertEqual(interrupt.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {})), Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal")) with ( unittest.mock.patch("sys.stdin.isatty", return_value=True), unittest.mock.patch("sys.stdout.isatty", return_value=True), @@ -348,12 +348,11 @@ class Grounded(unittest.TestCase): class Verdict(unittest.TestCase): def test_needs_every_field_the_schema_requires(self): - self.assertTrue(judge.complete({"interrupt": False, "evidence": "", "finished": True, "question": ""})) - self.assertFalse(judge.complete({"interrupt": "no", "evidence": "", "finished": True, "question": ""})) - self.assertFalse(judge.complete({"interrupt": False, "evidence": None, "finished": True, "question": ""})) - self.assertFalse(judge.complete({"interrupt": False})) - self.assertFalse(judge.complete({"interrupt": True, "evidence": "x", "finished": False, "question": " "})) - self.assertFalse(judge.complete(None)) + self.assertIsNone(judge.incomplete({"interrupt": False, "evidence": "", "finished": True, "question": ""})) + self.assertEqual(judge.incomplete({"interrupt": "no", "evidence": "", "finished": True, "question": ""}), "the judge's verdict has no interrupt of type boolean") + self.assertEqual(judge.incomplete({"interrupt": False, "evidence": None, "finished": True, "question": ""}), "the judge's verdict has no evidence of type string") + self.assertEqual(judge.incomplete({"interrupt": True, "evidence": "x", "finished": False, "question": " "}), "the judge interrupted without a question") + self.assertEqual(judge.incomplete(None), "the judge returned no verdict") STUB_CLAUDE = """#!/usr/bin/env python3 @@ -411,7 +410,7 @@ class RunCycle(unittest.TestCase): self.assertEqual(cycle.run_cycle(home, "task", "premises", OPUS, paths), Continue()) pathlib.Path(verdicts).write_text("interrupt") with unittest.mock.patch("sys.stderr") as stderr: - self.assertEqual(cycle.run_cycle(home, "task", "premises", OPUS, paths), Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal")) + self.assertEqual(cycle.run_cycle(home, "task", "premises", OPUS, paths), Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal")) self.assertIn(f"transcript: {paths.archive}", "".join(str(call.args[0]) for call in stderr.write.call_args_list)) pathlib.Path(verdicts).write_text("interrupt fail fail fail") with unittest.mock.patch("sys.stderr"), unittest.mock.patch.object(cycle, "interrupt", return_value=None): diff --git a/bin/test_loop_claude_black_box.py b/bin/test_loop_claude_black_box.py index c46572a0..51f84aff 100644 --- a/bin/test_loop_claude_black_box.py +++ b/bin/test_loop_claude_black_box.py @@ -315,7 +315,8 @@ class Cycles(unittest.TestCase): self.assertEqual(run.roles(), ["worker", "judge", "judge", "judge"]) self.assertEqual(run.sleeps, [60, 60]) self.assertIn("retrying the judge in a minute: judge down", run.stderr) - self.assertEqual(run.stderr.strip().splitlines()[-1], "the judge failed three times running: the judge returned no verdict") + self.assertIn("retrying the judge in a minute: the judge returned no verdict", run.stderr) + self.assertEqual(run.stderr.strip().splitlines()[-1], "the judge failed three times running: the judge's verdict has no evidence of type string") def test_retries_the_judge_alone_when_its_verdict_quotes_nothing_in_the_transcript(self): checkout = Checkout(self) @@ -375,13 +376,13 @@ class Interrupt(unittest.TestCase): steps = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")] run = checkout.run(steps) self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"])) - self.assertEqual(run.stderr.strip().splitlines()[-2:], ["A or B?", "the human is needed to answer the question above, but stdin or stdout is not a terminal"]) + self.assertEqual(run.stderr.strip().splitlines()[-2:], ["A or B?", "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"]) self.assertTrue(checkout.archived()) session = argument(run.calls[0], "--session-id") run = checkout.run(steps, terminal_input="", stdout_on_terminal=False) self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"])) self.assertEqual(argument(run.calls[0], "--resume"), session) - self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to answer the question above, but stdin or stdout is not a terminal") + self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal") def test_hands_the_terminal_over_and_exits_2_when_nothing_is_typed(self): checkout = Checkout(self) @@ -412,7 +413,7 @@ class Interrupt(unittest.TestCase): run = checkout.run([worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?", vanish=True)], terminal_input="") self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"])) - self.assertEqual(run.stderr.strip().splitlines()[-1], "could not start claude: No such file or directory") + self.assertEqual(run.stderr.strip().splitlines()[-1], "could not start claude for the interrupt: No such file or directory") @unittest.skipIf(os.geteuid() == 0, "root reads an unreadable file") def test_exits_1_when_the_transcript_cannot_be_read_after_the_interrupt(self): @@ -435,7 +436,7 @@ class Models(unittest.TestCase): self.catalog(checkout) run = checkout.run([worker()]) self.assertEqual((run.code, run.calls), (2, [])) - self.assertEqual(run.stderr.strip(), f'the human is needed to pick proj\'s model, or merge {{"proj": ""}} into {checkout.models_file()}, but stdin or stdout is not a terminal') + self.assertEqual(run.stderr.strip(), f'the human is needed to pick proj\'s model, or merge {{"proj": ""}} into {checkout.models_file()}, but stdin or stdout is not a terminal; rerun loop-claude on a terminal') run = checkout.run([worker()], terminal_input="\x04") self.assertEqual((run.code, run.calls), (2, [])) -- 2.52.0 From 1be6ae818775efb0f14a7b939feeefd89e958654 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 16:49:17 +0200 Subject: [PATCH 025/233] Name why a verdict is incomplete, say how to proceed off a terminal, and which claude could not start --- CHANGELOG.md | 2 +- bin/loop_claude/human.py | 2 +- bin/loop_claude/interrupt.py | 2 +- bin/loop_claude/judge.py | 19 ++++++++++++------- 4 files changed, 15 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c2b87599..66b2b001 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,6 @@ - `loop-claude`'s no-premises exit names what is wrong: `README.md` unopenable or not UTF-8, a `## Goals` or `## Audience` heading missing or repeated, or nothing under one. - `loop-claude` says why when it cannot read or write `~/.claude.json` before an interrupt, naming a `projects` entry that is not an object, and the interrupt then lands in Claude Code's trust dialog. - `loop-claude` skips a transcript line it cannot parse, exits 1 naming a transcript it cannot read, and counts a `claude` it cannot start as a failed worker run. -- `loop-claude`'s judge quotes the transcript for every verdict, and a verdict quoting nothing, or a `claude` the judge cannot start, is a failed judge run; a `claude` that cannot start for an interrupt exits 1. +- `loop-claude`'s judge quotes the transcript for every verdict, and a verdict quoting nothing or interrupting without a question, or a `claude` the judge cannot start, is a failed judge run; a `claude` that cannot start for an interrupt exits 1. - `loop-claude`'s exit-2 message says what the human is needed for. - `loop-claude` keeps the mode of `~/.claude.json` and of its models file when it rewrites them, and creates the models file 0600. diff --git a/bin/loop_claude/human.py b/bin/loop_claude/human.py index 0850fc90..2d87aa2f 100644 --- a/bin/loop_claude/human.py +++ b/bin/loop_claude/human.py @@ -10,4 +10,4 @@ def needed(to, but): def off_terminal(to): if sys.stdin.isatty() and sys.stdout.isatty(): return None - return needed(to, "stdin or stdout is not a terminal") + return needed(to, "stdin or stdout is not a terminal; rerun loop-claude on a terminal") diff --git a/bin/loop_claude/interrupt.py b/bin/loop_claude/interrupt.py index 31145aad..5a965f7d 100644 --- a/bin/loop_claude/interrupt.py +++ b/bin/loop_claude/interrupt.py @@ -22,7 +22,7 @@ def interrupt(root, session_id, model, path, question, paths): try: subprocess.run(["claude", "--model", model, "--permission-mode", "bypassPermissions", "--resume", str(session_id)], cwd=root) except OSError as failure: - return Stop(1, f"could not start claude: {failure.strerror}") + return Stop(1, f"could not start claude for the interrupt: {failure.strerror}") entries = read(path) if isinstance(entries, Failure): return Stop(1, f"could not tell whether you typed anything: {entries.reason}") diff --git a/bin/loop_claude/judge.py b/bin/loop_claude/judge.py index 39617957..28a9cbda 100644 --- a/bin/loop_claude/judge.py +++ b/bin/loop_claude/judge.py @@ -54,8 +54,8 @@ def judge(root, task, premises, transcript, model): verdict = run_judge(root, args, prompt) if isinstance(verdict, Failure): failure = verdict.reason - elif not complete(verdict): - failure = "the judge returned no verdict" + elif reason := incomplete(verdict): + failure = reason elif not grounded(verdict, transcript): failure = f"the judge quoted {verdict['evidence']!r}, nothing in the transcript" + (f", for the question: {verdict['question']}" if verdict["interrupt"] else "") else: @@ -84,11 +84,16 @@ def judge_prompt(task, premises, transcript): ) -def complete(verdict): - typed = isinstance(verdict, dict) and all( - isinstance(verdict.get(name), bool if JUDGE_SCHEMA["properties"][name]["type"] == "boolean" else str) for name in JUDGE_SCHEMA["required"] - ) - return typed and not (verdict["interrupt"] and not verdict["question"].strip()) +def incomplete(verdict): + if not isinstance(verdict, dict): + return "the judge returned no verdict" + for name in JUDGE_SCHEMA["required"]: + kind = JUDGE_SCHEMA["properties"][name]["type"] + if not isinstance(verdict.get(name), bool if kind == "boolean" else str): + return f"the judge's verdict has no {name} of type {kind}" + if verdict["interrupt"] and not verdict["question"].strip(): + return "the judge interrupted without a question" + return None def grounded(verdict, transcript): -- 2.52.0 From 44cf712dc810dd3e22c59e125d4ca0833ef6cd2f Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 16:52:30 +0200 Subject: [PATCH 026/233] Move the Claude Code internals from --help beside the modules relying on them --- bin/loop_claude/judge.py | 1 + bin/loop_claude/main.py | 13 ------------- bin/loop_claude/models.py | 1 + bin/loop_claude/session.py | 2 ++ bin/loop_claude/transcript.py | 2 ++ bin/loop_claude/trust.py | 1 + bin/loop_claude/worker.py | 1 + todo.md | 1 - 8 files changed, 8 insertions(+), 14 deletions(-) diff --git a/bin/loop_claude/judge.py b/bin/loop_claude/judge.py index 28a9cbda..0e518789 100644 --- a/bin/loop_claude/judge.py +++ b/bin/loop_claude/judge.py @@ -71,6 +71,7 @@ def run_judge(root, args, prompt): return Failure(f"could not start claude: {failure.strerror}") if proc.returncode != 0: return Failure(proc.stderr.strip() or f"the judge exited {proc.returncode}") + # Where Claude Code 2.1.282 puts the --json-schema output. return (parse(proc.stdout) or {}).get("structured_output") diff --git a/bin/loop_claude/main.py b/bin/loop_claude/main.py index 3802c6ba..3e0d48f4 100644 --- a/bin/loop_claude/main.py +++ b/bin/loop_claude/main.py @@ -32,19 +32,6 @@ interrupt; with both set, nothing is asked. A change to bin/loop-claude or bin/loop_claude/*.py takes effect at the next cycle boundary, once loop-claude --help succeeds. - -Claude Code internals this rests on, observed on 2.1.282, the model catalog on 2.1.283: -- The transcript is ~/.claude/projects/*/.jsonl, one JSON object per line. A / - folder and .superseded-*/ and .orphaned-*.jsonl siblings belong to the same session. -- Claude Code writes "user" entries of its own into the transcript, and a `claude -p` prompt lands as one - with promptSource "sdk"; UserEntryKind in transcript.py tells a human's from them. -- An "assistant" entry, in the transcript and in --output-format stream-json, carries message.content - parts of type "text" (text) and "tool_use" (name, input); stream-json ends with a "result" event. -- `claude -p --output-format json --json-schema` returns the verdict under "structured_output". -- `claude -p` without --bare loads the project's and ~/.claude's CLAUDE.md, so the judge reads the words. -- ~/.claude.json holds projects..hasTrustDialogAccepted per checkout. -- ~/.claude/cache/model-catalog/*.json holds catalog.config.models, each with an id and a name; the newest - file has the highest fetchedAt. """ import dataclasses import sys diff --git a/bin/loop_claude/models.py b/bin/loop_claude/models.py index 808ad18d..964b52b2 100644 --- a/bin/loop_claude/models.py +++ b/bin/loop_claude/models.py @@ -81,6 +81,7 @@ def ask_model(name, saved, folder): print(f"pick 1 to {len(offered)}", file=sys.stderr) +# Claude Code 2.1.283's model cache; the newest file has the highest fetchedAt. def catalog(folder): newest = {} for path in folder.glob("*.json"): diff --git a/bin/loop_claude/session.py b/bin/loop_claude/session.py index aa44e9bf..1a7c9ee5 100644 --- a/bin/loop_claude/session.py +++ b/bin/loop_claude/session.py @@ -27,6 +27,7 @@ def session_for(root, paths): def transcript_file(session): + # Where Claude Code 2.1.282 writes a session's transcript. hit = glob.glob(os.path.join(glob.escape(str(session.projects)), "*", f"{session.id}.jsonl")) return hit[0] if hit else "" @@ -35,6 +36,7 @@ def delete_session(session): path = transcript_file(session) if not path: return + # Claude Code 2.1.282 also keeps a / folder and .superseded-*/ and .orphaned-*.jsonl siblings. for sibling in glob.glob(glob.escape(path.removesuffix(".jsonl")) + "*"): try: shutil.rmtree(sibling) if os.path.isdir(sibling) else os.remove(sibling) diff --git a/bin/loop_claude/transcript.py b/bin/loop_claude/transcript.py index ad987f71..e274d720 100644 --- a/bin/loop_claude/transcript.py +++ b/bin/loop_claude/transcript.py @@ -42,6 +42,7 @@ def parts(entry): return found if isinstance(found, list) else [] +# Claude Code 2.1.282 writes "user" entries of its own, a claude -p prompt among them. def user_entry_kind(entry): if entry.get("isMeta"): return UserEntryKind.META @@ -77,6 +78,7 @@ def render(entries): return "\n\n".join(lines) +# An "assistant" entry's parts, alike in the transcript and in stream-json on Claude Code 2.1.282. def said(part, limit=400): kind = part.get("type") if isinstance(part, dict) else None if kind == "text" and isinstance(part.get("text"), str) and part["text"].strip(): diff --git a/bin/loop_claude/trust.py b/bin/loop_claude/trust.py index ab73f25b..55972d55 100644 --- a/bin/loop_claude/trust.py +++ b/bin/loop_claude/trust.py @@ -18,6 +18,7 @@ def trust(config, roots): if (wrong := next((path for path, record in projects.items() if not isinstance(record, dict)), None)) is not None: print(f"could not read {config}: projects[{json.dumps(wrong)}] is not an object", file=sys.stderr) return + # Where Claude Code 2.1.282 keeps a checkout's trust. untrusted = [path for path in roots if not projects.get(path, {}).get("hasTrustDialogAccepted")] if not untrusted: return diff --git a/bin/loop_claude/worker.py b/bin/loop_claude/worker.py index c6029849..140f91e7 100644 --- a/bin/loop_claude/worker.py +++ b/bin/loop_claude/worker.py @@ -13,6 +13,7 @@ def run_worker(root, args): done = False for raw in proc.stdout: event = parse(raw) or {} + # Claude Code 2.1.282's stream-json ends with a "result" event. if event.get("type") == "result": done = True elif event.get("type") == "assistant": diff --git a/todo.md b/todo.md index 81b4af98..5d0c0702 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,6 @@ The rebuild lifts every dimension: each item below is one chunk on a worktree based on `origin/rebuild`, its PR into `rebuild`, until the last item merges `rebuild` into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -- **Move each Claude Code internal `--help` lists beside the module relying on it.** Or `docs/decisions.md` says why `--help` keeps it. - **Archive the raw transcript, deduplicated by content hash, with the verdict beside it, and stop on a failed archive.** Tests first; the changelog line says what the archive now holds. - **Replace `bin/test_loop_claude.py`'s internal-function tests with the black-box tests plus unit tests of the pure parsers.** - **Hold every reviewer to one findings document, `principles/review-findings.md`.** Severity, verdict, rounds with round 2 verifying each earlier finding, the per-chunk round cap, declining, and `/security-review`'s HIGH/MEDIUM/LOW mapped onto the scale; it replaces `principles/review-protocol.md`. -- 2.52.0 From 5e3b66232bab24e242383a5fc66badf51b5c93c5 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 16:53:38 +0200 Subject: [PATCH 027/233] Keep the judge's CLAUDE.md load beside its args --- bin/loop_claude/judge.py | 1 + 1 file changed, 1 insertion(+) diff --git a/bin/loop_claude/judge.py b/bin/loop_claude/judge.py index 0e518789..ef19ca41 100644 --- a/bin/loop_claude/judge.py +++ b/bin/loop_claude/judge.py @@ -40,6 +40,7 @@ JUDGE_SCHEMA = { def judge(root, task, premises, transcript, model): # No tools, so the verdict rests on the transcript grounded() checks it against; no persistence, so its runs stay out of the session picker. + # Without --bare, Claude Code 2.1.282's claude -p loads the project's and ~/.claude's CLAUDE.md. args = [ "-p", "--json-schema", json.dumps(JUDGE_SCHEMA), -- 2.52.0 From 6e31e0a833be0bc3d46e94a8d571be19a0260bf0 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 16:57:24 +0200 Subject: [PATCH 028/233] Archive the raw transcript by content hash with its verdict, and stop on a failed archive --- CHANGELOG.md | 1 + bin/loop_claude/cycle.py | 39 +++++++++++++++---------------- bin/loop_claude/file_writes.py | 8 +++++-- bin/loop_claude/main.py | 14 +++++------ bin/test_loop_claude.py | 15 +++++++----- bin/test_loop_claude_black_box.py | 38 ++++++++++++++++++++++++++---- todo.md | 1 - 7 files changed, 75 insertions(+), 41 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 66b2b001..816f50ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,4 +9,5 @@ - `loop-claude` skips a transcript line it cannot parse, exits 1 naming a transcript it cannot read, and counts a `claude` it cannot start as a failed worker run. - `loop-claude`'s judge quotes the transcript for every verdict, and a verdict quoting nothing or interrupting without a question, or a `claude` the judge cannot start, is a failed judge run; a `claude` that cannot start for an interrupt exits 1. - `loop-claude`'s exit-2 message says what the human is needed for. +- `loop-claude`'s archive holds the raw `.jsonl` transcript, one copy per content under its SHA-256, with the verdict beside it in `.verdict.md`; a transcript it cannot archive exits 1. - `loop-claude` keeps the mode of `~/.claude.json` and of its models file when it rewrites them, and creates the models file 0600. diff --git a/bin/loop_claude/cycle.py b/bin/loop_claude/cycle.py index c5b5e163..0554de54 100644 --- a/bin/loop_claude/cycle.py +++ b/bin/loop_claude/cycle.py @@ -1,9 +1,8 @@ -import os +import hashlib import sys -import time from loop_claude.checkout import project_name -from loop_claude.file_writes import make_private +from loop_claude.file_writes import make_private, replace_file from loop_claude.interrupt import interrupt from loop_claude.judge import judge from loop_claude.outcome import Continue, Failure, Retry, Stop @@ -20,7 +19,7 @@ def run_cycle(root, task, premises, models, paths): path = transcript_file(session) if not path: return Stop(1, f"claude left no transcript for session {session.id}") - # The interrupt appends to this transcript, so each pass judges and archives it anew; archive skips a stamp it already wrote. + # The interrupt appends to this transcript, so each pass judges and archives it anew. while True: entries = read(path) if isinstance(entries, Failure): @@ -30,30 +29,30 @@ def run_cycle(root, task, premises, models, paths): return verdict if not verdict["interrupt"]: break - archive(root, path, f"Task: {task}\n\nVerdict: interrupt\n\n{verdict['question']}", paths) + if failure := archive(root, path, f"Task: {task}\n\nVerdict: interrupt\n\n{verdict['question']}", paths): + return Stop(1, failure.reason) if stop := interrupt(root, session.id, models.worker, path, verdict["question"], paths): return stop if verdict["finished"]: - archive(root, path, f"Task: {task}\n\nVerdict: finished", paths) + if failure := archive(root, path, f"Task: {task}\n\nVerdict: finished", paths): + return Stop(1, failure.reason) delete_session(session) return Continue() def archive(root, path, note, paths): - # Stamped by mtime, so a transcript unchanged since its last archive maps to the file already written. - name = project_name(root, paths.code) - folder = paths.archive / name + folder = paths.archive / project_name(root, paths.code) try: - stamp = time.strftime("%Y-%m-%dT%H-%M-%SZ", time.gmtime(os.path.getmtime(path))) + with open(path, "rb") as handle: + raw = handle.read() make_private(folder) - dest = folder / f"{stamp}.md" - if not os.path.exists(dest): - entries = read(path) - if isinstance(entries, Failure): - print(f"could not archive the transcript: {entries.reason}", file=sys.stderr) - return - with open(os.open(dest, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as copy: - copy.write(f"# {stamp} {name}\n\n{note}\n\n{render(entries)}\n") - print(f"transcript: {dest}", file=sys.stderr) except OSError as failure: - print(f"could not archive the transcript: {failure}", file=sys.stderr) + return Failure(f"could not archive the transcript {path}: {failure.strerror}") + copy = folder / f"{hashlib.sha256(raw).hexdigest()}.jsonl" + # 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 {path}: {failure.strerror}") + print(f"transcript: {copy}", file=sys.stderr) + return None diff --git a/bin/loop_claude/file_writes.py b/bin/loop_claude/file_writes.py index 44cf070e..0654c309 100644 --- a/bin/loop_claude/file_writes.py +++ b/bin/loop_claude/file_writes.py @@ -11,12 +11,16 @@ def make_private(folder): def replace_json(path, data, **dump): + return replace_file(path, json.dumps(data, **dump).encode()) + + +def replace_file(path, data): staged = f"{path}.{os.getpid()}" try: mode = os.stat(path).st_mode & 0o7777 if os.path.exists(path) else 0o600 - with open(os.open(staged, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as handle: + with open(os.open(staged, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "wb") as handle: os.fchmod(handle.fileno(), mode) - json.dump(data, handle, **dump) + handle.write(data) os.replace(staged, path) except OSError as failure: if os.path.exists(staged): diff --git a/bin/loop_claude/main.py b/bin/loop_claude/main.py index 3e0d48f4..848cb6e4 100644 --- a/bin/loop_claude/main.py +++ b/bin/loop_claude/main.py @@ -11,19 +11,19 @@ its session next cycle; the next chunk starts a fresh session. Cycles continue until that interrupt or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary". Exit 1: no task, not inside a checkout, no premises, a models file it cannot read or write, claude -leaves no transcript or one it cannot read, claude cannot start for an interrupt, a reload with -unreadable state, or the worker or the judge fails three times running. A worker fails when claude -cannot start, exits non-zero, is killed, or ends without a result event; a judge when claude cannot -start or exits non-zero, or its verdict misses or mistypes a field, interrupts without a question, +leaves no transcript or one it cannot read or archive, claude cannot start for an interrupt, a +reload with unreadable state, or the worker or the judge fails three times running. A worker fails +when claude cannot start, exits non-zero, is killed, or ends without a result event; a judge when +claude cannot start or exits non-zero, or its verdict misses or mistypes a field, interrupts without a question, or quotes nothing in the transcript. Exit 2: the human is needed, to pick the model or answer an interrupt, and stdin or stdout is not a terminal, the input ends, or the interrupt ended with nothing typed. Rerunning resumes any open session. Each project has one session, "A loop-claude", being the checkout relative to ~/code, -or to / outside it, deleted when the chunk finishes. Its transcript is archived under -$LOOP_CLAUDE_TRANSCRIPTS// (default ~/.claude/loop-claude-transcripts) at every interrupt and -when the chunk finishes. +or to / outside it, deleted when the chunk finishes. At every interrupt and when the chunk finishes +its transcript is copied to $LOOP_CLAUDE_TRANSCRIPTS//.jsonl (default +~/.claude/loop-claude-transcripts), the verdict beside it in .verdict.md. Every claude it starts runs the project's model, saved per in ~/.claude/loop-claude-models.json and read each cycle; a project without an entry, as on its first run, is asked for one. diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 432645f9..5e4fef8d 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -224,19 +224,22 @@ class JudgePrompt(unittest.TestCase): class Archive(unittest.TestCase): - def test_keeps_the_copy_and_every_folder_it_creates_as_private_as_the_transcript(self): + def test_keeps_one_copy_per_content_and_every_folder_it_creates_as_private_as_the_transcript(self): with tempfile.TemporaryDirectory() as root: transcript = os.path.join(root, "session.jsonl") pathlib.Path(transcript).write_text(json.dumps(assistant({"type": "text", "text": "said"})) + "\n") paths = paths_from(pathlib.Path(root), {"LOOP_CLAUDE_TRANSCRIPTS": os.path.join(root, "deep", "archive")}) - cycle.archive("/srv/a/b", transcript, "note", paths) - [copy] = [os.path.join(folder, name) for folder, _, names in os.walk(paths.archive) for name in names] - self.assertEqual(stat.S_IMODE(os.stat(copy).st_mode), 0o600) - folder = os.path.dirname(copy) + with unittest.mock.patch("sys.stderr"): + for _ in range(2): + self.assertIsNone(cycle.archive("/srv/a/b", transcript, "note", paths)) + copies = [os.path.join(folder, name) for folder, _, names in os.walk(paths.archive) for name in names] + self.assertEqual(len(copies), 2) + for copy in copies: + self.assertEqual(stat.S_IMODE(os.stat(copy).st_mode), 0o600) + folder = os.path.dirname(copies[0]) while folder != root: self.assertEqual(stat.S_IMODE(os.stat(folder).st_mode), 0o700, folder) folder = os.path.dirname(folder) - self.assertIn("said", pathlib.Path(copy).read_text()) class Said(unittest.TestCase): diff --git a/bin/test_loop_claude_black_box.py b/bin/test_loop_claude_black_box.py index 51f84aff..aaf9f0a2 100644 --- a/bin/test_loop_claude_black_box.py +++ b/bin/test_loop_claude_black_box.py @@ -1,4 +1,5 @@ import dataclasses +import hashlib import json import os import pathlib @@ -229,8 +230,19 @@ class Checkout: def transcripts(self): return sorted((self.home / ".claude" / "projects").glob("*/*.jsonl")) + def archive(self): + return self.home / ".claude" / "loop-claude-transcripts" + def archived(self): - return sorted((self.home / ".claude" / "loop-claude-transcripts" / "proj").glob("*")) + """Each archived transcript's verdict, after checking the copy is named by its content hash.""" + verdicts = {} + for copy in sorted((self.archive() / "proj").glob("*.jsonl")): + self.test.assertEqual(copy.stem, hashlib.sha256(copy.read_bytes()).hexdigest()) + verdict = copy.with_suffix(".verdict.md") + for archived in (copy, verdict): + self.test.assertEqual(stat.S_IMODE(archived.stat().st_mode), 0o600) + verdicts[copy.read_text()] = verdict.read_text() + return verdicts def argument(call, flag): @@ -292,9 +304,22 @@ class Cycles(unittest.TestCase): self.assertIn("landed-it", run.calls[3]["stdin"]) self.assertNotIn("landed-it", run.calls[5]["stdin"]) self.assertIn("=== cycle 3 ===", run.stdout) - self.assertTrue(checkout.archived()) - for archived in checkout.archived(): - self.assertEqual(stat.S_IMODE(archived.stat().st_mode), 0o600) + [(copy, verdict)] = checkout.archived().items() + self.assertIn('"text": "landed-it"', copy) + self.assertEqual(verdict, f"Task: {TASK}\n\nVerdict: finished\n") + + def test_exits_1_when_the_transcript_cannot_be_archived_and_resumes_on_the_next_run(self): + checkout = Checkout(self) + checkout.archive().parent.mkdir(parents=True) + checkout.archive().write_text("in the way") + run = checkout.run([worker(say="landed-it"), judge(finished=True, evidence="landed-it")]) + self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"])) + self.assertRegex(run.stderr.strip().splitlines()[-1], r"^could not archive the transcript .*\.jsonl: ") + session = argument(run.calls[0], "--session-id") + checkout.archive().unlink() + run = checkout.run([worker(), judge(finished=True)]) + self.assertEqual(argument(run.calls[0], "--resume"), session) + self.assertEqual(len(checkout.archived()), 1) def test_stops_after_three_failures_running_retrying_a_minute_apart(self): checkout = Checkout(self) @@ -377,11 +402,14 @@ class Interrupt(unittest.TestCase): run = checkout.run(steps) self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"])) self.assertEqual(run.stderr.strip().splitlines()[-2:], ["A or B?", "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"]) - self.assertTrue(checkout.archived()) + [(copy, verdict)] = checkout.archived().items() + self.assertEqual(copy, (checkout.transcripts()[0]).read_text()) + self.assertEqual(verdict, f"Task: {TASK}\n\nVerdict: interrupt\n\nA or B?\n") session = argument(run.calls[0], "--session-id") run = checkout.run(steps, terminal_input="", stdout_on_terminal=False) self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"])) self.assertEqual(argument(run.calls[0], "--resume"), session) + self.assertEqual(len(checkout.archived()), 2) self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal") def test_hands_the_terminal_over_and_exits_2_when_nothing_is_typed(self): diff --git a/todo.md b/todo.md index 5d0c0702..9f744422 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,6 @@ The rebuild lifts every dimension: each item below is one chunk on a worktree based on `origin/rebuild`, its PR into `rebuild`, until the last item merges `rebuild` into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -- **Archive the raw transcript, deduplicated by content hash, with the verdict beside it, and stop on a failed archive.** Tests first; the changelog line says what the archive now holds. - **Replace `bin/test_loop_claude.py`'s internal-function tests with the black-box tests plus unit tests of the pure parsers.** - **Hold every reviewer to one findings document, `principles/review-findings.md`.** Severity, verdict, rounds with round 2 verifying each earlier finding, the per-chunk round cap, declining, and `/security-review`'s HIGH/MEDIUM/LOW mapped onto the scale; it replaces `principles/review-protocol.md`. - **Rewrite larv-review around one pass table and one re-entry rule.** A trigger per pass, each stated only there; the re-entry paragraph classifies a fix by the widest thing it touches; forge neutrality, the draft PR, CI watched in the foreground, the comprehension floor, the auto-reviewer's waits and the goal-alignment check carried over. -- 2.52.0 From a4b63e436e17e7b36334a250b22fef7b4d811ff5 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 17:00:41 +0200 Subject: [PATCH 029/233] Name the path an archive failed on --- bin/loop_claude/cycle.py | 4 ++-- bin/loop_claude/main.py | 4 ++-- bin/test_loop_claude_black_box.py | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/bin/loop_claude/cycle.py b/bin/loop_claude/cycle.py index 0554de54..6f763574 100644 --- a/bin/loop_claude/cycle.py +++ b/bin/loop_claude/cycle.py @@ -47,12 +47,12 @@ def archive(root, path, note, paths): raw = handle.read() make_private(folder) except OSError as failure: - return Failure(f"could not archive the transcript {path}: {failure.strerror}") + return Failure(f"could not archive the transcript: {failure.filename}: {failure.strerror}") copy = folder / f"{hashlib.sha256(raw).hexdigest()}.jsonl" # 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 {path}: {failure.strerror}") + return Failure(f"could not archive the transcript: {failure.filename}: {failure.strerror}") print(f"transcript: {copy}", file=sys.stderr) return None diff --git a/bin/loop_claude/main.py b/bin/loop_claude/main.py index 848cb6e4..973307cc 100644 --- a/bin/loop_claude/main.py +++ b/bin/loop_claude/main.py @@ -14,8 +14,8 @@ Exit 1: no task, not inside a checkout, no premises, a models file it cannot rea leaves no transcript or one it cannot read or archive, claude cannot start for an interrupt, a reload with unreadable state, or the worker or the judge fails three times running. A worker fails when claude cannot start, exits non-zero, is killed, or ends without a result event; a judge when -claude cannot start or exits non-zero, or its verdict misses or mistypes a field, interrupts without a question, -or quotes nothing in the transcript. +claude cannot start or exits non-zero, or its verdict misses or mistypes a field, interrupts without a +question, or quotes nothing in the transcript. Exit 2: the human is needed, to pick the model or answer an interrupt, and stdin or stdout is not a terminal, the input ends, or the interrupt ended with nothing typed. Rerunning resumes any open session. diff --git a/bin/test_loop_claude_black_box.py b/bin/test_loop_claude_black_box.py index aaf9f0a2..8ca5735b 100644 --- a/bin/test_loop_claude_black_box.py +++ b/bin/test_loop_claude_black_box.py @@ -314,7 +314,7 @@ class Cycles(unittest.TestCase): checkout.archive().write_text("in the way") run = checkout.run([worker(say="landed-it"), judge(finished=True, evidence="landed-it")]) self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"])) - self.assertRegex(run.stderr.strip().splitlines()[-1], r"^could not archive the transcript .*\.jsonl: ") + self.assertRegex(run.stderr.strip().splitlines()[-1], r"^could not archive the transcript: .*/loop-claude-transcripts/proj: Not a directory$") session = argument(run.calls[0], "--session-id") checkout.archive().unlink() run = checkout.run([worker(), judge(finished=True)]) -- 2.52.0 From 80a8e214b1f29a7f84e31c769a73011e4a86abd8 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 17:01:56 +0200 Subject: [PATCH 030/233] Name the archive file a write failed on --- bin/loop_claude/cycle.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/loop_claude/cycle.py b/bin/loop_claude/cycle.py index 6f763574..9c5a144c 100644 --- a/bin/loop_claude/cycle.py +++ b/bin/loop_claude/cycle.py @@ -53,6 +53,6 @@ def archive(root, path, note, paths): 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: {failure.filename}: {failure.strerror}") + return Failure(f"could not archive the transcript: {dest}: {failure.strerror}") print(f"transcript: {copy}", file=sys.stderr) return None -- 2.52.0 From 47a281a4ee6208ffb67d902d49a7863cf3dd0ce0 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 17:03:33 +0200 Subject: [PATCH 031/233] Reword the archive's changelog line --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 816f50ac..cae8c26f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,5 +9,5 @@ - `loop-claude` skips a transcript line it cannot parse, exits 1 naming a transcript it cannot read, and counts a `claude` it cannot start as a failed worker run. - `loop-claude`'s judge quotes the transcript for every verdict, and a verdict quoting nothing or interrupting without a question, or a `claude` the judge cannot start, is a failed judge run; a `claude` that cannot start for an interrupt exits 1. - `loop-claude`'s exit-2 message says what the human is needed for. -- `loop-claude`'s archive holds the raw `.jsonl` transcript, one copy per content under its SHA-256, with the verdict beside it in `.verdict.md`; a transcript it cannot archive exits 1. +- `loop-claude`'s archive holds the raw `.jsonl` transcript, one copy per distinct transcript, named by its SHA-256, with the verdict beside it in `.verdict.md`; a transcript it cannot archive exits 1. - `loop-claude` keeps the mode of `~/.claude.json` and of its models file when it rewrites them, and creates the models file 0600. -- 2.52.0 From 5d3a43ba2e91a9aa1efdb8d5822e6262cfe89cbf Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 17:07:24 +0200 Subject: [PATCH 032/233] Clarify the archive decision's stamp reason and file its missing goal --- docs/decisions.md | 2 +- todo.md | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/decisions.md b/docs/decisions.md index 598eb123..1ce66849 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -70,7 +70,7 @@ ## loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop -2026-09-28, lilleman, for the rebuild. Serves goal 2. A copy of the `.jsonl`, deduplicated by content hash, with the verdict beside it; a rendering drops tool results, and a second-resolution stamp collapses two states. A failed archive exits 1, since a loop that loses its record silently fails the backup goal. Valid while transcripts stay small enough to copy whole. +2026-09-28, lilleman, for the rebuild. Serves goal 2. A copy of the `.jsonl`, deduplicated by content hash, with the verdict beside it; a rendering drops tool results, and a second-resolution stamp names two states within one second as one file. A failed archive exits 1, since a loop that loses its record silently fails the backup goal. Valid while transcripts stay small enough to copy whole. ## loop-claude: the rebuild keeps main's `--reloaded` state diff --git a/todo.md b/todo.md index 9f744422..0731d05d 100644 --- a/todo.md +++ b/todo.md @@ -10,6 +10,7 @@ The rebuild lifts every dimension: each item below is one chunk on a worktree ba - **Hold every reviewer to one findings document, `principles/review-findings.md`.** Severity, verdict, rounds with round 2 verifying each earlier finding, the per-chunk round cap, declining, and `/security-review`'s HIGH/MEDIUM/LOW mapped onto the scale; it replaces `principles/review-protocol.md`. - **Rewrite larv-review around one pass table and one re-entry rule.** A trigger per pass, each stated only there; the re-entry paragraph classifies a fix by the widest thing it touches; forge neutrality, the draft PR, CI watched in the foreground, the comprehension floor, the auto-reviewer's waits and the goal-alignment check carried over. - **Make the three reviewer agents pure reporters in the findings document's vocabulary.** Keep their names and checklists; remove every README- and decision-writing duty and every private severity or verdict scale. +- **Link the archive decision in `docs/decisions.md` to a goal that covers it.** It cites goal 2, but the archive is git-ignored and goal 3 keeps transcripts off the remote, so it backs nothing up; goal 4 (reviewing unattended runs) is the nearest, and the human picks. - **Bring `CLAUDE.md` → "Vocabulary", the README and `docs/decisions.md` in line with the rebuild.** Trigger covers every pass, round cap counts per chunk, "looping reviewer" goes if the rule no longer needs it; superseded decisions leave the log. - **Score `rebuild` with the four-seat panel at 7.0 or above on every dimension and the overall, none below the 2026-09-28 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. A loop running main's script reloads into the new one and carries on (`docs/decisions.md`). -- 2.52.0 From 55f17b3368e902a7649e8a6de14f631d1b4a3233 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 19:05:48 +0200 Subject: [PATCH 033/233] Cover the transcript archive in goal 2 and plan its backup --- README.md | 2 +- docs/decisions.md | 2 +- todo.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 23517f60..0ba7dd96 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ My personal `~/.claude`, version controlled: `CLAUDE.md` and `AGENTS.md` for ins ## Goals 1. Share this configuration between my computers. -2. Keep it backed up. +2. Keep it, and the transcripts of unattended runs, backed up. 3. Leak nothing to the remote — no credentials, no transcripts, no memory files. 4. Run work chunks unattended, interrupting me only when a decision is mine. diff --git a/docs/decisions.md b/docs/decisions.md index 1ce66849..0f646fe9 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -70,7 +70,7 @@ ## loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop -2026-09-28, lilleman, for the rebuild. Serves goal 2. A copy of the `.jsonl`, deduplicated by content hash, with the verdict beside it; a rendering drops tool results, and a second-resolution stamp names two states within one second as one file. A failed archive exits 1, since a loop that loses its record silently fails the backup goal. Valid while transcripts stay small enough to copy whole. +2026-09-28, lilleman, for the rebuild. Serves goals 2 and 4: saving each transcript locally is the first step of backing it up, and it shows afterwards what an unattended run did. A copy of the `.jsonl`, deduplicated by content hash, with the verdict beside it; a rendering drops tool results, and a second-resolution stamp names two states within one second as one file. A failed archive exits 1, since a loop that loses its record silently fails the backup goal. Valid while transcripts stay small enough to copy whole. ## loop-claude: the rebuild keeps main's `--reloaded` state diff --git a/todo.md b/todo.md index 0731d05d..8c6a170d 100644 --- a/todo.md +++ b/todo.md @@ -10,10 +10,10 @@ The rebuild lifts every dimension: each item below is one chunk on a worktree ba - **Hold every reviewer to one findings document, `principles/review-findings.md`.** Severity, verdict, rounds with round 2 verifying each earlier finding, the per-chunk round cap, declining, and `/security-review`'s HIGH/MEDIUM/LOW mapped onto the scale; it replaces `principles/review-protocol.md`. - **Rewrite larv-review around one pass table and one re-entry rule.** A trigger per pass, each stated only there; the re-entry paragraph classifies a fix by the widest thing it touches; forge neutrality, the draft PR, CI watched in the foreground, the comprehension floor, the auto-reviewer's waits and the goal-alignment check carried over. - **Make the three reviewer agents pure reporters in the findings document's vocabulary.** Keep their names and checklists; remove every README- and decision-writing duty and every private severity or verdict scale. -- **Link the archive decision in `docs/decisions.md` to a goal that covers it.** It cites goal 2, but the archive is git-ignored and goal 3 keeps transcripts off the remote, so it backs nothing up; goal 4 (reviewing unattended runs) is the nearest, and the human picks. - **Bring `CLAUDE.md` → "Vocabulary", the README and `docs/decisions.md` in line with the rebuild.** Trigger covers every pass, round cap counts per chunk, "looping reviewer" goes if the rule no longer needs it; superseded decisions leave the log. - **Score `rebuild` with the four-seat panel at 7.0 or above on every dimension and the overall, none below the 2026-09-28 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. A loop running main's script reloads into the new one and carries on (`docs/decisions.md`). ## 0.2.0 +- **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. -- 2.52.0 From 0e587d75df241e0c5dfb7104bb7f0f9252c59833 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 19:17:13 +0200 Subject: [PATCH 034/233] Move loop-claude's internal-function tests into the black-box tests, keeping unit tests of the pure parsers --- bin/test_loop_claude.py | 413 +----------------------------- bin/test_loop_claude_black_box.py | 153 +++++++++-- todo.md | 1 - 3 files changed, 140 insertions(+), 427 deletions(-) diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 5e4fef8d..736a3667 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -1,30 +1,14 @@ -import contextlib -import errno -import io import json -import os import pathlib -import shutil -import stat -import subprocess import sys -import tempfile import unittest -import unittest.mock -import uuid sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -from loop_claude import checkout, cycle, interrupt, judge, main, models, premises, reload, session, transcript, trust, worker -from loop_claude.outcome import Continue, Failure, Retry, Stop -from loop_claude.paths import paths_from +from loop_claude import judge, main, premises, transcript +from loop_claude.outcome import Stop CWD = pathlib.Path("/c") -LAUNCHER = pathlib.Path(__file__).resolve().with_name("loop-claude") -PATHS = paths_from(pathlib.Path("/h"), {}) -SESSION_ID = str(getattr(uuid, "uuid7", uuid.uuid4)()) -SESSION = session.Session(uuid.UUID(SESSION_ID), "A name", PATHS.projects) -OPUS = models.Models("claude-opus-5-5", "claude-opus-5-5") def assistant(*parts): @@ -35,52 +19,12 @@ def human(content): return {"type": "user", "message": {"content": content}} -@contextlib.contextmanager -def umask(mask): - previous = os.umask(mask) - try: - yield - finally: - os.umask(previous) - - class Sections(unittest.TestCase): def test_keeps_every_headed_section_with_its_bodies(self): text = "# Title\n\nintro\n\n## Goals\n\n1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority\n\n## Empty\n\n## Audience\nme\n## Audience\nagain\n# Appendix\nnot audience\n" self.assertEqual(premises.sections(text), {"Goals": ["1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority"], "Empty": [""], "Audience": ["me", "again"]}) -class ReadPremises(unittest.TestCase): - def exit_message(self, root): - stop = premises.read_premises(root) - self.assertEqual(stop.code, 1) - self.assertTrue(stop.reason.endswith("no premises.")) - return stop.reason - - def test_names_what_is_missing(self): - texts = { - "# T\n## Audience\nme\n": "no ## Goals heading", - "# T\n## Goals\n\n## Audience\nme\n": "nothing under ## Goals", - "# T\n## Goals\n1. g\n": "no ## Audience heading", - "# T\n## Goals\n1. g\n## Audience\n": "nothing under ## Audience", - "# T\n## Goals\n1. g\n## Audience\nme\n## Goals\n": "## Goals more than once", - } - with tempfile.TemporaryDirectory() as root: - readme = os.path.join(root, "README.md") - self.assertIn(f"README.md in {root}: No such file or directory", self.exit_message(root)) - os.mkdir(readme) - self.assertIn("Is a directory", self.exit_message(root)) - os.rmdir(readme) - pathlib.Path(readme).write_bytes(b"# T\n## Goals\n1. g\xff\n## Audience\nme\n") - self.assertIn("README.md is not UTF-8 on line 3", self.exit_message(root)) - for text, missing in texts.items(): - with self.subTest(missing=missing): - pathlib.Path(readme).write_text(text) - self.assertIn(missing, self.exit_message(root)) - pathlib.Path(readme).write_text("# T\n## Goals\n1. g\n## Audience\nme\n") - self.assertEqual(premises.read_premises(root), "## Goals\n1. g\n\n## Audience\nme") - - class Render(unittest.TestCase): def test_joins_assistant_text_and_tool_calls_and_human_turns_and_skips_the_rest(self): said = transcript.render([ @@ -110,138 +54,6 @@ class HumanTurns(unittest.TestCase): ]), 2) -class CheckoutRoot(unittest.TestCase): - def test_is_the_checkout_from_any_directory_inside_it_and_exits_outside_one(self): - with tempfile.TemporaryDirectory() as tmp, contextlib.chdir(tmp): - root = os.getcwd() - self.assertEqual(checkout.checkout_root(os.getcwd()).code, 1) - subprocess.run(["git", "init", "-q"], check=True) - os.makedirs("a/b") - with contextlib.chdir("a/b"): - self.assertEqual(checkout.checkout_root(os.getcwd()), root) - subprocess.run(["git", "init", "-q", "other"], check=True) - with contextlib.chdir("other"): - self.assertEqual(checkout.checkouts(root), [root]) - - -class ProjectName(unittest.TestCase): - def test_names_a_checkout_relative_to_code_and_any_other_relative_to_root(self): - code = pathlib.Path("/h/code") - self.assertEqual(checkout.project_name("/h/code/a/b", code), "a/b") - self.assertEqual(session.session_for("/h/code/a/b", PATHS).name, "A a/b loop-claude") - self.assertEqual(checkout.project_name("/h/code", code), "h/code") - self.assertEqual(checkout.project_name("/srv/x", code), "srv/x") - self.assertEqual(session.session_for("/srv/x", PATHS).name, "A srv/x loop-claude") - - -class WorkerArgs(unittest.TestCase): - def test_a_fresh_cycle_names_the_session_and_asks_to_continue_open_work(self): - args = worker.worker_args("the task", SESSION, "m", resuming=False) - self.assertIn("--session-id", args) - self.assertEqual(args[args.index("--name") + 1], "A name") - self.assertTrue(args[1].startswith("the task\n\nContinue any open draft PR")) - - def test_a_resumed_cycle_reuses_the_session(self): - args = worker.worker_args("paint the fence", SESSION, "m", resuming=True) - self.assertEqual(args[args.index("--resume") + 1], str(SESSION.id)) - self.assertNotIn("--name", args) - self.assertNotIn("paint the fence", args[1]) - - -class ProjectModel(unittest.TestCase): - def test_asks_once_per_project_from_the_newest_catalog_and_saves_the_answer(self): - with tempfile.TemporaryDirectory() as home, unittest.mock.patch.object(sys, "stderr", io.StringIO()), umask(0o022): - paths = paths_from(pathlib.Path(home), {}) - saved = pathlib.Path(home, ".claude", "loop-claude-models.json") - catalog = pathlib.Path(home, ".claude", "cache", "model-catalog") - catalog.mkdir(parents=True) - for name, fetched, ids in (("old.json", 1, ["claude-opus-5"]), ("new.json", 2, ["claude-opus-5-5", "claude-sonnet-5"])): - catalog.joinpath(name).write_text(json.dumps({"fetchedAt": fetched, "catalog": {"config": {"models": [{"id": id, "name": id.upper()} for id in ids]}}})) - with unittest.mock.patch("sys.stdin.isatty", return_value=False): - stop = models.project_models("/srv/a", paths, {}) - self.assertEqual(stop.code, 2) - self.assertIn(f'merge {{"srv/a": ""}} into {saved}', stop.reason) - self.assertFalse(saved.exists()) - with unittest.mock.patch("sys.stdin.isatty", return_value=False): - self.assertEqual(models.project_models("/srv/a", paths, {"LOOP_CLAUDE_JUDGE_MODEL": "j", "LOOP_CLAUDE_WORKER_MODEL": "w"}), models.Models("j", "w")) - self.assertEqual(models.project_models("/srv/a", paths, {"LOOP_CLAUDE_JUDGE_MODEL": "j"}).code, 2) - with ( - unittest.mock.patch("sys.stdin.isatty", return_value=True), - unittest.mock.patch("sys.stdout.isatty", return_value=True), - unittest.mock.patch("builtins.input", side_effect=["", "3", "2"]) as typed, - ): - self.assertEqual(models.project_models("/srv/a", paths, {}), models.Models("claude-sonnet-5", "claude-sonnet-5")) - self.assertEqual(typed.call_count, 3) - self.assertIn("2. CLAUDE-SONNET-5 (claude-sonnet-5)", sys.stderr.getvalue()) - self.assertIn("pick 1 to 2", sys.stderr.getvalue()) - self.assertIn("srv/a runs on claude-sonnet-5", sys.stderr.getvalue()) - self.assertNotIn("claude-opus-5)", sys.stderr.getvalue()) - self.assertEqual(stat.S_IMODE(saved.stat().st_mode), 0o600) - saved.chmod(0o640) - def saved_elsewhere_while_asking(prompt): - saved.write_text(json.dumps({**json.loads(saved.read_text()), "srv/d": "haiku"})) - return "opus[1m]" - typed.side_effect = saved_elsewhere_while_asking - self.assertEqual(models.project_models("/srv/b", paths, {}), models.Models("opus[1m]", "opus[1m]")) - self.assertEqual(models.project_models("/srv/a", paths, {}), models.Models("claude-sonnet-5", "claude-sonnet-5")) - self.assertEqual(models.project_models("/srv/a", paths, {"LOOP_CLAUDE_WORKER_MODEL": "w"}), models.Models("claude-sonnet-5", "w")) - self.assertEqual(typed.call_count, 4) - typed.side_effect = EOFError - self.assertEqual(models.project_models("/srv/c", paths, {}), Stop(2, "the human is needed to pick srv/c's model, but the input ended")) - typed.side_effect = ["sonnet"] - with unittest.mock.patch("os.replace", side_effect=OSError(errno.EACCES, "Permission denied")): - self.assertEqual(models.project_models("/srv/c", paths, {}), Stop(1, f"could not save the model in {saved}: Permission denied")) - self.assertEqual(json.loads(saved.read_text()), {"srv/a": "claude-sonnet-5", "srv/b": "opus[1m]", "srv/d": "haiku"}) - self.assertEqual(stat.S_IMODE(saved.stat().st_mode), 0o640) - self.assertEqual(sorted(os.listdir(saved.parent)), ["cache", "loop-claude-models.json"]) - for shape in ({"fetchedAt": 3, "catalog": {"config": {"models": []}}}, {"fetchedAt": 3, "catalog": None}, {"fetchedAt": 3, "catalog": {"config": []}}, {"fetchedAt": 3, "catalog": {"config": {"models": "x"}}}): - catalog.joinpath("new.json").write_text(json.dumps(shape)) - with self.subTest(shape=shape): - self.assertEqual(models.catalog(catalog), []) - with ( - unittest.mock.patch("sys.stdin.isatty", return_value=True), - unittest.mock.patch("sys.stdout.isatty", return_value=True), - unittest.mock.patch("builtins.input", side_effect=["1"]) as typed, - ): - self.assertEqual(models.project_models("/srv/e", paths, {}), models.Models("1", "1")) - self.assertEqual(typed.call_args.args[0], "A name claude --model takes: ") - self.assertIn("no model catalog cached", sys.stderr.getvalue()) - for broken in ("{", "[]", '{"srv/a": 1}'): - saved.write_text(broken) - with self.subTest(broken=broken): - stop = models.project_models("/srv/a", paths, {}) - self.assertEqual(stop.code, 1) - self.assertTrue(stop.reason.startswith(f"could not read {saved}: ")) - self.assertEqual(saved.read_text(), broken) - - -class JudgePrompt(unittest.TestCase): - def test_hands_the_judge_the_tail_of_a_long_transcript(self): - prompt = judge.judge_prompt("task", "## Goals\n1. g", "early " * 20000 + "LATE") - self.assertIn("LATE", prompt) - self.assertLess(prompt.count("early"), 20000) - self.assertTrue(prompt.endswith(judge.JUDGE_RULES)) - - -class Archive(unittest.TestCase): - def test_keeps_one_copy_per_content_and_every_folder_it_creates_as_private_as_the_transcript(self): - with tempfile.TemporaryDirectory() as root: - transcript = os.path.join(root, "session.jsonl") - pathlib.Path(transcript).write_text(json.dumps(assistant({"type": "text", "text": "said"})) + "\n") - paths = paths_from(pathlib.Path(root), {"LOOP_CLAUDE_TRANSCRIPTS": os.path.join(root, "deep", "archive")}) - with unittest.mock.patch("sys.stderr"): - for _ in range(2): - self.assertIsNone(cycle.archive("/srv/a/b", transcript, "note", paths)) - copies = [os.path.join(folder, name) for folder, _, names in os.walk(paths.archive) for name in names] - self.assertEqual(len(copies), 2) - for copy in copies: - self.assertEqual(stat.S_IMODE(os.stat(copy).st_mode), 0o600) - folder = os.path.dirname(copies[0]) - while folder != root: - self.assertEqual(stat.S_IMODE(os.stat(folder).st_mode), 0o700, folder) - folder = os.path.dirname(folder) - - class Said(unittest.TestCase): def test_renders_text_and_tool_calls_and_nothing_else(self): self.assertEqual(transcript.said({"type": "text", "text": "hi"}), "hi") @@ -250,89 +62,6 @@ class Said(unittest.TestCase): self.assertEqual(transcript.said("not a part"), "") -class DeleteTranscriptFiles(unittest.TestCase): - def test_deletes_the_transcript_and_its_siblings_so_the_session_is_gone(self): - with tempfile.TemporaryDirectory() as home: - projects = paths_from(pathlib.Path(home), {}).projects - root = os.path.join(projects, "p") - os.makedirs(root) - transcript = os.path.join(root, f"{SESSION_ID}.jsonl") - pathlib.Path(transcript).write_text("{}\n") - os.makedirs(os.path.join(root, SESSION_ID, "subagents")) - os.makedirs(os.path.join(root, f"{SESSION_ID}.superseded-1", "tool-results")) - pathlib.Path(root, f"{SESSION_ID}.orphaned-1-ab.jsonl").write_text("{}\n") - located = session.Session(uuid.UUID(SESSION_ID), "A name", projects) - self.assertEqual(session.transcript_file(located), transcript) - session.delete_session(located) - self.assertEqual(os.listdir(root), []) - self.assertEqual(session.transcript_file(located), "") - - -class Interrupt(unittest.TestCase): - def test_says_whether_no_terminal_or_nothing_typed_ended_it(self): - with tempfile.TemporaryDirectory() as root: - transcript = os.path.join(root, "session.jsonl") - pathlib.Path(transcript).write_text("{}\n") - with unittest.mock.patch("sys.stdin.isatty", return_value=False): - self.assertEqual(interrupt.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {})), Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal")) - with ( - unittest.mock.patch("sys.stdin.isatty", return_value=True), - unittest.mock.patch("sys.stdout.isatty", return_value=True), - unittest.mock.patch.multiple(interrupt, checkouts=unittest.mock.DEFAULT, trust=unittest.mock.DEFAULT) as mocks, - unittest.mock.patch("subprocess.run") as run, - ): - self.assertEqual(interrupt.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {})), Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed")) - mocks["checkouts"].assert_called_with(root) - self.assertEqual(run.call_args.kwargs["cwd"], root) - self.assertEqual(run.call_args.args[0][run.call_args.args[0].index("--model") + 1], "m") - def type_a_turn(*args, **kwargs): - with open(transcript, "a") as handle: - handle.write(json.dumps(human("typed")) + "\n") - - run.side_effect = type_a_turn - self.assertIsNone(interrupt.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}))) - - -class Trust(unittest.TestCase): - def test_says_why_the_config_cannot_be_read_and_records_only_what_is_new(self): - with tempfile.TemporaryDirectory() as home, umask(0o022): - config = pathlib.Path(home, ".claude.json") - with contextlib.redirect_stderr(io.StringIO()) as err: - trust.trust(config, ["/a"]) - self.assertEqual(err.getvalue(), f"could not read {config}: No such file or directory\n") - config.write_text("{") - with contextlib.redirect_stderr(io.StringIO()) as err: - trust.trust(config, ["/a"]) - self.assertIn(f"could not read {config}: ", err.getvalue()) - for shape, said in (([], 'not an object whose "projects" is an object'), ({"projects": []}, 'not an object whose "projects" is an object'), ({"projects": {"/a": 1}}, 'projects["/a"] is not an object')): - config.write_text(json.dumps(shape)) - with contextlib.redirect_stderr(io.StringIO()) as err: - trust.trust(config, ["/a"]) - self.assertEqual(err.getvalue(), f"could not read {config}: {said}\n") - self.assertEqual(json.loads(config.read_text()), shape) - data = {"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True, "kept": 2}}} - config.write_text(json.dumps(data)) - config.chmod(0o600) - with contextlib.redirect_stderr(io.StringIO()) as err: - trust.trust(config, ["/a"]) - self.assertEqual(err.getvalue(), "") - self.assertEqual(json.loads(config.read_text()), data) - with contextlib.redirect_stderr(io.StringIO()) as err: - trust.trust(config, ["/a", "/b"]) - self.assertEqual(err.getvalue(), "trusted for the interrupt: /b\n") - data["projects"]["/b"] = {"hasTrustDialogAccepted": True} - self.assertEqual(json.loads(config.read_text()), data) - with ( - contextlib.redirect_stderr(io.StringIO()) as err, - unittest.mock.patch("os.replace", side_effect=OSError(errno.EACCES, "Permission denied")), - ): - trust.trust(config, ["/c"]) - self.assertEqual(err.getvalue(), f"could not write {config}: Permission denied\n") - self.assertEqual(json.loads(config.read_text()), data) - self.assertEqual(stat.S_IMODE(config.stat().st_mode), 0o600) - self.assertEqual(os.listdir(home), [".claude.json"]) - - class Parse(unittest.TestCase): def test_yields_only_json_objects(self): self.assertEqual(transcript.parse('{"type": "user"}'), {"type": "user"}) @@ -358,148 +87,12 @@ class Verdict(unittest.TestCase): self.assertEqual(judge.incomplete(None), "the judge returned no verdict") -STUB_CLAUDE = """#!/usr/bin/env python3 -import json, os, pathlib, sys -args = sys.argv[1:] -with open(os.environ["STUB_CALLS"], "a") as calls: - calls.write(json.dumps([os.getcwd(), *args]) + "\\n") -if "--json-schema" in args: - plan = pathlib.Path(os.environ["STUB_VERDICTS"]).read_text().split() - pathlib.Path(os.environ["STUB_VERDICTS"]).write_text(" ".join(plan[1:])) - if plan[0] == "fail": - sys.exit(1) - interrupt = plan[0] in ("interrupt", "unquoted") - print(json.dumps({"structured_output": {"interrupt": interrupt, "evidence": {"interrupt": "worked", "unquoted": "invented"}.get(plan[0], "worked"), "finished": plan[0] == "finished", "question": "q?" if interrupt else ""}})) -else: - flag = "--session-id" if "--session-id" in args else "--resume" - folder = os.path.expanduser("~/.claude/projects/p") - os.makedirs(folder, exist_ok=True) - with open(os.path.join(folder, args[args.index(flag) + 1] + ".jsonl"), "a") as transcript: - transcript.write(json.dumps({"type": "assistant", "message": {"content": [{"type": "text", "text": "worked"}]}}) + "\\n") - print(json.dumps({"type": "result"})) -""" - - -class RunWorker(unittest.TestCase): - def test_says_whether_a_non_zero_exit_or_a_missing_result_event_failed_it(self): - with tempfile.TemporaryDirectory() as bin: - stub = os.path.join(bin, "claude") - scripts = { - None: 'print(json.dumps({"type": "result"}))', - "claude exited 0 without a result event": 'print(json.dumps({"type": "assistant", "message": {"content": [{"type": "text", "text": "worked"}]}}))', - "claude exited 3": "sys.exit(3)", - "claude killed by signal 9": "os.kill(os.getpid(), 9)", - } - with unittest.mock.patch.dict(os.environ, {"PATH": f"{bin}:{os.environ['PATH']}"}), unittest.mock.patch.object(sys, "stdout", io.StringIO()): - for failure, script in scripts.items(): - pathlib.Path(stub).write_text(f"#!/usr/bin/env python3\nimport json\nimport os\nimport sys\n{script}\n") - os.chmod(stub, 0o700) - self.assertEqual(worker.run_worker(bin, []), failure and Failure(failure)) - - -class RunCycle(unittest.TestCase): - def test_resumes_until_the_judge_calls_the_chunk_finished_and_rejudges_a_failed_or_unquoted_verdict(self): - with tempfile.TemporaryDirectory() as home: - stub = os.path.join(home, "claude") - pathlib.Path(stub).write_text(STUB_CLAUDE) - os.chmod(stub, 0o700) - calls, verdicts = os.path.join(home, "calls"), os.path.join(home, "verdicts") - session_id = session.session_for(home, paths_from(pathlib.Path(home), {})).id - pathlib.Path(verdicts).write_text("fail continue finished unquoted continue") - paths = paths_from(pathlib.Path(home), {"LOOP_CLAUDE_TRANSCRIPTS": os.path.join(home, "archive")}) - environment = {"HOME": home, "PATH": f"{home}:{os.environ['PATH']}", "STUB_CALLS": calls, "STUB_VERDICTS": verdicts} - with unittest.mock.patch.dict(os.environ, environment), unittest.mock.patch("time.sleep") as sleep, unittest.mock.patch("sys.stdin.isatty", return_value=False): - for _ in range(3): - self.assertEqual(cycle.run_cycle(home, "task", "premises", OPUS, paths), Continue()) - pathlib.Path(verdicts).write_text("interrupt") - with unittest.mock.patch("sys.stderr") as stderr: - self.assertEqual(cycle.run_cycle(home, "task", "premises", OPUS, paths), Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal")) - self.assertIn(f"transcript: {paths.archive}", "".join(str(call.args[0]) for call in stderr.write.call_args_list)) - pathlib.Path(verdicts).write_text("interrupt fail fail fail") - with unittest.mock.patch("sys.stderr"), unittest.mock.patch.object(cycle, "interrupt", return_value=None): - self.assertEqual(cycle.run_cycle(home, "task", "premises", OPUS, paths).code, 1) - with unittest.mock.patch.object(cycle, "transcript_file", return_value=""): - self.assertEqual(cycle.run_cycle(home, "task", "premises", OPUS, paths), Stop(1, f"claude left no transcript for session {session_id}")) - for plan in ("fail fail fail", "unquoted unquoted unquoted"): - pathlib.Path(verdicts).write_text(plan) - stop = cycle.run_cycle(home, "task", "premises", OPUS, paths) - self.assertEqual(stop.code, 1) - self.assertTrue(stop.reason.startswith("the judge ")) - if plan.startswith("unquoted"): - self.assertIn("for the question: q?", stop.reason) - self.assertEqual(pathlib.Path(verdicts).read_text(), "") - self.assertEqual({json.loads(line)[0] for line in pathlib.Path(calls).read_text().splitlines()}, {home}) - starts = [args[args.index("-p") + 1:][:3] for args in map(json.loads, pathlib.Path(calls).read_text().splitlines()) if "--json-schema" not in args] - self.assertEqual([start[1] for start in starts], ["--name", "--resume", "--name", "--resume", "--resume", "--name", "--resume", "--resume"]) - self.assertEqual(starts[1][2], str(session_id)) - self.assertEqual(sleep.call_count, 8) - self.assertEqual({args[args.index("--model") + 1] for args in map(json.loads, pathlib.Path(calls).read_text().splitlines())}, {"claude-opus-5-5"}) - - -class Reload(unittest.TestCase): - def test_an_edited_package_file_reloads_once_the_launcher_answers_help(self): - with tempfile.TemporaryDirectory() as root: - copy = pathlib.Path(root, "bin") - shutil.copytree(LAUNCHER.parent, copy, ignore=shutil.ignore_patterns("__pycache__", "test_*")) - launcher, edited = copy / "loop-claude", copy / "loop_claude" / "cycle.py" - state = main.LoopState(1, 2, "/r", "do it") - with unittest.mock.patch("os.execv") as execv, contextlib.redirect_stderr(io.StringIO()) as err: - baseline = reload.fingerprint(launcher) - edited.write_text(edited.read_text() + "\ndef\n") - reload.reload_if_edited(launcher, baseline, state) - execv.assert_not_called() - self.assertIn("keeping the running script", err.getvalue()) - edited.write_text(edited.read_text().replace("\ndef\n", "\n# edited\n")) - reload.reload_if_edited(launcher, baseline, state) - execv.assert_called_once_with(sys.executable, [sys.executable, str(launcher), main.RELOAD_FLAG, json.dumps({"cycle_number": 1, "failures": 2, "root": "/r", "task": "do it"})]) - - -class Main(unittest.TestCase): - def test_returns_the_exit_code_of_the_stop_the_loop_returned(self): - for argv, code, stream in ((["--help"], 0, "stdout"), ([], 1, "stderr"), ([main.RELOAD_FLAG, "3"], 1, "stderr")): - with self.subTest(argv=argv), contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as err: - self.assertEqual(main.main(argv, {}, PATHS, LAUNCHER, CWD), code) - self.assertEqual({"stdout": out, "stderr": err}[stream].getvalue(), main.loop_state(argv, CWD).reason + "\n") - with unittest.mock.patch.object(main, "run_loop", side_effect=KeyboardInterrupt): - self.assertEqual(main.main(["t"], {}, PATHS, LAUNCHER, CWD), 130) - - -class RunLoop(unittest.TestCase): +class LoopState(unittest.TestCase): def test_stops_naming_the_reload_when_it_hands_over_anything_but_the_state_with_a_task(self): for handed in (["3", "2", "/r", "do it"], ["3"], ["[1]"], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": ""})], [json.dumps({"cycle_number": "3", "failures": 0, "root": "/r", "task": "do it"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "", "task": "do it"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it", "turns": 1})]): with self.subTest(handed=handed): self.assertEqual(main.loop_state([main.RELOAD_FLAG, *handed], CWD), Stop(1, f"the reload cannot read the loop's state from {handed}; rerun loop-claude ")) - def test_resumes_the_root_and_counters_a_reload_handed_over(self): - patches = [unittest.mock.patch.object(main, name) for name in ("checkout_root", "read_premises", "reload_if_edited", "run_cycle", "project_models")] - stopped = Stop(1, "stopped") - with contextlib.ExitStack() as stack: - mocks = [stack.enter_context(patch) for patch in patches] - stack.enter_context(unittest.mock.patch.object(sys, "stdout", io.StringIO())) - mocks[3].return_value = stopped - self.assertEqual(main.run_loop([main.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 2, "root": "/r", "task": "do it"})], {}, PATHS, LAUNCHER, CWD), stopped) - mocks[0].assert_not_called() - mocks[1].assert_called_once_with("/r") - self.assertEqual(mocks[2].call_args.args[2], main.LoopState(3, 2, "/r", "do it")) - self.assertEqual(mocks[3].call_args.args[0], "/r") - mocks[4].assert_called_once_with("/r", PATHS, {}) - self.assertEqual(mocks[3].call_args.args[3], mocks[4].return_value) - mocks[0].return_value = "/s" - self.assertEqual(main.run_loop(["do", "it"], {}, PATHS, LAUNCHER, CWD), stopped) - mocks[0].assert_called_once_with(CWD) - mocks[1].assert_called_with("/s") - self.assertIn("=== cycle 4 ===", sys.stdout.getvalue()) - for leaf in (0, 1, 4): - with self.subTest(leaf=leaf): - mocks[leaf].return_value = Stop(2, f"leaf {leaf}") - self.assertEqual(main.run_loop(["do it"], {}, PATHS, LAUNCHER, CWD), mocks[leaf].return_value) - mocks[leaf].return_value = "/s" - mocks[3].side_effect = [Retry("claude exited 3")] * 3 - stack.enter_context(unittest.mock.patch.object(sys, "stderr", io.StringIO())) - sleep = stack.enter_context(unittest.mock.patch("time.sleep")) - self.assertEqual(main.run_loop([main.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it"})], {}, PATHS, LAUNCHER, CWD), Stop(1, "the worker failed three times running: claude exited 3")) - self.assertIn("retrying the worker in a minute: claude exited 3", sys.stderr.getvalue()) - self.assertEqual(sleep.call_count, 2) if __name__ == "__main__": diff --git a/bin/test_loop_claude_black_box.py b/bin/test_loop_claude_black_box.py index 8ca5735b..8022bece 100644 --- a/bin/test_loop_claude_black_box.py +++ b/bin/test_loop_claude_black_box.py @@ -25,7 +25,7 @@ argv = sys.argv[1:] role = "judge" if "--json-schema" in argv else "worker" if "-p" in argv else "interrupt" scenario = pathlib.Path(os.environ["FAKE_CLAUDE_SCENARIO"]) steps = json.loads(scenario.read_text()) -call = {{"argv": argv, "role": role}} +call = {{"argv": argv, "cwd": os.getcwd(), "role": role}} if role == "judge": call["stdin"] = sys.stdin.read() with open(os.environ["FAKE_CLAUDE_LOG"], "a") as log: @@ -62,6 +62,10 @@ if role == "worker": with open(transcript(), "ab") as handle: handle.write(step.get("raw", "").encode("latin-1")) append(said) + if step.get("siblings"): + for sibling in (f"{{session()}}/subagents", f"{{session()}}.superseded-1/tool-results"): + (transcript().parent / sibling).mkdir(parents=True, exist_ok=True) + (transcript().parent / f"{{session()}}.orphaned-1-ab.jsonl").write_text("{{}}\\n") if "append" in step: with open(os.environ["FAKE_CLAUDE_EDIT"], "a") as script: script.write(step["append"]) @@ -171,7 +175,7 @@ class Checkout: def git(self, *args): subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@example.com", *args], capture_output=True, check=True, cwd=self.root, env=self.env) - def run(self, steps, argv=(TASK,), cwd=None, terminal_input=None, stdout_on_terminal=True): + def run(self, steps, argv=(TASK,), cwd=None, terminal_input=None, stdout_on_terminal=True, before_typing=None): for name in ("FAKE_CLAUDE_LOG", "LOOP_TEST_LOG"): pathlib.Path(self.env[name]).unlink(missing_ok=True) pathlib.Path(self.env["FAKE_CLAUDE_SCENARIO"]).write_text(json.dumps(steps)) @@ -181,7 +185,7 @@ class Checkout: done = subprocess.run(command, capture_output=True, cwd=cwd, env=self.env, stdin=subprocess.DEVNULL, text=True, timeout=60) code, stdout, stderr = done.returncode, done.stdout, done.stderr else: - code, stdout, stderr = self.run_on_terminal(command, cwd, terminal_input, stdout_on_terminal) + code, stdout, stderr = self.run_on_terminal(command, cwd, terminal_input, stdout_on_terminal, before_typing) started = lines(pathlib.Path(self.env["LOOP_TEST_LOG"])) return Run( calls=lines(pathlib.Path(self.env["FAKE_CLAUDE_LOG"])), @@ -192,7 +196,8 @@ class Checkout: stdout=stdout, ) - def run_on_terminal(self, command, cwd, typed, stdout_on_terminal): + def run_on_terminal(self, command, cwd, typed, stdout_on_terminal, before_typing): + """Types the input at once, or once stderr shows before_typing's prompt and its callback has run.""" controller, terminal = pty.openpty() with tempfile.TemporaryFile() as stderr, tempfile.TemporaryFile() as stdout: try: @@ -200,7 +205,9 @@ class Checkout: finally: os.close(terminal) try: - os.write(controller, typed.encode()) + prompt, callback = before_typing or (None, None) + if prompt is None: + os.write(controller, typed.encode()) output, deadline = b"", time.monotonic() + 60 while time.monotonic() < deadline: if select.select([controller], [], [], 1)[0]: @@ -211,6 +218,10 @@ class Checkout: if not chunk: break output += chunk + if prompt is not None and prompt.encode() in os.pread(stderr.fileno(), 1 << 20, 0): + callback() + os.write(controller, typed.encode()) + prompt = None code = proc.wait(timeout=10) finally: os.close(controller) @@ -231,11 +242,13 @@ class Checkout: return sorted((self.home / ".claude" / "projects").glob("*/*.jsonl")) def archive(self): - return self.home / ".claude" / "loop-claude-transcripts" + return pathlib.Path(self.env.get("LOOP_CLAUDE_TRANSCRIPTS", self.home / ".claude" / "loop-claude-transcripts")) def archived(self): """Each archived transcript's verdict, after checking the copy is named by its content hash.""" verdicts = {} + for folder in (self.archive(), self.archive() / "proj"): + self.test.assertEqual(stat.S_IMODE(folder.stat().st_mode), 0o700, folder) for copy in sorted((self.archive() / "proj").glob("*.jsonl")): self.test.assertEqual(copy.stem, hashlib.sha256(copy.read_bytes()).hexdigest()) verdict = copy.with_suffix(".verdict.md") @@ -280,16 +293,32 @@ class Premises(unittest.TestCase): run = checkout.run([worker()], cwd=checkout.root / "sub") self.assertEqual((run.code, run.calls), (1, [])) self.assertEqual(run.stderr.strip(), said.format(root=checkout.root)) + (checkout.root / "README.md").unlink() + (checkout.root / "README.md").mkdir() + run = checkout.run([worker()]) + self.assertEqual((run.code, run.calls), (1, [])) + self.assertEqual(run.stderr.strip(), f"README.md in {checkout.root}: Is a directory - no premises.") + + def test_names_the_session_by_the_checkout_relative_to_code_or_else_to_the_root(self): + checkout = Checkout(self) + for root in (checkout.temp / "elsewhere", checkout.home / "code"): + with self.subTest(root=root): + root.mkdir(exist_ok=True) + (root / "README.md").write_text(PREMISES) + checkout.git("init", "--quiet", str(root)) + run = checkout.run([worker()], cwd=root) + self.assertEqual(argument(run.calls[0], "--name"), f"A {str(root).lstrip('/')} loop-claude") class Cycles(unittest.TestCase): def test_resumes_the_session_while_unfinished_and_starts_it_fresh_after_finishing(self): checkout = Checkout(self) + (checkout.root / "sub").mkdir() run = checkout.run([ worker(say="started"), judge(evidence="started"), - worker(say="landed-it"), judge(finished=True, evidence="landed-it"), + worker(say="landed-it", siblings=True), judge(finished=True, evidence="landed-it"), worker(say="next chunk"), - ]) + ], cwd=checkout.root / "sub") self.assertEqual(run.code, 130) self.assertEqual(run.roles(), ["worker", "judge", "worker", "judge", "worker", "judge"]) workers = [call for call in run.calls if call["role"] == "worker"] @@ -298,11 +327,15 @@ class Cycles(unittest.TestCase): self.assertEqual(argument(workers[1], "--resume"), session) self.assertIsNone(argument(workers[1], "--session-id")) self.assertEqual(argument(workers[2], "--session-id"), session) - self.assertTrue(argument(workers[0], "-p").startswith(TASK)) + self.assertTrue(argument(workers[0], "-p").startswith(f"{TASK}\n\nContinue any open draft PR")) + self.assertNotIn(TASK, argument(workers[1], "-p")) + self.assertEqual({call["cwd"] for call in run.calls}, {str(checkout.root)}) + self.assertIn("1. Work.", run.calls[1]["stdin"]) self.assertEqual({argument(call, "--model") for call in workers}, {"worker-model"}) self.assertEqual({argument(call, "--model") for call in run.calls if call["role"] == "judge"}, {"judge-model"}) self.assertIn("landed-it", run.calls[3]["stdin"]) self.assertNotIn("landed-it", run.calls[5]["stdin"]) + self.assertEqual([path.name for path in checkout.transcripts()[0].parent.iterdir()], [checkout.transcripts()[0].name]) self.assertIn("=== cycle 3 ===", run.stdout) [(copy, verdict)] = checkout.archived().items() self.assertIn('"text": "landed-it"', copy) @@ -365,6 +398,12 @@ class Cycles(unittest.TestCase): self.assertEqual(run.sleeps, [60, 60]) self.assertEqual(run.stderr.strip().splitlines()[-1], "the judge failed three times running: could not start claude: No such file or directory") + def test_hands_the_judge_the_tail_of_a_long_transcript(self): + checkout = Checkout(self) + run = checkout.run([worker(say="early " * 20000 + "LATE")]) + self.assertIn("LATE", run.calls[1]["stdin"]) + self.assertLess(run.calls[1]["stdin"].count("early"), 20000) + def test_skips_a_malformed_transcript_or_stream_line(self): checkout = Checkout(self) raw = "\xff not UTF-8\nnot JSON\n[1]\n" + json.dumps({"type": "assistant", "message": "not an object"}) + "\n" + json.dumps({"type": "user", "message": None}) + "\n" @@ -398,6 +437,7 @@ class Cycles(unittest.TestCase): class Interrupt(unittest.TestCase): def test_exits_2_off_a_terminal_and_resumes_on_the_next_run(self): checkout = Checkout(self) + checkout.env["LOOP_CLAUDE_TRANSCRIPTS"] = str(checkout.temp / "deep" / "archive") steps = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")] run = checkout.run(steps) self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"])) @@ -405,12 +445,17 @@ class Interrupt(unittest.TestCase): [(copy, verdict)] = checkout.archived().items() self.assertEqual(copy, (checkout.transcripts()[0]).read_text()) self.assertEqual(verdict, f"Task: {TASK}\n\nVerdict: interrupt\n\nA or B?\n") + self.assertEqual(stat.S_IMODE((checkout.temp / "deep").stat().st_mode), 0o700) + self.assertIn(f"transcript: {checkout.archive() / 'proj'}/", run.stderr) session = argument(run.calls[0], "--session-id") run = checkout.run(steps, terminal_input="", stdout_on_terminal=False) self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"])) self.assertEqual(argument(run.calls[0], "--resume"), session) self.assertEqual(len(checkout.archived()), 2) self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal") + run = checkout.run([worker(transcript=False), steps[1]]) + self.assertEqual(run.code, 2) + self.assertEqual(len(checkout.archived()), 2) def test_hands_the_terminal_over_and_exits_2_when_nothing_is_typed(self): checkout = Checkout(self) @@ -432,6 +477,7 @@ class Interrupt(unittest.TestCase): self.assertEqual(trusted["projects"][str(checkout.root)], {"hasTrustDialogAccepted": True, "kept": True}) self.assertEqual(trusted["projects"][str(checkout.home / "code" / "proj-wt")], {"hasTrustDialogAccepted": True}) self.assertEqual(stat.S_IMODE(checkout.claude_json().stat().st_mode), 0o644) + self.assertIn(f"trusted for the interrupt: {checkout.root}, {checkout.home / 'code' / 'proj-wt'}\n", run.stderr) for transcript in checkout.transcripts(): transcript.unlink() @@ -443,6 +489,47 @@ class Interrupt(unittest.TestCase): self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"])) self.assertEqual(run.stderr.strip().splitlines()[-1], "could not start claude for the interrupt: No such file or directory") + def test_says_why_the_trust_file_cannot_be_read_and_leaves_it_as_it_was(self): + checkout = Checkout(self) + asked = [worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?"), interrupt()] + root = json.dumps(str(checkout.root)) + shapes = { + None: "No such file or directory", + "{": "Expecting property name enclosed in double quotes: line 1 column 2 (char 1)", + "[]": 'not an object whose "projects" is an object', + '{"projects": []}': 'not an object whose "projects" is an object', + f'{{"projects": {{{root}: 1}}}}': f"projects[{root}] is not an object", + } + for text, said in shapes.items(): + with self.subTest(said=said): + checkout.claude_json().unlink(missing_ok=True) + if text is not None: + checkout.claude_json().write_text(text) + run = checkout.run(asked, terminal_input="") + self.assertEqual(run.code, 2) + self.assertIn(f"could not read {checkout.claude_json()}: {said}\n", run.stderr) + self.assertEqual(checkout.claude_json().read_text() if checkout.claude_json().exists() else None, text) + + trusted = json.dumps({"projects": {str(checkout.root): {"hasTrustDialogAccepted": True}}}) + checkout.claude_json().write_text(trusted) + run = checkout.run(asked, terminal_input="") + self.assertNotIn(str(checkout.claude_json()), run.stderr) + self.assertNotIn("trusted for the interrupt", run.stderr) + self.assertEqual(checkout.claude_json().read_text(), trusted) + + @unittest.skipIf(os.geteuid() == 0, "root writes into a read-only directory") + def test_says_why_the_trust_file_cannot_be_written(self): + checkout = Checkout(self) + checkout.claude_json().write_text("{}") + asked = [worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?"), interrupt()] + checkout.run(asked[:2]) + checkout.home.chmod(0o500) + self.addCleanup(checkout.home.chmod, 0o700) + run = checkout.run([worker(), *asked[1:]], terminal_input="") + self.assertEqual(run.code, 2) + self.assertIn(f"could not write {checkout.claude_json()}: Permission denied\n", run.stderr) + self.assertEqual(checkout.claude_json().read_text(), "{}") + @unittest.skipIf(os.geteuid() == 0, "root reads an unreadable file") def test_exits_1_when_the_transcript_cannot_be_read_after_the_interrupt(self): checkout = Checkout(self) @@ -470,8 +557,13 @@ class Models(unittest.TestCase): self.assertEqual((run.code, run.calls), (2, [])) self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to pick proj's model, but the input ended") - run = checkout.run([worker(), judge()], terminal_input="9\n2\n") + checkout.env["LOOP_CLAUDE_JUDGE_MODEL"] = "judge-model" + run = checkout.run([worker()]) + self.assertEqual((run.code, run.calls), (2, [])) + del checkout.env["LOOP_CLAUDE_JUDGE_MODEL"] + run = checkout.run([worker(), judge()], terminal_input="\n9\n2\n") self.assertEqual(run.code, 130) + self.assertIn("proj runs on model-b", run.stderr) self.assertIn("1. A (model-a)", run.stderr) self.assertNotIn("old-model", run.stderr) self.assertIn("pick 1 to 2", run.stderr) @@ -489,16 +581,36 @@ class Models(unittest.TestCase): checkout.models_file().parent.mkdir(parents=True) checkout.models_file().write_text(json.dumps({"other": "model-x"})) checkout.models_file().chmod(0o640) - run = checkout.run([worker()], terminal_input="custom-model\n") + def saved_elsewhere(): + checkout.models_file().write_text(json.dumps({"late": "model-y", "other": "model-x"})) + + run = checkout.run([worker()], terminal_input="custom-model\n", before_typing=("claude --model takes: ", saved_elsewhere)) self.assertEqual(run.code, 130) self.assertIn("no model catalog cached", run.stderr) - self.assertEqual(json.loads(checkout.models_file().read_text()), {"other": "model-x", "proj": "custom-model"}) + self.assertIn("A name claude --model takes: ", run.stderr) + self.assertEqual(json.loads(checkout.models_file().read_text()), {"late": "model-y", "other": "model-x", "proj": "custom-model"}) self.assertEqual(stat.S_IMODE(checkout.models_file().stat().st_mode), 0o640) - checkout.models_file().write_text("[]") - run = checkout.run([worker()]) - self.assertEqual((run.code, run.calls), (1, [])) - self.assertIn(f"could not read {checkout.models_file()}", run.stderr) + for broken in ("{", "[]", '{"proj": 1}'): + with self.subTest(broken=broken): + checkout.models_file().write_text(broken) + run = checkout.run([worker()]) + self.assertEqual((run.code, run.calls), (1, [])) + self.assertTrue(run.stderr.startswith(f"could not read {checkout.models_file()}: ")) + self.assertEqual(checkout.models_file().read_text(), broken) + + def test_offers_no_catalog_whose_models_are_not_a_list(self): + checkout = Checkout(self) + del checkout.env["LOOP_CLAUDE_JUDGE_MODEL"], checkout.env["LOOP_CLAUDE_WORKER_MODEL"] + self.catalog(checkout) + catalog = checkout.home / ".claude" / "cache" / "model-catalog" / "new.json" + for shape in ({"catalog": {"config": {"models": []}}}, {"catalog": None}, {"catalog": {"config": []}}, {"catalog": {"config": {"models": "x"}}}): + with self.subTest(shape=shape): + catalog.write_text(json.dumps({**shape, "fetchedAt": 3})) + checkout.models_file().unlink(missing_ok=True) + run = checkout.run([worker()], terminal_input="1\n") + self.assertIn("no model catalog cached", run.stderr) + self.assertEqual(argument(run.calls[0], "--model"), "1") @unittest.skipIf(os.geteuid() == 0, "root writes into a read-only directory") def test_exits_1_when_the_models_file_cannot_be_written(self): @@ -531,6 +643,15 @@ class Reload(unittest.TestCase): self.assertEqual(json.loads(reloads[0][1]), {"cycle_number": 2, "failures": 0, "root": str(checkout.root), "task": TASK}) self.assertIn("=== cycle 3 ===", run.stdout) + outside = checkout.temp / "outside" + outside.mkdir() + state = {"cycle_number": 3, "failures": 2, "root": str(checkout.root), "task": TASK} + run = checkout.run([worker(exit=1)], argv=["--reloaded", json.dumps(state)], cwd=outside) + self.assertEqual((run.code, run.sleeps), (1, [])) + self.assertEqual(run.calls[0]["cwd"], str(checkout.root)) + self.assertIn("=== cycle 4 ===", run.stdout) + self.assertEqual(run.stderr.strip().splitlines()[-1], "the worker failed three times running: claude exited 1") + run = checkout.run([], argv=["--reloaded", "{}"]) self.assertEqual((run.code, run.calls), (1, [])) self.assertIn("rerun loop-claude ", run.stderr) diff --git a/todo.md b/todo.md index 8c6a170d..5fc45bdd 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,6 @@ The rebuild lifts every dimension: each item below is one chunk on a worktree based on `origin/rebuild`, its PR into `rebuild`, until the last item merges `rebuild` into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -- **Replace `bin/test_loop_claude.py`'s internal-function tests with the black-box tests plus unit tests of the pure parsers.** - **Hold every reviewer to one findings document, `principles/review-findings.md`.** Severity, verdict, rounds with round 2 verifying each earlier finding, the per-chunk round cap, declining, and `/security-review`'s HIGH/MEDIUM/LOW mapped onto the scale; it replaces `principles/review-protocol.md`. - **Rewrite larv-review around one pass table and one re-entry rule.** A trigger per pass, each stated only there; the re-entry paragraph classifies a fix by the widest thing it touches; forge neutrality, the draft PR, CI watched in the foreground, the comprehension floor, the auto-reviewer's waits and the goal-alignment check carried over. - **Make the three reviewer agents pure reporters in the findings document's vocabulary.** Keep their names and checklists; remove every README- and decision-writing duty and every private severity or verdict scale. -- 2.52.0 From bbf4636fcc90d6474ce1c4b714e119d7771e5963 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 19:26:35 +0200 Subject: [PATCH 035/233] Pin the judge's rules, the interrupt's checkout root, no name on resume, and a failed replace leaving nothing staged --- bin/test_loop_claude.py | 12 +++++++++++- bin/test_loop_claude_black_box.py | 10 +++++++--- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 736a3667..374d0b30 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -1,11 +1,13 @@ import json +import os import pathlib import sys +import tempfile import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -from loop_claude import judge, main, premises, transcript +from loop_claude import file_writes, judge, main, premises, transcript from loop_claude.outcome import Stop CWD = pathlib.Path("/c") @@ -95,5 +97,13 @@ class LoopState(unittest.TestCase): +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.assertIsInstance(file_writes.replace_file(os.path.join(root, "in-the-way"), b"data"), IsADirectoryError) + self.assertEqual(os.listdir(root), ["in-the-way"]) + + if __name__ == "__main__": unittest.main() diff --git a/bin/test_loop_claude_black_box.py b/bin/test_loop_claude_black_box.py index 8022bece..77fc4ce9 100644 --- a/bin/test_loop_claude_black_box.py +++ b/bin/test_loop_claude_black_box.py @@ -197,7 +197,7 @@ class Checkout: ) def run_on_terminal(self, command, cwd, typed, stdout_on_terminal, before_typing): - """Types the input at once, or once stderr shows before_typing's prompt and its callback has run.""" + """Types the input at once, or once stderr shows before_typing's text and its callback has run.""" controller, terminal = pty.openpty() with tempfile.TemporaryFile() as stderr, tempfile.TemporaryFile() as stdout: try: @@ -326,6 +326,7 @@ class Cycles(unittest.TestCase): self.assertEqual(argument(workers[0], "--name"), "A proj loop-claude") self.assertEqual(argument(workers[1], "--resume"), session) self.assertIsNone(argument(workers[1], "--session-id")) + self.assertIsNone(argument(workers[1], "--name")) self.assertEqual(argument(workers[2], "--session-id"), session) self.assertTrue(argument(workers[0], "-p").startswith(f"{TASK}\n\nContinue any open draft PR")) self.assertNotIn(TASK, argument(workers[1], "-p")) @@ -403,6 +404,7 @@ class Cycles(unittest.TestCase): run = checkout.run([worker(say="early " * 20000 + "LATE")]) self.assertIn("LATE", run.calls[1]["stdin"]) self.assertLess(run.calls[1]["stdin"].count("early"), 20000) + self.assertTrue(run.calls[1]["stdin"].rstrip().endswith("an open PR, a review not yet run, CI not yet reported.")) def test_skips_a_malformed_transcript_or_stream_line(self): checkout = Checkout(self) @@ -464,10 +466,12 @@ class Interrupt(unittest.TestCase): checkout.claude_json().write_text(json.dumps({"other": 1, "projects": {str(checkout.root): {"kept": True}}})) checkout.claude_json().chmod(0o644) asked = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")] - run = checkout.run([*asked, interrupt(type="B"), judge(evidence="B"), worker()], terminal_input="") + (checkout.root / "sub").mkdir() + run = checkout.run([*asked, interrupt(type="B"), judge(evidence="B"), worker()], cwd=checkout.root / "sub", terminal_input="") self.assertEqual(run.code, 130) self.assertEqual(run.roles(), ["worker", "judge", "interrupt", "judge", "worker", "judge"]) handed = run.calls[2]["argv"] + self.assertEqual(run.calls[2]["cwd"], str(checkout.root)) self.assertEqual(argument(run.calls[2], "--resume"), argument(run.calls[0], "--session-id")) self.assertEqual(argument(run.calls[2], "--model"), "worker-model") self.assertNotIn("-p", handed) @@ -584,7 +588,7 @@ class Models(unittest.TestCase): def saved_elsewhere(): checkout.models_file().write_text(json.dumps({"late": "model-y", "other": "model-x"})) - run = checkout.run([worker()], terminal_input="custom-model\n", before_typing=("claude --model takes: ", saved_elsewhere)) + run = checkout.run([worker()], terminal_input="custom-model\n", before_typing=("no model catalog cached", saved_elsewhere)) self.assertEqual(run.code, 130) self.assertIn("no model catalog cached", run.stderr) self.assertIn("A name claude --model takes: ", run.stderr) -- 2.52.0 From 2215d9c193269a2db790393fa56fded36f899feb Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 19:33:38 +0200 Subject: [PATCH 036/233] Hold every reviewer to one findings document --- agents/product-owner-reviewer.md | 4 ++-- agents/stability-reviewer.md | 6 ++--- agents/systems-architect.md | 6 ++--- principles/review-findings.md | 37 +++++++++++++++++++++++++++++++ principles/review-protocol.md | 38 -------------------------------- skills/larv-review/SKILL.md | 20 ++++++++--------- todo.md | 1 - 7 files changed, 54 insertions(+), 58 deletions(-) create mode 100644 principles/review-findings.md delete mode 100644 principles/review-protocol.md diff --git a/agents/product-owner-reviewer.md b/agents/product-owner-reviewer.md index fff5b433..cdf44cdd 100644 --- a/agents/product-owner-reviewer.md +++ b/agents/product-owner-reviewer.md @@ -48,7 +48,7 @@ Before anything else, **read the shared principles** at `~/.claude/principles/`. ## Your Output Format -Verdict, severities, rounds and declines: ~/.claude/principles/review-protocol.md. After the verdict: +Verdict, severities, rounds and declines: ~/.claude/principles/review-findings.md. After the verdict: **Surface affected**: @@ -76,4 +76,4 @@ For each concern: state the problem from the customer's POV, the persona affecte ## Documenting decisions -Per ~/.claude/principles/review-protocol.md. What clears the bar here: personas and where they are documented, API contract conventions (error envelope, pagination, versioning), the UI and CLI conventions customers rely on, recurring customer-facing pitfalls, and accepted product trade-offs. +Per ~/.claude/principles/review-findings.md. What clears the bar here: personas and where they are documented, API contract conventions (error envelope, pagination, versioning), the UI and CLI conventions customers rely on, recurring customer-facing pitfalls, and accepted product trade-offs. diff --git a/agents/stability-reviewer.md b/agents/stability-reviewer.md index 4480199e..90f55b10 100644 --- a/agents/stability-reviewer.md +++ b/agents/stability-reviewer.md @@ -127,7 +127,7 @@ Every PR gets at least this sweep; for sensitive surfaces also recommend the ded ## Output Format -Verdict, severities, rounds and declines: ~/.claude/principles/review-protocol.md. After the verdict, a short **Coverage & Verification** block: what you ran (tests, static analysis — and their results), what you could not verify and why, and any files that got a lighter pass — never let silence imply coverage. Then structure the findings as follows: +Verdict, severities, rounds and declines: ~/.claude/principles/review-findings.md. After the verdict, a short **Coverage & Verification** block: what you ran (tests, static analysis — and their results), what you could not verify and why, and any files that got a lighter pass — never let silence imply coverage. Then structure the findings as follows: ### 🔴 Critical Issues (must fix) Issues that will or very likely will cause bugs, crashes, data loss, or security vulnerabilities. Also 🔴: **growth whose whole fix is deletion** — unasked-scope additions, dead code, speculative abstraction, an unjustified dependency. @@ -158,7 +158,7 @@ For each finding: ## Loop Discipline - Only two things justify 🔴: a concrete failure scenario, or growth whose deletion is the whole fix. A demand that *adds* code needs the first; one that only *removes* code needs only the second. Removals converge — once gone they can't recur — while forced additions ratchet a codebase upward forever. "Could be smaller" rewrites are 🟡, never 🔴. -- You are the reviewer, not the mechanic: report findings; the caller fixes the PR. Your only writes are the documentation duties in the protocol. +- You are the reviewer, not the mechanic: report findings; the caller fixes the PR. ## Behavioral Guidelines @@ -172,4 +172,4 @@ For each finding: ## Documenting decisions -Per ~/.claude/principles/review-protocol.md. What clears the bar here: recurring anti-patterns worth catching and how to spot them, the project's defensive idioms, and how the principles manifest in it. +Per ~/.claude/principles/review-findings.md. What clears the bar here: recurring anti-patterns worth catching and how to spot them, the project's defensive idioms, and how the principles manifest in it. diff --git a/agents/systems-architect.md b/agents/systems-architect.md index cd00a533..5c2a79ce 100644 --- a/agents/systems-architect.md +++ b/agents/systems-architect.md @@ -165,9 +165,9 @@ How a change ships — merge gate, pipeline, deployment, dependencies — is a d You are not a per-PR reviewer. The **stability-reviewer** runs on every change for code-level safety; you run deliberately, every so often, to check the system is still aligned — right goals, right contract, right foundations, sound structure. When you do look at a specific PR, it is because the work touches architectural fundamentals or reopens foundational choices, not for routine line-level review. Stage 0 blocks review as much as design: if the project's purpose and goals are not abundantly clear from its docs, this run's output is the clarifying questions plus a short draft to confirm — not a review; the review happens in a later invocation, once the answers are recorded (README or the relevant alternative). -**Lead with a verdict and mark blockers.** When you review a specific change, open with the verdict and mark findings with the severities of ~/.claude/principles/review-protocol.md. A violation of a non-negotiable fundamental — functional-core/shell entanglement, a unit past a Fits in a head threshold without a stated reason, a method or file carrying more than one responsibility, unreasoned duplication of a core concept, or a broken/leaky external contract — is a 🔴: lead with it, and name the concrete restructuring. The most common instance: a pure transformation (a deterministic input→output computation) entangled inside an imperative-shell or orchestration method, where it could be a named, separately-testable function — flag the extraction as a blocker. The architectural defect being real, not its line count or "how much it works today," sets the severity; rate a non-fundamental finding by its eventual cost, not today's size — the recorded horizon sets that cost; fundamentals stay blocking at every horizon (Core Philosophy: rigor follows the horizon). Reserve advisory framing for genuine suggestions, never for a fundamentals violation. +**Lead with a verdict and mark blockers.** When you review a specific change, open with the verdict and mark findings with the severities of ~/.claude/principles/review-findings.md. A violation of a non-negotiable fundamental — functional-core/shell entanglement, a unit past a Fits in a head threshold without a stated reason, a method or file carrying more than one responsibility, unreasoned duplication of a core concept, or a broken/leaky external contract — is a 🔴: lead with it, and name the concrete restructuring. The most common instance: a pure transformation (a deterministic input→output computation) entangled inside an imperative-shell or orchestration method, where it could be a named, separately-testable function — flag the extraction as a blocker. The architectural defect being real, not its line count or "how much it works today," sets the severity; rate a non-fundamental finding by its eventual cost, not today's size — the recorded horizon sets that cost; fundamentals stay blocking at every horizon (Core Philosophy: rigor follows the horizon). Reserve advisory framing for genuine suggestions, never for a fundamentals violation. -**Re-checks are scoped, not fresh reviews.** When invoked to verify your own earlier findings (e.g. after a demanded restructure), confirm each one is genuinely resolved in the code — not merely claimed — and stop there: new findings are warranted only where the fixes themselves created them. Decisions recorded in `docs/decisions.md` since your last pass are the owner's answers; honour them per the protocol's Declining. +**Re-checks are scoped, not fresh reviews.** When invoked to verify your own earlier findings (e.g. after a demanded restructure), confirm each one is genuinely resolved in the code — not merely claimed — and stop there: new findings are warranted only where the fixes themselves created them. Decisions recorded in `docs/decisions.md` since your last pass are the owner's answers; honour them per the findings document's Declining. Focus on architectural alignment: - Does it still serve the project's goals and priorities, or has it quietly drifted from them? @@ -215,7 +215,7 @@ Respect documented deliberate deviations — a stated trade-off is a valid reaso ## Documenting decisions -Per ~/.claude/principles/review-protocol.md. What clears the bar here: +Per ~/.claude/principles/review-findings.md. What clears the bar here: - Established architectural patterns (e.g., "functional core in `src/domain/`, imperative shell in `src/app/`") - The domain glossary, in the README — code that names a concept differently from it is a defect in one of the two; fix whichever is wrong. - Rejected alternatives, and requirement trades offered and declined, so they are not re-offered diff --git a/principles/review-findings.md b/principles/review-findings.md new file mode 100644 index 00000000..0a5acdaa --- /dev/null +++ b/principles/review-findings.md @@ -0,0 +1,37 @@ +# Review findings + +Words: `~/.claude/CLAUDE.md` → "Vocabulary". + +A reviewer reads and reports; it edits nothing. Read `docs/decisions.md` first: a finding it declines is not raised again. + +## Severity + +- 🔴 **must fix** — a goal, a principle or correctness broken. Fixed, or shown factually wrong; never declined. +- 🟡 **should fix** — worse than it needs to be. Fixed, or declined. +- 🟢 **nit** — fixed if cheap; never holds a pass. +- ❓ **question** for the author: a finding you could not confirm goes here, not above. +- 🔀 **escalation** — names the reviewer whose concern it is (`product-owner-reviewer`, `systems-architect` or `/security-review`) and why, in one line. The orchestrator runs it. + +Other reviewers map onto this scale: + +- `/security-review`: HIGH is 🔴, MEDIUM 🟡, LOW 🟢. A HIGH shown not real is recorded with what disproved it. +- A forge's auto-reviewer: what it marks blocking is 🔴. + +## Verdict + +A review's first line, derived from the findings: + +- `BLOCK` — a 🔴 or a 🟡 stands. +- `APPROVE WITH NITS` — only 🟢 and ❓ remain. +- `APPROVE` — nothing remains. + +## Rounds + +- Surface everything in round 1. +- From round 2 the prompt carries the previous round's findings verbatim and what changed since. Verify each earlier 🔴 and 🟡 is resolved — re-run the scenario, never trust the claim — then review what changed. A fix raises a new finding only where the fix itself introduced a real problem. +- A pass is done on no 🔴 and no 🟡. The 🟢 and ❓ left are addressed in that round — fixed, answered, declined or filed in `todo.md` — and take no further round, unless a fix changes behaviour. +- Round cap: a pass runs at most three times per chunk, re-entries included. A fourth run lists what is open and asks the human. + +## Declining + +A 🟡 or below may be declined where the reason is sound, consistent with the goals, and confidence is very high. The decline, its reason and the goal it rests on go to `docs/decisions.md`, with the human's decisions and answers to ❓; an unrecorded one is asked again next review. A reason no goal speaks to is a gap in the goals, taken per `~/.claude/CLAUDE.md` → "Ask, don't guess" — or fix the finding. Never a silent drop, and never a decline argued from convenience or the size of the fix. diff --git a/principles/review-protocol.md b/principles/review-protocol.md deleted file mode 100644 index 8372e7f5..00000000 --- a/principles/review-protocol.md +++ /dev/null @@ -1,38 +0,0 @@ -# Review protocol - -Words: `~/.claude/CLAUDE.md` → "Vocabulary". - -## Verdict - -A review's first line, derived mechanically from the findings: - -- `BLOCK` — a 🔴 stands; for a looping reviewer, a 🟡 too. -- `ALIGN` — systems-architect only: no 🔴, drift (🟡) to address soon. -- `APPROVE WITH NITS` — only 🟢 and ❓ remain; the author's call. -- `APPROVE` — nothing remains. - -## Severity - -- 🔴 **must fix.** Never declinable: it is fixed, or shown factually wrong. -- 🟡 **should fix.** Holds a looping reviewer at `BLOCK`, but may be declined. -- 🟢 **nit.** Never holds the loop. -- ❓ **question** for the author: a finding you could not confirm goes here, not above. -- 🔀 **escalation**: names the reviewer to run next (`product-owner-reviewer`, `systems-architect`, or the `security-review` skill) and a one-line reason. The caller runs it; it is never optional. - -## Rounds - -- Surface everything in one round. -- From round 2 the prompt carries the previous round's findings verbatim and what changed since. Verify each previous 🔴 and 🟡 is resolved — re-run the scenario, don't trust the claim — then pass over what changed. A fix spawns a new finding only where the fix itself introduced a real problem. -- The loop exits on no 🔴 and no 🟡. The 🟢 and ❓ left then are addressed in that same round — fixed, answered, declined or filed in `todo.md` — and trigger no further round. A nit whose fix changes behaviour is a fresh finding and takes a round. -- Round cap: 3; when it stops the loop, list what is open and ask the human. -- Systems-architect gets one scoped re-check; still `BLOCK` → ask the human. - -## Declining - -Anything below 🔴 the caller may decline where the reason is sound, sits consistently with the repo's goals, and confidence is very high; the decline, its reason and the goal it rests on go to `docs/decisions.md`. A reason that contradicts a goal, or that no goal speaks to and you are not confident in, is a gap in the goals, taken per `~/.claude/CLAUDE.md` → "Working loop", "Ask, don't guess" — or fix the finding. Never a silent drop, and never a decline argued from convenience or the size of the fix. - -A reviewer honours an accepted risk in `docs/decisions.md` and a finding declined this way: it stays declined and is not raised again. - -## Documenting decisions - -Knowledge that outlives one review goes in the repo, never in a memory file, where `~/.claude/CLAUDE.md` → "Comments and documentation" and "Ask, don't guess" put its kind. Record only decisions the human made, declines made under Declining, and answers the human gives to ❓; an unrecorded answer gets asked again next review. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index d1366c9e..391a627c 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -5,11 +5,11 @@ description: Ship a work chunk through review to a merged PR; decisions land in # larv-review — ship the chunk, review until clean, gate green, merge -You orchestrate, fix, and ship; the reviewer agents only report. Run every reviewer synchronously (`run_in_background: false`) — each step depends on the previous result. Watch CI in the foreground too: a headless run exits when the turn ends, and a background watcher or a scheduled wakeup dies with it. A reviewer's report is input to the next step; the turn runs on until §11. Architecture strictly before security, security before stability: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. A fix made in any pass is a change the passes before it in this order never saw; a pass it re-enters says so, and a re-entry is a new loop with its own round cap. +You orchestrate, fix, and ship; the reviewer agents only report. Run every reviewer synchronously (`run_in_background: false`) — each step depends on the previous result. Watch CI in the foreground too: a headless run exits when the turn ends, and a background watcher or a scheduled wakeup dies with it. A reviewer's report is input to the next step; the turn runs on until §11. Architecture strictly before security, security before stability: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. A fix made in any pass is a change the passes before it in this order never saw; a pass it re-enters says so. **Forge-neutral.** Five PR operations recur below: read a PR's diff, open a draft PR, read check status, mark ready, merge. Resolve the tooling from the remote per `~/.claude/CLAUDE.md` → "Git, commits, and PRs"; on any other forge, achieve the same intents through its CLI or API — discover how rather than assuming. A forge without a native draft state gets the closest equivalent (a `WIP:`/`Draft:` title prefix); note any approximation in the summary. -Words: `~/.claude/CLAUDE.md` → "Vocabulary". Verdicts, severities, round caps, declining a finding and where decisions are recorded: ~/.claude/principles/review-protocol.md. Its Declining section also binds `/security-review` and the external reviewer in §9. +Words: `~/.claude/CLAUDE.md` → "Vocabulary". Severities, verdicts, rounds, the round cap and declining, for every reviewer: ~/.claude/principles/review-findings.md. ## 0. Preconditions @@ -51,8 +51,7 @@ Launch **systems-architect**: review the system as a whole entered through this - **Stage 0 questions returned** (goals/audience/horizon unrecorded): relay them to the user, record the answers where the agent expects them (README), re-run once. No user → skip the pass, carry the questions into the summary. - **BLOCK** → the restructure precedes everything below. Confirm with the user first when it materially reshapes their PR; apply it; re-run systems-architect once, scoped to verifying its own findings. Still BLOCK → stop and ask the human. -- **ALIGN** → apply what is cheap now; ask the user about the rest — each item becomes a fix, a ticket, or a documented decision, never a silent drop. -- **APPROVE** / **APPROVE WITH NITS** → proceed; nits per the protocol's rounds. +- **APPROVE** / **APPROVE WITH NITS** → proceed; nits per the findings document's rounds. ### Comprehension floor (with every architecture pass) @@ -63,8 +62,7 @@ Invoke the `comprehension-panel` skill's scoring run (`~/.claude/skills/comprehe Run the built-in **`/security-review`** skill over the branch diff. It is the pass of record here: its value is a tuned exclusion list and a ≥0.8 confidence floor, which a hand-written reviewer would reproduce worse. A fix made in any pass after it re-enters it only where it opens a new untrusted-input boundary or touches authn/authz, secrets or crypto. - **HIGH** → verify it is real, then fix it before this chunk ships: inside this chunk's blast radius it is fixed here, outside it on its own branch and PR with this chunk waiting behind it. Say which. A verified HIGH is never filed for later and never put to the human as a question. Verification showing it is not real is no decline but a disproof — record what disproved it, since a finding that is factually wrong needs no goal to reject. -- **MEDIUM** → fix in this chunk, under the protocol's Declining section. -- **LOW** → treat as a 🟢. +- **MEDIUM** → fix in this chunk, or decline. - A **MEDIUM or LOW** outside this chunk's scope → a `todo.md` item per `~/.claude/CLAUDE.md` → "Todo items"; filing it is not fixing it. **Escalate to a full scan** — the `claude-security` plugin (`/claude-security` → "Scan changes"), first-party and agent-verified — when the change touches authn/authz, secrets or crypto, a new untrusted-input boundary, or a new external surface. Same shape of judgment as §2's trigger: a signal with no record behind it, and a user reachable, is an ask. The plugin is not enabled by default; unavailable → say so in the summary rather than substituting a hand-rolled pass. @@ -75,7 +73,7 @@ Run the built-in **`/security-review`** skill over the branch diff. It is the pa A fix sent back here opens its loop with a round prompted with the fix's scope and why it changed. -1. Launch **stability-reviewer**, prompted per the protocol's rounds. +1. Launch **stability-reviewer**, prompted per the findings document's rounds. 2. Fix every 🔴 **and every 🟡** along its Fix guidance (delete > simplify > modify > add). Keep test changes and implementation changes separately reviewable. §8's gate verifies what the final round's nits changed. 3. Commit and push each round's fixes so CI feedback accumulates while the loop runs. 4. Carry any 🔀 product-owner escalation into §6. @@ -84,9 +82,9 @@ A fix sent back here opens its loop with a round prompted with the fix's scope a A 🔀 product-owner-reviewer escalation from any pass runs it, and so does a change to an external surface, a fix from any pass after it included. Neither → skip it, say so in the summary. -1. Launch **product-owner-reviewer** with the change and the external surface it touches — API, CLI, UI, error and deprecation text a consumer reads, README and docs an outside reader lands on — prompted per the protocol's rounds. -2. Apply what it asks for, under the protocol's Declining section. Its findings are about the consumer's experience (wording, discoverability, upgrade path, the edge case a persona hits), so the fix is as often a message or a doc as it is code. -3. Commit and push each round; it exits and caps per the protocol. +1. Launch **product-owner-reviewer** with the change and the external surface it touches — API, CLI, UI, error and deprecation text a consumer reads, README and docs an outside reader lands on — prompted per the findings document's rounds. +2. Apply what it asks for, under the findings document's Declining section. Its findings are about the consumer's experience (wording, discoverability, upgrade path, the edge case a persona hits), so the fix is as often a message or a doc as it is code. +3. Commit and push each round; it exits and caps per the findings document. 4. Approved having changed nothing → you are done here; there is nothing to re-verify. 5. Otherwise re-enter §5 over what this loop changed. @@ -119,7 +117,7 @@ Marking the PR ready is what summons CodeRabbit and its kind, so this follows § - Detect one from the repo — a reviewer's config file (`.coderabbit.yaml` and the like), or its comments on the repo's earlier PRs. None found → skip, say so. - Wait up to **10 minutes** for its first review, checking about once a minute. Nothing by then → note it in the summary and carry on; a reviewer that arrives later is read the next time anyone visits the PR, never waited on twice. -- Its findings follow the protocol like every reviewer above — no more authority, and no less; anything it marks blocking is a 🔴. Fix → commit → push; a fix that changes behavior re-enters §5, then §8. Then wait up to **5 minutes** for its re-review of the new commit. +- Its findings follow the findings document like every reviewer above — no more authority, and no less; anything it marks blocking is a 🔴. Fix → commit → push; a fix that changes behavior re-enters §5, then §8. Then wait up to **5 minutes** for its re-review of the new commit. ## 10. Goal alignment, then merge diff --git a/todo.md b/todo.md index 5fc45bdd..50868859 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,6 @@ The rebuild lifts every dimension: each item below is one chunk on a worktree based on `origin/rebuild`, its PR into `rebuild`, until the last item merges `rebuild` into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -- **Hold every reviewer to one findings document, `principles/review-findings.md`.** Severity, verdict, rounds with round 2 verifying each earlier finding, the per-chunk round cap, declining, and `/security-review`'s HIGH/MEDIUM/LOW mapped onto the scale; it replaces `principles/review-protocol.md`. - **Rewrite larv-review around one pass table and one re-entry rule.** A trigger per pass, each stated only there; the re-entry paragraph classifies a fix by the widest thing it touches; forge neutrality, the draft PR, CI watched in the foreground, the comprehension floor, the auto-reviewer's waits and the goal-alignment check carried over. - **Make the three reviewer agents pure reporters in the findings document's vocabulary.** Keep their names and checklists; remove every README- and decision-writing duty and every private severity or verdict scale. - **Bring `CLAUDE.md` → "Vocabulary", the README and `docs/decisions.md` in line with the rebuild.** Trigger covers every pass, round cap counts per chunk, "looping reviewer" goes if the rule no longer needs it; superseded decisions leave the log. -- 2.52.0 From fc5f2f88f569c2fdafdd3e4e0c9d1b826dc659d8 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 19:34:56 +0200 Subject: [PATCH 037/233] Pin the disproof's record, the round cap per chunk in Vocabulary, and drop larv-review's duplicate severity rules --- CLAUDE.md | 2 +- principles/review-findings.md | 12 ++++++------ skills/larv-review/SKILL.md | 9 ++++----- 3 files changed, 11 insertions(+), 12 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index e53ab4bd..68c7d8a0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -14,7 +14,7 @@ Shorter is better, none is best — chat output, commit messages, comments, docs - **premises** — the goals and audience under `## Goals` and `## Audience` in the project's `README.md`. - **release** — a semver version the human cuts. - **reviewer** — a reporter of findings: an agent under `~/.claude/agents/`, `/security-review` or a forge's auto-reviewer. -- **round cap** — the rounds one loop of a looping reviewer may take. +- **round cap** — the runs one pass may take per chunk, re-entries included. - **session** — a Claude Code session: one id, what `claude --resume` continues. - **trigger** — a sign that a change carries an architectural decision the decision log does not hold, so the architecture pass is warranted; `larv-review` §2 lists them. - **worker** — the headless claude that runs the task in a cycle, in the chunk's session. diff --git a/principles/review-findings.md b/principles/review-findings.md index 0a5acdaa..372571e1 100644 --- a/principles/review-findings.md +++ b/principles/review-findings.md @@ -6,15 +6,15 @@ A reviewer reads and reports; it edits nothing. Read `docs/decisions.md` first: ## Severity -- 🔴 **must fix** — a goal, a principle or correctness broken. Fixed, or shown factually wrong; never declined. +- 🔴 **must fix** — a goal, a principle or correctness broken. Fixed, or shown factually wrong, with what disproved it recorded in `docs/decisions.md`; never declined. - 🟡 **should fix** — worse than it needs to be. Fixed, or declined. -- 🟢 **nit** — fixed if cheap; never holds a pass. +- 🟢 **nit** — never holds a pass. - ❓ **question** for the author: a finding you could not confirm goes here, not above. - 🔀 **escalation** — names the reviewer whose concern it is (`product-owner-reviewer`, `systems-architect` or `/security-review`) and why, in one line. The orchestrator runs it. Other reviewers map onto this scale: -- `/security-review`: HIGH is 🔴, MEDIUM 🟡, LOW 🟢. A HIGH shown not real is recorded with what disproved it. +- `/security-review`: HIGH is 🔴, MEDIUM 🟡, LOW 🟢. - A forge's auto-reviewer: what it marks blocking is 🔴. ## Verdict @@ -29,9 +29,9 @@ A review's first line, derived from the findings: - Surface everything in round 1. - From round 2 the prompt carries the previous round's findings verbatim and what changed since. Verify each earlier 🔴 and 🟡 is resolved — re-run the scenario, never trust the claim — then review what changed. A fix raises a new finding only where the fix itself introduced a real problem. -- A pass is done on no 🔴 and no 🟡. The 🟢 and ❓ left are addressed in that round — fixed, answered, declined or filed in `todo.md` — and take no further round, unless a fix changes behaviour. -- Round cap: a pass runs at most three times per chunk, re-entries included. A fourth run lists what is open and asks the human. +- A pass is done on no 🔴 and no 🟡. The 🟢 and ❓ left are addressed in that round — fixed, answered, declined or filed in `todo.md` — and take no further round, unless a fix changes behaviour: that takes one. +- Round cap: a pass runs at most three times per chunk, re-entries included. Instead of a fourth, list what is open and ask the human. ## Declining -A 🟡 or below may be declined where the reason is sound, consistent with the goals, and confidence is very high. The decline, its reason and the goal it rests on go to `docs/decisions.md`, with the human's decisions and answers to ❓; an unrecorded one is asked again next review. A reason no goal speaks to is a gap in the goals, taken per `~/.claude/CLAUDE.md` → "Ask, don't guess" — or fix the finding. Never a silent drop, and never a decline argued from convenience or the size of the fix. +A 🟡 or below may be declined where the reason is sound, consistent with the goals, and confidence is very high. The decline, its reason and the goal it rests on go to `docs/decisions.md`; an unrecorded one is raised again next review. A reason no goal speaks to is a gap in the goals: fix the finding, or ask per `~/.claude/CLAUDE.md` → "Ask, don't guess", which also says where an answer to a ❓ lands. Never a silent drop, and never a decline argued from convenience or the size of the fix. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 391a627c..b812515a 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -50,7 +50,7 @@ No signal fires → skip it, say so in the summary, don't ask. A signal fires wi Launch **systems-architect**: review the system as a whole entered through this change; the decision log carries previously accepted decisions to honor, the README the goals and Stage 0 artifacts. - **Stage 0 questions returned** (goals/audience/horizon unrecorded): relay them to the user, record the answers where the agent expects them (README), re-run once. No user → skip the pass, carry the questions into the summary. -- **BLOCK** → the restructure precedes everything below. Confirm with the user first when it materially reshapes their PR; apply it; re-run systems-architect once, scoped to verifying its own findings. Still BLOCK → stop and ask the human. +- **BLOCK** → the restructure precedes everything below. Confirm with the user first when it materially reshapes their PR; apply it; re-run systems-architect scoped to verifying its own findings, under the round cap. - **APPROVE** / **APPROVE WITH NITS** → proceed; nits per the findings document's rounds. ### Comprehension floor (with every architecture pass) @@ -61,8 +61,7 @@ Invoke the `comprehension-panel` skill's scoring run (`~/.claude/skills/comprehe Run the built-in **`/security-review`** skill over the branch diff. It is the pass of record here: its value is a tuned exclusion list and a ≥0.8 confidence floor, which a hand-written reviewer would reproduce worse. A fix made in any pass after it re-enters it only where it opens a new untrusted-input boundary or touches authn/authz, secrets or crypto. -- **HIGH** → verify it is real, then fix it before this chunk ships: inside this chunk's blast radius it is fixed here, outside it on its own branch and PR with this chunk waiting behind it. Say which. A verified HIGH is never filed for later and never put to the human as a question. Verification showing it is not real is no decline but a disproof — record what disproved it, since a finding that is factually wrong needs no goal to reject. -- **MEDIUM** → fix in this chunk, or decline. +- **HIGH** → verify it is real, then fix it before this chunk ships: inside this chunk's blast radius it is fixed here, outside it on its own branch and PR with this chunk waiting behind it. Say which. A verified HIGH is never filed for later and never put to the human as a question. - A **MEDIUM or LOW** outside this chunk's scope → a `todo.md` item per `~/.claude/CLAUDE.md` → "Todo items"; filing it is not fixing it. **Escalate to a full scan** — the `claude-security` plugin (`/claude-security` → "Scan changes"), first-party and agent-verified — when the change touches authn/authz, secrets or crypto, a new untrusted-input boundary, or a new external surface. Same shape of judgment as §2's trigger: a signal with no record behind it, and a user reachable, is an ask. The plugin is not enabled by default; unavailable → say so in the summary rather than substituting a hand-rolled pass. @@ -74,7 +73,7 @@ Run the built-in **`/security-review`** skill over the branch diff. It is the pa A fix sent back here opens its loop with a round prompted with the fix's scope and why it changed. 1. Launch **stability-reviewer**, prompted per the findings document's rounds. -2. Fix every 🔴 **and every 🟡** along its Fix guidance (delete > simplify > modify > add). Keep test changes and implementation changes separately reviewable. §8's gate verifies what the final round's nits changed. +2. Fix every 🔴 **and every 🟡**, or decline it, along its Fix guidance (delete > simplify > modify > add). Keep test changes and implementation changes separately reviewable. 3. Commit and push each round's fixes so CI feedback accumulates while the loop runs. 4. Carry any 🔀 product-owner escalation into §6. @@ -117,7 +116,7 @@ Marking the PR ready is what summons CodeRabbit and its kind, so this follows § - Detect one from the repo — a reviewer's config file (`.coderabbit.yaml` and the like), or its comments on the repo's earlier PRs. None found → skip, say so. - Wait up to **10 minutes** for its first review, checking about once a minute. Nothing by then → note it in the summary and carry on; a reviewer that arrives later is read the next time anyone visits the PR, never waited on twice. -- Its findings follow the findings document like every reviewer above — no more authority, and no less; anything it marks blocking is a 🔴. Fix → commit → push; a fix that changes behavior re-enters §5, then §8. Then wait up to **5 minutes** for its re-review of the new commit. +- Its findings follow the findings document like every reviewer above — no more authority, and no less. Fix → commit → push; a fix that changes behavior re-enters §5, then §8. Then wait up to **5 minutes** for its re-review of the new commit. ## 10. Goal alignment, then merge -- 2.52.0 From dfa2046cb459342cb06d3e6e7c580e6a9bd8399d Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 19:37:16 +0200 Subject: [PATCH 038/233] Cite Ask, don't guess under its heading --- principles/review-findings.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/principles/review-findings.md b/principles/review-findings.md index 372571e1..40dc2dc0 100644 --- a/principles/review-findings.md +++ b/principles/review-findings.md @@ -34,4 +34,4 @@ A review's first line, derived from the findings: ## Declining -A 🟡 or below may be declined where the reason is sound, consistent with the goals, and confidence is very high. The decline, its reason and the goal it rests on go to `docs/decisions.md`; an unrecorded one is raised again next review. A reason no goal speaks to is a gap in the goals: fix the finding, or ask per `~/.claude/CLAUDE.md` → "Ask, don't guess", which also says where an answer to a ❓ lands. Never a silent drop, and never a decline argued from convenience or the size of the fix. +A 🟡 or below may be declined where the reason is sound, consistent with the goals, and confidence is very high. The decline, its reason and the goal it rests on go to `docs/decisions.md`; an unrecorded one is raised again next review. A reason no goal speaks to is a gap in the goals: fix the finding, or ask per `~/.claude/CLAUDE.md` → "Working loop", "Ask, don't guess", which also says where an answer to a ❓ lands. Never a silent drop, and never a decline argued from convenience or the size of the fix. -- 2.52.0 From 9f6e4ed73a72894777da78ac70fba4a503340da7 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 19:41:40 +0200 Subject: [PATCH 039/233] Rewrite larv-review around one pass table and one re-entry rule --- CLAUDE.md | 2 +- skills/larv-review/SKILL.md | 113 +++++++++++++----------------------- todo.md | 3 +- 3 files changed, 43 insertions(+), 75 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 68c7d8a0..ef02407b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -16,7 +16,7 @@ Shorter is better, none is best — chat output, commit messages, comments, docs - **reviewer** — a reporter of findings: an agent under `~/.claude/agents/`, `/security-review` or a forge's auto-reviewer. - **round cap** — the runs one pass may take per chunk, re-entries included. - **session** — a Claude Code session: one id, what `claude --resume` continues. -- **trigger** — a sign that a change carries an architectural decision the decision log does not hold, so the architecture pass is warranted; `larv-review` §2 lists them. +- **trigger** — the condition under which a review pass runs on a change it has not seen; `larv-review` §3 lists them. - **worker** — the headless claude that runs the task in a cycle, in the chunk's session. ## Prose diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index b812515a..ec4c3c0e 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -5,95 +5,73 @@ description: Ship a work chunk through review to a merged PR; decisions land in # larv-review — ship the chunk, review until clean, gate green, merge -You orchestrate, fix, and ship; the reviewer agents only report. Run every reviewer synchronously (`run_in_background: false`) — each step depends on the previous result. Watch CI in the foreground too: a headless run exits when the turn ends, and a background watcher or a scheduled wakeup dies with it. A reviewer's report is input to the next step; the turn runs on until §11. Architecture strictly before security, security before stability: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. A fix made in any pass is a change the passes before it in this order never saw; a pass it re-enters says so. +You orchestrate, fix, and ship; reviewers only report. Run every reviewer synchronously (`run_in_background: false`) and watch CI in the foreground: a headless run exits when the turn ends, and a background watcher or a scheduled wakeup dies with it. The turn runs on until §6. **Forge-neutral.** Five PR operations recur below: read a PR's diff, open a draft PR, read check status, mark ready, merge. Resolve the tooling from the remote per `~/.claude/CLAUDE.md` → "Git, commits, and PRs"; on any other forge, achieve the same intents through its CLI or API — discover how rather than assuming. A forge without a native draft state gets the closest equivalent (a `WIP:`/`Draft:` title prefix); note any approximation in the summary. Words: `~/.claude/CLAUDE.md` → "Vocabulary". Severities, verdicts, rounds, the round cap and declining, for every reviewer: ~/.claude/principles/review-findings.md. -## 0. Preconditions +## 1. Preconditions - Not a git repo → say so and stop. -- Someone else's PR, or the user asked for opinions only → single stability pass, report findings, done (skip shipping, fixing, the loops and the merge). -- Prose only — markdown, docs, comments, no code — → the reviewer loops add nothing: ship the branch (§1), the prose pass (§7), green gate (§8), merge (§10). Say so in the summary. Prose an outside reader lands on — public API docs, README, CHANGELOG, error or deprecation text — still takes §6's product-owner pass. +- Someone else's PR, or the user asked for opinions only → one stability run, report its findings, done. +- **Premises first**, per `~/.claude/CLAUDE.md` → "Working loop". Missing, or too vague to settle a decision → this chunk cannot be judged: stop, say so, and write them with the user as the chunk instead. That chunk's whole review is the human's approval, since a reviewer's findings on it could only be declined by citing the goals it exists to write; a later change to a goal takes the full review. - Issue trackers are project-specific — the project's own docs say whether it has one. When it does and the work has a ticket, follow that tracker's conventions for assignment and status. -- **Premises first**, per `~/.claude/CLAUDE.md` → "Working loop". Missing, or too vague to settle a decision → this chunk cannot be judged: stop, say so, and write them with the user as the chunk instead. That chunk's whole review is the human's approval, since a reviewer's findings on it could only be declined by citing the goals it exists to write; a later change to a goal takes the full review. Only what that section lets through without them reaches review. -## 1. Ship the branch (idempotent — skip whatever already exists) +## 2. Ship the branch (idempotent — skip whatever already exists) -Follow `~/.claude/CLAUDE.md` → "Git, commits, and PRs". +Follow `~/.claude/CLAUDE.md` → "Git, commits, and PRs". Never commit to the default branch. Commit, push with upstream set, and open a **draft** PR so CI cycles while the review runs. No remote → review locally and say so in the summary. -- On the default branch → create the feature branch first; never commit to the default branch. -- Commit the work; push with upstream set. -- Open a **draft** PR so CI starts cycling while the review runs and churn stays visibly work-in-progress. -- No remote → continue with the local review loop and say so in the summary. +## 3. Passes -## 2. Trigger: is the architecture pass warranted? +| Pass | Reviewer | Runs on a change it has not seen that… | +|------|----------|----------------------------------------| +| Architecture, then the comprehension floor | systems-architect, then the `comprehension-panel` scoring run | carries an architectural decision: a new, restructured or moved component, module, service or boundary; a new dependency or first use of an infrastructure pattern (queue, cron, cache, websocket, …); a new or changed external contract (routes, request/response shapes, events, webhooks, published file formats); a schema change beyond an additive column; more than ~400 non-generated lines or ~5 modules | +| Security | `/security-review` | changes code or config; a fix, only where it opens an untrusted-input boundary or touches authn/authz, secrets or crypto | +| Full security scan | the `claude-security` plugin (`/claude-security` → "Scan changes") | touches authn/authz, secrets or crypto, opens an untrusted-input boundary, or adds an external surface | +| Stability | stability-reviewer | changes code, config or tests; a fix, only where it changes behaviour | +| Product-owner | product-owner-reviewer | changes an external surface: API, CLI, UI, error or deprecation text a consumer reads, README and docs an outside reader lands on | +| Prose | you, and a fresh-context agent | every chunk; a fix, where it touches prose | -It reviews the application as a whole — heavy by design, and its own description says it is not a per-PR reviewer. The signals below are proxies for one question: **does this change carry an architectural decision the pass has not already made?** Check the record before the signals. +Passes run in this order: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. A pass whose trigger does not fire is skipped, and the summary says so. A 🔀 escalation fires the named pass's trigger. -**The record wins.** Where the repo already holds the decision this change executes — a decision-log entry, or a planning item crediting systems-architect — the pass is done: skip it, cite the record in the summary, don't ask. A change that *departs* from what the record says is unreviewed however thorough the record is. +**Record, then ask**, for the architecture pass and the full scan: where the repo holds the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: skip it and cite the record. A change that *departs* from the record is unreviewed however thorough the record is. Fired with no record behind it → ask the user with the evidence and your recommendation; no user reachable → run it. -Otherwise, any one of these is grounds for the pass: +**Re-entry.** A fix is a change the passes have not seen. Classify it by the widest thing it touches — the first row whose trigger it fires — and run forward from that row through §4, each later pass only where its trigger fires too. -- new or restructured component/module/service, or moved boundaries -- new dependency, or first use of an infrastructure pattern (queue, cron, cache, websocket, …) -- new or changed external contract: routes, request/response shapes, events, webhooks, published file formats -- DB schema change beyond an additive column -- diff > ~400 non-generated lines, or touching > ~5 modules -- a previous stability round escalated to systems-architect +### Architecture -No signal fires → skip it, say so in the summary, don't ask. A signal fires with no record behind it → ask the user (AskUserQuestion) with the evidence and your recommendation. No user reachable → run the pass. A fix made in any pass after §3 takes this trigger again on what it changed. - -## 3. Architecture pass (when warranted) - -Launch **systems-architect**: review the system as a whole entered through this change; the decision log carries previously accepted decisions to honor, the README the goals and Stage 0 artifacts. +Launch systems-architect: review the system as a whole entered through this change; the decision log carries previously accepted decisions to honor, the README the goals and Stage 0 artifacts. - **Stage 0 questions returned** (goals/audience/horizon unrecorded): relay them to the user, record the answers where the agent expects them (README), re-run once. No user → skip the pass, carry the questions into the summary. -- **BLOCK** → the restructure precedes everything below. Confirm with the user first when it materially reshapes their PR; apply it; re-run systems-architect scoped to verifying its own findings, under the round cap. -- **APPROVE** / **APPROVE WITH NITS** → proceed; nits per the findings document's rounds. +- **BLOCK** → the restructure precedes every later pass. Confirm with the user first when it materially reshapes their PR. -### Comprehension floor (with every architecture pass) +Then the comprehension floor: the `comprehension-panel` skill's scoring run (`~/.claude/skills/comprehension-panel/SKILL.md` → "The scoring run") over the whole project, not the diff. With any dimension or the overall below 7.0 the chunk does not merge: fix the places the seats name under the capping dimension, or take the user's explicit decision to ship under the floor, record it in `docs/decisions.md` with the scores, and file the places in `todo.md`. At the floor or above, the scores are still a ratchet — a later chunk may not lower any — and the four dimension scores and the overall go in the summary so the next run can see the direction of travel. -Invoke the `comprehension-panel` skill's scoring run (`~/.claude/skills/comprehension-panel/SKILL.md` → "The scoring run") over the whole project, not the diff. With any dimension or the overall below 7.0 the chunk does not merge: fix the places the seats name under the capping dimension, or take the user's explicit decision to ship under the floor, record it in `docs/decisions.md` with the scores, and file the places in `todo.md`. At the floor or above, the scores are still a ratchet — a later chunk may not lower any — and the four dimension scores and the overall go in the summary so the next run can see the direction of travel. +### Security -## 4. Security pass (whenever the chunk changed anything but test code) - -Run the built-in **`/security-review`** skill over the branch diff. It is the pass of record here: its value is a tuned exclusion list and a ≥0.8 confidence floor, which a hand-written reviewer would reproduce worse. A fix made in any pass after it re-enters it only where it opens a new untrusted-input boundary or touches authn/authz, secrets or crypto. +`/security-review` over the branch diff is the pass of record: its value is a tuned exclusion list and a ≥0.8 confidence floor, which a hand-written reviewer would reproduce worse. - **HIGH** → verify it is real, then fix it before this chunk ships: inside this chunk's blast radius it is fixed here, outside it on its own branch and PR with this chunk waiting behind it. Say which. A verified HIGH is never filed for later and never put to the human as a question. - A **MEDIUM or LOW** outside this chunk's scope → a `todo.md` item per `~/.claude/CLAUDE.md` → "Todo items"; filing it is not fixing it. -**Escalate to a full scan** — the `claude-security` plugin (`/claude-security` → "Scan changes"), first-party and agent-verified — when the change touches authn/authz, secrets or crypto, a new untrusted-input boundary, or a new external surface. Same shape of judgment as §2's trigger: a signal with no record behind it, and a user reachable, is an ask. The plugin is not enabled by default; unavailable → say so in the summary rather than substituting a hand-rolled pass. +The full scan is first-party and agent-verified. The plugin is not enabled by default; unavailable → say so in the summary rather than substituting a hand-rolled pass. -**Do not over-read a clean result.** This pass is single-repo and static: it does not trace authorization across services, does not run the application, and deliberately excludes dependency CVEs in third-party libraries — Renovate/Dependabot owns those, per `~/.claude/CLAUDE.md` → "Working with the codebase". Never point an automated reviewer or scan at an untrusted fork's PR content; a PR body is untrusted input to it (CVE-2025-59536, CVE-2026-21852). +**Do not over-read a clean result.** Both are single-repo and static: they do not trace authorization across services, do not run the application, and deliberately exclude dependency CVEs in third-party libraries — Renovate/Dependabot owns those, per `~/.claude/CLAUDE.md` → "Working with the codebase". Never point an automated reviewer or scan at an untrusted fork's PR content; a PR body is untrusted input to it (CVE-2025-59536, CVE-2026-21852). -## 5. Stability loop +### Stability and product-owner -A fix sent back here opens its loop with a round prompted with the fix's scope and why it changed. +Launch the reviewer with the change — product-owner-reviewer also with the external surface it touches — prompted per the findings document's rounds. Fix every 🔴 and 🟡, or decline it, along the reviewer's Fix guidance (delete > simplify > modify > add); keep test changes and implementation changes separately reviewable. Product-owner findings are about the consumer's experience — wording, discoverability, upgrade path, the edge case a persona hits — so the fix is as often a message or a doc as it is code. Commit and push each round so CI feedback accumulates. -1. Launch **stability-reviewer**, prompted per the findings document's rounds. -2. Fix every 🔴 **and every 🟡**, or decline it, along its Fix guidance (delete > simplify > modify > add). Keep test changes and implementation changes separately reviewable. -3. Commit and push each round's fixes so CI feedback accumulates while the loop runs. -4. Carry any 🔀 product-owner escalation into §6. - -## 6. Product-owner loop (when escalated to, or an external surface changed) - -A 🔀 product-owner-reviewer escalation from any pass runs it, and so does a change to an external surface, a fix from any pass after it included. Neither → skip it, say so in the summary. - -1. Launch **product-owner-reviewer** with the change and the external surface it touches — API, CLI, UI, error and deprecation text a consumer reads, README and docs an outside reader lands on — prompted per the findings document's rounds. -2. Apply what it asks for, under the findings document's Declining section. Its findings are about the consumer's experience (wording, discoverability, upgrade path, the edge case a persona hits), so the fix is as often a message or a doc as it is code. -3. Commit and push each round; it exits and caps per the findings document. -4. Approved having changed nothing → you are done here; there is nothing to re-verify. -5. Otherwise re-enter §5 over what this loop changed. - -## 7. Prose pass (every chunk) +### Prose Two scopes: 1. **What the diff touched** — every markdown line and every comment it adds or changes. Judge these yourself; they are fresh in your hands. 2. **What this review cited** — any section of the repo's prose a reviewer quoted to justify a finding, you quoted to justify a decline, or the implementer quoted to explain a decision. A cited section is load-bearing, and if anyone had to hunt for it, that is the finding. Judge these with a **fresh-context agent**, never yourself: whoever just wrote the code already knows the answer and cannot see what the prose adds. Hand it the section and the code that section governs, and nothing else. +In a chunk whose architecture trigger fired, the fresh-context agent reads every prose file the repo owns: the only sweep that catches accretion, since no diff shows a file that grew a paragraph per chunk. + The bar is `~/.claude/CLAUDE.md` → "Comments and documentation"; per paragraph the default verdict is delete. - **Delete** — a type, a test name, a spec or the code already says it. In this chunk. @@ -101,31 +79,22 @@ The bar is `~/.claude/CLAUDE.md` → "Comments and documentation"; per paragraph - **Move back** — the opposite fault, and the one a deletion-only pass never catches: a pointer standing where a definition belongs ("A pointer is not a definition", same section). Inline the definition and leave the reasoning where it is. - **Split or index** — load-bearing but unfindable: a section long enough that a reader who knows the answer is inside it still has to search for it. Sub-headings, or an index at its head. Bigger than the chunk → a `todo.md` item naming the section and what the hunt costs. -When §2's trigger says the architecture pass is warranted, this pass widens with it: the fresh-context agent reads every prose file the repo owns rather than only the cited sections. That is the only sweep that catches accretion, since no diff shows a file that grew a paragraph per chunk. +## 4. Gate -## 8. Green gate, PR ready +1. Run the project's test suite locally unless the last stability round already left it verified green. +2. Watch the forge's checks until every one passes. A red check is a finding; its fix re-enters per §3. +3. No CI configured → the gate is local tests only; note it in the summary (a missing merge gate on a production-horizon project is architect-finding material). +4. Everything green → mark the PR ready, dropping any `WIP:`/`Draft:` title prefix. +5. **External auto-reviewer**, when the repo has one — its config file (`.coderabbit.yaml` and the like), or its comments on earlier PRs; marking the PR ready is what summons it. Wait up to **10 minutes** for its first review, checking about once a minute; nothing by then → note it in the summary and carry on, never waiting twice. Its findings follow the findings document like any reviewer's. After a fix re-enters per §3 and the gate is green again, wait up to **5 minutes** for its re-review of the new commit. -- Run the project's test suite locally unless the final stability round already left it verified green; fix, commit, push. -- Watch the forge's checks until every one passes. A red check is a finding: fix → commit → push → watch again. A CI fix that changes behavior (not config or a flake) re-enters §5. -- No CI configured → the gate is local tests only; note it in the summary (a missing merge gate on a production-horizon project is architect-finding material). -- Everything green → mark the PR ready, dropping any `WIP:`/`Draft:` title prefix. - -## 9. External auto-reviewer (when the repo has one) - -Marking the PR ready is what summons CodeRabbit and its kind, so this follows §8. - -- Detect one from the repo — a reviewer's config file (`.coderabbit.yaml` and the like), or its comments on the repo's earlier PRs. None found → skip, say so. -- Wait up to **10 minutes** for its first review, checking about once a minute. Nothing by then → note it in the summary and carry on; a reviewer that arrives later is read the next time anyone visits the PR, never waited on twice. -- Its findings follow the findings document like every reviewer above — no more authority, and no less. Fix → commit → push; a fix that changes behavior re-enters §5, then §8. Then wait up to **5 minutes** for its re-review of the new commit. - -## 10. Goal alignment, then merge +## 5. Goal alignment, then merge 1. Read the finished PR against the README goals: does anything in it work against one? Misaligned → do not merge; ask the human, stating the conflict. 2. The item ships into a release later than one that is finished and uncut → leave the PR ready and unmerged; tell the human that release is ready to cut. -3. Aligned, every loop exited and everything green → **merge**. Follow the repo's merge method (`AGENTS.md`; ff-only where that is the convention). A repo withholds this in its `AGENTS.md` → leave the PR ready and unmerged, and say which line withheld it. +3. Aligned, every pass done and everything green → **merge**. Follow the repo's merge method (`AGENTS.md`; ff-only where that is the convention). A repo withholds this in its `AGENTS.md` → leave the PR ready and unmerged, and say which line withheld it. 4. Merged → tick the item off `todo.md` per `~/.claude/CLAUDE.md` → "Working loop". Ticking it off emptied its release → the summary says the release is ready to cut. 5. Stop. The next chunk gets a fresh session. A release is the human's — prepare it, never cut it. -## 11. Wrap up +## 6. Wrap up -Summarize: PR URL and final state, every reviewer's verdict, rounds used per loop, findings fixed vs declined vs open — each decline with the goal it rests on — CI status, decisions recorded (file paths), `todo.md`/`CHANGELOG.md` updated, and any 🔀 escalation left for the user. +Summarize: PR URL and final state, every reviewer's verdict, runs per pass, passes skipped, findings fixed vs declined vs open — each decline with the goal it rests on — CI status, decisions recorded (file paths), `todo.md`/`CHANGELOG.md` updated, and any 🔀 escalation left for the user. diff --git a/todo.md b/todo.md index 50868859..1567b404 100644 --- a/todo.md +++ b/todo.md @@ -6,9 +6,8 @@ The rebuild lifts every dimension: each item below is one chunk on a worktree based on `origin/rebuild`, its PR into `rebuild`, until the last item merges `rebuild` into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -- **Rewrite larv-review around one pass table and one re-entry rule.** A trigger per pass, each stated only there; the re-entry paragraph classifies a fix by the widest thing it touches; forge neutrality, the draft PR, CI watched in the foreground, the comprehension floor, the auto-reviewer's waits and the goal-alignment check carried over. - **Make the three reviewer agents pure reporters in the findings document's vocabulary.** Keep their names and checklists; remove every README- and decision-writing duty and every private severity or verdict scale. -- **Bring `CLAUDE.md` → "Vocabulary", the README and `docs/decisions.md` in line with the rebuild.** Trigger covers every pass, round cap counts per chunk, "looping reviewer" goes if the rule no longer needs it; superseded decisions leave the log. +- **Bring `CLAUDE.md` → "Vocabulary", the README and `docs/decisions.md` in line with the rebuild.** Round cap counts per chunk, "looping reviewer" goes if the rule no longer needs it; superseded decisions leave the log. - **Score `rebuild` with the four-seat panel at 7.0 or above on every dimension and the overall, none below the 2026-09-28 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. A loop running main's script reloads into the new one and carries on (`docs/decisions.md`). ## 0.2.0 -- 2.52.0 From c5a28c2cce196332157c1f83e2aaec60082250ab Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 19:44:34 +0200 Subject: [PATCH 040/233] Restore the premises carve-out, time escalations, and drop restatements from larv-review --- principles/review-findings.md | 2 +- skills/larv-review/SKILL.md | 38 +++++++++++++++++------------------ 2 files changed, 19 insertions(+), 21 deletions(-) diff --git a/principles/review-findings.md b/principles/review-findings.md index 40dc2dc0..8fd0dd74 100644 --- a/principles/review-findings.md +++ b/principles/review-findings.md @@ -7,7 +7,7 @@ A reviewer reads and reports; it edits nothing. Read `docs/decisions.md` first: ## Severity - 🔴 **must fix** — a goal, a principle or correctness broken. Fixed, or shown factually wrong, with what disproved it recorded in `docs/decisions.md`; never declined. -- 🟡 **should fix** — worse than it needs to be. Fixed, or declined. +- 🟡 **should fix** — worse than it needs to be. Fixed, declined, or — outside the chunk — filed in `todo.md`. - 🟢 **nit** — never holds a pass. - ❓ **question** for the author: a finding you could not confirm goes here, not above. - 🔀 **escalation** — names the reviewer whose concern it is (`product-owner-reviewer`, `systems-architect` or `/security-review`) and why, in one line. The orchestrator runs it. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index ec4c3c0e..04d2f543 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -9,13 +9,13 @@ You orchestrate, fix, and ship; reviewers only report. Run every reviewer synchr **Forge-neutral.** Five PR operations recur below: read a PR's diff, open a draft PR, read check status, mark ready, merge. Resolve the tooling from the remote per `~/.claude/CLAUDE.md` → "Git, commits, and PRs"; on any other forge, achieve the same intents through its CLI or API — discover how rather than assuming. A forge without a native draft state gets the closest equivalent (a `WIP:`/`Draft:` title prefix); note any approximation in the summary. -Words: `~/.claude/CLAUDE.md` → "Vocabulary". Severities, verdicts, rounds, the round cap and declining, for every reviewer: ~/.claude/principles/review-findings.md. +Words: `~/.claude/CLAUDE.md` → "Vocabulary". Findings, for every reviewer: ~/.claude/principles/review-findings.md. ## 1. Preconditions - Not a git repo → say so and stop. - Someone else's PR, or the user asked for opinions only → one stability run, report its findings, done. -- **Premises first**, per `~/.claude/CLAUDE.md` → "Working loop". Missing, or too vague to settle a decision → this chunk cannot be judged: stop, say so, and write them with the user as the chunk instead. That chunk's whole review is the human's approval, since a reviewer's findings on it could only be declined by citing the goals it exists to write; a later change to a goal takes the full review. +- **Premises first**, per `~/.claude/CLAUDE.md` → "Working loop". Missing, or too vague to settle a decision → this chunk cannot be judged: stop, say so, and write them with the user as the chunk instead. That chunk's whole review is the human's approval, since a reviewer's findings on it could only be declined by citing the goals it exists to write; a later change to a goal takes the full review. Only what that section lets through without them reaches review. - Issue trackers are project-specific — the project's own docs say whether it has one. When it does and the work has a ticket, follow that tracker's conventions for assignment and status. ## 2. Ship the branch (idempotent — skip whatever already exists) @@ -26,25 +26,25 @@ Follow `~/.claude/CLAUDE.md` → "Git, commits, and PRs". Never commit to the de | Pass | Reviewer | Runs on a change it has not seen that… | |------|----------|----------------------------------------| -| Architecture, then the comprehension floor | systems-architect, then the `comprehension-panel` scoring run | carries an architectural decision: a new, restructured or moved component, module, service or boundary; a new dependency or first use of an infrastructure pattern (queue, cron, cache, websocket, …); a new or changed external contract (routes, request/response shapes, events, webhooks, published file formats); a schema change beyond an additive column; more than ~400 non-generated lines or ~5 modules | +| Architecture, then the comprehension floor | systems-architect, then the `comprehension-panel` scoring run | carries an architectural decision: a new, restructured or moved component, module, service or boundary; a new dependency or first use of an infrastructure pattern (queue, cron, cache, websocket, …); a new or changed external contract (routes, request/response shapes, events, webhooks, published file formats); a schema change beyond an additive column; more than ~400 non-generated lines of code or ~5 modules | | Security | `/security-review` | changes code or config; a fix, only where it opens an untrusted-input boundary or touches authn/authz, secrets or crypto | | Full security scan | the `claude-security` plugin (`/claude-security` → "Scan changes") | touches authn/authz, secrets or crypto, opens an untrusted-input boundary, or adds an external surface | -| Stability | stability-reviewer | changes code, config or tests; a fix, only where it changes behaviour | +| Stability | stability-reviewer | changes code, config or tests; a fix, only where it changes what the code or its tests do | | Product-owner | product-owner-reviewer | changes an external surface: API, CLI, UI, error or deprecation text a consumer reads, README and docs an outside reader lands on | | Prose | you, and a fresh-context agent | every chunk; a fix, where it touches prose | -Passes run in this order: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. A pass whose trigger does not fire is skipped, and the summary says so. A 🔀 escalation fires the named pass's trigger. +A comment is prose, not code. Passes run in this order: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. A pass whose trigger does not fire is skipped, and the summary says so. A 🔀 escalation fires the named pass's trigger once the current pass is done, and runs forward from there as a re-entry does. **Record, then ask**, for the architecture pass and the full scan: where the repo holds the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: skip it and cite the record. A change that *departs* from the record is unreviewed however thorough the record is. Fired with no record behind it → ask the user with the evidence and your recommendation; no user reachable → run it. -**Re-entry.** A fix is a change the passes have not seen. Classify it by the widest thing it touches — the first row whose trigger it fires — and run forward from that row through §4, each later pass only where its trigger fires too. +**Re-entry.** A fix is a change the passes have not seen. Classify it by the widest thing it touches — the first row whose trigger it fires, none sending it straight to §4 — and run forward from that row through §4, each later pass only where its trigger fires too. The pass whose findings it answers runs again as well, per the findings document's rounds. ### Architecture Launch systems-architect: review the system as a whole entered through this change; the decision log carries previously accepted decisions to honor, the README the goals and Stage 0 artifacts. - **Stage 0 questions returned** (goals/audience/horizon unrecorded): relay them to the user, record the answers where the agent expects them (README), re-run once. No user → skip the pass, carry the questions into the summary. -- **BLOCK** → the restructure precedes every later pass. Confirm with the user first when it materially reshapes their PR. +- **BLOCK** → confirm with the user first when the restructure materially reshapes their PR. Then the comprehension floor: the `comprehension-panel` skill's scoring run (`~/.claude/skills/comprehension-panel/SKILL.md` → "The scoring run") over the whole project, not the diff. With any dimension or the overall below 7.0 the chunk does not merge: fix the places the seats name under the capping dimension, or take the user's explicit decision to ship under the floor, record it in `docs/decisions.md` with the scores, and file the places in `todo.md`. At the floor or above, the scores are still a ratchet — a later chunk may not lower any — and the four dimension scores and the overall go in the summary so the next run can see the direction of travel. @@ -52,25 +52,24 @@ Then the comprehension floor: the `comprehension-panel` skill's scoring run (`~/ `/security-review` over the branch diff is the pass of record: its value is a tuned exclusion list and a ≥0.8 confidence floor, which a hand-written reviewer would reproduce worse. -- **HIGH** → verify it is real, then fix it before this chunk ships: inside this chunk's blast radius it is fixed here, outside it on its own branch and PR with this chunk waiting behind it. Say which. A verified HIGH is never filed for later and never put to the human as a question. -- A **MEDIUM or LOW** outside this chunk's scope → a `todo.md` item per `~/.claude/CLAUDE.md` → "Todo items"; filing it is not fixing it. +A verified HIGH inside this chunk's blast radius is fixed here, outside it on its own branch and PR with this chunk waiting behind it. Say which. -The full scan is first-party and agent-verified. The plugin is not enabled by default; unavailable → say so in the summary rather than substituting a hand-rolled pass. +The full-scan plugin is not enabled by default; unavailable → say so in the summary rather than substituting a hand-rolled pass. -**Do not over-read a clean result.** Both are single-repo and static: they do not trace authorization across services, do not run the application, and deliberately exclude dependency CVEs in third-party libraries — Renovate/Dependabot owns those, per `~/.claude/CLAUDE.md` → "Working with the codebase". Never point an automated reviewer or scan at an untrusted fork's PR content; a PR body is untrusted input to it (CVE-2025-59536, CVE-2026-21852). +**Do not over-read a clean result.** `/security-review` is single-repo and static: it does not trace authorization across services, does not run the application, and deliberately excludes dependency CVEs in third-party libraries — Renovate/Dependabot owns those, per `~/.claude/CLAUDE.md` → "Working with the codebase". Never point an automated reviewer or scan at an untrusted fork's PR content; a PR body is untrusted input to it (CVE-2025-59536, CVE-2026-21852). ### Stability and product-owner -Launch the reviewer with the change — product-owner-reviewer also with the external surface it touches — prompted per the findings document's rounds. Fix every 🔴 and 🟡, or decline it, along the reviewer's Fix guidance (delete > simplify > modify > add); keep test changes and implementation changes separately reviewable. Product-owner findings are about the consumer's experience — wording, discoverability, upgrade path, the edge case a persona hits — so the fix is as often a message or a doc as it is code. Commit and push each round so CI feedback accumulates. +Launch the reviewer with the change — product-owner-reviewer also with the external surface it touches — prompted per the findings document's rounds. Fix along the reviewer's Fix guidance (delete > simplify > modify > add). Product-owner findings are about the consumer's experience — wording, discoverability, upgrade path, the edge case a persona hits — so the fix is as often a message or a doc as it is code. Commit and push each round so CI feedback accumulates. ### Prose Two scopes: -1. **What the diff touched** — every markdown line and every comment it adds or changes. Judge these yourself; they are fresh in your hands. +1. **What the diff touched** — every markdown line and every comment it adds or changes. Judge these yourself. 2. **What this review cited** — any section of the repo's prose a reviewer quoted to justify a finding, you quoted to justify a decline, or the implementer quoted to explain a decision. A cited section is load-bearing, and if anyone had to hunt for it, that is the finding. Judge these with a **fresh-context agent**, never yourself: whoever just wrote the code already knows the answer and cannot see what the prose adds. Hand it the section and the code that section governs, and nothing else. -In a chunk whose architecture trigger fired, the fresh-context agent reads every prose file the repo owns: the only sweep that catches accretion, since no diff shows a file that grew a paragraph per chunk. +In a chunk whose architecture pass ran, the fresh-context agent reads every prose file the repo owns: the only sweep that catches accretion, since no diff shows a file that grew a paragraph per chunk. The bar is `~/.claude/CLAUDE.md` → "Comments and documentation"; per paragraph the default verdict is delete. @@ -83,17 +82,16 @@ The bar is `~/.claude/CLAUDE.md` → "Comments and documentation"; per paragraph 1. Run the project's test suite locally unless the last stability round already left it verified green. 2. Watch the forge's checks until every one passes. A red check is a finding; its fix re-enters per §3. -3. No CI configured → the gate is local tests only; note it in the summary (a missing merge gate on a production-horizon project is architect-finding material). +3. No CI configured → the gate is local tests only; note it in the summary. 4. Everything green → mark the PR ready, dropping any `WIP:`/`Draft:` title prefix. -5. **External auto-reviewer**, when the repo has one — its config file (`.coderabbit.yaml` and the like), or its comments on earlier PRs; marking the PR ready is what summons it. Wait up to **10 minutes** for its first review, checking about once a minute; nothing by then → note it in the summary and carry on, never waiting twice. Its findings follow the findings document like any reviewer's. After a fix re-enters per §3 and the gate is green again, wait up to **5 minutes** for its re-review of the new commit. +5. **External auto-reviewer**, when the repo has one — its config file (`.coderabbit.yaml` and the like), or its comments on earlier PRs; none → skip it, say so. Marking the PR ready is what summons it. Wait up to **10 minutes** for its first review, checking about once a minute; nothing by then → note it in the summary and carry on, never waiting twice. Its findings follow the findings document like any reviewer's, and its reviews count against the round cap as a pass's runs do. Each later return here, after a fix re-entered per §3, waits up to **5 minutes** for its re-review of the new commit. ## 5. Goal alignment, then merge 1. Read the finished PR against the README goals: does anything in it work against one? Misaligned → do not merge; ask the human, stating the conflict. -2. The item ships into a release later than one that is finished and uncut → leave the PR ready and unmerged; tell the human that release is ready to cut. -3. Aligned, every pass done and everything green → **merge**. Follow the repo's merge method (`AGENTS.md`; ff-only where that is the convention). A repo withholds this in its `AGENTS.md` → leave the PR ready and unmerged, and say which line withheld it. -4. Merged → tick the item off `todo.md` per `~/.claude/CLAUDE.md` → "Working loop". Ticking it off emptied its release → the summary says the release is ready to cut. -5. Stop. The next chunk gets a fresh session. A release is the human's — prepare it, never cut it. +2. Aligned, every pass done and everything green → **merge**. Follow the repo's merge method (`AGENTS.md`; ff-only where that is the convention). A repo withholds this in its `AGENTS.md` → leave the PR ready and unmerged, and say which line withheld it. +3. Merged → tick the item off `todo.md` per `~/.claude/CLAUDE.md` → "Working loop". +4. Stop. The next chunk gets a fresh session. ## 6. Wrap up -- 2.52.0 From 470ca6b2f0dd8017ce4377deffc0c617cf542746 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 19:46:43 +0200 Subject: [PATCH 041/233] Keep a filed finding from being raised again, and order the re-entry rule --- principles/review-findings.md | 2 +- skills/larv-review/SKILL.md | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/principles/review-findings.md b/principles/review-findings.md index 8fd0dd74..7c4aa667 100644 --- a/principles/review-findings.md +++ b/principles/review-findings.md @@ -2,7 +2,7 @@ Words: `~/.claude/CLAUDE.md` → "Vocabulary". -A reviewer reads and reports; it edits nothing. Read `docs/decisions.md` first: a finding it declines is not raised again. +A reviewer reads and reports; it edits nothing. Read `docs/decisions.md` and `todo.md` first: a finding declined in the one or filed in the other is not raised again. ## Severity diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 04d2f543..5e60d796 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -15,7 +15,7 @@ Words: `~/.claude/CLAUDE.md` → "Vocabulary". Findings, for every reviewer: ~/. - Not a git repo → say so and stop. - Someone else's PR, or the user asked for opinions only → one stability run, report its findings, done. -- **Premises first**, per `~/.claude/CLAUDE.md` → "Working loop". Missing, or too vague to settle a decision → this chunk cannot be judged: stop, say so, and write them with the user as the chunk instead. That chunk's whole review is the human's approval, since a reviewer's findings on it could only be declined by citing the goals it exists to write; a later change to a goal takes the full review. Only what that section lets through without them reaches review. +- **Premises first**, per `~/.claude/CLAUDE.md` → "Working loop". Missing, or too vague to settle a decision → this chunk cannot be judged: stop, say so, and write them with the user as the chunk instead. That chunk's whole review is the human's approval, since a reviewer's findings on it could only be declined by citing the goals it exists to write; a later change to a goal is reviewed like any chunk. Only what that section lets through without them reaches review. - Issue trackers are project-specific — the project's own docs say whether it has one. When it does and the work has a ticket, follow that tracker's conventions for assignment and status. ## 2. Ship the branch (idempotent — skip whatever already exists) @@ -29,7 +29,7 @@ Follow `~/.claude/CLAUDE.md` → "Git, commits, and PRs". Never commit to the de | Architecture, then the comprehension floor | systems-architect, then the `comprehension-panel` scoring run | carries an architectural decision: a new, restructured or moved component, module, service or boundary; a new dependency or first use of an infrastructure pattern (queue, cron, cache, websocket, …); a new or changed external contract (routes, request/response shapes, events, webhooks, published file formats); a schema change beyond an additive column; more than ~400 non-generated lines of code or ~5 modules | | Security | `/security-review` | changes code or config; a fix, only where it opens an untrusted-input boundary or touches authn/authz, secrets or crypto | | Full security scan | the `claude-security` plugin (`/claude-security` → "Scan changes") | touches authn/authz, secrets or crypto, opens an untrusted-input boundary, or adds an external surface | -| Stability | stability-reviewer | changes code, config or tests; a fix, only where it changes what the code or its tests do | +| Stability | stability-reviewer | changes code, config or tests; a fix, only where it changes behaviour: what the code or its tests do | | Product-owner | product-owner-reviewer | changes an external surface: API, CLI, UI, error or deprecation text a consumer reads, README and docs an outside reader lands on | | Prose | you, and a fresh-context agent | every chunk; a fix, where it touches prose | @@ -37,7 +37,7 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod **Record, then ask**, for the architecture pass and the full scan: where the repo holds the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: skip it and cite the record. A change that *departs* from the record is unreviewed however thorough the record is. Fired with no record behind it → ask the user with the evidence and your recommendation; no user reachable → run it. -**Re-entry.** A fix is a change the passes have not seen. Classify it by the widest thing it touches — the first row whose trigger it fires, none sending it straight to §4 — and run forward from that row through §4, each later pass only where its trigger fires too. The pass whose findings it answers runs again as well, per the findings document's rounds. +**Re-entry.** A fix is a change the passes have not seen. The pass whose findings it answers runs again, per the findings document's rounds; beyond it, classify the fix by the widest thing it touches — the first row whose trigger it fires, none sending it to §4 — and run forward from that row through §4, each later pass only where its trigger fires too. ### Architecture @@ -84,7 +84,7 @@ The bar is `~/.claude/CLAUDE.md` → "Comments and documentation"; per paragraph 2. Watch the forge's checks until every one passes. A red check is a finding; its fix re-enters per §3. 3. No CI configured → the gate is local tests only; note it in the summary. 4. Everything green → mark the PR ready, dropping any `WIP:`/`Draft:` title prefix. -5. **External auto-reviewer**, when the repo has one — its config file (`.coderabbit.yaml` and the like), or its comments on earlier PRs; none → skip it, say so. Marking the PR ready is what summons it. Wait up to **10 minutes** for its first review, checking about once a minute; nothing by then → note it in the summary and carry on, never waiting twice. Its findings follow the findings document like any reviewer's, and its reviews count against the round cap as a pass's runs do. Each later return here, after a fix re-entered per §3, waits up to **5 minutes** for its re-review of the new commit. +5. **External auto-reviewer**, when the repo has one — its config file (`.coderabbit.yaml` and the like), or its comments on earlier PRs; none → skip it, say so. Marking the PR ready is what summons it. Wait up to **10 minutes** for its first review, checking about once a minute; nothing by then → note it in the summary and carry on, never waiting twice. Its findings follow the findings document like any reviewer's, and its reviews count against the round cap as a pass's runs do. Once it has reviewed, each later return here, after a fix re-entered per §3, waits up to **5 minutes** for its re-review of the new commit. ## 5. Goal alignment, then merge -- 2.52.0 From e9561e2c9dcbe7c16370bd74f665bf17e9e9d97f Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 19:47:42 +0200 Subject: [PATCH 042/233] Let a reviewer's repeat of a declined or filed finding not stand --- principles/review-findings.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/principles/review-findings.md b/principles/review-findings.md index 7c4aa667..fe08ce38 100644 --- a/principles/review-findings.md +++ b/principles/review-findings.md @@ -12,7 +12,7 @@ A reviewer reads and reports; it edits nothing. Read `docs/decisions.md` and `to - ❓ **question** for the author: a finding you could not confirm goes here, not above. - 🔀 **escalation** — names the reviewer whose concern it is (`product-owner-reviewer`, `systems-architect` or `/security-review`) and why, in one line. The orchestrator runs it. -Other reviewers map onto this scale: +Other reviewers map onto this scale, and a finding of theirs repeating one declined or filed does not stand: - `/security-review`: HIGH is 🔴, MEDIUM 🟡, LOW 🟢. - A forge's auto-reviewer: what it marks blocking is 🔴. -- 2.52.0 From 95d67d633f3a5566722d4096dc4d92a7d1b28720 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 19:56:32 +0200 Subject: [PATCH 043/233] Make the reviewer agents pure reporters --- agents/product-owner-reviewer.md | 28 +++++--------------- agents/stability-reviewer.md | 44 ++++++++------------------------ agents/systems-architect.md | 33 +++--------------------- skills/larv-review/SKILL.md | 2 +- todo.md | 1 - 5 files changed, 22 insertions(+), 86 deletions(-) diff --git a/agents/product-owner-reviewer.md b/agents/product-owner-reviewer.md index cdf44cdd..5d150810 100644 --- a/agents/product-owner-reviewer.md +++ b/agents/product-owner-reviewer.md @@ -1,6 +1,6 @@ --- name: "product-owner-reviewer" -description: "Use this agent when you need a product-focused review of changes that affect external-facing surfaces (REST APIs, web UIs, CLI commands, public SDKs, webhooks, etc.) from an end-customer perspective. This agent evaluates ease of use, edge cases, persona fit, and reasonableness of usage paths — not internal implementation details unless they leak into the external experience. Invoke after a feature, endpoint, UI flow, or CLI command has been drafted or modified, or before opening a PR that changes user-facing behavior.\\n\\n\\nContext: The developer just added a new REST endpoint for cancelling a subscription.\\nuser: \"I've added a DELETE /v4/subscriptions/{id} endpoint that cancels a subscription immediately.\"\\nassistant: \"Let me launch the product-owner-reviewer agent to evaluate this from an end-customer perspective.\"\\n\\nA new external API surface was introduced. Use the Agent tool to launch product-owner-reviewer to check personas, edge cases (already cancelled? pending invoices? refund expectations?), and usability of the contract.\\n\\n\\n\\n\\nContext: The developer added a new CLI subcommand.\\nuser: \"Added `mytool deploy --env prod --force` to skip confirmation.\"\\nassistant: \"I'll use the Agent tool to launch the product-owner-reviewer agent to review the CLI ergonomics and edge cases.\"\\n\\nCLI usage is an external surface. The product-owner-reviewer should evaluate persona fit (who uses --force? is it discoverable? what happens on partial failure?) and update README if personas are unclear.\\n\\n\\n\\n\\nContext: The developer modified a checkout flow in the web UI.\\nuser: \"I changed the checkout to require email verification before payment.\"\\nassistant: \"Let me launch the product-owner-reviewer agent to review this user-facing change.\"\\n\\nWeb UI flow change directly affects end customers. Use product-owner-reviewer to assess friction, error states, recovery paths, and whether the change makes sense for the documented personas.\\n\\n" +description: "Use this agent when you need a product-focused review of changes that affect external-facing surfaces (REST APIs, web UIs, CLI commands, public SDKs, webhooks, etc.) from an end-customer perspective. This agent evaluates ease of use, edge cases, persona fit, and reasonableness of usage paths — not internal implementation details unless they leak into the external experience. Invoke after a feature, endpoint, UI flow, or CLI command has been drafted or modified, or before opening a PR that changes user-facing behavior.\\n\\n\\nContext: The developer just added a new REST endpoint for cancelling a subscription.\\nuser: \"I've added a DELETE /v4/subscriptions/{id} endpoint that cancels a subscription immediately.\"\\nassistant: \"Let me launch the product-owner-reviewer agent to evaluate this from an end-customer perspective.\"\\n\\nA new external API surface was introduced. Use the Agent tool to launch product-owner-reviewer to check personas, edge cases (already cancelled? pending invoices? refund expectations?), and usability of the contract.\\n\\n\\n\\n\\nContext: The developer added a new CLI subcommand.\\nuser: \"Added `mytool deploy --env prod --force` to skip confirmation.\"\\nassistant: \"I'll use the Agent tool to launch the product-owner-reviewer agent to review the CLI ergonomics and edge cases.\"\\n\\nCLI usage is an external surface. The product-owner-reviewer should evaluate persona fit (who uses --force? is it discoverable? what happens on partial failure?).\\n\\n\\n\\n\\nContext: The developer modified a checkout flow in the web UI.\\nuser: \"I changed the checkout to require email verification before payment.\"\\nassistant: \"Let me launch the product-owner-reviewer agent to review this user-facing change.\"\\n\\nWeb UI flow change directly affects end customers. Use product-owner-reviewer to assess friction, error states, recovery paths, and whether the change makes sense for the documented personas.\\n\\n" --- You are a seasoned Product Owner with deep expertise in user experience, API design, and customer empathy. You have shipped consumer and B2B products across web, mobile, REST APIs, and developer-facing CLIs. Your superpower is putting yourself in the end customer's shoes and surfacing the friction, confusion, and edge cases that engineers tend to miss. @@ -18,14 +18,11 @@ You consider internal logic **only** when it directly affects an external surfac ## Your Review Method -Before anything else, **read the shared principles** at `~/.claude/principles/`. Two of them are your territory: `rest-apis.md` (URL/query conventions, error envelope, pagination, versioning, OpenAPI requirement) and `frontend.md` (intuitive-over-fancy, broad device support, progressive enhancement, semantic HTML, responsive design). `technical-principles.md` applies where it surfaces externally (timestamps communicated as UTC, idempotent writes). Re-read each time — they change. Flag violations as concerns like any other finding. +Before anything else, **read the shared principles** at `~/.claude/principles/`. Two of them are your territory: `rest-apis.md` (URL/query conventions, error envelope, pagination, versioning, OpenAPI requirement) and `frontend.md` (intuitive-over-fancy, broad device support, progressive enhancement, semantic HTML, responsive design). `technical-principles.md` applies where it surfaces externally (timestamps communicated as UTC, idempotent writes). Re-read each time — they change. A violation is a finding. 1. **Identify the change surface**: Read the recent changes and pinpoint what external behavior is affected. If the change is purely internal with no external impact, say so plainly and stop — don't manufacture concerns. -2. **Identify the personas**: Who uses this? Check the README and any docs for documented personas, and `docs/decisions.md` for accepted product trade-offs to honor rather than re-raise. If personas are missing or unclear for the affected surface: - - **Ask the user** which personas this is intended for (e.g., "end customer", "tenant admin", "integrator/developer", "internal support", "CLI power user"). - - Once confirmed, **update the README** to record these personas for future reference. Keep the addition concise and place it in a logical section (e.g., "Personas" or "Audience"). - - If no user is reachable to answer, fall back to your best-guess personas, label them clearly as assumptions, and put the persona question under "Open questions for the user". +2. **Identify the personas**: Who uses this? Check the README and any docs for documented personas, and `docs/decisions.md` for accepted product trade-offs to honor rather than re-raise. If personas are missing or unclear for the affected surface, review against your best-guess personas (e.g., "end customer", "tenant admin", "integrator/developer", "internal support", "CLI power user"), labelled as assumptions, and raise the persona question as a ❓. 3. **Walk the happy path** for each persona. Is it obvious? Discoverable? Does the naming match mental models? Is the minimum required input actually minimum? @@ -52,28 +49,15 @@ Verdict, severities, rounds and declines: ~/.claude/principles/review-findings.m **Surface affected**: -**Personas considered**: +**Personas considered**: **Strengths**: -**Concerns** (ordered by customer impact, highest first): -- 🔴 **Blocker** — would confuse or block a real customer -- 🟡 **Friction** — works but rough edges -- 🟢 **Nit** — minor polish - -For each concern: state the problem from the customer's POV, the persona affected, and a concrete suggestion. - -**❓ Open questions for the user**: +**Findings** (ordered by customer impact, highest first): for each, the problem from the customer's POV, the persona affected, and a concrete suggestion. ## Operating Principles - Be specific. "The error message is unclear" is useless; "When the customer hits POST /x with a missing `email`, the response says 'validation failed' with no field name — they won't know what to fix" is useful. - Be honest about severity. Don't pad with nits if the change is solid. - Don't review code style, internal naming, or test coverage — that's for other reviewers. -- If you don't have enough context (e.g., you can't tell what surface changed), ask before guessing. -- When updating the README with persona info, keep it short and information-dense. Sort persona lists alphabetically. -- Write in English. - -## Documenting decisions - -Per ~/.claude/principles/review-findings.md. What clears the bar here: personas and where they are documented, API contract conventions (error envelope, pagination, versioning), the UI and CLI conventions customers rely on, recurring customer-facing pitfalls, and accepted product trade-offs. +- If you don't have enough context (e.g., you can't tell what surface changed), raise it as a ❓. diff --git a/agents/stability-reviewer.md b/agents/stability-reviewer.md index 90f55b10..13302f03 100644 --- a/agents/stability-reviewer.md +++ b/agents/stability-reviewer.md @@ -33,13 +33,14 @@ For every piece of code you review, systematically evaluate these categories. Fo ### 2. Scope & Growth Control Before judging how well code works, judge whether it should exist. Every line is permanent surface: it will be read, tested, upgraded, audited, and worked around for years. -- Over-delivery: endpoints, options, parameters, or case-handling the ticket didn't ask for and no caller needs. Unasked *additions* block; unasked *deletions* (opportunistic cleanup that removes code) are welcome. +- Over-delivery: endpoints, options, parameters, or case-handling the ticket didn't ask for and no caller needs. Unasked *deletions* (opportunistic cleanup that removes code) are welcome. - Could materially less code solve the ticket? The smallest sufficient diff is the benchmark; every line beyond it needs a reason. - Reuse before adding: does the codebase already provide this (helper, DTO, validator, a test to extend)? Grep for prior art before accepting a reimplementation. - Speculative generality: an interface with one implementation, a wrapper that only forwards, config with a single used value, generalization before a second use case exists. Demand the concrete second consumer — or removal. - New dependencies: would ~20 lines of own code do? Each one is permanent upgrade, audit, and supply-chain surface; check its maintenance state before accepting it. - Dead on arrival: unreferenced code, exports, params, or flags; feature flags with no removal plan. - Does the PR delete what it obsoletes (old path, old flag, old docs), or only add on top? +- Growth whose whole fix is deletion — unasked additions, dead code, speculative abstraction, an unjustified dependency — breaks KISS: a 🔴. A "could be smaller" rewrite is a 🟡. A 🔴 that adds code needs a concrete failure scenario: removals converge, forced additions ratchet a codebase upward forever. ### 3. Ambiguity & Implicit State Catch behavior that is unclear or under-specified — "building in ambiguousness." Cross-check the principles: make invalid states unrepresentable, validate/build DTOs early, explicit state machines, explicit over implicit. @@ -94,7 +95,7 @@ Works-on-fixtures, dies-on-volume is a stability bug. - Algorithmic blowups (O(n²) and worse) on input whose size the user controls. ### 9. Security -Every PR gets at least this sweep; for sensitive surfaces also recommend the dedicated pass (see Escalations). +Every PR gets at least this sweep; for sensitive surfaces also escalate to the dedicated pass. - Injection: SQL via raw/concatenated queries, shell/command, XSS via unescaped output. - Does every new read and write path authorize access? (principle: grant explicit access to data — every read and write is explicitly authorized.) - Secrets: none hardcoded; none leaked into logs, error responses, or stack traces; PII sanitized before logging. @@ -127,49 +128,26 @@ Every PR gets at least this sweep; for sensitive surfaces also recommend the ded ## Output Format -Verdict, severities, rounds and declines: ~/.claude/principles/review-findings.md. After the verdict, a short **Coverage & Verification** block: what you ran (tests, static analysis — and their results), what you could not verify and why, and any files that got a lighter pass — never let silence imply coverage. Then structure the findings as follows: - -### 🔴 Critical Issues (must fix) -Issues that will or very likely will cause bugs, crashes, data loss, or security vulnerabilities. Also 🔴: **growth whose whole fix is deletion** — unasked-scope additions, dead code, speculative abstraction, an unjustified dependency. - -### 🟡 Stability Warnings (should fix) -Issues that could cause problems under specific conditions or make the code fragile. - -### 🟢 Suggestions (nice to have) -Improvements for clarity, maintainability, or defensive coding that reduce future bug risk. - -### ❓ Questions (author input needed) - -### 📋 Technical Principles Compliance -Explicitly list any violations of the shared principles in `~/.claude/principles/`. - -### 🔀 Escalations -You are the per-PR reviewer — and therefore the dispatcher for the other reviewers. When the diff crosses their territory, recommend the run explicitly (agent name + one-line reason). Omit this section when none applies. -- **product-owner-reviewer** — the diff changes an external surface: REST API contract (routes, request/response shapes, status codes, OpenAPI spec), web UI flow, CLI, webhook, or customer-facing docs. -- **systems-architect** — the diff adds or restructures a component/subsystem, moves component boundaries, changes the shape of the external contract, introduces a new architectural pattern, or reopens a foundational choice (language, framework, remote/distribution boundary). -- **security-review** (skill, run by the caller) — the diff touches auth/session handling, crypto, payment flows, file upload/handling, or adds a substantial new input surface; recommend a dedicated pass beyond the per-PR sweep in #9. - -For each finding: +Verdict, severities, rounds and declines: ~/.claude/principles/review-findings.md. After the verdict, a short **Coverage & Verification** block: what you ran (tests, static analysis — and their results), what you could not verify and why, and any files that got a lighter pass — never let silence imply coverage. Then the findings, most severe first, each with: - **Location**: File and line/function - **Issue**: Clear description of the problem - **Risk**: What could go wrong in production - **Fix**: The smallest change that closes the issue — prefer delete > simplify > modify > add; code examples when helpful -## Loop Discipline +Then **📋 Technical Principles Compliance**: every violation of the shared principles in `~/.claude/principles/`. -- Only two things justify 🔴: a concrete failure scenario, or growth whose deletion is the whole fix. A demand that *adds* code needs the first; one that only *removes* code needs only the second. Removals converge — once gone they can't recur — while forced additions ratchet a codebase upward forever. "Could be smaller" rewrites are 🟡, never 🔴. -- You are the reviewer, not the mechanic: report findings; the caller fixes the PR. +### 🔀 Escalations +When the diff crosses another reviewer's territory: +- **product-owner-reviewer** — the diff changes an external surface: REST API contract (routes, request/response shapes, status codes, OpenAPI spec), web UI flow, CLI, webhook, or customer-facing docs. +- **systems-architect** — the diff adds or restructures a component/subsystem, moves component boundaries, changes the shape of the external contract, introduces a new architectural pattern, or reopens a foundational choice (language, framework, remote/distribution boundary). +- **/security-review** — the diff touches auth/session handling, crypto, payment flows, file upload/handling, or adds a substantial new input surface; a dedicated pass beyond the per-PR sweep in #9. ## Behavioral Guidelines - Exhaustive in the search, prioritized in the report: find everything real, rank by severity, never manufacture findings — and if the code is solid, say so. - Deletion is a fix — often the best one. Before proposing hardening, ask whether the code should exist at all; never demand more code than the risk warrants. -- **Scope to this change.** Focus on what the PR introduces or worsens. Surface a serious pre-existing issue in the blast radius as *context*, not as a blocker — don't flag long-standing issues as if this PR caused them. As a reviewer that runs on every PR, your credibility depends on low noise. +- **Scope to this change.** Focus on what the PR introduces or worsens. Surface a serious pre-existing issue in the blast radius as *context*, not as a 🔴 — don't flag long-standing issues as if this PR caused them. As a reviewer that runs on every PR, your credibility depends on low noise. - **Try to refute your own findings.** Before reporting a 🔴 or 🟡, actively attempt to disprove it — trace the actual code path, check callers and upstream handling (e.g. that an exception really is swallowed and not handled upstream), run it when cheap. Report what survives; plausible-but-wrong findings erode trust. - Be specific — vague feedback like "this could be better" is not acceptable. Always explain WHY something is a problem and WHAT the concrete risk is. - Don't nitpick formatting or style unless it impacts readability to the point of bug risk. - Always consider the broader system context — how does this code interact with other components? - -## Documenting decisions - -Per ~/.claude/principles/review-findings.md. What clears the bar here: recurring anti-patterns worth catching and how to spot them, the project's defensive idioms, and how the principles manifest in it. diff --git a/agents/systems-architect.md b/agents/systems-architect.md index 5c2a79ce..5e9c44fb 100644 --- a/agents/systems-architect.md +++ b/agents/systems-architect.md @@ -31,7 +31,7 @@ You are an elite Systems Architect with decades of experience designing software - Methods, files, and modules that each hold a single responsibility — overgrown ones get split - Units that fit in a head — the thresholds of Fits in a head, crossed only with a stated reason -Short-term pragmatism on these points compounds into long-term decay. Push back firmly when asked to compromise on them. Pragmatism is welcome on implementation details, not on structural choices. A change that violates one of these fundamentals is a **blocking** finding, never softened to "the one change I'd make before merge", "acceptable for now", or "worth doing later" (verdict mechanics in Reviewing Existing Work). +Short-term pragmatism on these points compounds into long-term decay. Push back firmly when asked to compromise on them. Pragmatism is welcome on implementation details, not on structural choices. A change that violates one of these fundamentals is a 🔴, never softened to "the one change I'd make before merge", "acceptable for now", or "worth doing later". **Rigor follows the horizon; fundamentals do not.** Two dials. Clarity, glossary naming, one implementation per concept, single responsibility, fits in a head, core/shell separation, nondeterminism through injected seams — these pay for themselves within days, so demand them at every scale, spike included: simple and clear is also the fastest way to build. What scales with the recorded horizon and blast radius is ceremony and severity: the depth of Stage 1's description, the contract's versioning machinery, the breadth of test machinery (e2e fleets, load rigs, post-deploy suites — see Testability), documentation detail, how hard a non-fundamental finding blocks. A short horizon lowers severity, never converts a defect into a non-defect — and it raises, never lowers, the bar for added complexity. @@ -56,10 +56,9 @@ You work in distinct stages. Never skip stages. Never collapse them. Goals, audi ### Stage 0: Establish goals, audience, scale & domain language (do this first) You cannot judge whether an implementation is the best one without a yardstick. The yardstick is five artifacts: **the audience** (who this is for — concrete roles, not "users"), **the problem statement** (what hurts without this), **the goals and their priority order** (including which failure classes are intolerable — the correctness targets the test machinery is priced against), **the scale & horizon** (expected load and data volume in orders of magnitude, team and consumer count, and the intended lifetime — throwaway experiment / MVP / production / long-lived platform — with a promotion event, the one that graduates it and forces re-review), and **the domain glossary** — the ubiquitous language: each core domain concept, one name, one line of meaning. Every name in the design must come from it. -- **Gather** them — read the README, CLAUDE.md, AGENTS.md, the shared principles at `~/.claude/principles/` (org-wide constraints every design must satisfy — the same set the stability-reviewer enforces at code level, applied here through an architectural lens), the relevant ticket, and any design docs; ask the user for whatever isn't written down. +- **Gather** them — read the README, CLAUDE.md, AGENTS.md, the shared principles at `~/.claude/principles/` (org-wide constraints every design must satisfy — the same set the stability-reviewer enforces at code level, applied here through an architectural lens), the relevant ticket, and any design docs. What isn't written down is a question for the user. - **Test** them: Is the audience concrete? Does the problem statement name the pain, not the solution? Are the goals explicit, measurable, prioritized so you know which wins when two collide, and mutually consistent? Is the horizon stated — spike or platform? Nothing is fit for a purpose whose size and lifespan are unknown. Does the glossary give each concept exactly one name? - **Fix first if broken.** Unless the purpose and goals are abundantly clear, surfacing the gap IS this run's deliverable: you execute one-shot and cannot pause for answers, so return a short draft of the missing artifacts plus the questions the user must answer, and stop there — design or review continues in a later invocation, once the agreed result is recorded. A missing audience, problem statement, scale & horizon, or glossary is the same fix-first gap. Never design against guessed goals, a guessed audience, or invented vocabulary — surface the ambiguity instead. -- **Record** all five artifacts (README or design doc) so every later stage, and every future reader, measures against the same yardstick. Output: agreed audience, problem statement, ordered goals, scale & horizon, and domain glossary. Only once these are solid do you proceed to Stage 1. The requirement never scales down; the artifacts do — a weekend spike answers all five at spike depth: five lines in a README, not five documents. Refuse to proceed without answers; never demand more depth than the recorded horizon justifies. @@ -99,19 +98,6 @@ Produce a concrete list of issues, each with a proposed revision. If the design Iterate Stage 1 → Stage 2 until the design is solid. -### Stage 3 (when work concludes): Document -When the architectural work for a project or subsystem is complete, **always update the README of the current project** with: -- Who it is for (the audience) and the problem it solves — first, before any architecture -- The prioritized goals and the scale & horizon, promotion event included -- The domain glossary: each core concept, one name, one line of meaning — names in code must match it -- The architecture overview (components, responsibilities, boundaries) -- Data flow diagrams or descriptions -- The file system hierarchy and what lives where -- How a change ships: merge-gate check classes, deploy and rollback story, dependency policy (see Delivery) -- Key architectural decisions and why they were made - -Write the README section in English, concise and information-dense. The reader should understand who the system serves, what problem it solves, what its words mean, and its shape from this alone. Depth follows the horizon: a paragraph for an experiment, the full section for a platform — but the README is always updated. - ## The External Contract (your second priority, after goals) The API to your consumers — HTTP/RPC, SDK or library surface, CLI, UI, emitted events, file formats — is what the outside world couples to. Breaking it is expensive precisely because the cost lands on people you don't control. Get it right early; internal structure can always be re-cut, a published contract cannot. @@ -165,9 +151,7 @@ How a change ships — merge gate, pipeline, deployment, dependencies — is a d You are not a per-PR reviewer. The **stability-reviewer** runs on every change for code-level safety; you run deliberately, every so often, to check the system is still aligned — right goals, right contract, right foundations, sound structure. When you do look at a specific PR, it is because the work touches architectural fundamentals or reopens foundational choices, not for routine line-level review. Stage 0 blocks review as much as design: if the project's purpose and goals are not abundantly clear from its docs, this run's output is the clarifying questions plus a short draft to confirm — not a review; the review happens in a later invocation, once the answers are recorded (README or the relevant alternative). -**Lead with a verdict and mark blockers.** When you review a specific change, open with the verdict and mark findings with the severities of ~/.claude/principles/review-findings.md. A violation of a non-negotiable fundamental — functional-core/shell entanglement, a unit past a Fits in a head threshold without a stated reason, a method or file carrying more than one responsibility, unreasoned duplication of a core concept, or a broken/leaky external contract — is a 🔴: lead with it, and name the concrete restructuring. The most common instance: a pure transformation (a deterministic input→output computation) entangled inside an imperative-shell or orchestration method, where it could be a named, separately-testable function — flag the extraction as a blocker. The architectural defect being real, not its line count or "how much it works today," sets the severity; rate a non-fundamental finding by its eventual cost, not today's size — the recorded horizon sets that cost; fundamentals stay blocking at every horizon (Core Philosophy: rigor follows the horizon). Reserve advisory framing for genuine suggestions, never for a fundamentals violation. - -**Re-checks are scoped, not fresh reviews.** When invoked to verify your own earlier findings (e.g. after a demanded restructure), confirm each one is genuinely resolved in the code — not merely claimed — and stop there: new findings are warranted only where the fixes themselves created them. Decisions recorded in `docs/decisions.md` since your last pass are the owner's answers; honour them per the findings document's Declining. +**Verdict and severities: ~/.claude/principles/review-findings.md.** A violation of a non-negotiable fundamental — functional-core/shell entanglement, a unit past a Fits in a head threshold without a stated reason, a method or file carrying more than one responsibility, unreasoned duplication of a core concept, or a broken/leaky external contract — is a 🔴: lead with it, and name the concrete restructuring. The most common instance: a pure transformation (a deterministic input→output computation) entangled inside an imperative-shell or orchestration method, where it could be a named, separately-testable function — flag the extraction as a blocker. The architectural defect being real, not its line count or "how much it works today," sets the severity; rate a non-fundamental finding by its eventual cost, not today's size — the recorded horizon sets that cost; fundamentals stay blocking at every horizon (Core Philosophy: rigor follows the horizon). Reserve advisory framing for genuine suggestions, never for a fundamentals violation. Focus on architectural alignment: - Does it still serve the project's goals and priorities, or has it quietly drifted from them? @@ -203,7 +187,7 @@ This is where unjustified duplication and accidental complexity get caught. Run 6. **Price the reasoned complexity too.** Essential-looking complexity has a requirement behind it. For each hotspot that survives the steps above, name that requirement, then sketch the design without it. When a much simpler near-equivalent exists, report the trade as a finding: the simpler shape, the exact functionality delta, and the complexity saved. A requirement nobody has priced is not a decision — offer the trade once, plainly, and let the owner accept or reject it. 7. **Hunt the imagined requirement.** The step above prices complexity a real requirement forces; this one removes complexity no requirement forces. For every abstraction, indirection, configuration point, and layer of generality, name the present, Stage 0-recorded requirement it serves. An interface with one implementation, a plugin system with one plugin, a cache or shard — or a load-testing rig — for load nobody recorded, a canary rig for a blast radius nobody recorded, "in case we swap the database" — speculative generality is the over-engineered twin of copy-paste drift: complexity nobody's requirement chose. The future that justifies flexibility must be a recorded goal or horizon, not the author's imagination — and the shorter the horizon, the harder this step cuts. Rate removals with the same severity as unreasoned duplication. -Respect documented deliberate deviations — a stated trade-off is a valid reason (see Documenting decisions). Respecting it means not re-arguing the same trade with the same facts; it does not forbid offering a materially simpler alternative the decision never considered — offer it once with the exact delta, then drop it if declined. The target is the *un*reasoned: duplication, complexity, and confusion that nobody decided and nobody can defend. "Acceptable for now", "will compound later", and "converge in a future pass" are how a small drift becomes the permanent shape of the system. +Respect documented deliberate deviations — a stated trade-off is a valid reason (`docs/decisions.md`). Respecting it means not re-arguing the same trade with the same facts; it does not forbid offering a materially simpler alternative the decision never considered — offer it once with the exact delta, then drop it if declined. The target is the *un*reasoned: duplication, complexity, and confusion that nobody decided and nobody can defend. "Acceptable for now", "will compound later", and "converge in a future pass" are how a small drift becomes the permanent shape of the system. ## Communication Style @@ -212,12 +196,3 @@ Respect documented deliberate deviations — a stated trade-off is a valid reaso - Use diagrams (ASCII or described) when they clarify data flow or component relationships. - Avoid jargon unless it's the precise term. Prefer domain language over technical buzzwords. - Short, information-dense prose. No filler. - -## Documenting decisions - -Per ~/.claude/principles/review-findings.md. What clears the bar here: -- Established architectural patterns (e.g., "functional core in `src/domain/`, imperative shell in `src/app/`") -- The domain glossary, in the README — code that names a concept differently from it is a defect in one of the two; fix whichever is wrong. -- Rejected alternatives, and requirement trades offered and declined, so they are not re-offered -- Recurring complexity hotspots that need future restructuring -- **Deliberate deviations from the architectural defaults, with the reason** — the "stated reasons" your Reasonability Review honours; an undocumented deviation is indistinguishable from an accident. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 5e60d796..8e1ebb7b 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -43,7 +43,7 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod Launch systems-architect: review the system as a whole entered through this change; the decision log carries previously accepted decisions to honor, the README the goals and Stage 0 artifacts. -- **Stage 0 questions returned** (goals/audience/horizon unrecorded): relay them to the user, record the answers where the agent expects them (README), re-run once. No user → skip the pass, carry the questions into the summary. +- **Stage 0 questions returned** (goals/audience/horizon unrecorded): relay them to the user, record the answers in the README, re-run once. No user → skip the pass, carry the questions into the summary. - **BLOCK** → confirm with the user first when the restructure materially reshapes their PR. Then the comprehension floor: the `comprehension-panel` skill's scoring run (`~/.claude/skills/comprehension-panel/SKILL.md` → "The scoring run") over the whole project, not the diff. With any dimension or the overall below 7.0 the chunk does not merge: fix the places the seats name under the capping dimension, or take the user's explicit decision to ship under the floor, record it in `docs/decisions.md` with the scores, and file the places in `todo.md`. At the floor or above, the scores are still a ratchet — a later chunk may not lower any — and the four dimension scores and the overall go in the summary so the next run can see the direction of travel. diff --git a/todo.md b/todo.md index 1567b404..5ff901b2 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,6 @@ The rebuild lifts every dimension: each item below is one chunk on a worktree based on `origin/rebuild`, its PR into `rebuild`, until the last item merges `rebuild` into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -- **Make the three reviewer agents pure reporters in the findings document's vocabulary.** Keep their names and checklists; remove every README- and decision-writing duty and every private severity or verdict scale. - **Bring `CLAUDE.md` → "Vocabulary", the README and `docs/decisions.md` in line with the rebuild.** Round cap counts per chunk, "looping reviewer" goes if the rule no longer needs it; superseded decisions leave the log. - **Score `rebuild` with the four-seat panel at 7.0 or above on every dimension and the overall, none below the 2026-09-28 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. A loop running main's script reloads into the new one and carries on (`docs/decisions.md`). -- 2.52.0 From b55e59dceb4c110140e594d7449cbaead501f7d0 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 19:59:17 +0200 Subject: [PATCH 044/233] Keep severity in the findings document's words --- agents/product-owner-reviewer.md | 6 +++--- agents/stability-reviewer.md | 13 +++++-------- agents/systems-architect.md | 10 +++++----- 3 files changed, 13 insertions(+), 16 deletions(-) diff --git a/agents/product-owner-reviewer.md b/agents/product-owner-reviewer.md index 5d150810..c253e899 100644 --- a/agents/product-owner-reviewer.md +++ b/agents/product-owner-reviewer.md @@ -18,11 +18,11 @@ You consider internal logic **only** when it directly affects an external surfac ## Your Review Method -Before anything else, **read the shared principles** at `~/.claude/principles/`. Two of them are your territory: `rest-apis.md` (URL/query conventions, error envelope, pagination, versioning, OpenAPI requirement) and `frontend.md` (intuitive-over-fancy, broad device support, progressive enhancement, semantic HTML, responsive design). `technical-principles.md` applies where it surfaces externally (timestamps communicated as UTC, idempotent writes). Re-read each time — they change. A violation is a finding. +Before anything else, **read the shared principles** at `~/.claude/principles/`. Two of them are your territory: `rest-apis.md` (URL/query conventions, error envelope, pagination, versioning, OpenAPI requirement) and `frontend.md` (intuitive-over-fancy, broad device support, progressive enhancement, semantic HTML, responsive design). `technical-principles.md` applies where it surfaces externally (timestamps communicated as UTC, idempotent writes). Re-read each time — they change. 1. **Identify the change surface**: Read the recent changes and pinpoint what external behavior is affected. If the change is purely internal with no external impact, say so plainly and stop — don't manufacture concerns. -2. **Identify the personas**: Who uses this? Check the README and any docs for documented personas, and `docs/decisions.md` for accepted product trade-offs to honor rather than re-raise. If personas are missing or unclear for the affected surface, review against your best-guess personas (e.g., "end customer", "tenant admin", "integrator/developer", "internal support", "CLI power user"), labelled as assumptions, and raise the persona question as a ❓. +2. **Identify the personas**: Who uses this? Check the README and any docs for documented personas. If personas are missing or unclear for the affected surface, review against your best-guess personas (e.g., "end customer", "tenant admin", "integrator/developer", "internal support", "CLI power user"), labelled as assumptions, and raise the persona question as a ❓. 3. **Walk the happy path** for each persona. Is it obvious? Discoverable? Does the naming match mental models? Is the minimum required input actually minimum? @@ -53,7 +53,7 @@ Verdict, severities, rounds and declines: ~/.claude/principles/review-findings.m **Strengths**: -**Findings** (ordered by customer impact, highest first): for each, the problem from the customer's POV, the persona affected, and a concrete suggestion. +**Findings**, most severe first and by customer impact within a severity: for each, the problem from the customer's POV, the persona affected, and a concrete suggestion. ## Operating Principles diff --git a/agents/stability-reviewer.md b/agents/stability-reviewer.md index 13302f03..61b0791b 100644 --- a/agents/stability-reviewer.md +++ b/agents/stability-reviewer.md @@ -40,7 +40,7 @@ Before judging how well code works, judge whether it should exist. Every line is - New dependencies: would ~20 lines of own code do? Each one is permanent upgrade, audit, and supply-chain surface; check its maintenance state before accepting it. - Dead on arrival: unreferenced code, exports, params, or flags; feature flags with no removal plan. - Does the PR delete what it obsoletes (old path, old flag, old docs), or only add on top? -- Growth whose whole fix is deletion — unasked additions, dead code, speculative abstraction, an unjustified dependency — breaks KISS: a 🔴. A "could be smaller" rewrite is a 🟡. A 🔴 that adds code needs a concrete failure scenario: removals converge, forced additions ratchet a codebase upward forever. +- Growth whose whole fix is deletion — unasked additions, dead code, speculative abstraction, an unjustified dependency — breaks KISS: a 🔴. A "could be smaller" rewrite is a 🟡. ### 3. Ambiguity & Implicit State Catch behavior that is unclear or under-specified — "building in ambiguousness." Cross-check the principles: make invalid states unrepresentable, validate/build DTOs early, explicit state machines, explicit over implicit. @@ -95,7 +95,7 @@ Works-on-fixtures, dies-on-volume is a stability bug. - Algorithmic blowups (O(n²) and worse) on input whose size the user controls. ### 9. Security -Every PR gets at least this sweep; for sensitive surfaces also escalate to the dedicated pass. +Every PR gets at least this sweep. - Injection: SQL via raw/concatenated queries, shell/command, XSS via unescaped output. - Does every new read and write path authorize access? (principle: grant explicit access to data — every read and write is explicitly authorized.) - Secrets: none hardcoded; none leaked into logs, error responses, or stack traces; PII sanitized before logging. @@ -112,7 +112,7 @@ Every PR gets at least this sweep; for sensitive surfaces also escalate to the d - **Judge every comment and prose line the diff adds against `~/.claude/CLAUDE.md` → "Comments and documentation"**; report a density breach with the ratio and the files driving it. - **Flag a caveat the diff has outlived**, anywhere in the repo: report the sentence's `file:line` and the behaviour that replaced it. - **Flag a pointer standing where a definition belongs** — `~/.claude/CLAUDE.md` → "Comments and documentation", "A pointer is not a definition". -- **Never propose new documentation as a "nice to have".** Suggesting a doc paragraph is proposing bulk someone must maintain. Raise it as a Stability Warning only when its absence would actively mislead someone, and say which mistake it prevents; otherwise don't raise it at all. Deleting redundant prose is always the cheaper fix. +- **Never propose new documentation as a "nice to have".** Suggesting a doc paragraph is proposing bulk someone must maintain. Raise it as a 🟡 only when its absence would actively mislead someone, and say which mistake it prevents; otherwise don't raise it at all. Deleting redundant prose is always the cheaper fix. - **Never let documentation stand in for a fix.** A finding is not closed by describing the defect in a README, and neither is one of yours: if the only available remedy is telling the reader, say so and mark it a decision for the human, so it lands in the PR or ticket where a decision record belongs. Naming a residual risk is your job; choosing to publish it in the repo is not yours to hand out. ### 11. Tests @@ -134,10 +134,7 @@ Verdict, severities, rounds and declines: ~/.claude/principles/review-findings.m - **Risk**: What could go wrong in production - **Fix**: The smallest change that closes the issue — prefer delete > simplify > modify > add; code examples when helpful -Then **📋 Technical Principles Compliance**: every violation of the shared principles in `~/.claude/principles/`. - -### 🔀 Escalations -When the diff crosses another reviewer's territory: +Raise a 🔀 for: - **product-owner-reviewer** — the diff changes an external surface: REST API contract (routes, request/response shapes, status codes, OpenAPI spec), web UI flow, CLI, webhook, or customer-facing docs. - **systems-architect** — the diff adds or restructures a component/subsystem, moves component boundaries, changes the shape of the external contract, introduces a new architectural pattern, or reopens a foundational choice (language, framework, remote/distribution boundary). - **/security-review** — the diff touches auth/session handling, crypto, payment flows, file upload/handling, or adds a substantial new input surface; a dedicated pass beyond the per-PR sweep in #9. @@ -146,7 +143,7 @@ When the diff crosses another reviewer's territory: - Exhaustive in the search, prioritized in the report: find everything real, rank by severity, never manufacture findings — and if the code is solid, say so. - Deletion is a fix — often the best one. Before proposing hardening, ask whether the code should exist at all; never demand more code than the risk warrants. -- **Scope to this change.** Focus on what the PR introduces or worsens. Surface a serious pre-existing issue in the blast radius as *context*, not as a 🔴 — don't flag long-standing issues as if this PR caused them. As a reviewer that runs on every PR, your credibility depends on low noise. +- **Scope to this change.** Focus on what the PR introduces or worsens. A serious pre-existing issue in the blast radius is a 🟡, marked pre-existing — don't flag long-standing issues as if this PR caused them. As a reviewer that runs on every PR, your credibility depends on low noise. - **Try to refute your own findings.** Before reporting a 🔴 or 🟡, actively attempt to disprove it — trace the actual code path, check callers and upstream handling (e.g. that an exception really is swallowed and not handled upstream), run it when cheap. Report what survives; plausible-but-wrong findings erode trust. - Be specific — vague feedback like "this could be better" is not acceptable. Always explain WHY something is a problem and WHAT the concrete risk is. - Don't nitpick formatting or style unless it impacts readability to the point of bug risk. diff --git a/agents/systems-architect.md b/agents/systems-architect.md index 5e9c44fb..3cbc5211 100644 --- a/agents/systems-architect.md +++ b/agents/systems-architect.md @@ -1,6 +1,6 @@ --- name: systems-architect -description: "Use this agent when designing new systems, planning major features, reviewing architectural decisions in PRs, or evaluating the high-level structure of a codebase. It runs as a periodic, deliberate alignment review — not a per-PR reviewer; the stability-reviewer is the per-PR, code-level companion. This agent focuses on architectural patterns (functional core/imperative shell), the external contract with consumers, component boundaries, internal API design, testability seams and verification strategy (never individual tests), delivery strategy (merge gate with tests and static analysis, deployment path, dependency automation — as architecture, never pipeline configs or lint rules), naming, file system organization, the simplicity and reasonability of the core (questioning unjustified duplication and accidental complexity, demanding a stated reason for every repeated or complex structure), quantitative fits-in-your-head guardrails (per Code That Fits in Your Head), simpler near-equivalent solutions (trading a small, named behavior delta for a large complexity reduction), and long-term maintainability rather than implementation details. It also evaluates fitness for purpose — whether the chosen language, frameworks, and overall solution approach are the best fit for the project's goals and priorities — and treats missing, vague, or contradictory goals, priorities, audience, problem statement, scale and horizon, or domain vocabulary as the first thing to fix. It should be used proactively when starting new projects or significant new subsystems, and when reviewing PRs that introduce new architectural patterns or restructure existing ones.\\n\\n\\nContext: The user is starting a new project and needs architectural guidance before writing code.\\nuser: \"I'm building a service that ingests events from multiple sources, deduplicates them, and forwards them to downstream systems.\"\\nassistant: \"Before we start implementing, let me use the Agent tool to launch the systems-architect agent to design the high-level architecture and data flows.\"\\n\\nA new project is being started — use the systems-architect agent to deliberately design the architecture before any code is written.\\n\\n\\n\\n\\nContext: A PR has been opened that introduces a new module or restructures existing components.\\nuser: \"Here's the PR for the new payment processing subsystem: #4521\"\\nassistant: \"I'll use the Agent tool to launch the systems-architect agent to review the high-level architecture and component boundaries in this PR.\"\\n\\nA PR introduces a new subsystem — the systems-architect agent should review architectural choices, not line-level details.\\n\\n\\n\\n\\nContext: The user is adding a significant new feature that crosses multiple components.\\nuser: \"We need to add real-time notifications across the web app, mobile app, and email.\"\\nassistant: \"This crosses several system boundaries. Let me use the Agent tool to launch the systems-architect agent to design how this should fit into the existing architecture.\"\\n\\nA feature crossing multiple components needs deliberate architectural design — use the systems-architect agent proactively.\\n\\n\\n\\n\\nContext: The user asks for an architecture review but the project has no clearly stated goals or priorities.\\nuser: \"Can you review the architecture of our new sync service?\"\\nassistant: \"I'll use the Agent tool to launch the systems-architect agent. Because fitness-for-purpose depends on goals, it will first pin down the project's goals and priorities, then judge whether the language, frameworks, and approach actually serve them.\"\\n\\nJudging whether an implementation is the best one requires explicit goals and priorities — the systems-architect agent establishes or repairs those before evaluating fitness.\\n\\n" +description: "Use this agent when designing new systems, planning major features, reviewing architectural decisions in PRs, or evaluating the high-level structure of a codebase. It runs as a periodic, deliberate alignment review — not a per-PR reviewer; the stability-reviewer is the per-PR, code-level companion. This agent focuses on architectural patterns (functional core/imperative shell), the external contract with consumers, component boundaries, internal API design, testability seams and verification strategy (never individual tests), delivery strategy (merge gate with tests and static analysis, deployment path, dependency automation — as architecture, never pipeline configs or lint rules), naming, file system organization, the simplicity and reasonability of the core (questioning unjustified duplication and accidental complexity, demanding a stated reason for every repeated or complex structure), quantitative fits-in-your-head guardrails (per Code That Fits in Your Head), simpler near-equivalent solutions (trading a small, named behavior delta for a large complexity reduction), and long-term maintainability rather than implementation details. It also evaluates fitness for purpose — whether the chosen language, frameworks, and overall solution approach are the best fit for the project's goals and priorities — and treats missing, vague, or contradictory goals, priorities, audience, problem statement, scale and horizon, or domain vocabulary as the first thing to fix. It should be used proactively when starting new projects or significant new subsystems, and when reviewing PRs that introduce new architectural patterns or restructure existing ones.\\n\\n\\nContext: The user is starting a new project and needs architectural guidance before writing code.\\nuser: \"I'm building a service that ingests events from multiple sources, deduplicates them, and forwards them to downstream systems.\"\\nassistant: \"Before we start implementing, let me use the Agent tool to launch the systems-architect agent to design the high-level architecture and data flows.\"\\n\\nA new project is being started — use the systems-architect agent to deliberately design the architecture before any code is written.\\n\\n\\n\\n\\nContext: A PR has been opened that introduces a new module or restructures existing components.\\nuser: \"Here's the PR for the new payment processing subsystem: #4521\"\\nassistant: \"I'll use the Agent tool to launch the systems-architect agent to review the high-level architecture and component boundaries in this PR.\"\\n\\nA PR introduces a new subsystem — the systems-architect agent should review architectural choices, not line-level details.\\n\\n\\n\\n\\nContext: The user is adding a significant new feature that crosses multiple components.\\nuser: \"We need to add real-time notifications across the web app, mobile app, and email.\"\\nassistant: \"This crosses several system boundaries. Let me use the Agent tool to launch the systems-architect agent to design how this should fit into the existing architecture.\"\\n\\nA feature crossing multiple components needs deliberate architectural design — use the systems-architect agent proactively.\\n\\n\\n\\n\\nContext: The user asks for an architecture review but the project has no clearly stated goals or priorities.\\nuser: \"Can you review the architecture of our new sync service?\"\\nassistant: \"I'll use the Agent tool to launch the systems-architect agent. Because fitness-for-purpose depends on goals, it will first pin down the project's goals and priorities, then judge whether the language, frameworks, and approach actually serve them.\"\\n\\nJudging whether an implementation is the best one requires explicit goals and priorities — the systems-architect agent drafts the missing goals and priorities and asks the user to confirm them before evaluating fitness.\\n\\n" --- You are an elite Systems Architect with decades of experience designing software systems that endure for as long as their horizon demands. Your philosophy is uncompromising on fundamentals: clarity, simplicity, and deliberate structural choices trump short-term convenience every time. You design systems people will read, understand, and extend for their whole recorded lifetime. @@ -33,7 +33,7 @@ You are an elite Systems Architect with decades of experience designing software Short-term pragmatism on these points compounds into long-term decay. Push back firmly when asked to compromise on them. Pragmatism is welcome on implementation details, not on structural choices. A change that violates one of these fundamentals is a 🔴, never softened to "the one change I'd make before merge", "acceptable for now", or "worth doing later". -**Rigor follows the horizon; fundamentals do not.** Two dials. Clarity, glossary naming, one implementation per concept, single responsibility, fits in a head, core/shell separation, nondeterminism through injected seams — these pay for themselves within days, so demand them at every scale, spike included: simple and clear is also the fastest way to build. What scales with the recorded horizon and blast radius is ceremony and severity: the depth of Stage 1's description, the contract's versioning machinery, the breadth of test machinery (e2e fleets, load rigs, post-deploy suites — see Testability), documentation detail, how hard a non-fundamental finding blocks. A short horizon lowers severity, never converts a defect into a non-defect — and it raises, never lowers, the bar for added complexity. +**Rigor follows the horizon; fundamentals do not.** Two dials. Clarity, glossary naming, one implementation per concept, single responsibility, fits in a head, core/shell separation, nondeterminism through injected seams — these pay for themselves within days, so demand them at every scale, spike included: simple and clear is also the fastest way to build. What scales with the recorded horizon and blast radius is ceremony and severity: the depth of Stage 1's description, the contract's versioning machinery, the breadth of test machinery (e2e fleets, load rigs, post-deploy suites — see Testability), documentation detail, the severity of a non-fundamental finding. A short horizon lowers severity, never converts a defect into a non-defect — and it raises, never lowers, the bar for added complexity. **You design for the recorded horizon, not just today's problem.** The current ticket is a forcing function, not the scope of your thinking — the Stage 0 horizon is. A recorded long-lived platform makes decade-thinking a duty; a recorded short-lived experiment makes decade-proofing a defect — speculative generality, not diligence. No recorded horizon: ask, never assume. Distrust "temporary" — prototypes that gain users become permanent, which is why the horizon carries a promotion event. Long-lived systems survive by staying cheap to change, not by carrying structure for guessed requirements. @@ -60,7 +60,7 @@ You cannot judge whether an implementation is the best one without a yardstick. - **Test** them: Is the audience concrete? Does the problem statement name the pain, not the solution? Are the goals explicit, measurable, prioritized so you know which wins when two collide, and mutually consistent? Is the horizon stated — spike or platform? Nothing is fit for a purpose whose size and lifespan are unknown. Does the glossary give each concept exactly one name? - **Fix first if broken.** Unless the purpose and goals are abundantly clear, surfacing the gap IS this run's deliverable: you execute one-shot and cannot pause for answers, so return a short draft of the missing artifacts plus the questions the user must answer, and stop there — design or review continues in a later invocation, once the agreed result is recorded. A missing audience, problem statement, scale & horizon, or glossary is the same fix-first gap. Never design against guessed goals, a guessed audience, or invented vocabulary — surface the ambiguity instead. -Output: agreed audience, problem statement, ordered goals, scale & horizon, and domain glossary. Only once these are solid do you proceed to Stage 1. The requirement never scales down; the artifacts do — a weekend spike answers all five at spike depth: five lines in a README, not five documents. Refuse to proceed without answers; never demand more depth than the recorded horizon justifies. +Output: agreed audience, problem statement, ordered goals, scale & horizon, and domain glossary, recorded in the README. Only once these are solid do you proceed to Stage 1. The requirement never scales down; the artifacts do — a weekend spike answers all five at spike depth: five lines in a README, not five documents. Refuse to proceed without answers; never demand more depth than the recorded horizon justifies. ### Stage 1: Describe Produce an architectural description covering: @@ -149,9 +149,9 @@ How a change ships — merge gate, pipeline, deployment, dependencies — is a d ## Reviewing Existing Work (periodic alignment) -You are not a per-PR reviewer. The **stability-reviewer** runs on every change for code-level safety; you run deliberately, every so often, to check the system is still aligned — right goals, right contract, right foundations, sound structure. When you do look at a specific PR, it is because the work touches architectural fundamentals or reopens foundational choices, not for routine line-level review. Stage 0 blocks review as much as design: if the project's purpose and goals are not abundantly clear from its docs, this run's output is the clarifying questions plus a short draft to confirm — not a review; the review happens in a later invocation, once the answers are recorded (README or the relevant alternative). +You are not a per-PR reviewer. The **stability-reviewer** runs on every change for code-level safety; you run deliberately, every so often, to check the system is still aligned — right goals, right contract, right foundations, sound structure. When you do look at a specific PR, it is because the work touches architectural fundamentals or reopens foundational choices, not for routine line-level review. Stage 0 blocks review as much as design: if the project's purpose and goals are not abundantly clear from its docs, this run's output is the clarifying questions plus a short draft to confirm — not a review; the review happens in a later invocation, once the answers are recorded in the README. -**Verdict and severities: ~/.claude/principles/review-findings.md.** A violation of a non-negotiable fundamental — functional-core/shell entanglement, a unit past a Fits in a head threshold without a stated reason, a method or file carrying more than one responsibility, unreasoned duplication of a core concept, or a broken/leaky external contract — is a 🔴: lead with it, and name the concrete restructuring. The most common instance: a pure transformation (a deterministic input→output computation) entangled inside an imperative-shell or orchestration method, where it could be a named, separately-testable function — flag the extraction as a blocker. The architectural defect being real, not its line count or "how much it works today," sets the severity; rate a non-fundamental finding by its eventual cost, not today's size — the recorded horizon sets that cost; fundamentals stay blocking at every horizon (Core Philosophy: rigor follows the horizon). Reserve advisory framing for genuine suggestions, never for a fundamentals violation. +**Verdict and severities: ~/.claude/principles/review-findings.md.** A violation of a non-negotiable fundamental — functional-core/shell entanglement, a unit past a Fits in a head threshold without a stated reason, a method or file carrying more than one responsibility, unreasoned duplication of a core concept, or a broken/leaky external contract — is a 🔴: lead with it, and name the concrete restructuring. The most common instance: a pure transformation (a deterministic input→output computation) entangled inside an imperative-shell or orchestration method, where it could be a named, separately-testable function — the extraction is a 🔴. The architectural defect being real, not its line count or "how much it works today," sets the severity; rate a non-fundamental finding by its eventual cost — the recorded horizon sets that cost; fundamentals stay 🔴 at every horizon (Core Philosophy: rigor follows the horizon). Focus on architectural alignment: - Does it still serve the project's goals and priorities, or has it quietly drifted from them? -- 2.52.0 From 73bfa9d22fccfa4cf896326986d53f5f76b49ca3 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 19:59:59 +0200 Subject: [PATCH 045/233] Drop two restatements from the reviewer agents --- agents/stability-reviewer.md | 2 +- agents/systems-architect.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/agents/stability-reviewer.md b/agents/stability-reviewer.md index 61b0791b..05580c94 100644 --- a/agents/stability-reviewer.md +++ b/agents/stability-reviewer.md @@ -143,7 +143,7 @@ Raise a 🔀 for: - Exhaustive in the search, prioritized in the report: find everything real, rank by severity, never manufacture findings — and if the code is solid, say so. - Deletion is a fix — often the best one. Before proposing hardening, ask whether the code should exist at all; never demand more code than the risk warrants. -- **Scope to this change.** Focus on what the PR introduces or worsens. A serious pre-existing issue in the blast radius is a 🟡, marked pre-existing — don't flag long-standing issues as if this PR caused them. As a reviewer that runs on every PR, your credibility depends on low noise. +- **Scope to this change.** Focus on what the PR introduces or worsens. A serious pre-existing issue in the blast radius is a 🟡, marked pre-existing. As a reviewer that runs on every PR, your credibility depends on low noise. - **Try to refute your own findings.** Before reporting a 🔴 or 🟡, actively attempt to disprove it — trace the actual code path, check callers and upstream handling (e.g. that an exception really is swallowed and not handled upstream), run it when cheap. Report what survives; plausible-but-wrong findings erode trust. - Be specific — vague feedback like "this could be better" is not acceptable. Always explain WHY something is a problem and WHAT the concrete risk is. - Don't nitpick formatting or style unless it impacts readability to the point of bug risk. diff --git a/agents/systems-architect.md b/agents/systems-architect.md index 3cbc5211..a320aa14 100644 --- a/agents/systems-architect.md +++ b/agents/systems-architect.md @@ -151,7 +151,7 @@ How a change ships — merge gate, pipeline, deployment, dependencies — is a d You are not a per-PR reviewer. The **stability-reviewer** runs on every change for code-level safety; you run deliberately, every so often, to check the system is still aligned — right goals, right contract, right foundations, sound structure. When you do look at a specific PR, it is because the work touches architectural fundamentals or reopens foundational choices, not for routine line-level review. Stage 0 blocks review as much as design: if the project's purpose and goals are not abundantly clear from its docs, this run's output is the clarifying questions plus a short draft to confirm — not a review; the review happens in a later invocation, once the answers are recorded in the README. -**Verdict and severities: ~/.claude/principles/review-findings.md.** A violation of a non-negotiable fundamental — functional-core/shell entanglement, a unit past a Fits in a head threshold without a stated reason, a method or file carrying more than one responsibility, unreasoned duplication of a core concept, or a broken/leaky external contract — is a 🔴: lead with it, and name the concrete restructuring. The most common instance: a pure transformation (a deterministic input→output computation) entangled inside an imperative-shell or orchestration method, where it could be a named, separately-testable function — the extraction is a 🔴. The architectural defect being real, not its line count or "how much it works today," sets the severity; rate a non-fundamental finding by its eventual cost — the recorded horizon sets that cost; fundamentals stay 🔴 at every horizon (Core Philosophy: rigor follows the horizon). +**Verdict and severities: ~/.claude/principles/review-findings.md.** A violation of a non-negotiable fundamental — functional-core/shell entanglement, a unit past a Fits in a head threshold without a stated reason, a method or file carrying more than one responsibility, unreasoned duplication of a core concept, or a broken/leaky external contract — is a 🔴: lead with it, and name the concrete restructuring. The most common instance: a pure transformation (a deterministic input→output computation) entangled inside an imperative-shell or orchestration method, where it could be a named, separately-testable function. The architectural defect being real, not its line count or "how much it works today," sets the severity; rate a non-fundamental finding by its eventual cost — the recorded horizon sets that cost; fundamentals stay 🔴 at every horizon (Core Philosophy: rigor follows the horizon). Focus on architectural alignment: - Does it still serve the project's goals and priorities, or has it quietly drifted from them? -- 2.52.0 From a825cac55787987cd277c2d67227bc94ad7b86db Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 20:00:08 +0200 Subject: [PATCH 046/233] Leave severity and the README record to their owners --- agents/stability-reviewer.md | 2 +- agents/systems-architect.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/agents/stability-reviewer.md b/agents/stability-reviewer.md index 05580c94..93f9b74a 100644 --- a/agents/stability-reviewer.md +++ b/agents/stability-reviewer.md @@ -143,7 +143,7 @@ Raise a 🔀 for: - Exhaustive in the search, prioritized in the report: find everything real, rank by severity, never manufacture findings — and if the code is solid, say so. - Deletion is a fix — often the best one. Before proposing hardening, ask whether the code should exist at all; never demand more code than the risk warrants. -- **Scope to this change.** Focus on what the PR introduces or worsens. A serious pre-existing issue in the blast radius is a 🟡, marked pre-existing. As a reviewer that runs on every PR, your credibility depends on low noise. +- **Scope to this change.** Focus on what the PR introduces or worsens. Mark a serious pre-existing issue in the blast radius as pre-existing. As a reviewer that runs on every PR, your credibility depends on low noise. - **Try to refute your own findings.** Before reporting a 🔴 or 🟡, actively attempt to disprove it — trace the actual code path, check callers and upstream handling (e.g. that an exception really is swallowed and not handled upstream), run it when cheap. Report what survives; plausible-but-wrong findings erode trust. - Be specific — vague feedback like "this could be better" is not acceptable. Always explain WHY something is a problem and WHAT the concrete risk is. - Don't nitpick formatting or style unless it impacts readability to the point of bug risk. diff --git a/agents/systems-architect.md b/agents/systems-architect.md index a320aa14..5266bb77 100644 --- a/agents/systems-architect.md +++ b/agents/systems-architect.md @@ -60,7 +60,7 @@ You cannot judge whether an implementation is the best one without a yardstick. - **Test** them: Is the audience concrete? Does the problem statement name the pain, not the solution? Are the goals explicit, measurable, prioritized so you know which wins when two collide, and mutually consistent? Is the horizon stated — spike or platform? Nothing is fit for a purpose whose size and lifespan are unknown. Does the glossary give each concept exactly one name? - **Fix first if broken.** Unless the purpose and goals are abundantly clear, surfacing the gap IS this run's deliverable: you execute one-shot and cannot pause for answers, so return a short draft of the missing artifacts plus the questions the user must answer, and stop there — design or review continues in a later invocation, once the agreed result is recorded. A missing audience, problem statement, scale & horizon, or glossary is the same fix-first gap. Never design against guessed goals, a guessed audience, or invented vocabulary — surface the ambiguity instead. -Output: agreed audience, problem statement, ordered goals, scale & horizon, and domain glossary, recorded in the README. Only once these are solid do you proceed to Stage 1. The requirement never scales down; the artifacts do — a weekend spike answers all five at spike depth: five lines in a README, not five documents. Refuse to proceed without answers; never demand more depth than the recorded horizon justifies. +Output: agreed audience, problem statement, ordered goals, scale & horizon, and domain glossary. Only once these are recorded in the README do you proceed to Stage 1. The requirement never scales down; the artifacts do — a weekend spike answers all five at spike depth: five lines in a README, not five documents. Refuse to proceed without answers; never demand more depth than the recorded horizon justifies. ### Stage 1: Describe Produce an architectural description covering: -- 2.52.0 From 37edc9a8fe56bf75a9aa4993ab6c14549161c70f Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 20:03:52 +0200 Subject: [PATCH 047/233] Drop the looping-reviewer word and the superseded round-cap decision --- AGENTS.md | 1 - CLAUDE.md | 1 - docs/decisions.md | 4 ---- todo.md | 1 - 4 files changed, 7 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e6eb6094..b7873096 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,7 +13,6 @@ Decisions live in `docs/decisions.md`: - bin/: host python, no container - comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it - vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link -- larv-review: a re-entered loop takes a fresh round cap - loop-claude: a reload into an older file is unsupported - loop-claude: a CR-only README.md is reported at line 1 - loop-claude: each project's model lives in loop-claude's own file diff --git a/CLAUDE.md b/CLAUDE.md index ef02407b..59f2a4a6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -9,7 +9,6 @@ Shorter is better, none is best — chat output, commit messages, comments, docs - **gate** — the merge gate: the checks a PR passes before it merges. - **interrupt** — `loop-claude` handing the terminal to the human, `claude --resume`, for a decision that is theirs. - **judge** — the headless claude that reads a worker's transcript each cycle and decides whether to interrupt and whether the chunk is finished. -- **looping reviewer** — a reviewer rerun in rounds: stability, product-owner and a forge's auto-reviewer. - **plan** — `todo.md`. - **premises** — the goals and audience under `## Goals` and `## Audience` in the project's `README.md`. - **release** — a semver version the human cuts. diff --git a/docs/decisions.md b/docs/decisions.md index 0f646fe9..518e2511 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -36,10 +36,6 @@ 2026-09-24, larv-review. Serves goal 4. Three seats of the 2026-09-24 panel found the words only in the changelog; a definition at each rule lands one reader and misses the next, so the section is the one landing place and each file using the words links it once, and `bin/test_citations.py` fails on a citation no heading or bold lead answers, so the pointer's rot is visible. `loop-claude --help` restates chunk, cycle, interrupt and premises, since a terminal reader has no link to follow. Valid until the next scoring run. -## larv-review: a re-entered loop takes a fresh round cap - -2026-09-24, larv-review. Serves goal 4. The cap stops a loop that does not converge on one set of findings; a re-entry is a new set. A cap shared across the whole flow would skip §6.5's closing round exactly when §5 ran long. Valid until the rebuild merges; superseded then by "review: the round cap counts a pass's runs per chunk". - ## loop-claude: a reload into an older file is unsupported 2026-09-26, lilleman. Serves goal 4. A running loop whose `bin/loop-claude` or `bin/loop_claude/` on disk is rolled back to a version with an older handover fails in that older file, or, older than the handover itself, runs `--reloaded ` as its task; this version cannot change either; the human who rolled it back reruns `loop-claude `. Valid while nobody but the developer runs it: other team members running it while it is still developed reopens this. diff --git a/todo.md b/todo.md index 5ff901b2..5d136a49 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,6 @@ The rebuild lifts every dimension: each item below is one chunk on a worktree based on `origin/rebuild`, its PR into `rebuild`, until the last item merges `rebuild` into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -- **Bring `CLAUDE.md` → "Vocabulary", the README and `docs/decisions.md` in line with the rebuild.** Round cap counts per chunk, "looping reviewer" goes if the rule no longer needs it; superseded decisions leave the log. - **Score `rebuild` with the four-seat panel at 7.0 or above on every dimension and the overall, none below the 2026-09-28 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. A loop running main's script reloads into the new one and carries on (`docs/decisions.md`). ## 0.2.0 -- 2.52.0 From b7538bd21d86cbaf3d93d6be244b1724356dfa7a Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 20:11:02 +0200 Subject: [PATCH 048/233] File the places the panel on rebuild named under the floor --- docs/decisions.md | 4 ++-- todo.md | 12 +++++++++++- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index 518e2511..140dcc44 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -30,7 +30,7 @@ ## comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it -2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The rebuild planned in `todo.md` under 0.1.0 answers the places named, and a later chunk may not lower any dimension. Valid until the next scoring run, which uses the same four seats. +2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` at 37edc9a, later that day, scored 7.5, 6.63, 6.88, 6.5, 7.0; the places they named are filed in `todo.md` under 0.1.0, and a later chunk may not lower any dimension. Valid until the next scoring run, which uses the same four seats. ## vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link @@ -70,7 +70,7 @@ ## loop-claude: the rebuild keeps main's `--reloaded` state -2026-09-28, lilleman, for the rebuild. Serves goal 4. A loop running main's script reloads into the rebuilt one at its next cycle boundary and carries on; the state keeps main's four fields, `cycle_number`, `failures`, `root` and `task`, so no code exists only for the cut-over. Valid until the rebuild merges. +2026-09-28, lilleman, for the rebuild. Serves goal 4. A loop running main's script reloads into the rebuilt one at its next cycle boundary and carries on; `decode_state` accepts only JSON whose keys and value types match `LoopState` exactly, so renaming, adding, dropping or retyping a field breaks that reload, and no code exists only for the cut-over. Valid until the rebuild merges. ## rebuild: a chunk into `rebuild` takes no comprehension scoring run diff --git a/todo.md b/todo.md index 5d136a49..8cb45939 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,17 @@ The rebuild lifts every dimension: each item below is one chunk on a worktree based on `origin/rebuild`, its PR into `rebuild`, until the last item merges `rebuild` into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -- **Score `rebuild` with the four-seat panel at 7.0 or above on every dimension and the overall, none below the 2026-09-28 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. A loop running main's script reloads into the new one and carries on (`docs/decisions.md`). +The panel on `rebuild` at 37edc9a scored Self-sufficiency 6.5, Locality 6.63 and Shape 6.88 (`docs/decisions.md`). The places its seats named, capping dimension first: + +- **Gather every Claude Code format loop-claude parses into one adapter, each shown by a sample of what it reads, under one verified version.** All four seats: `transcript.py` `user_entry_kind`, the stream-json result (`worker.py`), the trust key (`trust.py`), `structured_output` (`judge.py`), the model cache (`models.py` `catalog`); today eight comments pin 2.1.282 and `models.py` 2.1.283. +- **State in larv-review's §3 what a pass's run is, and whether a Stage 0 rerun, a panel rerun after a floor fix, an auto-reviewer re-review and a 🔀 escalation each count against the round cap.** Four seats reread the re-entry rule with the table, `principles/review-findings.md` → "Rounds" and the Vocabulary open; round and run name one thing. +- **Point `agents/stability-reviewer.md`'s 🔀 list at larv-review's pass table.** Its security trigger (auth/session, payment, file upload) disagrees with the table's (authn/authz, secrets, crypto, untrusted input). +- **Return the verdict from `run_cycle`'s judge–interrupt loop, so nothing reads `verdict` after it.** Three seats; `archive`'s skip on an existing copy holds only because each interrupt appends a turn, which nothing at `cycle.py` says. +- **Name the minute `strike` sleeps, and the exec `reload_if_edited` may not return from, where each is called.** Four seats and three. +- **Let `render` join a human entry's text without relying on `user_entry_kind` having checked every part.** Three seats. +- **Give failure one spelling: `Failure.reason` and `Retry.failure`, `replace_file`'s raw `OSError`, and `typed`/`said` named for what they test.** Keep `LoopState`'s fields: they are main's `--reloaded` state (`docs/decisions.md`). +- **Group `bin/loop_claude/`'s 17 flat modules, and move `principles/review-findings.md` beside larv-review.** Two seats; the adapter above is the first group. +- **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. A loop running main's script reloads into the new one and carries on (`docs/decisions.md`). ## 0.2.0 -- 2.52.0 From 80629fc6d9d84315f7b87d15f02cb7fa5d1519fe Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 20:17:39 +0200 Subject: [PATCH 049/233] Gather every Claude Code format loop-claude reads into claude_code.py, verified on 2.1.284 --- bin/loop_claude/claude_code.py | 133 +++++++++++++++++++++++++++++++++ bin/loop_claude/judge.py | 7 +- bin/loop_claude/models.py | 18 +---- bin/loop_claude/session.py | 9 +-- bin/loop_claude/transcript.py | 65 +--------------- bin/loop_claude/trust.py | 16 ++-- bin/loop_claude/worker.py | 5 +- bin/test_loop_claude.py | 16 ++-- todo.md | 3 +- 9 files changed, 158 insertions(+), 114 deletions(-) create mode 100644 bin/loop_claude/claude_code.py diff --git a/bin/loop_claude/claude_code.py b/bin/loop_claude/claude_code.py new file mode 100644 index 00000000..129600ce --- /dev/null +++ b/bin/loop_claude/claude_code.py @@ -0,0 +1,133 @@ +"""Every Claude Code format loop-claude reads, each under a sample of it, as Claude Code 2.1.284 writes it.""" +import enum +import glob +import json +import os + +from loop_claude.outcome import Failure + + +class UserEntryKind(enum.Enum): + """Who wrote a "user" entry: the human wrote HUMAN, Claude Code every other kind.""" + + COMMAND = enum.auto() + CTRL_C = enum.auto() + EMPTY = enum.auto() + HUMAN = enum.auto() + META = enum.auto() + NON_TEXT = enum.auto() + SDK_PROMPT = enum.auto() + + +# /-home-me-code-log/.jsonl +def transcript_path(projects, session_id): + hit = glob.glob(os.path.join(glob.escape(str(projects)), "*", f"{session_id}.jsonl")) + return hit[0] if hit else "" + + +# .jsonl, /subagents/, .superseded-1789290815002/ +def session_files(transcript): + return glob.glob(glob.escape(transcript.removesuffix(".jsonl")) + "*") + + +# One line of a transcript or of stream-json, or --output-format json's whole output. +def parse(raw): + try: + entry = json.loads(raw) + except ValueError: + return None + return entry if isinstance(entry, dict) else None + + +# {"type": "user", "message": {"role": "user", "content": "merge it"}} +def content(entry): + message = entry.get("message") + return message.get("content") if isinstance(message, dict) else None + + +# {"type": "assistant", "message": {"content": [{"type": "text", "text": "ok"}]}} +def parts(entry): + found = content(entry) + return found if isinstance(found, list) else [] + + +def user_entry_kind(entry): + # {"type": "user", "isMeta": true, "message": {"content": "Caveat: ..."}} + if entry.get("isMeta"): + return UserEntryKind.META + # {"type": "user", "promptSource": "sdk", "message": {"content": "Continue the task; ..."}} + if entry.get("promptSource") == "sdk": + return UserEntryKind.SDK_PROMPT + # {"type": "user", "message": {"content": "/model\n..."}} + # {"type": "user", "promptSource": "typed", "message": {"content": "merge it"}} + if isinstance(text := content(entry), str): + return UserEntryKind.COMMAND if text.startswith("<") else UserEntryKind.HUMAN + if not parts(entry): + return UserEntryKind.EMPTY + # {"type": "user", "message": {"content": [{"tool_use_id": "toolu_01…", "type": "tool_result", "content": "hi"}]}} + if any(not isinstance(part, dict) or part.get("type") != "text" or not isinstance(part.get("text"), str) for part in parts(entry)): + return UserEntryKind.NON_TEXT + # {"type": "user", "message": {"content": [{"type": "text", "text": "[Request interrupted by user]"}]}} + if any(part["text"].startswith("[Request interrupted") for part in parts(entry)): + return UserEntryKind.CTRL_C + return UserEntryKind.HUMAN + + +def typed(entry): + return entry.get("type") == "user" and user_entry_kind(entry) is UserEntryKind.HUMAN + + +# An "assistant" entry's part, alike in the transcript and in stream-json: +# {"type": "text", "text": "ok"}, {"type": "tool_use", "name": "Bash", "input": {"command": "echo hi"}} +def said(part, limit=400): + kind = part.get("type") if isinstance(part, dict) else None + if kind == "text" and isinstance(part.get("text"), str) and part["text"].strip(): + return part["text"] + if kind == "tool_use": + return f"[tool {part.get('name')}] {json.dumps(part.get('input'))[:limit]}" + return "" + + +# stream-json's last line: {"type": "result", "subtype": "success", ...} +def ends_stream(event): + return event.get("type") == "result" + + +# {"type": "result", "structured_output": {"evidence": "...", ...}, ...} +def structured_output(stdout): + return (parse(stdout) or {}).get("structured_output") + + +# ~/.claude.json: {"projects": {"/home/me/code/log": {"hasTrustDialogAccepted": true, ...}}, ...} +def trust_records(config): + projects = config.setdefault("projects", {}) if isinstance(config, dict) else None + if not isinstance(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") + return projects + + +def mark_trusted(projects, roots): + untrusted = [path for path in roots if not projects.get(path, {}).get("hasTrustDialogAccepted")] + for path in untrusted: + projects.setdefault(path, {})["hasTrustDialogAccepted"] = True + return untrusted + + +# /*.json: {"fetchedAt": 1790618085238, "catalog": {"config": {"models": [{"id": "claude-opus-5-5", "name": "Opus 5.5", ...}]}}} +# The newest file has the highest fetchedAt. +def catalog(folder): + newest = {} + for path in folder.glob("*.json"): + try: + with open(path, encoding="utf-8") as handle: + data = json.load(handle) + except (OSError, ValueError): + continue + if isinstance(data, dict) and isinstance(data.get("fetchedAt"), (int, float)) and data["fetchedAt"] > newest.get("fetchedAt", -1): + newest = data + models = 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 [] diff --git a/bin/loop_claude/judge.py b/bin/loop_claude/judge.py index ef19ca41..b6fcdfe8 100644 --- a/bin/loop_claude/judge.py +++ b/bin/loop_claude/judge.py @@ -2,9 +2,9 @@ import itertools import json import subprocess +from loop_claude.claude_code import structured_output from loop_claude.outcome import Failure from loop_claude.strike import strike -from loop_claude.transcript import parse JUDGE_RULES = ( "Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n" @@ -40,7 +40,7 @@ JUDGE_SCHEMA = { def judge(root, task, premises, transcript, model): # No tools, so the verdict rests on the transcript grounded() checks it against; no persistence, so its runs stay out of the session picker. - # Without --bare, Claude Code 2.1.282's claude -p loads the project's and ~/.claude's CLAUDE.md. + # Without --bare, claude -p loads the project's and ~/.claude's CLAUDE.md. args = [ "-p", "--json-schema", json.dumps(JUDGE_SCHEMA), @@ -72,8 +72,7 @@ def run_judge(root, args, prompt): return Failure(f"could not start claude: {failure.strerror}") if proc.returncode != 0: return Failure(proc.stderr.strip() or f"the judge exited {proc.returncode}") - # Where Claude Code 2.1.282 puts the --json-schema output. - return (parse(proc.stdout) or {}).get("structured_output") + return structured_output(proc.stdout) def judge_prompt(task, premises, transcript): diff --git a/bin/loop_claude/models.py b/bin/loop_claude/models.py index 964b52b2..bb184cfe 100644 --- a/bin/loop_claude/models.py +++ b/bin/loop_claude/models.py @@ -4,6 +4,7 @@ import sys from loop_claude import human from loop_claude.checkout import project_name +from loop_claude.claude_code import catalog from loop_claude.file_writes import replace_json from loop_claude.outcome import Stop @@ -79,20 +80,3 @@ def ask_model(name, saved, folder): if 1 <= int(answer) <= len(offered): return offered[int(answer) - 1][0] print(f"pick 1 to {len(offered)}", file=sys.stderr) - - -# Claude Code 2.1.283's model cache; the newest file has the highest fetchedAt. -def catalog(folder): - newest = {} - for path in folder.glob("*.json"): - try: - with open(path, encoding="utf-8") as handle: - data = json.load(handle) - except (OSError, ValueError): - continue - if isinstance(data, dict) and isinstance(data.get("fetchedAt"), (int, float)) and data["fetchedAt"] > newest.get("fetchedAt", -1): - newest = data - models = 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 [] diff --git a/bin/loop_claude/session.py b/bin/loop_claude/session.py index 1a7c9ee5..3f937aca 100644 --- a/bin/loop_claude/session.py +++ b/bin/loop_claude/session.py @@ -1,5 +1,4 @@ import dataclasses -import glob import os import pathlib import shutil @@ -7,6 +6,7 @@ import sys import uuid from loop_claude.checkout import project_name +from loop_claude.claude_code import session_files, transcript_path NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec") @@ -27,17 +27,14 @@ def session_for(root, paths): def transcript_file(session): - # Where Claude Code 2.1.282 writes a session's transcript. - hit = glob.glob(os.path.join(glob.escape(str(session.projects)), "*", f"{session.id}.jsonl")) - return hit[0] if hit else "" + return transcript_path(session.projects, session.id) def delete_session(session): path = transcript_file(session) if not path: return - # Claude Code 2.1.282 also keeps a / folder and .superseded-*/ and .orphaned-*.jsonl siblings. - for sibling in glob.glob(glob.escape(path.removesuffix(".jsonl")) + "*"): + for sibling in session_files(path): try: shutil.rmtree(sibling) if os.path.isdir(sibling) else os.remove(sibling) except OSError as failure: diff --git a/bin/loop_claude/transcript.py b/bin/loop_claude/transcript.py index e274d720..4155d526 100644 --- a/bin/loop_claude/transcript.py +++ b/bin/loop_claude/transcript.py @@ -1,21 +1,7 @@ -import enum -import json - +from loop_claude.claude_code import content, parse, parts, said, typed from loop_claude.outcome import Failure -class UserEntryKind(enum.Enum): - """Who wrote a "user" entry: the human wrote HUMAN, Claude Code every other kind.""" - - COMMAND = enum.auto() - CTRL_C = enum.auto() - EMPTY = enum.auto() - HUMAN = enum.auto() - META = enum.auto() - NON_TEXT = enum.auto() - SDK_PROMPT = enum.auto() - - def read(path): try: with open(path, "rb") as handle: @@ -24,45 +10,6 @@ def read(path): return Failure(f"could not read the transcript {path}: {failure.strerror}") -def parse(raw): - try: - entry = json.loads(raw) - except ValueError: - return None - return entry if isinstance(entry, dict) else None - - -def content(entry): - message = entry.get("message") - return message.get("content") if isinstance(message, dict) else None - - -def parts(entry): - found = content(entry) - return found if isinstance(found, list) else [] - - -# Claude Code 2.1.282 writes "user" entries of its own, a claude -p prompt among them. -def user_entry_kind(entry): - if entry.get("isMeta"): - return UserEntryKind.META - if entry.get("promptSource") == "sdk": - return UserEntryKind.SDK_PROMPT - if isinstance(text := content(entry), str): - return UserEntryKind.COMMAND if text.startswith("<") else UserEntryKind.HUMAN - if not parts(entry): - return UserEntryKind.EMPTY - if any(not isinstance(part, dict) or part.get("type") != "text" or not isinstance(part.get("text"), str) for part in parts(entry)): - return UserEntryKind.NON_TEXT - if any(part["text"].startswith("[Request interrupted") for part in parts(entry)): - return UserEntryKind.CTRL_C - return UserEntryKind.HUMAN - - -def typed(entry): - return entry.get("type") == "user" and user_entry_kind(entry) is UserEntryKind.HUMAN - - def human_turns(entries): return sum(1 for entry in entries if typed(entry)) @@ -76,13 +23,3 @@ def render(entries): text = content(entry) lines.append("[human] " + (text if isinstance(text, str) else "".join(part["text"] for part in text))) return "\n\n".join(lines) - - -# An "assistant" entry's parts, alike in the transcript and in stream-json on Claude Code 2.1.282. -def said(part, limit=400): - kind = part.get("type") if isinstance(part, dict) else None - if kind == "text" and isinstance(part.get("text"), str) and part["text"].strip(): - return part["text"] - if kind == "tool_use": - return f"[tool {part.get('name')}] {json.dumps(part.get('input'))[:limit]}" - return "" diff --git a/bin/loop_claude/trust.py b/bin/loop_claude/trust.py index 55972d55..14d93e46 100644 --- a/bin/loop_claude/trust.py +++ b/bin/loop_claude/trust.py @@ -1,7 +1,9 @@ import json import sys +from loop_claude.claude_code import mark_trusted, trust_records from loop_claude.file_writes import replace_json +from loop_claude.outcome import Failure def trust(config, roots): @@ -11,19 +13,13 @@ def trust(config, roots): except (OSError, ValueError) as failure: print(f"could not read {config}: {getattr(failure, 'strerror', failure)}", file=sys.stderr) return - projects = data.setdefault("projects", {}) if isinstance(data, dict) else None - if not isinstance(projects, dict): - print(f"could not read {config}: not an object whose \"projects\" is an object", file=sys.stderr) + projects = trust_records(data) + if isinstance(projects, Failure): + print(f"could not read {config}: {projects.reason}", file=sys.stderr) return - if (wrong := next((path for path, record in projects.items() if not isinstance(record, dict)), None)) is not None: - print(f"could not read {config}: projects[{json.dumps(wrong)}] is not an object", file=sys.stderr) - return - # Where Claude Code 2.1.282 keeps a checkout's trust. - untrusted = [path for path in roots if not projects.get(path, {}).get("hasTrustDialogAccepted")] + untrusted = mark_trusted(projects, roots) if not untrusted: return - for path in untrusted: - projects.setdefault(path, {})["hasTrustDialogAccepted"] = True if failure := replace_json(config, data, indent=2): print(f"could not write {config}: {failure.strerror}", file=sys.stderr) return diff --git a/bin/loop_claude/worker.py b/bin/loop_claude/worker.py index 140f91e7..c86988d4 100644 --- a/bin/loop_claude/worker.py +++ b/bin/loop_claude/worker.py @@ -1,7 +1,7 @@ import subprocess from loop_claude.outcome import Failure -from loop_claude.transcript import parse, parts, said +from loop_claude.claude_code import ends_stream, parse, parts, said def run_worker(root, args): @@ -13,8 +13,7 @@ def run_worker(root, args): done = False for raw in proc.stdout: event = parse(raw) or {} - # Claude Code 2.1.282's stream-json ends with a "result" event. - if event.get("type") == "result": + if ends_stream(event): done = True elif event.get("type") == "assistant": for part in parts(event): diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 374d0b30..01f385f8 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -7,7 +7,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -from loop_claude import file_writes, judge, main, premises, transcript +from loop_claude import claude_code, file_writes, judge, main, premises, transcript from loop_claude.outcome import Stop CWD = pathlib.Path("/c") @@ -58,17 +58,17 @@ class HumanTurns(unittest.TestCase): class Said(unittest.TestCase): def test_renders_text_and_tool_calls_and_nothing_else(self): - self.assertEqual(transcript.said({"type": "text", "text": "hi"}), "hi") - self.assertEqual(transcript.said({"type": "text", "text": " \n"}), "") - self.assertEqual(transcript.said({"type": "tool_use", "name": "Bash", "input": {"command": "x" * 500}}, 20), '[tool Bash] {"command": "xxxxxxx') - self.assertEqual(transcript.said("not a part"), "") + self.assertEqual(claude_code.said({"type": "text", "text": "hi"}), "hi") + self.assertEqual(claude_code.said({"type": "text", "text": " \n"}), "") + self.assertEqual(claude_code.said({"type": "tool_use", "name": "Bash", "input": {"command": "x" * 500}}, 20), '[tool Bash] {"command": "xxxxxxx') + self.assertEqual(claude_code.said("not a part"), "") class Parse(unittest.TestCase): def test_yields_only_json_objects(self): - self.assertEqual(transcript.parse('{"type": "user"}'), {"type": "user"}) - self.assertIsNone(transcript.parse("not json")) - self.assertIsNone(transcript.parse("[1, 2]")) + self.assertEqual(claude_code.parse('{"type": "user"}'), {"type": "user"}) + self.assertIsNone(claude_code.parse("not json")) + self.assertIsNone(claude_code.parse("[1, 2]")) class Grounded(unittest.TestCase): diff --git a/todo.md b/todo.md index 8cb45939..0798c4b0 100644 --- a/todo.md +++ b/todo.md @@ -8,14 +8,13 @@ The rebuild lifts every dimension: each item below is one chunk on a worktree ba The panel on `rebuild` at 37edc9a scored Self-sufficiency 6.5, Locality 6.63 and Shape 6.88 (`docs/decisions.md`). The places its seats named, capping dimension first: -- **Gather every Claude Code format loop-claude parses into one adapter, each shown by a sample of what it reads, under one verified version.** All four seats: `transcript.py` `user_entry_kind`, the stream-json result (`worker.py`), the trust key (`trust.py`), `structured_output` (`judge.py`), the model cache (`models.py` `catalog`); today eight comments pin 2.1.282 and `models.py` 2.1.283. - **State in larv-review's §3 what a pass's run is, and whether a Stage 0 rerun, a panel rerun after a floor fix, an auto-reviewer re-review and a 🔀 escalation each count against the round cap.** Four seats reread the re-entry rule with the table, `principles/review-findings.md` → "Rounds" and the Vocabulary open; round and run name one thing. - **Point `agents/stability-reviewer.md`'s 🔀 list at larv-review's pass table.** Its security trigger (auth/session, payment, file upload) disagrees with the table's (authn/authz, secrets, crypto, untrusted input). - **Return the verdict from `run_cycle`'s judge–interrupt loop, so nothing reads `verdict` after it.** Three seats; `archive`'s skip on an existing copy holds only because each interrupt appends a turn, which nothing at `cycle.py` says. - **Name the minute `strike` sleeps, and the exec `reload_if_edited` may not return from, where each is called.** Four seats and three. - **Let `render` join a human entry's text without relying on `user_entry_kind` having checked every part.** Three seats. - **Give failure one spelling: `Failure.reason` and `Retry.failure`, `replace_file`'s raw `OSError`, and `typed`/`said` named for what they test.** Keep `LoopState`'s fields: they are main's `--reloaded` state (`docs/decisions.md`). -- **Group `bin/loop_claude/`'s 17 flat modules, and move `principles/review-findings.md` beside larv-review.** Two seats; the adapter above is the first group. +- **Group `bin/loop_claude/`'s 17 flat modules, and move `principles/review-findings.md` beside larv-review.** Two seats; `claude_code.py` is the first group. - **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. A loop running main's script reloads into the new one and carries on (`docs/decisions.md`). ## 0.2.0 -- 2.52.0 From 938eaf69fc24188979b9774d0d31f50ebaea5bf2 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 20:17:50 +0200 Subject: [PATCH 050/233] Count the adapter among the flat modules --- todo.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/todo.md b/todo.md index 0798c4b0..5c5ed393 100644 --- a/todo.md +++ b/todo.md @@ -14,7 +14,7 @@ The panel on `rebuild` at 37edc9a scored Self-sufficiency 6.5, Locality 6.63 and - **Name the minute `strike` sleeps, and the exec `reload_if_edited` may not return from, where each is called.** Four seats and three. - **Let `render` join a human entry's text without relying on `user_entry_kind` having checked every part.** Three seats. - **Give failure one spelling: `Failure.reason` and `Retry.failure`, `replace_file`'s raw `OSError`, and `typed`/`said` named for what they test.** Keep `LoopState`'s fields: they are main's `--reloaded` state (`docs/decisions.md`). -- **Group `bin/loop_claude/`'s 17 flat modules, and move `principles/review-findings.md` beside larv-review.** Two seats; `claude_code.py` is the first group. +- **Group `bin/loop_claude/`'s 18 flat modules, and move `principles/review-findings.md` beside larv-review.** Two seats; `claude_code.py` is the first group. - **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. A loop running main's script reloads into the new one and carries on (`docs/decisions.md`). ## 0.2.0 -- 2.52.0 From 711d13b71bd6a20fef53b2864c3f8893da95cdee Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 20:21:01 +0200 Subject: [PATCH 051/233] Keep loop-claude's rendering out of the adapter and Claude Code's locations in it --- bin/loop_claude/claude_code.py | 31 ++++++++++++++++++------------- bin/loop_claude/paths.py | 6 +++--- bin/loop_claude/transcript.py | 18 ++++++++++++++---- bin/loop_claude/worker.py | 13 ++++++------- bin/test_loop_claude.py | 8 ++++---- 5 files changed, 45 insertions(+), 31 deletions(-) diff --git a/bin/loop_claude/claude_code.py b/bin/loop_claude/claude_code.py index 129600ce..0cba4f73 100644 --- a/bin/loop_claude/claude_code.py +++ b/bin/loop_claude/claude_code.py @@ -19,13 +19,17 @@ class UserEntryKind(enum.Enum): SDK_PROMPT = enum.auto() +def locations(home): + return {"claude_json": home / ".claude.json", "model_catalog": home / ".claude" / "cache" / "model-catalog", "projects": home / ".claude" / "projects"} + + # /-home-me-code-log/.jsonl def transcript_path(projects, session_id): hit = glob.glob(os.path.join(glob.escape(str(projects)), "*", f"{session_id}.jsonl")) return hit[0] if hit else "" -# .jsonl, /subagents/, .superseded-1789290815002/ +# .jsonl, /subagents/, and from older versions .superseded-1789290815002/ def session_files(transcript): return glob.glob(glob.escape(transcript.removesuffix(".jsonl")) + "*") @@ -39,18 +43,21 @@ def parse(raw): return entry if isinstance(entry, dict) else None -# {"type": "user", "message": {"role": "user", "content": "merge it"}} def content(entry): message = entry.get("message") return message.get("content") if isinstance(message, dict) else None -# {"type": "assistant", "message": {"content": [{"type": "text", "text": "ok"}]}} def parts(entry): 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): + return parts(entry) if entry.get("type") == "assistant" else [] + + def user_entry_kind(entry): # {"type": "user", "isMeta": true, "message": {"content": "Caveat: ..."}} if entry.get("isMeta"): @@ -77,15 +84,14 @@ def typed(entry): return entry.get("type") == "user" and user_entry_kind(entry) is UserEntryKind.HUMAN -# An "assistant" entry's part, alike in the transcript and in stream-json: -# {"type": "text", "text": "ok"}, {"type": "tool_use", "name": "Bash", "input": {"command": "echo hi"}} -def said(part, limit=400): - kind = part.get("type") if isinstance(part, dict) else None - if kind == "text" and isinstance(part.get("text"), str) and part["text"].strip(): - return part["text"] - if kind == "tool_use": - return f"[tool {part.get('name')}] {json.dumps(part.get('input'))[:limit]}" - return "" +# {"type": "text", "text": "ok"} +def part_text(part): + 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): + 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", ...} @@ -116,7 +122,6 @@ def mark_trusted(projects, roots): # /*.json: {"fetchedAt": 1790618085238, "catalog": {"config": {"models": [{"id": "claude-opus-5-5", "name": "Opus 5.5", ...}]}}} -# The newest file has the highest fetchedAt. def catalog(folder): newest = {} for path in folder.glob("*.json"): diff --git a/bin/loop_claude/paths.py b/bin/loop_claude/paths.py index cdf05a48..ee6ef17e 100644 --- a/bin/loop_claude/paths.py +++ b/bin/loop_claude/paths.py @@ -1,6 +1,8 @@ import dataclasses import pathlib +from loop_claude.claude_code import locations + @dataclasses.dataclass(frozen=True) class Paths: @@ -16,9 +18,7 @@ def paths_from(home, env): claude = home / ".claude" return Paths( archive=pathlib.Path(env["LOOP_CLAUDE_TRANSCRIPTS"]).expanduser() if env.get("LOOP_CLAUDE_TRANSCRIPTS") else claude / "loop-claude-transcripts", - claude_json=home / ".claude.json", code=home / "code", - model_catalog=claude / "cache" / "model-catalog", models_file=claude / "loop-claude-models.json", - projects=claude / "projects", + **locations(home), ) diff --git a/bin/loop_claude/transcript.py b/bin/loop_claude/transcript.py index 4155d526..50cb7b99 100644 --- a/bin/loop_claude/transcript.py +++ b/bin/loop_claude/transcript.py @@ -1,4 +1,6 @@ -from loop_claude.claude_code import content, parse, parts, said, typed +import json + +from loop_claude.claude_code import assistant_parts, content, parse, part_text, tool_call, typed from loop_claude.outcome import Failure @@ -17,9 +19,17 @@ def human_turns(entries): def render(entries): lines = [] for entry in entries: - if entry.get("type") == "assistant": - lines += [line for part in parts(entry) if (line := said(part))] - elif typed(entry): + lines += [line for part in assistant_parts(entry) if (line := said(part))] + if typed(entry): text = content(entry) lines.append("[human] " + (text if isinstance(text, str) else "".join(part["text"] for part in text))) return "\n\n".join(lines) + + +def said(part, limit=400): + if (text := part_text(part)) and text.strip(): + return text + if call := tool_call(part): + name, arguments = call + return f"[tool {name}] {json.dumps(arguments)[:limit]}" + return "" diff --git a/bin/loop_claude/worker.py b/bin/loop_claude/worker.py index c86988d4..2688e1b8 100644 --- a/bin/loop_claude/worker.py +++ b/bin/loop_claude/worker.py @@ -1,7 +1,8 @@ import subprocess +from loop_claude.claude_code import assistant_parts, ends_stream, parse from loop_claude.outcome import Failure -from loop_claude.claude_code import ends_stream, parse, parts, said +from loop_claude.transcript import said def run_worker(root, args): @@ -13,12 +14,10 @@ def run_worker(root, args): done = False for raw in proc.stdout: event = parse(raw) or {} - if ends_stream(event): - done = True - elif event.get("type") == "assistant": - for part in parts(event): - if line := said(part, 160): - print(line, flush=True) + done = done or ends_stream(event) + for part in assistant_parts(event): + if line := said(part, 160): + print(line, flush=True) code = proc.wait() if code < 0: return Failure(f"claude killed by signal {-code}") diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 01f385f8..9ed8006f 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -58,10 +58,10 @@ class HumanTurns(unittest.TestCase): class Said(unittest.TestCase): def test_renders_text_and_tool_calls_and_nothing_else(self): - self.assertEqual(claude_code.said({"type": "text", "text": "hi"}), "hi") - self.assertEqual(claude_code.said({"type": "text", "text": " \n"}), "") - self.assertEqual(claude_code.said({"type": "tool_use", "name": "Bash", "input": {"command": "x" * 500}}, 20), '[tool Bash] {"command": "xxxxxxx') - self.assertEqual(claude_code.said("not a part"), "") + self.assertEqual(transcript.said({"type": "text", "text": "hi"}), "hi") + self.assertEqual(transcript.said({"type": "text", "text": " \n"}), "") + self.assertEqual(transcript.said({"type": "tool_use", "name": "Bash", "input": {"command": "x" * 500}}, 20), '[tool Bash] {"command": "xxxxxxx') + self.assertEqual(transcript.said("not a part"), "") class Parse(unittest.TestCase): -- 2.52.0 From 424f83c5c698cc9f640fc3d2cbddeba059c5ca40 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 20:22:36 +0200 Subject: [PATCH 052/233] Return Claude Code's locations positionally --- bin/loop_claude/claude_code.py | 3 ++- bin/loop_claude/paths.py | 5 ++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/bin/loop_claude/claude_code.py b/bin/loop_claude/claude_code.py index 0cba4f73..7c0aaea6 100644 --- a/bin/loop_claude/claude_code.py +++ b/bin/loop_claude/claude_code.py @@ -20,7 +20,8 @@ class UserEntryKind(enum.Enum): def locations(home): - return {"claude_json": home / ".claude.json", "model_catalog": home / ".claude" / "cache" / "model-catalog", "projects": home / ".claude" / "projects"} + """~/.claude.json, the model catalog folder and the projects folder.""" + return home / ".claude.json", home / ".claude" / "cache" / "model-catalog", home / ".claude" / "projects" # /-home-me-code-log/.jsonl diff --git a/bin/loop_claude/paths.py b/bin/loop_claude/paths.py index ee6ef17e..7f42eabe 100644 --- a/bin/loop_claude/paths.py +++ b/bin/loop_claude/paths.py @@ -16,9 +16,12 @@ class Paths: def paths_from(home, env): claude = home / ".claude" + claude_json, model_catalog, projects = locations(home) return Paths( archive=pathlib.Path(env["LOOP_CLAUDE_TRANSCRIPTS"]).expanduser() if env.get("LOOP_CLAUDE_TRANSCRIPTS") else claude / "loop-claude-transcripts", + claude_json=claude_json, code=home / "code", + model_catalog=model_catalog, models_file=claude / "loop-claude-models.json", - **locations(home), + projects=projects, ) -- 2.52.0 From 74c2841b8db7e1f4cd95bbb2503743d260d71fda Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 20:25:56 +0200 Subject: [PATCH 053/233] Count a typed reply starting with < as the human's --- bin/test_loop_claude.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 9ed8006f..ba0d67a6 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -48,12 +48,14 @@ class HumanTurns(unittest.TestCase): human([{"type": "text", "text": "typed as a block"}]), human([{"type": "tool_result", "content": "not typed"}]), human("/model"), + {**human("<3 merge it"), "promptSource": "typed"}, + {**human("done"), "promptSource": "system"}, {**human("peer message"), "isMeta": True}, {**human("the loop's own prompt"), "promptSource": "sdk"}, human([{"type": "text", "text": "[Request interrupted by user]"}]), human([]), assistant({"type": "text", "text": "said"}), - ]), 2) + ]), 3) class Said(unittest.TestCase): -- 2.52.0 From 8e15ff7f3759cf291540f981da039b56124db32e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 20:26:34 +0200 Subject: [PATCH 054/233] Classify a string user entry by promptSource before its leading < --- bin/loop_claude/claude_code.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/bin/loop_claude/claude_code.py b/bin/loop_claude/claude_code.py index 7c0aaea6..7f2e5499 100644 --- a/bin/loop_claude/claude_code.py +++ b/bin/loop_claude/claude_code.py @@ -30,7 +30,7 @@ def transcript_path(projects, session_id): return hit[0] if hit else "" -# .jsonl, /subagents/, and from older versions .superseded-1789290815002/ +# .jsonl, /subagents/, and from older versions .superseded-1789290815002/ and .orphaned-*.jsonl def session_files(transcript): return glob.glob(glob.escape(transcript.removesuffix(".jsonl")) + "*") @@ -67,9 +67,11 @@ def user_entry_kind(entry): if entry.get("promptSource") == "sdk": return UserEntryKind.SDK_PROMPT # {"type": "user", "message": {"content": "/model\n..."}} + # {"type": "user", "promptSource": "system", "message": {"content": "..."}} # {"type": "user", "promptSource": "typed", "message": {"content": "merge it"}} if isinstance(text := content(entry), str): - return UserEntryKind.COMMAND if text.startswith("<") else UserEntryKind.HUMAN + source = entry.get("promptSource") + return UserEntryKind.COMMAND if source == "system" or (source is None and text.startswith("<")) else UserEntryKind.HUMAN if not parts(entry): return UserEntryKind.EMPTY # {"type": "user", "message": {"content": [{"tool_use_id": "toolu_01…", "type": "tool_result", "content": "hi"}]}} -- 2.52.0 From 4adcefdc21e1e7feccc2d2de0005b9dfe06a3515 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 20:28:28 +0200 Subject: [PATCH 055/233] Let only a typed entry's leading < pass as the human's --- bin/loop_claude/claude_code.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/loop_claude/claude_code.py b/bin/loop_claude/claude_code.py index 7f2e5499..9c39080d 100644 --- a/bin/loop_claude/claude_code.py +++ b/bin/loop_claude/claude_code.py @@ -71,7 +71,7 @@ def user_entry_kind(entry): # {"type": "user", "promptSource": "typed", "message": {"content": "merge it"}} if isinstance(text := content(entry), str): source = entry.get("promptSource") - return UserEntryKind.COMMAND if source == "system" or (source is None and text.startswith("<")) else UserEntryKind.HUMAN + return UserEntryKind.COMMAND if source == "system" or (source != "typed" and text.startswith("<")) else UserEntryKind.HUMAN if not parts(entry): return UserEntryKind.EMPTY # {"type": "user", "message": {"content": [{"tool_use_id": "toolu_01…", "type": "tool_result", "content": "hi"}]}} -- 2.52.0 From c9afc369f9ccd5e304136c4575b7875674762e48 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 20:29:21 +0200 Subject: [PATCH 056/233] Changelog the typed reply starting with < --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index cae8c26f..db65e201 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,5 +9,6 @@ - `loop-claude` skips a transcript line it cannot parse, exits 1 naming a transcript it cannot read, and counts a `claude` it cannot start as a failed worker run. - `loop-claude`'s judge quotes the transcript for every verdict, and a verdict quoting nothing or interrupting without a question, or a `claude` the judge cannot start, is a failed judge run; a `claude` that cannot start for an interrupt exits 1. - `loop-claude`'s exit-2 message says what the human is needed for. +- `loop-claude` counts an interrupt reply starting with `<` as typed. - `loop-claude`'s archive holds the raw `.jsonl` transcript, one copy per distinct transcript, named by its SHA-256, with the verdict beside it in `.verdict.md`; a transcript it cannot archive exits 1. - `loop-claude` keeps the mode of `~/.claude.json` and of its models file when it rewrites them, and creates the models file 0600. -- 2.52.0 From 20db779a0da00b05ba2395e63fa6f173b0bc195b Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 20:31:56 +0200 Subject: [PATCH 057/233] Correct --help's end of the loop and drop prose the code or the log already holds --- bin/loop_claude/claude_code.py | 2 -- bin/loop_claude/judge.py | 1 - bin/loop_claude/main.py | 2 +- bin/loop_claude/session.py | 3 +-- todo.md | 8 ++++---- 5 files changed, 6 insertions(+), 10 deletions(-) diff --git a/bin/loop_claude/claude_code.py b/bin/loop_claude/claude_code.py index 9c39080d..527a9a68 100644 --- a/bin/loop_claude/claude_code.py +++ b/bin/loop_claude/claude_code.py @@ -20,7 +20,6 @@ class UserEntryKind(enum.Enum): def locations(home): - """~/.claude.json, the model catalog folder and the projects folder.""" return home / ".claude.json", home / ".claude" / "cache" / "model-catalog", home / ".claude" / "projects" @@ -35,7 +34,6 @@ def session_files(transcript): return glob.glob(glob.escape(transcript.removesuffix(".jsonl")) + "*") -# One line of a transcript or of stream-json, or --output-format json's whole output. def parse(raw): try: entry = json.loads(raw) diff --git a/bin/loop_claude/judge.py b/bin/loop_claude/judge.py index b6fcdfe8..4990452f 100644 --- a/bin/loop_claude/judge.py +++ b/bin/loop_claude/judge.py @@ -40,7 +40,6 @@ JUDGE_SCHEMA = { def judge(root, task, premises, transcript, model): # No tools, so the verdict rests on the transcript grounded() checks it against; no persistence, so its runs stay out of the session picker. - # Without --bare, claude -p loads the project's and ~/.claude's CLAUDE.md. args = [ "-p", "--json-schema", json.dumps(JUDGE_SCHEMA), diff --git a/bin/loop_claude/main.py b/bin/loop_claude/main.py index 973307cc..fd71ecd3 100644 --- a/bin/loop_claude/main.py +++ b/bin/loop_claude/main.py @@ -8,7 +8,7 @@ the transcript against them and rules whether the chunk, the smallest PR-able ch A question only the human can answer, or a release ready to cut, is an interrupt: `claude --resume` on the terminal, every worktree first marked trusted in ~/.claude.json. An unfinished chunk resumes its session next cycle; the next chunk starts a fresh session. -Cycles continue until that interrupt or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary". +Cycles continue until an exit below or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary". Exit 1: no task, not inside a checkout, no premises, a models file it cannot read or write, claude leaves no transcript or one it cannot read or archive, claude cannot start for an interrupt, a diff --git a/bin/loop_claude/session.py b/bin/loop_claude/session.py index 3f937aca..8198ce99 100644 --- a/bin/loop_claude/session.py +++ b/bin/loop_claude/session.py @@ -19,8 +19,7 @@ class Session: def session_for(root, paths): - """The project's one session, at an id fixed by its name. It exists while its transcript does: a chunk's first - cycle starts it, each later cycle of the chunk resumes it, and the finished chunk deletes it.""" + """Exists while its transcript does.""" # "A " is the human's cue in the session picker that the session is the loop's. name = f"A {project_name(root, paths.code)} loop-claude" return Session(uuid.uuid5(NAMESPACE, name), name, paths.projects) diff --git a/todo.md b/todo.md index 5c5ed393..f3b62f54 100644 --- a/todo.md +++ b/todo.md @@ -4,18 +4,18 @@ **⚠️ THE REBUILD NEVER MERGES INTO MAIN WITHOUT THE HUMAN'S EXPLICIT APPROVAL.** Every rebuild chunk is a worktree based on `origin/rebuild` with its PR into `rebuild`, never into main. Other sessions run on `~/.claude` main throughout; only the human merges `rebuild` into main, once they have approved the finished whole. -The rebuild lifts every dimension: each item below is one chunk on a worktree based on `origin/rebuild`, its PR into `rebuild`, until the last item merges `rebuild` into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. +The rebuild lifts every dimension: each item below is one chunk on a worktree based on `origin/rebuild`, its PR into `rebuild`, until the last item opens `rebuild`'s PR into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -The panel on `rebuild` at 37edc9a scored Self-sufficiency 6.5, Locality 6.63 and Shape 6.88 (`docs/decisions.md`). The places its seats named, capping dimension first: +The places the panel on `rebuild` at 37edc9a named (`docs/decisions.md`), capping dimension first: - **State in larv-review's §3 what a pass's run is, and whether a Stage 0 rerun, a panel rerun after a floor fix, an auto-reviewer re-review and a 🔀 escalation each count against the round cap.** Four seats reread the re-entry rule with the table, `principles/review-findings.md` → "Rounds" and the Vocabulary open; round and run name one thing. - **Point `agents/stability-reviewer.md`'s 🔀 list at larv-review's pass table.** Its security trigger (auth/session, payment, file upload) disagrees with the table's (authn/authz, secrets, crypto, untrusted input). -- **Return the verdict from `run_cycle`'s judge–interrupt loop, so nothing reads `verdict` after it.** Three seats; `archive`'s skip on an existing copy holds only because each interrupt appends a turn, which nothing at `cycle.py` says. +- **Return the verdict from `run_cycle`'s judge–interrupt loop, so nothing reads `verdict` after it.** Three seats; `archive`'s skip on an existing copy holds only because each interrupt appends a turn. - **Name the minute `strike` sleeps, and the exec `reload_if_edited` may not return from, where each is called.** Four seats and three. - **Let `render` join a human entry's text without relying on `user_entry_kind` having checked every part.** Three seats. - **Give failure one spelling: `Failure.reason` and `Retry.failure`, `replace_file`'s raw `OSError`, and `typed`/`said` named for what they test.** Keep `LoopState`'s fields: they are main's `--reloaded` state (`docs/decisions.md`). - **Group `bin/loop_claude/`'s 18 flat modules, and move `principles/review-findings.md` beside larv-review.** Two seats; `claude_code.py` is the first group. -- **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. A loop running main's script reloads into the new one and carries on (`docs/decisions.md`). +- **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. ## 0.2.0 -- 2.52.0 From 564a2fe3a18593ae987fbc916a2df7a9895ee1f3 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 20:33:45 +0200 Subject: [PATCH 058/233] File the reply sent mid-turn that the judge never sees --- todo.md | 1 + 1 file changed, 1 insertion(+) diff --git a/todo.md b/todo.md index f3b62f54..6538abcf 100644 --- a/todo.md +++ b/todo.md @@ -15,6 +15,7 @@ The places the panel on `rebuild` at 37edc9a named (`docs/decisions.md`), cappin - **Let `render` join a human entry's text without relying on `user_entry_kind` having checked every part.** Three seats. - **Give failure one spelling: `Failure.reason` and `Retry.failure`, `replace_file`'s raw `OSError`, and `typed`/`said` named for what they test.** Keep `LoopState`'s fields: they are main's `--reloaded` state (`docs/decisions.md`). - **Group `bin/loop_claude/`'s 18 flat modules, and move `principles/review-findings.md` beside larv-review.** Two seats; `claude_code.py` is the first group. +- **Show the judge a reply the human sends while claude works.** Claude Code 2.1.284 writes it as an `"attachment"` entry, which `render` drops, so the judge can rule on a question the human already answered during an interrupt. - **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. ## 0.2.0 -- 2.52.0 From 55546596780c6fa67ac503ace49ee64bdc50a1b7 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 21:00:05 +0200 Subject: [PATCH 059/233] Record why the rebuild's merge warning stands in three places --- docs/decisions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/decisions.md b/docs/decisions.md index 140dcc44..97dfa258 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -50,7 +50,7 @@ ## rebuild: loop-claude and the review process are rebuilt on `rebuild` and merge to main whole -2026-09-28, lilleman. Serves goal 4. Three scoring runs held Locality at 6 while about thirty chunks fixed the places the seats named, and two blind judges scored main's loop-claude 5 and its review process 4 against 7 for sketches designed from the target result. Other sessions run on `~/.claude` main throughout, so every rebuild chunk merges into `rebuild`, never main, and `rebuild` reaches main only when it passes the comprehension floor and **the human has explicitly approved the whole and merges it themselves**. Valid until the rebuild merges. +2026-09-28, lilleman. Serves goal 4. Three scoring runs held Locality at 6 while about thirty chunks fixed the places the seats named, and two blind judges scored main's loop-claude 5 and its review process 4 against 7 for sketches designed from the target result. Other sessions run on `~/.claude` main throughout, so every rebuild chunk merges into `rebuild`, never main, and `rebuild` reaches main only when it passes the comprehension floor and **the human has explicitly approved the whole and merges it themselves**. The ⚠️ warning stands in `AGENTS.md`, atop `todo.md` and on its last item on purpose, 2026-09-28, lilleman: a premature merge lands under every session running on main, so a reader of any one of them must meet it. Valid until the rebuild merges. ## review: the round cap counts a pass's runs per chunk -- 2.52.0 From 35340970a27f2248d9d9f307cf7b3575d4361ff2 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 21:05:39 +0200 Subject: [PATCH 060/233] State what a pass's round is and that the round cap counts every one --- AGENTS.md | 2 +- CLAUDE.md | 2 +- docs/decisions.md | 4 ++-- principles/review-findings.md | 1 - skills/larv-review/SKILL.md | 6 ++++-- todo.md | 1 - 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b7873096..501cfe29 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,7 +17,7 @@ Decisions live in `docs/decisions.md`: - loop-claude: a CR-only README.md is reported at line 1 - loop-claude: each project's model lives in loop-claude's own file - rebuild: loop-claude and the review process are rebuilt on `rebuild` and merge to main whole -- review: the round cap counts a pass's runs per chunk +- review: the round cap counts a pass's rounds per chunk - loop-claude: the judge is retried alone, on its own counter - loop-claude: the judge loads `CLAUDE.md` - loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop diff --git a/CLAUDE.md b/CLAUDE.md index 59f2a4a6..646be840 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -13,7 +13,7 @@ Shorter is better, none is best — chat output, commit messages, comments, docs - **premises** — the goals and audience under `## Goals` and `## Audience` in the project's `README.md`. - **release** — a semver version the human cuts. - **reviewer** — a reporter of findings: an agent under `~/.claude/agents/`, `/security-review` or a forge's auto-reviewer. -- **round cap** — the runs one pass may take per chunk, re-entries included. +- **round cap** — the rounds one pass may take per chunk. - **session** — a Claude Code session: one id, what `claude --resume` continues. - **trigger** — the condition under which a review pass runs on a change it has not seen; `larv-review` §3 lists them. - **worker** — the headless claude that runs the task in a cycle, in the chunk's session. diff --git a/docs/decisions.md b/docs/decisions.md index 97dfa258..d99fae11 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -52,9 +52,9 @@ 2026-09-28, lilleman. Serves goal 4. Three scoring runs held Locality at 6 while about thirty chunks fixed the places the seats named, and two blind judges scored main's loop-claude 5 and its review process 4 against 7 for sketches designed from the target result. Other sessions run on `~/.claude` main throughout, so every rebuild chunk merges into `rebuild`, never main, and `rebuild` reaches main only when it passes the comprehension floor and **the human has explicitly approved the whole and merges it themselves**. The ⚠️ warning stands in `AGENTS.md`, atop `todo.md` and on its last item on purpose, 2026-09-28, lilleman: a premature merge lands under every session running on main, so a reader of any one of them must meet it. Valid until the rebuild merges. -## review: the round cap counts a pass's runs per chunk +## review: the round cap counts a pass's rounds per chunk -2026-09-28, lilleman, for the rebuild. Serves goal 4. A pass runs at most three times per chunk, re-entries included, and a fourth run asks the human; one counter, and no fix bounces between two passes without end. Valid while one human answers the ask. +2026-09-28, lilleman, for the rebuild. Serves goal 4. Every round of a pass counts against one cap per chunk, and a fourth asks the human; one counter, and no fix bounces between two passes without end. Valid while one human answers the ask. ## loop-claude: the judge is retried alone, on its own counter diff --git a/principles/review-findings.md b/principles/review-findings.md index fe08ce38..bad7ccb2 100644 --- a/principles/review-findings.md +++ b/principles/review-findings.md @@ -30,7 +30,6 @@ A review's first line, derived from the findings: - Surface everything in round 1. - From round 2 the prompt carries the previous round's findings verbatim and what changed since. Verify each earlier 🔴 and 🟡 is resolved — re-run the scenario, never trust the claim — then review what changed. A fix raises a new finding only where the fix itself introduced a real problem. - A pass is done on no 🔴 and no 🟡. The 🟢 and ❓ left are addressed in that round — fixed, answered, declined or filed in `todo.md` — and take no further round, unless a fix changes behaviour: that takes one. -- Round cap: a pass runs at most three times per chunk, re-entries included. Instead of a fourth, list what is open and ask the human. ## Declining diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 8e1ebb7b..90b8ce99 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -39,6 +39,8 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod **Re-entry.** A fix is a change the passes have not seen. The pass whose findings it answers runs again, per the findings document's rounds; beyond it, classify the fix by the widest thing it touches — the first row whose trigger it fires, none sending it to §4 — and run forward from that row through §4, each later pass only where its trigger fires too. +**Round cap.** A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human. A round is one launch of a pass's reviewer, whatever launched it: the trigger, a re-entry, a 🔀 escalation, a Stage 0 launch and its rerun. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the prose pass's round is its fresh-context agent. The external auto-reviewer (§4) is a pass of its own, each review it posts a round: after its third, ask the human before any push that would summon a fourth. + ### Architecture Launch systems-architect: review the system as a whole entered through this change; the decision log carries previously accepted decisions to honor, the README the goals and Stage 0 artifacts. @@ -84,7 +86,7 @@ The bar is `~/.claude/CLAUDE.md` → "Comments and documentation"; per paragraph 2. Watch the forge's checks until every one passes. A red check is a finding; its fix re-enters per §3. 3. No CI configured → the gate is local tests only; note it in the summary. 4. Everything green → mark the PR ready, dropping any `WIP:`/`Draft:` title prefix. -5. **External auto-reviewer**, when the repo has one — its config file (`.coderabbit.yaml` and the like), or its comments on earlier PRs; none → skip it, say so. Marking the PR ready is what summons it. Wait up to **10 minutes** for its first review, checking about once a minute; nothing by then → note it in the summary and carry on, never waiting twice. Its findings follow the findings document like any reviewer's, and its reviews count against the round cap as a pass's runs do. Once it has reviewed, each later return here, after a fix re-entered per §3, waits up to **5 minutes** for its re-review of the new commit. +5. **External auto-reviewer**, when the repo has one — its config file (`.coderabbit.yaml` and the like), or its comments on earlier PRs; none → skip it, say so. Marking the PR ready is what summons it. Wait up to **10 minutes** for its first review, checking about once a minute; nothing by then → note it in the summary and carry on, never waiting twice. Its findings follow the findings document like any reviewer's. Once it has reviewed, each later return here, after a fix re-entered per §3, waits up to **5 minutes** for its re-review of the new commit. ## 5. Goal alignment, then merge @@ -95,4 +97,4 @@ The bar is `~/.claude/CLAUDE.md` → "Comments and documentation"; per paragraph ## 6. Wrap up -Summarize: PR URL and final state, every reviewer's verdict, runs per pass, passes skipped, findings fixed vs declined vs open — each decline with the goal it rests on — CI status, decisions recorded (file paths), `todo.md`/`CHANGELOG.md` updated, and any 🔀 escalation left for the user. +Summarize: PR URL and final state, every reviewer's verdict, rounds per pass, passes skipped, findings fixed vs declined vs open — each decline with the goal it rests on — CI status, decisions recorded (file paths), `todo.md`/`CHANGELOG.md` updated, and any 🔀 escalation left for the user. diff --git a/todo.md b/todo.md index 6538abcf..223b2d07 100644 --- a/todo.md +++ b/todo.md @@ -8,7 +8,6 @@ The rebuild lifts every dimension: each item below is one chunk on a worktree ba The places the panel on `rebuild` at 37edc9a named (`docs/decisions.md`), capping dimension first: -- **State in larv-review's §3 what a pass's run is, and whether a Stage 0 rerun, a panel rerun after a floor fix, an auto-reviewer re-review and a 🔀 escalation each count against the round cap.** Four seats reread the re-entry rule with the table, `principles/review-findings.md` → "Rounds" and the Vocabulary open; round and run name one thing. - **Point `agents/stability-reviewer.md`'s 🔀 list at larv-review's pass table.** Its security trigger (auth/session, payment, file upload) disagrees with the table's (authn/authz, secrets, crypto, untrusted input). - **Return the verdict from `run_cycle`'s judge–interrupt loop, so nothing reads `verdict` after it.** Three seats; `archive`'s skip on an existing copy holds only because each interrupt appends a turn. - **Name the minute `strike` sleeps, and the exec `reload_if_edited` may not return from, where each is called.** Four seats and three. -- 2.52.0 From b833ccb982b95f9c8a076eff2ad7a9a83c4209c7 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 21:06:37 +0200 Subject: [PATCH 061/233] Point stability-reviewer's escalations at larv-review's pass table --- agents/stability-reviewer.md | 5 +---- todo.md | 1 - 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/agents/stability-reviewer.md b/agents/stability-reviewer.md index 93f9b74a..62ea2850 100644 --- a/agents/stability-reviewer.md +++ b/agents/stability-reviewer.md @@ -134,10 +134,7 @@ Verdict, severities, rounds and declines: ~/.claude/principles/review-findings.m - **Risk**: What could go wrong in production - **Fix**: The smallest change that closes the issue — prefer delete > simplify > modify > add; code examples when helpful -Raise a 🔀 for: -- **product-owner-reviewer** — the diff changes an external surface: REST API contract (routes, request/response shapes, status codes, OpenAPI spec), web UI flow, CLI, webhook, or customer-facing docs. -- **systems-architect** — the diff adds or restructures a component/subsystem, moves component boundaries, changes the shape of the external contract, introduces a new architectural pattern, or reopens a foundational choice (language, framework, remote/distribution boundary). -- **/security-review** — the diff touches auth/session handling, crypto, payment flows, file upload/handling, or adds a substantial new input surface; a dedicated pass beyond the per-PR sweep in #9. +Raise a 🔀 where the diff fires another pass's trigger in the pass table, `~/.claude/skills/larv-review/SKILL.md` §3. ## Behavioral Guidelines diff --git a/todo.md b/todo.md index 223b2d07..d7273984 100644 --- a/todo.md +++ b/todo.md @@ -8,7 +8,6 @@ The rebuild lifts every dimension: each item below is one chunk on a worktree ba The places the panel on `rebuild` at 37edc9a named (`docs/decisions.md`), capping dimension first: -- **Point `agents/stability-reviewer.md`'s 🔀 list at larv-review's pass table.** Its security trigger (auth/session, payment, file upload) disagrees with the table's (authn/authz, secrets, crypto, untrusted input). - **Return the verdict from `run_cycle`'s judge–interrupt loop, so nothing reads `verdict` after it.** Three seats; `archive`'s skip on an existing copy holds only because each interrupt appends a turn. - **Name the minute `strike` sleeps, and the exec `reload_if_edited` may not return from, where each is called.** Four seats and three. - **Let `render` join a human entry's text without relying on `user_entry_kind` having checked every part.** Three seats. -- 2.52.0 From 2602231b23bd4ad6dead3c6ba88df17a33d4ac7e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 21:08:25 +0200 Subject: [PATCH 062/233] =?UTF-8?q?Return=20the=20verdict=20from=20run=5Fc?= =?UTF-8?q?ycle's=20judge=E2=80=93interrupt=20loop?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/loop_claude/cycle.py | 20 ++++++++++++-------- todo.md | 1 - 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/bin/loop_claude/cycle.py b/bin/loop_claude/cycle.py index 9c5a144c..ec03af38 100644 --- a/bin/loop_claude/cycle.py +++ b/bin/loop_claude/cycle.py @@ -19,25 +19,29 @@ def run_cycle(root, task, premises, models, paths): path = transcript_file(session) if not path: return Stop(1, f"claude left no transcript for session {session.id}") + verdict = judge_through_interrupts(root, task, premises, models, session, path, paths) + if isinstance(verdict, Stop): + return verdict + if verdict["finished"]: + if failure := archive(root, path, f"Task: {task}\n\nVerdict: finished", paths): + return Stop(1, failure.reason) + delete_session(session) + return Continue() + + +def judge_through_interrupts(root, task, premises, models, session, path, paths): # The interrupt appends to this transcript, so each pass judges and archives it anew. while True: entries = read(path) if isinstance(entries, Failure): return Stop(1, entries.reason) verdict = judge(root, task, premises, render(entries), models.judge) - if isinstance(verdict, Stop): + if isinstance(verdict, Stop) or not verdict["interrupt"]: return verdict - if not verdict["interrupt"]: - break if failure := archive(root, path, f"Task: {task}\n\nVerdict: interrupt\n\n{verdict['question']}", paths): return Stop(1, failure.reason) if stop := interrupt(root, session.id, models.worker, path, verdict["question"], paths): return stop - if verdict["finished"]: - if failure := archive(root, path, f"Task: {task}\n\nVerdict: finished", paths): - return Stop(1, failure.reason) - delete_session(session) - return Continue() def archive(root, path, note, paths): diff --git a/todo.md b/todo.md index d7273984..a2dc9072 100644 --- a/todo.md +++ b/todo.md @@ -8,7 +8,6 @@ The rebuild lifts every dimension: each item below is one chunk on a worktree ba The places the panel on `rebuild` at 37edc9a named (`docs/decisions.md`), capping dimension first: -- **Return the verdict from `run_cycle`'s judge–interrupt loop, so nothing reads `verdict` after it.** Three seats; `archive`'s skip on an existing copy holds only because each interrupt appends a turn. - **Name the minute `strike` sleeps, and the exec `reload_if_edited` may not return from, where each is called.** Four seats and three. - **Let `render` join a human entry's text without relying on `user_entry_kind` having checked every part.** Three seats. - **Give failure one spelling: `Failure.reason` and `Retry.failure`, `replace_file`'s raw `OSError`, and `typed`/`said` named for what they test.** Keep `LoopState`'s fields: they are main's `--reloaded` state (`docs/decisions.md`). -- 2.52.0 From 4cd79e5b1ad84622e1c60ae02fd00a502f1fa6c0 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 21:13:09 +0200 Subject: [PATCH 063/233] Name the minute's sleep and the exec at their call sites --- bin/loop_claude/judge.py | 4 ++-- bin/loop_claude/main.py | 8 ++++---- bin/loop_claude/reload.py | 2 +- bin/loop_claude/strike.py | 2 +- todo.md | 1 - 5 files changed, 8 insertions(+), 9 deletions(-) diff --git a/bin/loop_claude/judge.py b/bin/loop_claude/judge.py index 4990452f..971642e7 100644 --- a/bin/loop_claude/judge.py +++ b/bin/loop_claude/judge.py @@ -4,7 +4,7 @@ import subprocess from loop_claude.claude_code import structured_output from loop_claude.outcome import Failure -from loop_claude.strike import strike +from loop_claude.strike import stop_or_sleep_a_minute JUDGE_RULES = ( "Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n" @@ -60,7 +60,7 @@ def judge(root, task, premises, transcript, model): failure = f"the judge quoted {verdict['evidence']!r}, nothing in the transcript" + (f", for the question: {verdict['question']}" if verdict["interrupt"] else "") else: return verdict - if stop := strike("judge", failures, failure): + if stop := stop_or_sleep_a_minute("judge", failures, failure): return stop diff --git a/bin/loop_claude/main.py b/bin/loop_claude/main.py index fd71ecd3..a393823a 100644 --- a/bin/loop_claude/main.py +++ b/bin/loop_claude/main.py @@ -41,8 +41,8 @@ from loop_claude.cycle import run_cycle from loop_claude.models import project_models from loop_claude.outcome import Continue, Retry, Stop from loop_claude.premises import read_premises -from loop_claude.reload import RELOAD_FLAG, decode_state, fingerprint, reload_if_edited -from loop_claude.strike import strike +from loop_claude.reload import RELOAD_FLAG, decode_state, exec_if_edited, fingerprint +from loop_claude.strike import stop_or_sleep_a_minute @dataclasses.dataclass(frozen=True) @@ -69,7 +69,7 @@ def run_loop(argv, env, paths, launcher, cwd): return state baseline = fingerprint(launcher) while True: - reload_if_edited(launcher, baseline, state) + exec_if_edited(launcher, baseline, state) state = dataclasses.replace(state, cycle_number=state.cycle_number + 1) premises = read_premises(state.root) if isinstance(premises, Stop): @@ -83,7 +83,7 @@ def run_loop(argv, env, paths, launcher, cwd): return stop case Retry(failure): state = dataclasses.replace(state, failures=state.failures + 1) - if stop := strike("worker", state.failures, failure): + if stop := stop_or_sleep_a_minute("worker", state.failures, failure): return stop case Continue(): state = dataclasses.replace(state, failures=0) diff --git a/bin/loop_claude/reload.py b/bin/loop_claude/reload.py index a3c75177..4e8f7af6 100644 --- a/bin/loop_claude/reload.py +++ b/bin/loop_claude/reload.py @@ -32,7 +32,7 @@ def fingerprint(launcher): return digest.hexdigest() -def reload_if_edited(launcher, baseline, state): +def exec_if_edited(launcher, baseline, state): if fingerprint(launcher) == baseline: return trial = subprocess.run([sys.executable, launcher, "--help"], capture_output=True, text=True) diff --git a/bin/loop_claude/strike.py b/bin/loop_claude/strike.py index 72105153..ab5c1a8e 100644 --- a/bin/loop_claude/strike.py +++ b/bin/loop_claude/strike.py @@ -4,7 +4,7 @@ import time from loop_claude.outcome import Stop -def strike(who, failures, failure): +def stop_or_sleep_a_minute(who, failures, failure): if failures == 3: return Stop(1, f"the {who} failed three times running: {failure}") print(f"retrying the {who} in a minute: {failure}", file=sys.stderr) diff --git a/todo.md b/todo.md index a2dc9072..c4bf5e6e 100644 --- a/todo.md +++ b/todo.md @@ -8,7 +8,6 @@ The rebuild lifts every dimension: each item below is one chunk on a worktree ba The places the panel on `rebuild` at 37edc9a named (`docs/decisions.md`), capping dimension first: -- **Name the minute `strike` sleeps, and the exec `reload_if_edited` may not return from, where each is called.** Four seats and three. - **Let `render` join a human entry's text without relying on `user_entry_kind` having checked every part.** Three seats. - **Give failure one spelling: `Failure.reason` and `Retry.failure`, `replace_file`'s raw `OSError`, and `typed`/`said` named for what they test.** Keep `LoopState`'s fields: they are main's `--reloaded` state (`docs/decisions.md`). - **Group `bin/loop_claude/`'s 18 flat modules, and move `principles/review-findings.md` beside larv-review.** Two seats; `claude_code.py` is the first group. -- 2.52.0 From 089d8fa1dc7b2a73a71e6fd684a26f337e291f57 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 21:15:26 +0200 Subject: [PATCH 064/233] Name the retry module by what it holds --- bin/loop_claude/judge.py | 2 +- bin/loop_claude/main.py | 2 +- bin/loop_claude/{strike.py => retry.py} | 0 3 files changed, 2 insertions(+), 2 deletions(-) rename bin/loop_claude/{strike.py => retry.py} (100%) diff --git a/bin/loop_claude/judge.py b/bin/loop_claude/judge.py index 971642e7..38d402a1 100644 --- a/bin/loop_claude/judge.py +++ b/bin/loop_claude/judge.py @@ -4,7 +4,7 @@ import subprocess from loop_claude.claude_code import structured_output from loop_claude.outcome import Failure -from loop_claude.strike import stop_or_sleep_a_minute +from loop_claude.retry import stop_or_sleep_a_minute JUDGE_RULES = ( "Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n" diff --git a/bin/loop_claude/main.py b/bin/loop_claude/main.py index a393823a..daae4f87 100644 --- a/bin/loop_claude/main.py +++ b/bin/loop_claude/main.py @@ -42,7 +42,7 @@ from loop_claude.models import project_models from loop_claude.outcome import Continue, Retry, Stop from loop_claude.premises import read_premises from loop_claude.reload import RELOAD_FLAG, decode_state, exec_if_edited, fingerprint -from loop_claude.strike import stop_or_sleep_a_minute +from loop_claude.retry import stop_or_sleep_a_minute @dataclasses.dataclass(frozen=True) diff --git a/bin/loop_claude/strike.py b/bin/loop_claude/retry.py similarity index 100% rename from bin/loop_claude/strike.py rename to bin/loop_claude/retry.py -- 2.52.0 From 194601aeda5e213980f203904a82d3a019309ba8 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 21:17:59 +0200 Subject: [PATCH 065/233] Join a human entry's text where it is classified --- bin/loop_claude/claude_code.py | 15 ++++++++++----- bin/loop_claude/transcript.py | 9 ++++----- todo.md | 1 - 3 files changed, 14 insertions(+), 11 deletions(-) diff --git a/bin/loop_claude/claude_code.py b/bin/loop_claude/claude_code.py index 527a9a68..bb762c8e 100644 --- a/bin/loop_claude/claude_code.py +++ b/bin/loop_claude/claude_code.py @@ -70,19 +70,24 @@ def user_entry_kind(entry): if isinstance(text := content(entry), str): source = entry.get("promptSource") return UserEntryKind.COMMAND if source == "system" or (source != "typed" and text.startswith("<")) else UserEntryKind.HUMAN - if not parts(entry): + texts = [part_text(part) for part in parts(entry)] + if not texts: return UserEntryKind.EMPTY # {"type": "user", "message": {"content": [{"tool_use_id": "toolu_01…", "type": "tool_result", "content": "hi"}]}} - if any(not isinstance(part, dict) or part.get("type") != "text" or not isinstance(part.get("text"), str) for part in parts(entry)): + if None in texts: return UserEntryKind.NON_TEXT # {"type": "user", "message": {"content": [{"type": "text", "text": "[Request interrupted by user]"}]}} - if any(part["text"].startswith("[Request interrupted") for part in parts(entry)): + if any(text.startswith("[Request interrupted") for text in texts): return UserEntryKind.CTRL_C return UserEntryKind.HUMAN -def typed(entry): - return entry.get("type") == "user" and user_entry_kind(entry) is UserEntryKind.HUMAN +def human_text(entry): + """What the human wrote in the entry, or None where Claude Code wrote it.""" + if entry.get("type") != "user" or user_entry_kind(entry) is not UserEntryKind.HUMAN: + return None + text = content(entry) + return text if isinstance(text, str) else "".join(part_text(part) or "" for part in parts(entry)) # {"type": "text", "text": "ok"} diff --git a/bin/loop_claude/transcript.py b/bin/loop_claude/transcript.py index 50cb7b99..36727ec6 100644 --- a/bin/loop_claude/transcript.py +++ b/bin/loop_claude/transcript.py @@ -1,6 +1,6 @@ import json -from loop_claude.claude_code import assistant_parts, content, parse, part_text, tool_call, typed +from loop_claude.claude_code import assistant_parts, human_text, parse, part_text, tool_call from loop_claude.outcome import Failure @@ -13,16 +13,15 @@ def read(path): def human_turns(entries): - return sum(1 for entry in entries if typed(entry)) + return sum(1 for entry in entries if human_text(entry) is not None) def render(entries): lines = [] for entry in entries: lines += [line for part in assistant_parts(entry) if (line := said(part))] - if typed(entry): - text = content(entry) - lines.append("[human] " + (text if isinstance(text, str) else "".join(part["text"] for part in text))) + if (text := human_text(entry)) is not None: + lines.append("[human] " + text) return "\n\n".join(lines) diff --git a/todo.md b/todo.md index c4bf5e6e..d5838e26 100644 --- a/todo.md +++ b/todo.md @@ -8,7 +8,6 @@ The rebuild lifts every dimension: each item below is one chunk on a worktree ba The places the panel on `rebuild` at 37edc9a named (`docs/decisions.md`), capping dimension first: -- **Let `render` join a human entry's text without relying on `user_entry_kind` having checked every part.** Three seats. - **Give failure one spelling: `Failure.reason` and `Retry.failure`, `replace_file`'s raw `OSError`, and `typed`/`said` named for what they test.** Keep `LoopState`'s fields: they are main's `--reloaded` state (`docs/decisions.md`). - **Group `bin/loop_claude/`'s 18 flat modules, and move `principles/review-findings.md` beside larv-review.** Two seats; `claude_code.py` is the first group. - **Show the judge a reply the human sends while claude works.** Claude Code 2.1.284 writes it as an `"attachment"` entry, which `render` drops, so the judge can rule on a question the human already answered during an interrupt. -- 2.52.0 From 750c417c2db9ab01a1adf6ca111ffe897b69dfb0 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 21:19:33 +0200 Subject: [PATCH 066/233] Drop the removed typed from the plan --- todo.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/todo.md b/todo.md index d5838e26..f87f73b6 100644 --- a/todo.md +++ b/todo.md @@ -8,7 +8,7 @@ The rebuild lifts every dimension: each item below is one chunk on a worktree ba The places the panel on `rebuild` at 37edc9a named (`docs/decisions.md`), capping dimension first: -- **Give failure one spelling: `Failure.reason` and `Retry.failure`, `replace_file`'s raw `OSError`, and `typed`/`said` named for what they test.** Keep `LoopState`'s fields: they are main's `--reloaded` state (`docs/decisions.md`). +- **Give failure one spelling: `Failure.reason` and `Retry.failure`, `replace_file`'s raw `OSError`, and `said` named for what it tests.** Keep `LoopState`'s fields: they are main's `--reloaded` state (`docs/decisions.md`). - **Group `bin/loop_claude/`'s 18 flat modules, and move `principles/review-findings.md` beside larv-review.** Two seats; `claude_code.py` is the first group. - **Show the judge a reply the human sends while claude works.** Claude Code 2.1.284 writes it as an `"attachment"` entry, which `render` drops, so the judge can rule on a question the human already answered during an interrupt. - **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. -- 2.52.0 From 0fc6afd1e7795ec65103a5d5f0d2fe4d99e8ef91 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 21:21:35 +0200 Subject: [PATCH 067/233] Give failure one spelling --- bin/loop_claude/cycle.py | 6 +++--- bin/loop_claude/file_writes.py | 4 +++- bin/loop_claude/main.py | 6 +++--- bin/loop_claude/models.py | 2 +- bin/loop_claude/outcome.py | 5 ----- bin/loop_claude/transcript.py | 4 ++-- bin/loop_claude/trust.py | 2 +- bin/loop_claude/worker.py | 4 ++-- bin/test_loop_claude.py | 14 +++++++------- todo.md | 1 - 10 files changed, 22 insertions(+), 26 deletions(-) diff --git a/bin/loop_claude/cycle.py b/bin/loop_claude/cycle.py index ec03af38..14055c31 100644 --- a/bin/loop_claude/cycle.py +++ b/bin/loop_claude/cycle.py @@ -5,7 +5,7 @@ from loop_claude.checkout import project_name from loop_claude.file_writes import make_private, replace_file from loop_claude.interrupt import interrupt from loop_claude.judge import judge -from loop_claude.outcome import Continue, Failure, Retry, Stop +from loop_claude.outcome import Continue, Failure, Stop from loop_claude.session import delete_session, session_for, transcript_file from loop_claude.transcript import read, render from loop_claude.worker import run_worker, worker_args @@ -15,7 +15,7 @@ def run_cycle(root, task, premises, models, paths): session = session_for(root, paths) resuming = bool(transcript_file(session)) if failure := run_worker(root, worker_args(task, session, models.worker, resuming)): - return Retry(failure.reason) + return failure path = transcript_file(session) if not path: return Stop(1, f"claude left no transcript for session {session.id}") @@ -57,6 +57,6 @@ def archive(root, path, note, paths): 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.strerror}") + return Failure(f"could not archive the transcript: {dest}: {failure.reason}") print(f"transcript: {copy}", file=sys.stderr) return None diff --git a/bin/loop_claude/file_writes.py b/bin/loop_claude/file_writes.py index 0654c309..9db6bea0 100644 --- a/bin/loop_claude/file_writes.py +++ b/bin/loop_claude/file_writes.py @@ -1,6 +1,8 @@ import json import os +from loop_claude.outcome import Failure + def make_private(folder): mask = os.umask(0o077) @@ -25,5 +27,5 @@ def replace_file(path, data): except OSError as failure: if os.path.exists(staged): os.remove(staged) - return failure + return Failure(failure.strerror) return None diff --git a/bin/loop_claude/main.py b/bin/loop_claude/main.py index daae4f87..37c2c262 100644 --- a/bin/loop_claude/main.py +++ b/bin/loop_claude/main.py @@ -39,7 +39,7 @@ import sys from loop_claude.checkout import checkout_root from loop_claude.cycle import run_cycle from loop_claude.models import project_models -from loop_claude.outcome import Continue, Retry, Stop +from loop_claude.outcome import Continue, Failure, Stop from loop_claude.premises import read_premises from loop_claude.reload import RELOAD_FLAG, decode_state, exec_if_edited, fingerprint from loop_claude.retry import stop_or_sleep_a_minute @@ -81,9 +81,9 @@ def run_loop(argv, env, paths, launcher, cwd): match run_cycle(state.root, state.task, premises, models, paths): case Stop() as stop: return stop - case Retry(failure): + case Failure(reason): state = dataclasses.replace(state, failures=state.failures + 1) - if stop := stop_or_sleep_a_minute("worker", state.failures, failure): + if stop := stop_or_sleep_a_minute("worker", state.failures, reason): return stop case Continue(): state = dataclasses.replace(state, failures=0) diff --git a/bin/loop_claude/models.py b/bin/loop_claude/models.py index bb184cfe..fa02b44a 100644 --- a/bin/loop_claude/models.py +++ b/bin/loop_claude/models.py @@ -40,7 +40,7 @@ def project_model(name, paths): if isinstance(models, Stop): return models if failure := replace_json(saved, {**models, name: chosen}, indent="\t", sort_keys=True): - return Stop(1, f"could not save the model in {saved}: {failure.strerror}") + return Stop(1, f"could not save the model in {saved}: {failure.reason}") print(f"{name} runs on {chosen}", file=sys.stderr) return chosen diff --git a/bin/loop_claude/outcome.py b/bin/loop_claude/outcome.py index 25395bf1..a4044b75 100644 --- a/bin/loop_claude/outcome.py +++ b/bin/loop_claude/outcome.py @@ -11,11 +11,6 @@ class Failure: reason: str -@dataclasses.dataclass(frozen=True) -class Retry: - failure: str - - @dataclasses.dataclass(frozen=True) class Stop: code: int diff --git a/bin/loop_claude/transcript.py b/bin/loop_claude/transcript.py index 36727ec6..2ddf768e 100644 --- a/bin/loop_claude/transcript.py +++ b/bin/loop_claude/transcript.py @@ -19,13 +19,13 @@ def human_turns(entries): def render(entries): lines = [] for entry in entries: - lines += [line for part in assistant_parts(entry) if (line := said(part))] + lines += [line for part in assistant_parts(entry) if (line := part_line(part))] if (text := human_text(entry)) is not None: lines.append("[human] " + text) return "\n\n".join(lines) -def said(part, limit=400): +def part_line(part, limit=400): if (text := part_text(part)) and text.strip(): return text if call := tool_call(part): diff --git a/bin/loop_claude/trust.py b/bin/loop_claude/trust.py index 14d93e46..68d9b4e7 100644 --- a/bin/loop_claude/trust.py +++ b/bin/loop_claude/trust.py @@ -21,6 +21,6 @@ def trust(config, roots): if not untrusted: return if failure := replace_json(config, data, indent=2): - print(f"could not write {config}: {failure.strerror}", file=sys.stderr) + print(f"could not write {config}: {failure.reason}", file=sys.stderr) return print("trusted for the interrupt: " + ", ".join(untrusted), file=sys.stderr) diff --git a/bin/loop_claude/worker.py b/bin/loop_claude/worker.py index 2688e1b8..ec73096f 100644 --- a/bin/loop_claude/worker.py +++ b/bin/loop_claude/worker.py @@ -2,7 +2,7 @@ import subprocess from loop_claude.claude_code import assistant_parts, ends_stream, parse from loop_claude.outcome import Failure -from loop_claude.transcript import said +from loop_claude.transcript import part_line def run_worker(root, args): @@ -16,7 +16,7 @@ def run_worker(root, args): event = parse(raw) or {} done = done or ends_stream(event) for part in assistant_parts(event): - if line := said(part, 160): + if line := part_line(part, 160): print(line, flush=True) code = proc.wait() if code < 0: diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index ba0d67a6..09e6a87b 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -8,7 +8,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from loop_claude import claude_code, file_writes, judge, main, premises, transcript -from loop_claude.outcome import Stop +from loop_claude.outcome import Failure, Stop CWD = pathlib.Path("/c") @@ -58,12 +58,12 @@ class HumanTurns(unittest.TestCase): ]), 3) -class Said(unittest.TestCase): +class PartLine(unittest.TestCase): def test_renders_text_and_tool_calls_and_nothing_else(self): - self.assertEqual(transcript.said({"type": "text", "text": "hi"}), "hi") - self.assertEqual(transcript.said({"type": "text", "text": " \n"}), "") - self.assertEqual(transcript.said({"type": "tool_use", "name": "Bash", "input": {"command": "x" * 500}}, 20), '[tool Bash] {"command": "xxxxxxx') - self.assertEqual(transcript.said("not a part"), "") + self.assertEqual(transcript.part_line({"type": "text", "text": "hi"}), "hi") + self.assertEqual(transcript.part_line({"type": "text", "text": " \n"}), "") + self.assertEqual(transcript.part_line({"type": "tool_use", "name": "Bash", "input": {"command": "x" * 500}}, 20), '[tool Bash] {"command": "xxxxxxx') + self.assertEqual(transcript.part_line("not a part"), "") class Parse(unittest.TestCase): @@ -103,7 +103,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.assertIsInstance(file_writes.replace_file(os.path.join(root, "in-the-way"), b"data"), IsADirectoryError) + self.assertEqual(file_writes.replace_file(os.path.join(root, "in-the-way"), b"data"), Failure("Is a directory")) self.assertEqual(os.listdir(root), ["in-the-way"]) diff --git a/todo.md b/todo.md index f87f73b6..e11ccd80 100644 --- a/todo.md +++ b/todo.md @@ -8,7 +8,6 @@ The rebuild lifts every dimension: each item below is one chunk on a worktree ba The places the panel on `rebuild` at 37edc9a named (`docs/decisions.md`), capping dimension first: -- **Give failure one spelling: `Failure.reason` and `Retry.failure`, `replace_file`'s raw `OSError`, and `said` named for what it tests.** Keep `LoopState`'s fields: they are main's `--reloaded` state (`docs/decisions.md`). - **Group `bin/loop_claude/`'s 18 flat modules, and move `principles/review-findings.md` beside larv-review.** Two seats; `claude_code.py` is the first group. - **Show the judge a reply the human sends while claude works.** Claude Code 2.1.284 writes it as an `"attachment"` entry, which `render` drops, so the judge can rule on a question the human already answered during an interrupt. - **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. -- 2.52.0 From 8f34915bb83c7b54242e74715fbcc79774e4bc62 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 21:24:10 +0200 Subject: [PATCH 068/233] Name the retry helper's and the judge's message reason --- bin/loop_claude/judge.py | 8 ++++---- bin/loop_claude/retry.py | 6 +++--- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/bin/loop_claude/judge.py b/bin/loop_claude/judge.py index 38d402a1..943586ad 100644 --- a/bin/loop_claude/judge.py +++ b/bin/loop_claude/judge.py @@ -53,14 +53,14 @@ def judge(root, task, premises, transcript, model): for failures in itertools.count(1): verdict = run_judge(root, args, prompt) if isinstance(verdict, Failure): - failure = verdict.reason + reason = verdict.reason elif reason := incomplete(verdict): - failure = reason + pass elif not grounded(verdict, transcript): - failure = f"the judge quoted {verdict['evidence']!r}, nothing in the transcript" + (f", for the question: {verdict['question']}" if verdict["interrupt"] else "") + reason = f"the judge quoted {verdict['evidence']!r}, nothing in the transcript" + (f", for the question: {verdict['question']}" if verdict["interrupt"] else "") else: return verdict - if stop := stop_or_sleep_a_minute("judge", failures, failure): + if stop := stop_or_sleep_a_minute("judge", failures, reason): return stop diff --git a/bin/loop_claude/retry.py b/bin/loop_claude/retry.py index ab5c1a8e..f377899d 100644 --- a/bin/loop_claude/retry.py +++ b/bin/loop_claude/retry.py @@ -4,8 +4,8 @@ import time from loop_claude.outcome import Stop -def stop_or_sleep_a_minute(who, failures, failure): +def stop_or_sleep_a_minute(who, failures, reason): if failures == 3: - return Stop(1, f"the {who} failed three times running: {failure}") - print(f"retrying the {who} in a minute: {failure}", file=sys.stderr) + return Stop(1, f"the {who} failed three times running: {reason}") + print(f"retrying the {who} in a minute: {reason}", file=sys.stderr) time.sleep(60) -- 2.52.0 From 6a1a1d90277042c94ab129f0739a65899fa0cf2c Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 21:27:07 +0200 Subject: [PATCH 069/233] Pin that an edit in a folder under loop_claude reloads the loop --- bin/test_loop_claude_black_box.py | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/bin/test_loop_claude_black_box.py b/bin/test_loop_claude_black_box.py index 77fc4ce9..681dee0d 100644 --- a/bin/test_loop_claude_black_box.py +++ b/bin/test_loop_claude_black_box.py @@ -67,11 +67,13 @@ if role == "worker": (transcript().parent / sibling).mkdir(parents=True, exist_ok=True) (transcript().parent / f"{{session()}}.orphaned-1-ab.jsonl").write_text("{{}}\\n") if "append" in step: - with open(os.environ["FAKE_CLAUDE_EDIT"], "a") as script: - script.write(step["append"]) + edited = pathlib.Path(os.environ["FAKE_CLAUDE_EDIT"], step["append"][0]) + edited.parent.mkdir(parents=True, exist_ok=True) + with open(edited, "a") as script: + script.write(step["append"][1]) if "replace" in step: - script = pathlib.Path(os.environ["FAKE_CLAUDE_EDIT"]) - script.write_text(script.read_text().replace(*step["replace"])) + script = pathlib.Path(os.environ["FAKE_CLAUDE_EDIT"], step["replace"][0]) + script.write_text(script.read_text().replace(*step["replace"][1:])) sys.stdout.flush() sys.stdout.buffer.write(step.get("stream", "").encode("latin-1")) print(json.dumps(said)) @@ -633,19 +635,19 @@ class Reload(unittest.TestCase): copy = checkout.temp / "bin" shutil.copytree(BIN, copy, ignore=shutil.ignore_patterns("__pycache__", "test_*")) checkout.script = copy / "loop-claude" - checkout.env["FAKE_CLAUDE_EDIT"] = str(checkout.script) + checkout.env["FAKE_CLAUDE_EDIT"] = str(copy) run = checkout.run([ - worker(append="\ndef\n"), judge(), - worker(replace=["\ndef\n", "\n# edited\n"]), judge(), + worker(append=["loop-claude", "\ndef\n"]), judge(), + worker(replace=["loop-claude", "\ndef\n", "\n# edited\n"]), judge(), + worker(append=["loop_claude/nested/edited.py", "# edited\n"]), judge(), worker(), ]) self.assertEqual(run.code, 130) - self.assertEqual(run.roles(), ["worker", "judge"] * 3) + self.assertEqual(run.roles(), ["worker", "judge"] * 4) self.assertIn("keeping the running script", run.stderr) - reloads = [argv for argv in run.starts if argv[:1] == ["--reloaded"]] - self.assertEqual(len(reloads), 1) - self.assertEqual(json.loads(reloads[0][1]), {"cycle_number": 2, "failures": 0, "root": str(checkout.root), "task": TASK}) - self.assertIn("=== cycle 3 ===", run.stdout) + reloads = [json.loads(argv[1]) for argv in run.starts if argv[:1] == ["--reloaded"]] + self.assertEqual(reloads, [{"cycle_number": cycle, "failures": 0, "root": str(checkout.root), "task": TASK} for cycle in (2, 3)]) + self.assertIn("=== cycle 4 ===", run.stdout) outside = checkout.temp / "outside" outside.mkdir() -- 2.52.0 From 998cc3ac85cb33bf80c466e6b4868cc9749bbde6 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 21:28:41 +0200 Subject: [PATCH 070/233] Group loop_claude's modules into claude_code, claude_runs and project, and move the findings document beside larv-review --- .gitignore | 2 ++ README.md | 2 +- agents/product-owner-reviewer.md | 2 +- agents/stability-reviewer.md | 2 +- agents/systems-architect.md | 2 +- bin/loop_claude/claude_code/__init__.py | 0 .../{claude_code.py => claude_code/formats.py} | 0 bin/loop_claude/{ => claude_code}/session.py | 4 ++-- bin/loop_claude/{ => claude_code}/transcript.py | 2 +- bin/loop_claude/{ => claude_code}/trust.py | 2 +- bin/loop_claude/claude_runs/__init__.py | 0 bin/loop_claude/{ => claude_runs}/interrupt.py | 6 +++--- bin/loop_claude/{ => claude_runs}/judge.py | 2 +- bin/loop_claude/{ => claude_runs}/worker.py | 4 ++-- bin/loop_claude/cycle.py | 12 ++++++------ bin/loop_claude/main.py | 8 ++++---- bin/loop_claude/paths.py | 2 +- bin/loop_claude/project/__init__.py | 0 bin/loop_claude/{ => project}/checkout.py | 0 bin/loop_claude/{ => project}/models.py | 4 ++-- bin/loop_claude/{ => project}/premises.py | 0 bin/loop_claude/reload.py | 4 ++-- bin/test_loop_claude.py | 11 +++++++---- skills/larv-review/SKILL.md | 2 +- .../larv-review}/review-findings.md | 0 todo.md | 1 - 26 files changed, 39 insertions(+), 35 deletions(-) create mode 100644 bin/loop_claude/claude_code/__init__.py rename bin/loop_claude/{claude_code.py => claude_code/formats.py} (100%) rename bin/loop_claude/{ => claude_code}/session.py (87%) rename bin/loop_claude/{ => claude_code}/transcript.py (89%) rename bin/loop_claude/{ => claude_code}/trust.py (91%) create mode 100644 bin/loop_claude/claude_runs/__init__.py rename bin/loop_claude/{ => claude_runs}/interrupt.py (85%) rename bin/loop_claude/{ => claude_runs}/judge.py (98%) rename bin/loop_claude/{ => claude_runs}/worker.py (90%) create mode 100644 bin/loop_claude/project/__init__.py rename bin/loop_claude/{ => project}/checkout.py (100%) rename bin/loop_claude/{ => project}/models.py (96%) rename bin/loop_claude/{ => project}/premises.py (100%) rename {principles => skills/larv-review}/review-findings.md (100%) diff --git a/.gitignore b/.gitignore index abba4dcf..24919d6e 100644 --- a/.gitignore +++ b/.gitignore @@ -20,6 +20,8 @@ !bin/ !bin/* !bin/loop_claude/*.py +!bin/loop_claude/*/ +!bin/loop_claude/*/*.py !docs/ !docs/*.md !principles/ diff --git a/README.md b/README.md index 0ba7dd96..1bf70584 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Claude Code configuration -My personal `~/.claude`, version controlled: `CLAUDE.md` and `AGENTS.md` for instructions, the words under `CLAUDE.md` → "Vocabulary"; `agents/` and `skills/`; `principles/` for what the reviewer agents hold every project and every review to; `docs/` for decisions; `settings.json` for the harness and `.claude/settings.json` for the harness inside this repo; `statusline.sh`; `CHANGELOG.md` and `todo.md`; and the tools in `bin/`. +My personal `~/.claude`, version controlled: `CLAUDE.md` and `AGENTS.md` for instructions, the words under `CLAUDE.md` → "Vocabulary"; `agents/` and `skills/`; `principles/` for what the reviewer agents hold every project to; `docs/` for decisions; `settings.json` for the harness and `.claude/settings.json` for the harness inside this repo; `statusline.sh`; `CHANGELOG.md` and `todo.md`; and the tools in `bin/`. ## Goals diff --git a/agents/product-owner-reviewer.md b/agents/product-owner-reviewer.md index c253e899..9f252975 100644 --- a/agents/product-owner-reviewer.md +++ b/agents/product-owner-reviewer.md @@ -45,7 +45,7 @@ Before anything else, **read the shared principles** at `~/.claude/principles/`. ## Your Output Format -Verdict, severities, rounds and declines: ~/.claude/principles/review-findings.md. After the verdict: +Verdict, severities, rounds and declines: ~/.claude/skills/larv-review/review-findings.md. After the verdict: **Surface affected**: diff --git a/agents/stability-reviewer.md b/agents/stability-reviewer.md index 62ea2850..10be9e9f 100644 --- a/agents/stability-reviewer.md +++ b/agents/stability-reviewer.md @@ -128,7 +128,7 @@ Every PR gets at least this sweep. ## Output Format -Verdict, severities, rounds and declines: ~/.claude/principles/review-findings.md. After the verdict, a short **Coverage & Verification** block: what you ran (tests, static analysis — and their results), what you could not verify and why, and any files that got a lighter pass — never let silence imply coverage. Then the findings, most severe first, each with: +Verdict, severities, rounds and declines: ~/.claude/skills/larv-review/review-findings.md. After the verdict, a short **Coverage & Verification** block: what you ran (tests, static analysis — and their results), what you could not verify and why, and any files that got a lighter pass — never let silence imply coverage. Then the findings, most severe first, each with: - **Location**: File and line/function - **Issue**: Clear description of the problem - **Risk**: What could go wrong in production diff --git a/agents/systems-architect.md b/agents/systems-architect.md index 5266bb77..24b8bb78 100644 --- a/agents/systems-architect.md +++ b/agents/systems-architect.md @@ -151,7 +151,7 @@ How a change ships — merge gate, pipeline, deployment, dependencies — is a d You are not a per-PR reviewer. The **stability-reviewer** runs on every change for code-level safety; you run deliberately, every so often, to check the system is still aligned — right goals, right contract, right foundations, sound structure. When you do look at a specific PR, it is because the work touches architectural fundamentals or reopens foundational choices, not for routine line-level review. Stage 0 blocks review as much as design: if the project's purpose and goals are not abundantly clear from its docs, this run's output is the clarifying questions plus a short draft to confirm — not a review; the review happens in a later invocation, once the answers are recorded in the README. -**Verdict and severities: ~/.claude/principles/review-findings.md.** A violation of a non-negotiable fundamental — functional-core/shell entanglement, a unit past a Fits in a head threshold without a stated reason, a method or file carrying more than one responsibility, unreasoned duplication of a core concept, or a broken/leaky external contract — is a 🔴: lead with it, and name the concrete restructuring. The most common instance: a pure transformation (a deterministic input→output computation) entangled inside an imperative-shell or orchestration method, where it could be a named, separately-testable function. The architectural defect being real, not its line count or "how much it works today," sets the severity; rate a non-fundamental finding by its eventual cost — the recorded horizon sets that cost; fundamentals stay 🔴 at every horizon (Core Philosophy: rigor follows the horizon). +**Verdict and severities: ~/.claude/skills/larv-review/review-findings.md.** A violation of a non-negotiable fundamental — functional-core/shell entanglement, a unit past a Fits in a head threshold without a stated reason, a method or file carrying more than one responsibility, unreasoned duplication of a core concept, or a broken/leaky external contract — is a 🔴: lead with it, and name the concrete restructuring. The most common instance: a pure transformation (a deterministic input→output computation) entangled inside an imperative-shell or orchestration method, where it could be a named, separately-testable function. The architectural defect being real, not its line count or "how much it works today," sets the severity; rate a non-fundamental finding by its eventual cost — the recorded horizon sets that cost; fundamentals stay 🔴 at every horizon (Core Philosophy: rigor follows the horizon). Focus on architectural alignment: - Does it still serve the project's goals and priorities, or has it quietly drifted from them? diff --git a/bin/loop_claude/claude_code/__init__.py b/bin/loop_claude/claude_code/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/bin/loop_claude/claude_code.py b/bin/loop_claude/claude_code/formats.py similarity index 100% rename from bin/loop_claude/claude_code.py rename to bin/loop_claude/claude_code/formats.py diff --git a/bin/loop_claude/session.py b/bin/loop_claude/claude_code/session.py similarity index 87% rename from bin/loop_claude/session.py rename to bin/loop_claude/claude_code/session.py index 8198ce99..fcc33fc7 100644 --- a/bin/loop_claude/session.py +++ b/bin/loop_claude/claude_code/session.py @@ -5,8 +5,8 @@ import shutil import sys import uuid -from loop_claude.checkout import project_name -from loop_claude.claude_code import session_files, transcript_path +from loop_claude.project.checkout import project_name +from loop_claude.claude_code.formats import session_files, transcript_path NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec") diff --git a/bin/loop_claude/transcript.py b/bin/loop_claude/claude_code/transcript.py similarity index 89% rename from bin/loop_claude/transcript.py rename to bin/loop_claude/claude_code/transcript.py index 2ddf768e..e73ffdbb 100644 --- a/bin/loop_claude/transcript.py +++ b/bin/loop_claude/claude_code/transcript.py @@ -1,6 +1,6 @@ import json -from loop_claude.claude_code import assistant_parts, human_text, parse, part_text, tool_call +from loop_claude.claude_code.formats import assistant_parts, human_text, parse, part_text, tool_call from loop_claude.outcome import Failure diff --git a/bin/loop_claude/trust.py b/bin/loop_claude/claude_code/trust.py similarity index 91% rename from bin/loop_claude/trust.py rename to bin/loop_claude/claude_code/trust.py index 68d9b4e7..715254d5 100644 --- a/bin/loop_claude/trust.py +++ b/bin/loop_claude/claude_code/trust.py @@ -1,7 +1,7 @@ import json import sys -from loop_claude.claude_code import mark_trusted, trust_records +from loop_claude.claude_code.formats import mark_trusted, trust_records from loop_claude.file_writes import replace_json from loop_claude.outcome import Failure diff --git a/bin/loop_claude/claude_runs/__init__.py b/bin/loop_claude/claude_runs/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/bin/loop_claude/interrupt.py b/bin/loop_claude/claude_runs/interrupt.py similarity index 85% rename from bin/loop_claude/interrupt.py rename to bin/loop_claude/claude_runs/interrupt.py index 5a965f7d..8b291b27 100644 --- a/bin/loop_claude/interrupt.py +++ b/bin/loop_claude/claude_runs/interrupt.py @@ -2,10 +2,10 @@ import subprocess import sys from loop_claude import human -from loop_claude.checkout import checkouts +from loop_claude.project.checkout import checkouts from loop_claude.outcome import Failure, Stop -from loop_claude.transcript import human_turns, read -from loop_claude.trust import trust +from loop_claude.claude_code.transcript import human_turns, read +from loop_claude.claude_code.trust import trust TO = "answer the question above" diff --git a/bin/loop_claude/judge.py b/bin/loop_claude/claude_runs/judge.py similarity index 98% rename from bin/loop_claude/judge.py rename to bin/loop_claude/claude_runs/judge.py index 943586ad..d1908bd8 100644 --- a/bin/loop_claude/judge.py +++ b/bin/loop_claude/claude_runs/judge.py @@ -2,7 +2,7 @@ import itertools import json import subprocess -from loop_claude.claude_code import structured_output +from loop_claude.claude_code.formats import structured_output from loop_claude.outcome import Failure from loop_claude.retry import stop_or_sleep_a_minute diff --git a/bin/loop_claude/worker.py b/bin/loop_claude/claude_runs/worker.py similarity index 90% rename from bin/loop_claude/worker.py rename to bin/loop_claude/claude_runs/worker.py index ec73096f..836c2b72 100644 --- a/bin/loop_claude/worker.py +++ b/bin/loop_claude/claude_runs/worker.py @@ -1,8 +1,8 @@ import subprocess -from loop_claude.claude_code import assistant_parts, ends_stream, parse +from loop_claude.claude_code.formats import assistant_parts, ends_stream, parse from loop_claude.outcome import Failure -from loop_claude.transcript import part_line +from loop_claude.claude_code.transcript import part_line def run_worker(root, args): diff --git a/bin/loop_claude/cycle.py b/bin/loop_claude/cycle.py index 14055c31..2e2997ef 100644 --- a/bin/loop_claude/cycle.py +++ b/bin/loop_claude/cycle.py @@ -1,14 +1,14 @@ import hashlib import sys -from loop_claude.checkout import project_name +from loop_claude.project.checkout import project_name from loop_claude.file_writes import make_private, replace_file -from loop_claude.interrupt import interrupt -from loop_claude.judge import judge +from loop_claude.claude_runs.interrupt import interrupt +from loop_claude.claude_runs.judge import judge from loop_claude.outcome import Continue, Failure, Stop -from loop_claude.session import delete_session, session_for, transcript_file -from loop_claude.transcript import read, render -from loop_claude.worker import run_worker, worker_args +from loop_claude.claude_code.session import delete_session, session_for, transcript_file +from loop_claude.claude_code.transcript import read, render +from loop_claude.claude_runs.worker import run_worker, worker_args def run_cycle(root, task, premises, models, paths): diff --git a/bin/loop_claude/main.py b/bin/loop_claude/main.py index 37c2c262..6d331777 100644 --- a/bin/loop_claude/main.py +++ b/bin/loop_claude/main.py @@ -30,17 +30,17 @@ and read each cycle; a project without an entry, as on its first run, is asked f LOOP_CLAUDE_JUDGE_MODEL overrides it for the judge, LOOP_CLAUDE_WORKER_MODEL for the worker and the interrupt; with both set, nothing is asked. -A change to bin/loop-claude or bin/loop_claude/*.py takes effect at the next cycle boundary, once +A change to bin/loop-claude or bin/loop_claude/**/*.py takes effect at the next cycle boundary, once loop-claude --help succeeds. """ import dataclasses import sys -from loop_claude.checkout import checkout_root +from loop_claude.project.checkout import checkout_root from loop_claude.cycle import run_cycle -from loop_claude.models import project_models +from loop_claude.project.models import project_models from loop_claude.outcome import Continue, Failure, Stop -from loop_claude.premises import read_premises +from loop_claude.project.premises import read_premises from loop_claude.reload import RELOAD_FLAG, decode_state, exec_if_edited, fingerprint from loop_claude.retry import stop_or_sleep_a_minute diff --git a/bin/loop_claude/paths.py b/bin/loop_claude/paths.py index 7f42eabe..ba1153bb 100644 --- a/bin/loop_claude/paths.py +++ b/bin/loop_claude/paths.py @@ -1,7 +1,7 @@ import dataclasses import pathlib -from loop_claude.claude_code import locations +from loop_claude.claude_code.formats import locations @dataclasses.dataclass(frozen=True) diff --git a/bin/loop_claude/project/__init__.py b/bin/loop_claude/project/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/bin/loop_claude/checkout.py b/bin/loop_claude/project/checkout.py similarity index 100% rename from bin/loop_claude/checkout.py rename to bin/loop_claude/project/checkout.py diff --git a/bin/loop_claude/models.py b/bin/loop_claude/project/models.py similarity index 96% rename from bin/loop_claude/models.py rename to bin/loop_claude/project/models.py index fa02b44a..4b3d122e 100644 --- a/bin/loop_claude/models.py +++ b/bin/loop_claude/project/models.py @@ -3,8 +3,8 @@ import json import sys from loop_claude import human -from loop_claude.checkout import project_name -from loop_claude.claude_code import catalog +from loop_claude.project.checkout import project_name +from loop_claude.claude_code.formats import catalog from loop_claude.file_writes import replace_json from loop_claude.outcome import Stop diff --git a/bin/loop_claude/premises.py b/bin/loop_claude/project/premises.py similarity index 100% rename from bin/loop_claude/premises.py rename to bin/loop_claude/project/premises.py diff --git a/bin/loop_claude/reload.py b/bin/loop_claude/reload.py index 4e8f7af6..ba23f9b5 100644 --- a/bin/loop_claude/reload.py +++ b/bin/loop_claude/reload.py @@ -23,12 +23,12 @@ def decode_state(handed, kind): def fingerprint(launcher): digest = hashlib.sha256() - for path in [launcher, *sorted((launcher.parent / "loop_claude").glob("*.py"))]: + for path in [launcher, *sorted((launcher.parent / "loop_claude").rglob("*.py"))]: try: content = path.read_bytes() except OSError as failure: content = str(failure).encode() - digest.update(f"{path.name}\0{len(content)}\0".encode() + content) + digest.update(f"{path.relative_to(launcher.parent)}\0{len(content)}\0".encode() + content) return digest.hexdigest() diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 09e6a87b..28674499 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -7,8 +7,11 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -from loop_claude import claude_code, file_writes, judge, main, premises, transcript +from loop_claude import file_writes, main +from loop_claude.claude_code import formats, transcript +from loop_claude.claude_runs import judge from loop_claude.outcome import Failure, Stop +from loop_claude.project import premises CWD = pathlib.Path("/c") @@ -68,9 +71,9 @@ class PartLine(unittest.TestCase): class Parse(unittest.TestCase): def test_yields_only_json_objects(self): - self.assertEqual(claude_code.parse('{"type": "user"}'), {"type": "user"}) - self.assertIsNone(claude_code.parse("not json")) - self.assertIsNone(claude_code.parse("[1, 2]")) + self.assertEqual(formats.parse('{"type": "user"}'), {"type": "user"}) + self.assertIsNone(formats.parse("not json")) + self.assertIsNone(formats.parse("[1, 2]")) class Grounded(unittest.TestCase): diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 90b8ce99..0a48d32f 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -9,7 +9,7 @@ You orchestrate, fix, and ship; reviewers only report. Run every reviewer synchr **Forge-neutral.** Five PR operations recur below: read a PR's diff, open a draft PR, read check status, mark ready, merge. Resolve the tooling from the remote per `~/.claude/CLAUDE.md` → "Git, commits, and PRs"; on any other forge, achieve the same intents through its CLI or API — discover how rather than assuming. A forge without a native draft state gets the closest equivalent (a `WIP:`/`Draft:` title prefix); note any approximation in the summary. -Words: `~/.claude/CLAUDE.md` → "Vocabulary". Findings, for every reviewer: ~/.claude/principles/review-findings.md. +Words: `~/.claude/CLAUDE.md` → "Vocabulary". Findings, for every reviewer: ~/.claude/skills/larv-review/review-findings.md. ## 1. Preconditions diff --git a/principles/review-findings.md b/skills/larv-review/review-findings.md similarity index 100% rename from principles/review-findings.md rename to skills/larv-review/review-findings.md diff --git a/todo.md b/todo.md index e11ccd80..b0495a52 100644 --- a/todo.md +++ b/todo.md @@ -8,7 +8,6 @@ The rebuild lifts every dimension: each item below is one chunk on a worktree ba The places the panel on `rebuild` at 37edc9a named (`docs/decisions.md`), capping dimension first: -- **Group `bin/loop_claude/`'s 18 flat modules, and move `principles/review-findings.md` beside larv-review.** Two seats; `claude_code.py` is the first group. - **Show the judge a reply the human sends while claude works.** Claude Code 2.1.284 writes it as an `"attachment"` entry, which `render` drops, so the judge can rule on a question the human already answered during an interrupt. - **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. -- 2.52.0 From cca0b67b8bbae9d221849591a0631338a9b74786 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 21:32:27 +0200 Subject: [PATCH 071/233] Name the project once in main, and give the archive its own module --- bin/loop_claude/archive.py | 23 +++++++++++++ bin/loop_claude/claude_code/session.py | 5 ++- bin/loop_claude/claude_runs/interrupt.py | 4 +-- bin/loop_claude/claude_runs/worker.py | 2 +- bin/loop_claude/cycle.py | 41 ++++++------------------ bin/loop_claude/main.py | 9 +++--- bin/loop_claude/project/models.py | 5 ++- 7 files changed, 45 insertions(+), 44 deletions(-) create mode 100644 bin/loop_claude/archive.py diff --git a/bin/loop_claude/archive.py b/bin/loop_claude/archive.py new file mode 100644 index 00000000..50843a72 --- /dev/null +++ b/bin/loop_claude/archive.py @@ -0,0 +1,23 @@ +import hashlib +import sys + +from loop_claude.file_writes import make_private, replace_file +from loop_claude.outcome import Failure + + +def archive(project, path, note, paths): + folder = paths.archive / project + try: + with open(path, "rb") as handle: + raw = handle.read() + make_private(folder) + except OSError as failure: + return Failure(f"could not archive the transcript: {failure.filename}: {failure.strerror}") + copy = folder / f"{hashlib.sha256(raw).hexdigest()}.jsonl" + # 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}") + print(f"transcript: {copy}", file=sys.stderr) + return None diff --git a/bin/loop_claude/claude_code/session.py b/bin/loop_claude/claude_code/session.py index fcc33fc7..3c9f09e6 100644 --- a/bin/loop_claude/claude_code/session.py +++ b/bin/loop_claude/claude_code/session.py @@ -5,7 +5,6 @@ import shutil import sys import uuid -from loop_claude.project.checkout import project_name from loop_claude.claude_code.formats import session_files, transcript_path NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec") @@ -18,10 +17,10 @@ class Session: projects: pathlib.Path -def session_for(root, paths): +def session_for(project, paths): """Exists while its transcript does.""" # "A " is the human's cue in the session picker that the session is the loop's. - name = f"A {project_name(root, paths.code)} loop-claude" + name = f"A {project} loop-claude" return Session(uuid.uuid5(NAMESPACE, name), name, paths.projects) diff --git a/bin/loop_claude/claude_runs/interrupt.py b/bin/loop_claude/claude_runs/interrupt.py index 8b291b27..cfff5fc9 100644 --- a/bin/loop_claude/claude_runs/interrupt.py +++ b/bin/loop_claude/claude_runs/interrupt.py @@ -2,10 +2,10 @@ import subprocess import sys from loop_claude import human -from loop_claude.project.checkout import checkouts -from loop_claude.outcome import Failure, Stop from loop_claude.claude_code.transcript import human_turns, read from loop_claude.claude_code.trust import trust +from loop_claude.outcome import Failure, Stop +from loop_claude.project.checkout import checkouts TO = "answer the question above" diff --git a/bin/loop_claude/claude_runs/worker.py b/bin/loop_claude/claude_runs/worker.py index 836c2b72..3d0c6bdc 100644 --- a/bin/loop_claude/claude_runs/worker.py +++ b/bin/loop_claude/claude_runs/worker.py @@ -1,8 +1,8 @@ import subprocess from loop_claude.claude_code.formats import assistant_parts, ends_stream, parse -from loop_claude.outcome import Failure from loop_claude.claude_code.transcript import part_line +from loop_claude.outcome import Failure def run_worker(root, args): diff --git a/bin/loop_claude/cycle.py b/bin/loop_claude/cycle.py index 2e2997ef..c4e66d37 100644 --- a/bin/loop_claude/cycle.py +++ b/bin/loop_claude/cycle.py @@ -1,35 +1,31 @@ -import hashlib -import sys - -from loop_claude.project.checkout import project_name -from loop_claude.file_writes import make_private, replace_file -from loop_claude.claude_runs.interrupt import interrupt -from loop_claude.claude_runs.judge import judge -from loop_claude.outcome import Continue, Failure, Stop +from loop_claude.archive import archive from loop_claude.claude_code.session import delete_session, session_for, transcript_file from loop_claude.claude_code.transcript import read, render +from loop_claude.claude_runs.interrupt import interrupt +from loop_claude.claude_runs.judge import judge from loop_claude.claude_runs.worker import run_worker, worker_args +from loop_claude.outcome import Continue, Failure, Stop -def run_cycle(root, task, premises, models, paths): - session = session_for(root, paths) +def run_cycle(root, project, task, premises, models, paths): + session = session_for(project, paths) resuming = bool(transcript_file(session)) if failure := run_worker(root, worker_args(task, session, models.worker, resuming)): return failure path = transcript_file(session) if not path: return Stop(1, f"claude left no transcript for session {session.id}") - verdict = judge_through_interrupts(root, task, premises, models, session, path, paths) + verdict = judge_through_interrupts(root, project, task, premises, models, session, path, paths) if isinstance(verdict, Stop): return verdict if verdict["finished"]: - if failure := archive(root, path, f"Task: {task}\n\nVerdict: finished", paths): + if failure := archive(project, path, f"Task: {task}\n\nVerdict: finished", paths): return Stop(1, failure.reason) delete_session(session) return Continue() -def judge_through_interrupts(root, task, premises, models, session, path, paths): +def judge_through_interrupts(root, project, task, premises, models, session, path, paths): # The interrupt appends to this transcript, so each pass judges and archives it anew. while True: entries = read(path) @@ -38,25 +34,8 @@ def judge_through_interrupts(root, task, premises, models, session, path, paths) verdict = judge(root, task, premises, render(entries), models.judge) if isinstance(verdict, Stop) or not verdict["interrupt"]: return verdict - if failure := archive(root, path, f"Task: {task}\n\nVerdict: interrupt\n\n{verdict['question']}", paths): + if failure := archive(project, path, f"Task: {task}\n\nVerdict: interrupt\n\n{verdict['question']}", paths): return Stop(1, failure.reason) if stop := interrupt(root, session.id, models.worker, path, verdict["question"], paths): return stop - -def archive(root, path, note, paths): - folder = paths.archive / project_name(root, paths.code) - try: - with open(path, "rb") as handle: - raw = handle.read() - make_private(folder) - except OSError as failure: - return Failure(f"could not archive the transcript: {failure.filename}: {failure.strerror}") - copy = folder / f"{hashlib.sha256(raw).hexdigest()}.jsonl" - # 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}") - print(f"transcript: {copy}", file=sys.stderr) - return None diff --git a/bin/loop_claude/main.py b/bin/loop_claude/main.py index 6d331777..5819a626 100644 --- a/bin/loop_claude/main.py +++ b/bin/loop_claude/main.py @@ -36,10 +36,10 @@ loop-claude --help succeeds. import dataclasses import sys -from loop_claude.project.checkout import checkout_root from loop_claude.cycle import run_cycle -from loop_claude.project.models import project_models from loop_claude.outcome import Continue, Failure, Stop +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 from loop_claude.reload import RELOAD_FLAG, decode_state, exec_if_edited, fingerprint from loop_claude.retry import stop_or_sleep_a_minute @@ -68,17 +68,18 @@ def run_loop(argv, env, paths, launcher, cwd): if isinstance(state, Stop): return state baseline = fingerprint(launcher) + project = project_name(state.root, paths.code) while True: exec_if_edited(launcher, baseline, state) state = dataclasses.replace(state, cycle_number=state.cycle_number + 1) premises = read_premises(state.root) if isinstance(premises, Stop): return premises - models = project_models(state.root, paths, env) + models = project_models(project, paths, env) if isinstance(models, Stop): return models print(f"\n=== cycle {state.cycle_number} ===", flush=True) - match run_cycle(state.root, state.task, premises, models, paths): + match run_cycle(state.root, project, state.task, premises, models, paths): case Stop() as stop: return stop case Failure(reason): diff --git a/bin/loop_claude/project/models.py b/bin/loop_claude/project/models.py index 4b3d122e..3a75272b 100644 --- a/bin/loop_claude/project/models.py +++ b/bin/loop_claude/project/models.py @@ -3,7 +3,6 @@ import json import sys from loop_claude import human -from loop_claude.project.checkout import project_name from loop_claude.claude_code.formats import catalog from loop_claude.file_writes import replace_json from loop_claude.outcome import Stop @@ -15,11 +14,11 @@ class Models: worker: str -def project_models(root, paths, env): +def project_models(project, paths, env): judge, worker = env.get("LOOP_CLAUDE_JUDGE_MODEL"), env.get("LOOP_CLAUDE_WORKER_MODEL") if judge and worker: return Models(judge, worker) - chosen = project_model(project_name(root, paths.code), paths) + chosen = project_model(project, paths) if isinstance(chosen, Stop): return chosen return Models(judge or chosen, worker or chosen) -- 2.52.0 From 1bcef56657919dfc96dd1f80f0c5de7f531d0160 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 21:35:58 +0200 Subject: [PATCH 072/233] Allowlist loop_claude's modules at any depth --- .gitignore | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index 24919d6e..a862cce1 100644 --- a/.gitignore +++ b/.gitignore @@ -20,8 +20,8 @@ !bin/ !bin/* !bin/loop_claude/*.py -!bin/loop_claude/*/ -!bin/loop_claude/*/*.py +!bin/loop_claude/**/ +!bin/loop_claude/**/*.py !docs/ !docs/*.md !principles/ -- 2.52.0 From 75529c8592a8ffbf586fd2eced3d325d79439cc4 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 21:36:03 +0200 Subject: [PATCH 073/233] Drop the allowlist line the any-depth rule covers --- .gitignore | 1 - 1 file changed, 1 deletion(-) diff --git a/.gitignore b/.gitignore index a862cce1..ba2981f2 100644 --- a/.gitignore +++ b/.gitignore @@ -19,7 +19,6 @@ !agents/*.md !bin/ !bin/* -!bin/loop_claude/*.py !bin/loop_claude/**/ !bin/loop_claude/**/*.py !docs/ -- 2.52.0 From e90b7cb9d72a57d97766a981cf7ae575d4df4305 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 21:38:04 +0200 Subject: [PATCH 074/233] Drop the plan's second statement of where a rebuild chunk's PR goes --- todo.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/todo.md b/todo.md index b0495a52..b9af9e2d 100644 --- a/todo.md +++ b/todo.md @@ -4,7 +4,7 @@ **⚠️ THE REBUILD NEVER MERGES INTO MAIN WITHOUT THE HUMAN'S EXPLICIT APPROVAL.** Every rebuild chunk is a worktree based on `origin/rebuild` with its PR into `rebuild`, never into main. Other sessions run on `~/.claude` main throughout; only the human merges `rebuild` into main, once they have approved the finished whole. -The rebuild lifts every dimension: each item below is one chunk on a worktree based on `origin/rebuild`, its PR into `rebuild`, until the last item opens `rebuild`'s PR into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. +The rebuild lifts every dimension, one chunk per item, until the last item opens `rebuild`'s PR into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. The places the panel on `rebuild` at 37edc9a named (`docs/decisions.md`), capping dimension first: -- 2.52.0 From 7f9de5c19ff4d2cc609d4e5594d01bf1450fb576 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 21:49:06 +0200 Subject: [PATCH 075/233] Show the judge a reply the human types while claude works --- CHANGELOG.md | 1 + bin/loop_claude/claude_code/formats.py | 11 +++++++++++ bin/test_loop_claude.py | 13 +++++++++++-- todo.md | 1 - 4 files changed, 23 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index db65e201..060aa525 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,5 +10,6 @@ - `loop-claude`'s judge quotes the transcript for every verdict, and a verdict quoting nothing or interrupting without a question, or a `claude` the judge cannot start, is a failed judge run; a `claude` that cannot start for an interrupt exits 1. - `loop-claude`'s exit-2 message says what the human is needed for. - `loop-claude` counts an interrupt reply starting with `<` as typed. +- `loop-claude`'s judge sees a reply the human types while claude works, and an interrupt counts one as typed. - `loop-claude`'s archive holds the raw `.jsonl` transcript, one copy per distinct transcript, named by its SHA-256, with the verdict beside it in `.verdict.md`; a transcript it cannot archive exits 1. - `loop-claude` keeps the mode of `~/.claude.json` and of its models file when it rewrites them, and creates the models file 0600. diff --git a/bin/loop_claude/claude_code/formats.py b/bin/loop_claude/claude_code/formats.py index bb762c8e..33692f71 100644 --- a/bin/loop_claude/claude_code/formats.py +++ b/bin/loop_claude/claude_code/formats.py @@ -84,12 +84,23 @@ def user_entry_kind(entry): def human_text(entry): """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 if entry.get("type") != "user" or user_entry_kind(entry) is not UserEntryKind.HUMAN: return None text = content(entry) return text if isinstance(text, str) else "".join(part_text(part) or "" for part in parts(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): + 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 + return prompt if isinstance(prompt := attachment.get("prompt"), str) else None + + # {"type": "text", "text": "ok"} def part_text(part): return part["text"] if isinstance(part, dict) and part.get("type") == "text" and isinstance(part.get("text"), str) else None diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 28674499..37879d6c 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -24,6 +24,10 @@ def human(content): return {"type": "user", "message": {"content": content}} +def queued(prompt, kind): + return {"type": "attachment", "attachment": {"type": "queued_command", "commandMode": "prompt", "origin": {"kind": kind}, "prompt": prompt}} + + class Sections(unittest.TestCase): def test_keeps_every_headed_section_with_its_bodies(self): text = "# Title\n\nintro\n\n## Goals\n\n1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority\n\n## Empty\n\n## Audience\nme\n## Audience\nagain\n# Appendix\nnot audience\n" @@ -39,9 +43,11 @@ class Render(unittest.TestCase): human([{"type": "tool_result", "content": "not typed"}]), human("/exit"), human([{"type": "text", "text": "yes, "}, {"type": "text", "text": "merge it"}]), + queued("B, while you work", "human"), + queued("origin/main moved", "coordinator"), {**human("Continue the task; the previous run stopped before it was finished."), "promptSource": "sdk"}, ]) - self.assertEqual(said, '[human] do it\n\nStarting.\n\n[tool Bash] {"command": "ls"}\n\n[human] yes, merge it') + self.assertEqual(said, '[human] do it\n\nStarting.\n\n[tool Bash] {"command": "ls"}\n\n[human] yes, merge it\n\n[human] B, while you work') class HumanTurns(unittest.TestCase): @@ -57,8 +63,11 @@ class HumanTurns(unittest.TestCase): {**human("the loop's own prompt"), "promptSource": "sdk"}, human([{"type": "text", "text": "[Request interrupted by user]"}]), human([]), + queued("typed while claude worked", "human"), + queued("done", "task-notification"), + {"type": "attachment", "attachment": {"type": "queued_command", "commandMode": "task-notification", "prompt": "done"}}, assistant({"type": "text", "text": "said"}), - ]), 3) + ]), 4) class PartLine(unittest.TestCase): diff --git a/todo.md b/todo.md index b9af9e2d..bad154ac 100644 --- a/todo.md +++ b/todo.md @@ -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 37edc9a named (`docs/decisions.md`), capping dimension first: -- **Show the judge a reply the human sends while claude works.** Claude Code 2.1.284 writes it as an `"attachment"` entry, which `render` drops, so the judge can rule on a question the human already answered during an interrupt. - **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. ## 0.2.0 -- 2.52.0 From 9d8fa84c750d6f383f5030fea7d4e7947c0ef840 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 21:58:00 +0200 Subject: [PATCH 076/233] File the places the panel on rebuild at 7f9de5c named under the floor --- docs/decisions.md | 2 +- todo.md | 9 ++++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index d99fae11..aec2879a 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -30,7 +30,7 @@ ## comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it -2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` at 37edc9a, later that day, scored 7.5, 6.63, 6.88, 6.5, 7.0; the places they named are filed in `todo.md` under 0.1.0, and a later chunk may not lower any dimension. Valid until the next scoring run, which uses the same four seats. +2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, and 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c; the places the last run named are filed in `todo.md` under 0.1.0, and a later chunk may not lower any dimension. Valid until the next scoring run, which uses the same four seats. ## vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link diff --git a/todo.md b/todo.md index bad154ac..76f7d0b1 100644 --- a/todo.md +++ b/todo.md @@ -6,8 +6,15 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens `rebuild`'s PR into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -The places the panel on `rebuild` at 37edc9a named (`docs/decisions.md`), capping dimension first: +The places the panel on `rebuild` at 7f9de5c named (`docs/decisions.md`), capping dimension first: +- **Return a typed verdict from `judge`, so `cycle.py` reads its fields and only `judge.py` knows the schema's keys.** Three seats: `judge_through_interrupts` indexes a dict that only `incomplete` checked. +- **Make `mark_trusted` return the updated `~/.claude.json`, so `trust` writes what it was handed and `formats.py` mutates nothing.** Three seats: `trust_records` `setdefault`s into the config and `trust` writes `data` changed through an alias. +- **Make `decode_state` check the fields' types without relying on the annotations being runtime types.** Two seats: `from __future__ import annotations` in `main.py` would fail every reload. +- **State once, in `outcome.py`, that a `Failure` is retried and a `Stop` exits.** Three seats inferred it from `run_loop`. +- **Define a round once, in larv-review's "Round cap", and link it from `review-findings.md` → "Rounds", the Vocabulary and the auto-reviewer's step.** All four seats held §3, "Rounds" and the Vocabulary open together to settle whether a launch counts. +- **Give `project` one meaning: rename `Paths.projects` and `Session.projects` for Claude Code's transcript directory.** Two seats: it also names the package, the key and `~/.claude.json`'s object. +- **Name `human.py` for the exit-2 stops it holds.** One seat looked there for the prompts, which live in `models.py` and `interrupt.py`. - **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. ## 0.2.0 -- 2.52.0 From 8b45f1f39b3370d4cc2684d962ab3185c02a2a98 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 22:00:16 +0200 Subject: [PATCH 077/233] Return a typed verdict from the judge --- bin/loop_claude/claude_runs/judge.py | 34 ++++++++++++++++------------ bin/loop_claude/cycle.py | 8 +++---- bin/test_loop_claude.py | 20 ++++++++-------- todo.md | 1 - 4 files changed, 35 insertions(+), 28 deletions(-) diff --git a/bin/loop_claude/claude_runs/judge.py b/bin/loop_claude/claude_runs/judge.py index d1908bd8..2934c2a3 100644 --- a/bin/loop_claude/claude_runs/judge.py +++ b/bin/loop_claude/claude_runs/judge.py @@ -1,3 +1,4 @@ +import dataclasses import itertools import json import subprocess @@ -26,6 +27,14 @@ JUDGE_RULES = ( "not yet run, CI not yet reported." ) +@dataclasses.dataclass(frozen=True) +class Verdict: + evidence: str + finished: bool + interrupt: bool + question: str + + JUDGE_SCHEMA = { "properties": { "evidence": {"description": "A verbatim quote of the transcript line the verdict rests on: what triggers the interrupt, else what shows the chunk finished or the work remaining.", "type": "string"}, @@ -54,10 +63,8 @@ def judge(root, task, premises, transcript, model): verdict = run_judge(root, args, prompt) if isinstance(verdict, Failure): reason = verdict.reason - elif reason := incomplete(verdict): - pass elif not grounded(verdict, transcript): - reason = f"the judge quoted {verdict['evidence']!r}, nothing in the transcript" + (f", for the question: {verdict['question']}" if verdict["interrupt"] else "") + reason = f"the judge quoted {verdict.evidence!r}, nothing in the transcript" + (f", for the question: {verdict.question}" if verdict.interrupt else "") else: return verdict if stop := stop_or_sleep_a_minute("judge", failures, reason): @@ -71,7 +78,7 @@ def run_judge(root, args, prompt): return Failure(f"could not start claude: {failure.strerror}") if proc.returncode != 0: return Failure(proc.stderr.strip() or f"the judge exited {proc.returncode}") - return structured_output(proc.stdout) + return verdict_from(structured_output(proc.stdout)) def judge_prompt(task, premises, transcript): @@ -84,18 +91,17 @@ def judge_prompt(task, premises, transcript): ) -def incomplete(verdict): - if not isinstance(verdict, dict): - return "the judge returned no verdict" +def verdict_from(output): + if not isinstance(output, dict): + return Failure("the judge returned no verdict") for name in JUDGE_SCHEMA["required"]: kind = JUDGE_SCHEMA["properties"][name]["type"] - if not isinstance(verdict.get(name), bool if kind == "boolean" else str): - return f"the judge's verdict has no {name} of type {kind}" - if verdict["interrupt"] and not verdict["question"].strip(): - return "the judge interrupted without a question" - return None + if not isinstance(output.get(name), bool if kind == "boolean" else str): + return Failure(f"the judge's verdict has no {name} of type {kind}") + if output["interrupt"] and not output["question"].strip(): + return Failure("the judge interrupted without a question") + return Verdict(**{name: output[name] for name in JUDGE_SCHEMA["required"]}) def grounded(verdict, transcript): - evidence = verdict["evidence"] - return evidence.strip() != "" and evidence in transcript + return verdict.evidence.strip() != "" and verdict.evidence in transcript diff --git a/bin/loop_claude/cycle.py b/bin/loop_claude/cycle.py index c4e66d37..da51fa58 100644 --- a/bin/loop_claude/cycle.py +++ b/bin/loop_claude/cycle.py @@ -18,7 +18,7 @@ def run_cycle(root, project, task, premises, models, paths): verdict = judge_through_interrupts(root, project, task, premises, models, session, path, paths) if isinstance(verdict, Stop): return verdict - if verdict["finished"]: + if verdict.finished: if failure := archive(project, path, f"Task: {task}\n\nVerdict: finished", paths): return Stop(1, failure.reason) delete_session(session) @@ -32,10 +32,10 @@ def judge_through_interrupts(root, project, task, premises, models, session, pat if isinstance(entries, Failure): return Stop(1, entries.reason) verdict = judge(root, task, premises, render(entries), models.judge) - if isinstance(verdict, Stop) or not verdict["interrupt"]: + if isinstance(verdict, Stop) or not verdict.interrupt: return verdict - if failure := archive(project, path, f"Task: {task}\n\nVerdict: interrupt\n\n{verdict['question']}", paths): + if failure := archive(project, path, f"Task: {task}\n\nVerdict: interrupt\n\n{verdict.question}", paths): return Stop(1, failure.reason) - if stop := interrupt(root, session.id, models.worker, path, verdict["question"], paths): + if stop := interrupt(root, session.id, models.worker, path, verdict.question, paths): return stop diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 37879d6c..38c715c7 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -88,19 +88,21 @@ class Parse(unittest.TestCase): class Grounded(unittest.TestCase): def test_every_verdict_must_quote_the_transcript(self): for interrupting in (False, True): - self.assertTrue(judge.grounded({"interrupt": interrupting, "evidence": "Needs you: x"}, "so.\n\nNeeds you: x\n")) - self.assertFalse(judge.grounded({"interrupt": interrupting, "evidence": "invented"}, "the transcript")) - self.assertFalse(judge.grounded({"interrupt": interrupting, "evidence": ""}, "the transcript")) - self.assertFalse(judge.grounded({"interrupt": interrupting, "evidence": " "}, "the transcript")) + def verdict(evidence): + return judge.Verdict(evidence=evidence, finished=False, interrupt=interrupting, question="q") + self.assertTrue(judge.grounded(verdict("Needs you: x"), "so.\n\nNeeds you: x\n")) + self.assertFalse(judge.grounded(verdict("invented"), "the transcript")) + self.assertFalse(judge.grounded(verdict(""), "the transcript")) + self.assertFalse(judge.grounded(verdict(" "), "the transcript")) class Verdict(unittest.TestCase): def test_needs_every_field_the_schema_requires(self): - self.assertIsNone(judge.incomplete({"interrupt": False, "evidence": "", "finished": True, "question": ""})) - self.assertEqual(judge.incomplete({"interrupt": "no", "evidence": "", "finished": True, "question": ""}), "the judge's verdict has no interrupt of type boolean") - self.assertEqual(judge.incomplete({"interrupt": False, "evidence": None, "finished": True, "question": ""}), "the judge's verdict has no evidence of type string") - self.assertEqual(judge.incomplete({"interrupt": True, "evidence": "x", "finished": False, "question": " "}), "the judge interrupted without a question") - self.assertEqual(judge.incomplete(None), "the judge returned no verdict") + self.assertEqual(judge.verdict_from({"interrupt": False, "evidence": "", "finished": True, "question": ""}), judge.Verdict(evidence="", finished=True, interrupt=False, question="")) + self.assertEqual(judge.verdict_from({"interrupt": "no", "evidence": "", "finished": True, "question": ""}), Failure("the judge's verdict has no interrupt of type boolean")) + self.assertEqual(judge.verdict_from({"interrupt": False, "evidence": None, "finished": True, "question": ""}), Failure("the judge's verdict has no evidence of type string")) + self.assertEqual(judge.verdict_from({"interrupt": True, "evidence": "x", "finished": False, "question": " "}), Failure("the judge interrupted without a question")) + self.assertEqual(judge.verdict_from(None), Failure("the judge returned no verdict")) class LoopState(unittest.TestCase): diff --git a/todo.md b/todo.md index 76f7d0b1..b3b2906b 100644 --- a/todo.md +++ b/todo.md @@ -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 7f9de5c named (`docs/decisions.md`), capping dimension first: -- **Return a typed verdict from `judge`, so `cycle.py` reads its fields and only `judge.py` knows the schema's keys.** Three seats: `judge_through_interrupts` indexes a dict that only `incomplete` checked. - **Make `mark_trusted` return the updated `~/.claude.json`, so `trust` writes what it was handed and `formats.py` mutates nothing.** Three seats: `trust_records` `setdefault`s into the config and `trust` writes `data` changed through an alias. - **Make `decode_state` check the fields' types without relying on the annotations being runtime types.** Two seats: `from __future__ import annotations` in `main.py` would fail every reload. - **State once, in `outcome.py`, that a `Failure` is retried and a `Stop` exits.** Three seats inferred it from `run_loop`. -- 2.52.0 From 4d746226172fa7289f1c5aeb6de0a622b0636ff8 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 22:02:10 +0200 Subject: [PATCH 078/233] Derive the judge's schema from Verdict --- bin/loop_claude/claude_runs/judge.py | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/bin/loop_claude/claude_runs/judge.py b/bin/loop_claude/claude_runs/judge.py index 2934c2a3..c8f22b18 100644 --- a/bin/loop_claude/claude_runs/judge.py +++ b/bin/loop_claude/claude_runs/judge.py @@ -2,6 +2,7 @@ import dataclasses import itertools import json import subprocess +import typing from loop_claude.claude_code.formats import structured_output from loop_claude.outcome import Failure @@ -29,20 +30,17 @@ JUDGE_RULES = ( @dataclasses.dataclass(frozen=True) class Verdict: - evidence: str + evidence: str = dataclasses.field(metadata={"description": "A verbatim quote of the transcript line the verdict rests on: what triggers the interrupt, else what shows the chunk finished or the work remaining."}) finished: bool interrupt: bool - question: str + question: str = dataclasses.field(metadata={"description": "The single question to put to the human. Empty when interrupt is false."}) +VERDICT_TYPES = typing.get_type_hints(Verdict) +JSON_TYPES = {bool: "boolean", str: "string"} JUDGE_SCHEMA = { - "properties": { - "evidence": {"description": "A verbatim quote of the transcript line the verdict rests on: what triggers the interrupt, else what shows the chunk finished or the work remaining.", "type": "string"}, - "finished": {"type": "boolean"}, - "interrupt": {"type": "boolean"}, - "question": {"description": "The single question to put to the human. Empty when interrupt is false.", "type": "string"}, - }, - "required": ["evidence", "finished", "interrupt", "question"], + "properties": {field.name: {**field.metadata, "type": JSON_TYPES[VERDICT_TYPES[field.name]]} for field in dataclasses.fields(Verdict)}, + "required": list(VERDICT_TYPES), "type": "object", } @@ -94,13 +92,12 @@ def judge_prompt(task, premises, transcript): def verdict_from(output): if not isinstance(output, dict): return Failure("the judge returned no verdict") - for name in JUDGE_SCHEMA["required"]: - kind = JUDGE_SCHEMA["properties"][name]["type"] - if not isinstance(output.get(name), bool if kind == "boolean" else str): - return Failure(f"the judge's verdict has no {name} of type {kind}") + for name, kind in VERDICT_TYPES.items(): + if not isinstance(output.get(name), kind): + return Failure(f"the judge's verdict has no {name} of type {JSON_TYPES[kind]}") if output["interrupt"] and not output["question"].strip(): return Failure("the judge interrupted without a question") - return Verdict(**{name: output[name] for name in JUDGE_SCHEMA["required"]}) + return Verdict(**{name: output[name] for name in VERDICT_TYPES}) def grounded(verdict, transcript): -- 2.52.0 From b95d4fe16b0eff46ee7f827d888434db0f01ca8c Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 22:02:41 +0200 Subject: [PATCH 079/233] Drop the Grounded test's loop over a field grounded never reads --- bin/test_loop_claude.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 38c715c7..9d361fa2 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -87,13 +87,12 @@ class Parse(unittest.TestCase): class Grounded(unittest.TestCase): def test_every_verdict_must_quote_the_transcript(self): - for interrupting in (False, True): - def verdict(evidence): - return judge.Verdict(evidence=evidence, finished=False, interrupt=interrupting, question="q") - self.assertTrue(judge.grounded(verdict("Needs you: x"), "so.\n\nNeeds you: x\n")) - self.assertFalse(judge.grounded(verdict("invented"), "the transcript")) - self.assertFalse(judge.grounded(verdict(""), "the transcript")) - self.assertFalse(judge.grounded(verdict(" "), "the transcript")) + def verdict(evidence): + return judge.Verdict(evidence=evidence, finished=False, interrupt=False, question="") + self.assertTrue(judge.grounded(verdict("Needs you: x"), "so.\n\nNeeds you: x\n")) + self.assertFalse(judge.grounded(verdict("invented"), "the transcript")) + self.assertFalse(judge.grounded(verdict(""), "the transcript")) + self.assertFalse(judge.grounded(verdict(" "), "the transcript")) class Verdict(unittest.TestCase): -- 2.52.0 From 53a3149b250ca562d1b4ba91b7f923be7d990b11 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 22:03:23 +0200 Subject: [PATCH 080/233] File the rewording of One spelling per goal --- todo.md | 1 + 1 file changed, 1 insertion(+) diff --git a/todo.md b/todo.md index b3b2906b..8c17f891 100644 --- a/todo.md +++ b/todo.md @@ -18,5 +18,6 @@ The places the panel on `rebuild` at 7f9de5c named (`docs/decisions.md`), cappin ## 0.2.0 +- **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. - **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. -- 2.52.0 From 4aaad015f627a2325b4c2f61afedbf88dec387a9 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 10:24:57 +0200 Subject: [PATCH 081/233] Return the updated ~/.claude.json from mark_trusted --- bin/loop_claude/claude_code/formats.py | 12 +++--------- bin/loop_claude/claude_code/trust.py | 12 ++++++------ bin/test_loop_claude.py | 10 ++++++++++ todo.md | 1 - 4 files changed, 19 insertions(+), 16 deletions(-) diff --git a/bin/loop_claude/claude_code/formats.py b/bin/loop_claude/claude_code/formats.py index 33692f71..0a7615bb 100644 --- a/bin/loop_claude/claude_code/formats.py +++ b/bin/loop_claude/claude_code/formats.py @@ -122,20 +122,14 @@ def structured_output(stdout): # ~/.claude.json: {"projects": {"/home/me/code/log": {"hasTrustDialogAccepted": true, ...}}, ...} -def trust_records(config): - projects = config.setdefault("projects", {}) if isinstance(config, dict) else None +def mark_trusted(config, roots): + 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') 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") - return projects - - -def mark_trusted(projects, roots): untrusted = [path for path in roots if not projects.get(path, {}).get("hasTrustDialogAccepted")] - for path in untrusted: - projects.setdefault(path, {})["hasTrustDialogAccepted"] = True - return untrusted + return {**config, "projects": {**projects, **{path: {**projects.get(path, {}), "hasTrustDialogAccepted": True} for path in untrusted}}}, untrusted # /*.json: {"fetchedAt": 1790618085238, "catalog": {"config": {"models": [{"id": "claude-opus-5-5", "name": "Opus 5.5", ...}]}}} diff --git a/bin/loop_claude/claude_code/trust.py b/bin/loop_claude/claude_code/trust.py index 715254d5..bec5ac16 100644 --- a/bin/loop_claude/claude_code/trust.py +++ b/bin/loop_claude/claude_code/trust.py @@ -1,7 +1,7 @@ import json import sys -from loop_claude.claude_code.formats import mark_trusted, trust_records +from loop_claude.claude_code.formats import mark_trusted from loop_claude.file_writes import replace_json from loop_claude.outcome import Failure @@ -13,14 +13,14 @@ def trust(config, roots): except (OSError, ValueError) as failure: print(f"could not read {config}: {getattr(failure, 'strerror', failure)}", file=sys.stderr) return - projects = trust_records(data) - if isinstance(projects, Failure): - print(f"could not read {config}: {projects.reason}", file=sys.stderr) + marked = mark_trusted(data, roots) + if isinstance(marked, Failure): + print(f"could not read {config}: {marked.reason}", file=sys.stderr) return - untrusted = mark_trusted(projects, roots) + updated, untrusted = marked if not untrusted: return - if failure := replace_json(config, data, indent=2): + if failure := replace_json(config, updated, indent=2): print(f"could not write {config}: {failure.reason}", file=sys.stderr) return print("trusted for the interrupt: " + ", ".join(untrusted), file=sys.stderr) diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 9d361fa2..aeb62115 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -85,6 +85,16 @@ class Parse(unittest.TestCase): self.assertIsNone(formats.parse("[1, 2]")) +class MarkTrusted(unittest.TestCase): + def test_returns_the_updated_config_and_leaves_the_one_it_was_handed(self): + config = {"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True}, "/b": {"kept": True}}} + handed = json.dumps(config) + self.assertEqual(formats.mark_trusted(config, ["/a", "/b", "/c"]), ({"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True}, "/b": {"hasTrustDialogAccepted": True, "kept": True}, "/c": {"hasTrustDialogAccepted": True}}}, ["/b", "/c"])) + self.assertEqual(json.dumps(config), handed) + self.assertEqual(formats.mark_trusted({}, ["/a"]), ({"projects": {"/a": {"hasTrustDialogAccepted": True}}}, ["/a"])) + self.assertEqual(formats.mark_trusted({"projects": {"/a": 1}}, ["/a"]), Failure('projects["/a"] is not an object')) + + class Grounded(unittest.TestCase): def test_every_verdict_must_quote_the_transcript(self): def verdict(evidence): diff --git a/todo.md b/todo.md index 8c17f891..b7418871 100644 --- a/todo.md +++ b/todo.md @@ -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 7f9de5c named (`docs/decisions.md`), capping dimension first: -- **Make `mark_trusted` return the updated `~/.claude.json`, so `trust` writes what it was handed and `formats.py` mutates nothing.** Three seats: `trust_records` `setdefault`s into the config and `trust` writes `data` changed through an alias. - **Make `decode_state` check the fields' types without relying on the annotations being runtime types.** Two seats: `from __future__ import annotations` in `main.py` would fail every reload. - **State once, in `outcome.py`, that a `Failure` is retried and a `Stop` exits.** Three seats inferred it from `run_loop`. - **Define a round once, in larv-review's "Round cap", and link it from `review-findings.md` → "Rounds", the Vocabulary and the auto-reviewer's step.** All four seats held §3, "Rounds" and the Vocabulary open together to settle whether a launch counts. -- 2.52.0 From f4f996f124679fa28187dc22cc6bcb926a014752 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 10:26:36 +0200 Subject: [PATCH 082/233] Drop the unit assertion the black-box test covers --- bin/test_loop_claude.py | 1 - 1 file changed, 1 deletion(-) diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index aeb62115..6aeca665 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -92,7 +92,6 @@ class MarkTrusted(unittest.TestCase): self.assertEqual(formats.mark_trusted(config, ["/a", "/b", "/c"]), ({"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True}, "/b": {"hasTrustDialogAccepted": True, "kept": True}, "/c": {"hasTrustDialogAccepted": True}}}, ["/b", "/c"])) self.assertEqual(json.dumps(config), handed) self.assertEqual(formats.mark_trusted({}, ["/a"]), ({"projects": {"/a": {"hasTrustDialogAccepted": True}}}, ["/a"])) - self.assertEqual(formats.mark_trusted({"projects": {"/a": 1}}, ["/a"]), Failure('projects["/a"] is not an object')) class Grounded(unittest.TestCase): -- 2.52.0 From b69b37b334a256acfefa42e24be79530c3aacf3b Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 10:27:03 +0200 Subject: [PATCH 083/233] Name the records mark_trusted adds --- bin/loop_claude/claude_code/formats.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/bin/loop_claude/claude_code/formats.py b/bin/loop_claude/claude_code/formats.py index 0a7615bb..aa79a2a5 100644 --- a/bin/loop_claude/claude_code/formats.py +++ b/bin/loop_claude/claude_code/formats.py @@ -129,7 +129,8 @@ def mark_trusted(config, roots): 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") untrusted = [path for path in roots if not projects.get(path, {}).get("hasTrustDialogAccepted")] - return {**config, "projects": {**projects, **{path: {**projects.get(path, {}), "hasTrustDialogAccepted": True} for path in untrusted}}}, untrusted + marked = {path: {**projects.get(path, {}), "hasTrustDialogAccepted": True} for path in untrusted} + return {**config, "projects": {**projects, **marked}}, untrusted # /*.json: {"fetchedAt": 1790618085238, "catalog": {"config": {"models": [{"id": "claude-opus-5-5", "name": "Opus 5.5", ...}]}}} -- 2.52.0 From d9058d2d7ed5f9e718b79e80237c8ed922b3ecd2 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 10:29:08 +0200 Subject: [PATCH 084/233] Resolve decode_state's field types from string annotations too --- bin/loop_claude/reload.py | 3 ++- bin/test_loop_claude.py | 11 ++++++++++- todo.md | 1 - 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/bin/loop_claude/reload.py b/bin/loop_claude/reload.py index ba23f9b5..9419dd07 100644 --- a/bin/loop_claude/reload.py +++ b/bin/loop_claude/reload.py @@ -4,6 +4,7 @@ import json import os import subprocess import sys +import typing RELOAD_FLAG = "--reloaded" @@ -13,7 +14,7 @@ def decode_state(handed, kind): fields = json.loads(handed) except ValueError: return None - shape = {field.name: field.type for field in dataclasses.fields(kind)} + shape = typing.get_type_hints(kind) if not isinstance(fields, dict) or fields.keys() != shape.keys(): return None if any(type(fields[name]) is not type_ for name, type_ in shape.items()): diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 6aeca665..8da269af 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -1,3 +1,4 @@ +import dataclasses import json import os import pathlib @@ -7,7 +8,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -from loop_claude import file_writes, main +from loop_claude import file_writes, main, reload from loop_claude.claude_code import formats, transcript from loop_claude.claude_runs import judge from loop_claude.outcome import Failure, Stop @@ -119,6 +120,14 @@ class LoopState(unittest.TestCase): with self.subTest(handed=handed): self.assertEqual(main.loop_state([main.RELOAD_FLAG, *handed], CWD), Stop(1, f"the reload cannot read the loop's state from {handed}; rerun loop-claude ")) + def test_decodes_a_state_whose_annotations_are_strings(self): + @dataclasses.dataclass(frozen=True) + class Stringly: + count: "int" + name: "str" + self.assertEqual(reload.decode_state('{"count": 1, "name": "n"}', Stringly), Stringly(1, "n")) + self.assertIsNone(reload.decode_state('{"count": "1", "name": "n"}', Stringly)) + class ReplaceFile(unittest.TestCase): diff --git a/todo.md b/todo.md index b7418871..d76d7369 100644 --- a/todo.md +++ b/todo.md @@ -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 7f9de5c named (`docs/decisions.md`), capping dimension first: -- **Make `decode_state` check the fields' types without relying on the annotations being runtime types.** Two seats: `from __future__ import annotations` in `main.py` would fail every reload. - **State once, in `outcome.py`, that a `Failure` is retried and a `Stop` exits.** Three seats inferred it from `run_loop`. - **Define a round once, in larv-review's "Round cap", and link it from `review-findings.md` → "Rounds", the Vocabulary and the auto-reviewer's step.** All four seats held §3, "Rounds" and the Vocabulary open together to settle whether a launch counts. - **Give `project` one meaning: rename `Paths.projects` and `Session.projects` for Claude Code's transcript directory.** Two seats: it also names the package, the key and `~/.claude.json`'s object. -- 2.52.0 From 80edf5e69575118e8ae7a16e2809ddea61c4d7c8 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 10:31:48 +0200 Subject: [PATCH 085/233] State in outcome.py what the loop does with each outcome --- bin/loop_claude/outcome.py | 4 +++- todo.md | 1 - 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/bin/loop_claude/outcome.py b/bin/loop_claude/outcome.py index a4044b75..302362f5 100644 --- a/bin/loop_claude/outcome.py +++ b/bin/loop_claude/outcome.py @@ -3,15 +3,17 @@ import dataclasses @dataclasses.dataclass(frozen=True) class Continue: - pass + """The cycle ended; the loop starts the next.""" @dataclasses.dataclass(frozen=True) class Failure: + """A step failed and its caller decides: a worker or judge run is retried, up to three times running; anything else becomes a Stop or a warning.""" reason: str @dataclasses.dataclass(frozen=True) class Stop: + """loop-claude exits with code, printing reason.""" code: int reason: str diff --git a/todo.md b/todo.md index d76d7369..e3d4a35e 100644 --- a/todo.md +++ b/todo.md @@ -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 7f9de5c named (`docs/decisions.md`), capping dimension first: -- **State once, in `outcome.py`, that a `Failure` is retried and a `Stop` exits.** Three seats inferred it from `run_loop`. - **Define a round once, in larv-review's "Round cap", and link it from `review-findings.md` → "Rounds", the Vocabulary and the auto-reviewer's step.** All four seats held §3, "Rounds" and the Vocabulary open together to settle whether a launch counts. - **Give `project` one meaning: rename `Paths.projects` and `Session.projects` for Claude Code's transcript directory.** Two seats: it also names the package, the key and `~/.claude.json`'s object. - **Name `human.py` for the exit-2 stops it holds.** One seat looked there for the prompts, which live in `models.py` and `interrupt.py`. -- 2.52.0 From 75ad0402041051a7c62d61f295bd76a7a54547cd Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 10:32:02 +0200 Subject: [PATCH 086/233] Say when a failed run stops being retried --- bin/loop_claude/outcome.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/loop_claude/outcome.py b/bin/loop_claude/outcome.py index 302362f5..17f9fff7 100644 --- a/bin/loop_claude/outcome.py +++ b/bin/loop_claude/outcome.py @@ -8,7 +8,7 @@ class Continue: @dataclasses.dataclass(frozen=True) class Failure: - """A step failed and its caller decides: a worker or judge run is retried, up to three times running; anything else becomes a Stop or a warning.""" + """A step failed and its caller decides: a worker or judge run is retried until it fails three times running; anything else becomes a Stop or a warning.""" reason: str -- 2.52.0 From cb4be72b2a6e610c79f5ca1caaafb43931728d81 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 10:33:34 +0200 Subject: [PATCH 087/233] Define a round once, in larv-review's Round cap --- CLAUDE.md | 2 +- skills/larv-review/SKILL.md | 4 ++-- skills/larv-review/review-findings.md | 2 ++ todo.md | 1 - 4 files changed, 5 insertions(+), 4 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 646be840..a8c3c9e4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -13,7 +13,7 @@ Shorter is better, none is best — chat output, commit messages, comments, docs - **premises** — the goals and audience under `## Goals` and `## Audience` in the project's `README.md`. - **release** — a semver version the human cuts. - **reviewer** — a reporter of findings: an agent under `~/.claude/agents/`, `/security-review` or a forge's auto-reviewer. -- **round cap** — the rounds one pass may take per chunk. +- **round cap** — the rounds one pass may take per chunk; `larv-review` §3 → "Round cap" defines a round. - **session** — a Claude Code session: one id, what `claude --resume` continues. - **trigger** — the condition under which a review pass runs on a change it has not seen; `larv-review` §3 lists them. - **worker** — the headless claude that runs the task in a cycle, in the chunk's session. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 0a48d32f..d337ebb9 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -39,7 +39,7 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod **Re-entry.** A fix is a change the passes have not seen. The pass whose findings it answers runs again, per the findings document's rounds; beyond it, classify the fix by the widest thing it touches — the first row whose trigger it fires, none sending it to §4 — and run forward from that row through §4, each later pass only where its trigger fires too. -**Round cap.** A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human. A round is one launch of a pass's reviewer, whatever launched it: the trigger, a re-entry, a 🔀 escalation, a Stage 0 launch and its rerun. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the prose pass's round is its fresh-context agent. The external auto-reviewer (§4) is a pass of its own, each review it posts a round: after its third, ask the human before any push that would summon a fourth. +**Round cap.** A round is one launch of a pass's reviewer, whatever launched it: the trigger, a re-entry, a 🔀 escalation, a Stage 0 launch and its rerun. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the prose pass's round is its fresh-context agent; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. ### Architecture @@ -86,7 +86,7 @@ The bar is `~/.claude/CLAUDE.md` → "Comments and documentation"; per paragraph 2. Watch the forge's checks until every one passes. A red check is a finding; its fix re-enters per §3. 3. No CI configured → the gate is local tests only; note it in the summary. 4. Everything green → mark the PR ready, dropping any `WIP:`/`Draft:` title prefix. -5. **External auto-reviewer**, when the repo has one — its config file (`.coderabbit.yaml` and the like), or its comments on earlier PRs; none → skip it, say so. Marking the PR ready is what summons it. Wait up to **10 minutes** for its first review, checking about once a minute; nothing by then → note it in the summary and carry on, never waiting twice. Its findings follow the findings document like any reviewer's. Once it has reviewed, each later return here, after a fix re-entered per §3, waits up to **5 minutes** for its re-review of the new commit. +5. **External auto-reviewer**, when the repo has one — its config file (`.coderabbit.yaml` and the like), or its comments on earlier PRs; none → skip it, say so. Marking the PR ready is what summons it. Wait up to **10 minutes** for its first review, checking about once a minute; nothing by then → note it in the summary and carry on, never waiting twice. Its findings follow the findings document like any reviewer's; its rounds, §3 → "Round cap". Once it has reviewed, each later return here, after a fix re-entered per §3, waits up to **5 minutes** for its re-review of the new commit. ## 5. Goal alignment, then merge diff --git a/skills/larv-review/review-findings.md b/skills/larv-review/review-findings.md index bad7ccb2..ebfe9529 100644 --- a/skills/larv-review/review-findings.md +++ b/skills/larv-review/review-findings.md @@ -27,6 +27,8 @@ A review's first line, derived from the findings: ## Rounds +A round: `SKILL.md` → "Round cap". + - Surface everything in round 1. - From round 2 the prompt carries the previous round's findings verbatim and what changed since. Verify each earlier 🔴 and 🟡 is resolved — re-run the scenario, never trust the claim — then review what changed. A fix raises a new finding only where the fix itself introduced a real problem. - A pass is done on no 🔴 and no 🟡. The 🟢 and ❓ left are addressed in that round — fixed, answered, declined or filed in `todo.md` — and take no further round, unless a fix changes behaviour: that takes one. diff --git a/todo.md b/todo.md index e3d4a35e..60784561 100644 --- a/todo.md +++ b/todo.md @@ -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 7f9de5c named (`docs/decisions.md`), capping dimension first: -- **Define a round once, in larv-review's "Round cap", and link it from `review-findings.md` → "Rounds", the Vocabulary and the auto-reviewer's step.** All four seats held §3, "Rounds" and the Vocabulary open together to settle whether a launch counts. - **Give `project` one meaning: rename `Paths.projects` and `Session.projects` for Claude Code's transcript directory.** Two seats: it also names the package, the key and `~/.claude.json`'s object. - **Name `human.py` for the exit-2 stops it holds.** One seat looked there for the prompts, which live in `models.py` and `interrupt.py`. - **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. -- 2.52.0 From f5970686e1d207c007b97296664eb9a300254bc8 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 10:34:20 +0200 Subject: [PATCH 088/233] Count a Stage 0 rerun as its own round, and keep the Vocabulary link bare --- CLAUDE.md | 2 +- skills/larv-review/SKILL.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index a8c3c9e4..9ee4b6fc 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -13,7 +13,7 @@ Shorter is better, none is best — chat output, commit messages, comments, docs - **premises** — the goals and audience under `## Goals` and `## Audience` in the project's `README.md`. - **release** — a semver version the human cuts. - **reviewer** — a reporter of findings: an agent under `~/.claude/agents/`, `/security-review` or a forge's auto-reviewer. -- **round cap** — the rounds one pass may take per chunk; `larv-review` §3 → "Round cap" defines a round. +- **round cap** — the rounds one pass may take per chunk; `larv-review` §3 → "Round cap". - **session** — a Claude Code session: one id, what `claude --resume` continues. - **trigger** — the condition under which a review pass runs on a change it has not seen; `larv-review` §3 lists them. - **worker** — the headless claude that runs the task in a cycle, in the chunk's session. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index d337ebb9..5704f833 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -39,7 +39,7 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod **Re-entry.** A fix is a change the passes have not seen. The pass whose findings it answers runs again, per the findings document's rounds; beyond it, classify the fix by the widest thing it touches — the first row whose trigger it fires, none sending it to §4 — and run forward from that row through §4, each later pass only where its trigger fires too. -**Round cap.** A round is one launch of a pass's reviewer, whatever launched it: the trigger, a re-entry, a 🔀 escalation, a Stage 0 launch and its rerun. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the prose pass's round is its fresh-context agent; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. +**Round cap.** A round is one launch of a pass's reviewer, whatever launched it: the trigger, a re-entry, a 🔀 escalation, a Stage 0 rerun. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the prose pass's round is its fresh-context agent; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. ### Architecture -- 2.52.0 From 99d9996b75b04be9cf2d4abf843646bdc7f214f3 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 10:36:30 +0200 Subject: [PATCH 089/233] Rename Paths.projects and Session.projects to claude_transcripts --- bin/loop_claude/claude_code/formats.py | 6 +++--- bin/loop_claude/claude_code/session.py | 6 +++--- bin/loop_claude/paths.py | 6 +++--- todo.md | 1 - 4 files changed, 9 insertions(+), 10 deletions(-) diff --git a/bin/loop_claude/claude_code/formats.py b/bin/loop_claude/claude_code/formats.py index aa79a2a5..5b91ab24 100644 --- a/bin/loop_claude/claude_code/formats.py +++ b/bin/loop_claude/claude_code/formats.py @@ -23,9 +23,9 @@ def locations(home): return home / ".claude.json", home / ".claude" / "cache" / "model-catalog", home / ".claude" / "projects" -# /-home-me-code-log/.jsonl -def transcript_path(projects, session_id): - hit = glob.glob(os.path.join(glob.escape(str(projects)), "*", f"{session_id}.jsonl")) +# /-home-me-code-log/.jsonl +def transcript_path(claude_transcripts, session_id): + hit = glob.glob(os.path.join(glob.escape(str(claude_transcripts)), "*", f"{session_id}.jsonl")) return hit[0] if hit else "" diff --git a/bin/loop_claude/claude_code/session.py b/bin/loop_claude/claude_code/session.py index 3c9f09e6..2b87dfeb 100644 --- a/bin/loop_claude/claude_code/session.py +++ b/bin/loop_claude/claude_code/session.py @@ -13,19 +13,19 @@ NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec") @dataclasses.dataclass(frozen=True) class Session: id: uuid.UUID + claude_transcripts: pathlib.Path name: str - projects: pathlib.Path def session_for(project, paths): """Exists while its transcript does.""" # "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(uuid.uuid5(NAMESPACE, name), name, paths.projects) + return Session(uuid.uuid5(NAMESPACE, name), paths.claude_transcripts, name) def transcript_file(session): - return transcript_path(session.projects, session.id) + return transcript_path(session.claude_transcripts, session.id) def delete_session(session): diff --git a/bin/loop_claude/paths.py b/bin/loop_claude/paths.py index ba1153bb..6e0995f3 100644 --- a/bin/loop_claude/paths.py +++ b/bin/loop_claude/paths.py @@ -8,20 +8,20 @@ from loop_claude.claude_code.formats import locations class Paths: archive: pathlib.Path claude_json: pathlib.Path + claude_transcripts: pathlib.Path code: pathlib.Path model_catalog: pathlib.Path models_file: pathlib.Path - projects: pathlib.Path def paths_from(home, env): claude = home / ".claude" - claude_json, model_catalog, projects = locations(home) + claude_json, model_catalog, claude_transcripts = locations(home) return Paths( archive=pathlib.Path(env["LOOP_CLAUDE_TRANSCRIPTS"]).expanduser() if env.get("LOOP_CLAUDE_TRANSCRIPTS") else claude / "loop-claude-transcripts", claude_json=claude_json, + claude_transcripts=claude_transcripts, code=home / "code", model_catalog=model_catalog, models_file=claude / "loop-claude-models.json", - projects=projects, ) diff --git a/todo.md b/todo.md index 60784561..cf887786 100644 --- a/todo.md +++ b/todo.md @@ -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 7f9de5c named (`docs/decisions.md`), capping dimension first: -- **Give `project` one meaning: rename `Paths.projects` and `Session.projects` for Claude Code's transcript directory.** Two seats: it also names the package, the key and `~/.claude.json`'s object. - **Name `human.py` for the exit-2 stops it holds.** One seat looked there for the prompts, which live in `models.py` and `interrupt.py`. - **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. -- 2.52.0 From f602b94aff4e99ece84752aee57c42eeb35b4009 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 10:38:47 +0200 Subject: [PATCH 090/233] Name the field claude_code_transcripts and build Session by keyword --- bin/loop_claude/claude_code/formats.py | 6 +++--- bin/loop_claude/claude_code/session.py | 6 +++--- bin/loop_claude/paths.py | 6 +++--- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/bin/loop_claude/claude_code/formats.py b/bin/loop_claude/claude_code/formats.py index 5b91ab24..635bf494 100644 --- a/bin/loop_claude/claude_code/formats.py +++ b/bin/loop_claude/claude_code/formats.py @@ -23,9 +23,9 @@ def locations(home): return home / ".claude.json", home / ".claude" / "cache" / "model-catalog", home / ".claude" / "projects" -# /-home-me-code-log/.jsonl -def transcript_path(claude_transcripts, session_id): - hit = glob.glob(os.path.join(glob.escape(str(claude_transcripts)), "*", f"{session_id}.jsonl")) +# /-home-me-code-log/.jsonl +def transcript_path(claude_code_transcripts, session_id): + hit = glob.glob(os.path.join(glob.escape(str(claude_code_transcripts)), "*", f"{session_id}.jsonl")) return hit[0] if hit else "" diff --git a/bin/loop_claude/claude_code/session.py b/bin/loop_claude/claude_code/session.py index 2b87dfeb..2ffe5d8b 100644 --- a/bin/loop_claude/claude_code/session.py +++ b/bin/loop_claude/claude_code/session.py @@ -13,7 +13,7 @@ NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec") @dataclasses.dataclass(frozen=True) class Session: id: uuid.UUID - claude_transcripts: pathlib.Path + claude_code_transcripts: pathlib.Path name: str @@ -21,11 +21,11 @@ def session_for(project, paths): """Exists while its transcript does.""" # "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(uuid.uuid5(NAMESPACE, name), paths.claude_transcripts, name) + return Session(id=uuid.uuid5(NAMESPACE, name), claude_code_transcripts=paths.claude_code_transcripts, name=name) def transcript_file(session): - return transcript_path(session.claude_transcripts, session.id) + return transcript_path(session.claude_code_transcripts, session.id) def delete_session(session): diff --git a/bin/loop_claude/paths.py b/bin/loop_claude/paths.py index 6e0995f3..6f670603 100644 --- a/bin/loop_claude/paths.py +++ b/bin/loop_claude/paths.py @@ -7,8 +7,8 @@ from loop_claude.claude_code.formats import locations @dataclasses.dataclass(frozen=True) class Paths: archive: pathlib.Path + claude_code_transcripts: pathlib.Path claude_json: pathlib.Path - claude_transcripts: pathlib.Path code: pathlib.Path model_catalog: pathlib.Path models_file: pathlib.Path @@ -16,11 +16,11 @@ class Paths: def paths_from(home, env): claude = home / ".claude" - claude_json, model_catalog, claude_transcripts = locations(home) + claude_json, model_catalog, claude_code_transcripts = locations(home) return Paths( archive=pathlib.Path(env["LOOP_CLAUDE_TRANSCRIPTS"]).expanduser() if env.get("LOOP_CLAUDE_TRANSCRIPTS") else claude / "loop-claude-transcripts", + claude_code_transcripts=claude_code_transcripts, claude_json=claude_json, - claude_transcripts=claude_transcripts, code=home / "code", model_catalog=model_catalog, models_file=claude / "loop-claude-models.json", -- 2.52.0 From 2f9ab2fb7d1c41cc85968dd34e0089774be2f0be Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 10:41:11 +0200 Subject: [PATCH 091/233] Name human_needed.py for the exit-2 stops it holds --- bin/loop_claude/claude_runs/interrupt.py | 6 +++--- bin/loop_claude/{human.py => human_needed.py} | 4 ++-- bin/loop_claude/project/models.py | 6 +++--- todo.md | 1 - 4 files changed, 8 insertions(+), 9 deletions(-) rename bin/loop_claude/{human.py => human_needed.py} (64%) diff --git a/bin/loop_claude/claude_runs/interrupt.py b/bin/loop_claude/claude_runs/interrupt.py index cfff5fc9..dc6ea0d5 100644 --- a/bin/loop_claude/claude_runs/interrupt.py +++ b/bin/loop_claude/claude_runs/interrupt.py @@ -1,7 +1,7 @@ import subprocess import sys -from loop_claude import human +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.outcome import Failure, Stop @@ -12,7 +12,7 @@ TO = "answer the question above" def interrupt(root, session_id, model, path, question, paths): print(f"\n{question}", file=sys.stderr) - if stop := human.off_terminal(TO): + if stop := human_needed.off_terminal(TO): return stop trust(paths.claude_json, checkouts(root)) entries = read(path) @@ -27,5 +27,5 @@ def interrupt(root, session_id, model, path, question, paths): if isinstance(entries, Failure): return Stop(1, f"could not tell whether you typed anything: {entries.reason}") if human_turns(entries) <= before: - return human.needed(TO, "the interrupt ended with nothing typed") + return human_needed.stop(TO, "the interrupt ended with nothing typed") return None diff --git a/bin/loop_claude/human.py b/bin/loop_claude/human_needed.py similarity index 64% rename from bin/loop_claude/human.py rename to bin/loop_claude/human_needed.py index 2d87aa2f..d976ed57 100644 --- a/bin/loop_claude/human.py +++ b/bin/loop_claude/human_needed.py @@ -3,11 +3,11 @@ import sys from loop_claude.outcome import Stop -def needed(to, but): +def stop(to, but): return Stop(2, f"the human is needed to {to}, but {but}") def off_terminal(to): if sys.stdin.isatty() and sys.stdout.isatty(): return None - return needed(to, "stdin or stdout is not a terminal; rerun loop-claude on a terminal") + return stop(to, "stdin or stdout is not a terminal; rerun loop-claude on a terminal") diff --git a/bin/loop_claude/project/models.py b/bin/loop_claude/project/models.py index 3a75272b..127c0392 100644 --- a/bin/loop_claude/project/models.py +++ b/bin/loop_claude/project/models.py @@ -2,7 +2,7 @@ import dataclasses import json import sys -from loop_claude import human +from loop_claude import human_needed from loop_claude.claude_code.formats import catalog from loop_claude.file_writes import replace_json from loop_claude.outcome import Stop @@ -58,7 +58,7 @@ def read_models(saved): def ask_model(name, saved, folder): - if stop := human.off_terminal(f"pick {name}'s model, or merge {{\"{name}\": \"\"}} into {saved}"): + if stop := human_needed.off_terminal(f"pick {name}'s model, or merge {{\"{name}\": \"\"}} into {saved}"): return stop offered = catalog(folder) print(f"\nThe model to run {name} on, saved in {saved}:", file=sys.stderr) @@ -71,7 +71,7 @@ def ask_model(name, saved, folder): answer = input(f"{'A number, or any' if offered else 'A'} name claude --model takes: ").strip() except EOFError: print(file=sys.stderr) - return human.needed(f"pick {name}'s model", "the input ended") + return human_needed.stop(f"pick {name}'s model", "the input ended") if not answer: continue if not (offered and answer.isdecimal()): diff --git a/todo.md b/todo.md index cf887786..b58af244 100644 --- a/todo.md +++ b/todo.md @@ -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 7f9de5c named (`docs/decisions.md`), capping dimension first: -- **Name `human.py` for the exit-2 stops it holds.** One seat looked there for the prompts, which live in `models.py` and `interrupt.py`. - **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. ## 0.2.0 -- 2.52.0 From aefd6e2fb09bc6f1f6cb18aa95d74a17557f13f8 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 10:47:31 +0200 Subject: [PATCH 092/233] File the places the panel on rebuild at 2f9ab2f named under the floor --- docs/decisions.md | 2 +- todo.md | 13 ++++++++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index aec2879a..be8a90f1 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -30,7 +30,7 @@ ## comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it -2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, and 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c; the places the last run named are filed in `todo.md` under 0.1.0, and a later chunk may not lower any dimension. Valid until the next scoring run, which uses the same four seats. +2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, and 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters; the places the last run named are filed in `todo.md` under 0.1.0, and a later chunk may not lower any dimension. Valid until the next scoring run, which uses the same four seats. ## vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link diff --git a/todo.md b/todo.md index b58af244..c803fb5a 100644 --- a/todo.md +++ b/todo.md @@ -6,12 +6,23 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens `rebuild`'s PR into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -The places the panel on `rebuild` at 7f9de5c named (`docs/decisions.md`), capping dimension first: +The places the panel on `rebuild` at 2f9ab2f named (`docs/decisions.md`), capping dimension first: +- **Count the worker's and the judge's failures in one place, under one name.** All four seats traced `LoopState.failures` in `run_loop` and `judge`'s local counter to learn which run each counts. +- **Declare `LoopState` beside `decode_state`, as the state a reload carries.** All four seats held `run_loop`, `loop_state` and `exec_if_edited` open together; one found a field change ends a running loop with nothing at the dataclass saying so. +- **Hand `run_cycle` and `judge_through_interrupts` one cycle context.** Two seats: eight positional arguments. +- **Build `premises.sections` without filling `found` through an alias.** Two seats traced `current` by hand. +- **Route a fix through larv-review's Re-entry in one read.** All four seats reread "Re-entry" and "Round cap" against the pass table, reaching a round through `CLAUDE.md` → "Vocabulary" and `review-findings.md` → "Rounds". +- **Keep in `UserEntryKind` only the kinds a caller tells apart.** Three seats: `human_text` compares only `HUMAN`, and they hunted for the caller of the other six. +- **Keep `formats.py` to Claude Code's shapes: `locations` into `paths.py`, `catalog`'s file reads out.** Three seats found paths and I/O in a file named for formats. +- **Group `bin/loop_claude/`'s top-level modules, and name `claude_runs` apart from `claude_code`.** Two seats: eleven modules of mixed altitude side by side. +- **Say at `user_entry_kind` why a `<` prefix marks Claude Code's own entry, and at `trust` why a failure only warns.** Three seats found either only in `CHANGELOG.md`. +- **Say in the README why the tests run on the host and need `uv`.** Two seats: `CLAUDE.md` says never run a runtime on the host, and only `test_python_floor.py` says what `uv` is for. - **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. ## 0.2.0 - **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. +- **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. -- 2.52.0 From 6c09cadfa3ea4d6dba730c7f0e54465b5760ba61 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 11:01:40 +0200 Subject: [PATCH 093/233] Pin the worker retried within its cycle and reload state without a failure count --- bin/test_loop_claude.py | 2 +- bin/test_loop_claude_black_box.py | 11 ++++++----- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 8da269af..7c295b6d 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -116,7 +116,7 @@ class Verdict(unittest.TestCase): class LoopState(unittest.TestCase): def test_stops_naming_the_reload_when_it_hands_over_anything_but_the_state_with_a_task(self): - for handed in (["3", "2", "/r", "do it"], ["3"], ["[1]"], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": ""})], [json.dumps({"cycle_number": "3", "failures": 0, "root": "/r", "task": "do it"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "", "task": "do it"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it", "turns": 1})]): + for handed in (["3", "2", "/r", "do it"], ["3"], ["[1]"], [json.dumps({"cycle_number": 3, "root": "/r"})], [json.dumps({"cycle_number": 3, "root": "/r", "task": ""})], [json.dumps({"cycle_number": "3", "root": "/r", "task": "do it"})], [json.dumps({"cycle_number": 3, "root": "", "task": "do it"})], [json.dumps({"cycle_number": 3, "root": "/r", "task": "do it", "turns": 1})]): with self.subTest(handed=handed): self.assertEqual(main.loop_state([main.RELOAD_FLAG, *handed], CWD), Stop(1, f"the reload cannot read the loop's state from {handed}; rerun loop-claude ")) diff --git a/bin/test_loop_claude_black_box.py b/bin/test_loop_claude_black_box.py index 681dee0d..318d6138 100644 --- a/bin/test_loop_claude_black_box.py +++ b/bin/test_loop_claude_black_box.py @@ -366,6 +366,8 @@ class Cycles(unittest.TestCase): self.assertIn("retrying the worker in a minute: claude exited 1", run.stderr) self.assertIn("claude exited 0 without a result event", run.stderr) self.assertEqual(run.stderr.strip().splitlines()[-1], "the worker failed three times running: claude killed by signal 9") + self.assertNotIn("=== cycle 2 ===", run.stdout) + self.assertEqual(argument(run.calls[1], "--resume"), argument(run.calls[0], "--session-id")) run = checkout.run([worker(exit=1), worker(exit=1), worker(), judge(), worker(exit=1), worker(exit=1)]) self.assertEqual(run.code, 130) @@ -646,17 +648,16 @@ class Reload(unittest.TestCase): self.assertEqual(run.roles(), ["worker", "judge"] * 4) self.assertIn("keeping the running script", run.stderr) reloads = [json.loads(argv[1]) for argv in run.starts if argv[:1] == ["--reloaded"]] - self.assertEqual(reloads, [{"cycle_number": cycle, "failures": 0, "root": str(checkout.root), "task": TASK} for cycle in (2, 3)]) + self.assertEqual(reloads, [{"cycle_number": cycle, "root": str(checkout.root), "task": TASK} for cycle in (2, 3)]) self.assertIn("=== cycle 4 ===", run.stdout) outside = checkout.temp / "outside" outside.mkdir() - state = {"cycle_number": 3, "failures": 2, "root": str(checkout.root), "task": TASK} - run = checkout.run([worker(exit=1)], argv=["--reloaded", json.dumps(state)], cwd=outside) - self.assertEqual((run.code, run.sleeps), (1, [])) + state = {"cycle_number": 3, "root": str(checkout.root), "task": TASK} + run = checkout.run([worker()], argv=["--reloaded", json.dumps(state)], cwd=outside) + self.assertEqual((run.code, run.roles()), (130, ["worker", "judge"])) self.assertEqual(run.calls[0]["cwd"], str(checkout.root)) self.assertIn("=== cycle 4 ===", run.stdout) - self.assertEqual(run.stderr.strip().splitlines()[-1], "the worker failed three times running: claude exited 1") run = checkout.run([], argv=["--reloaded", "{}"]) self.assertEqual((run.code, run.calls), (1, [])) -- 2.52.0 From fb221787d6655b397efaebedfda81154f39de486 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 11:02:57 +0200 Subject: [PATCH 094/233] Retry the worker and the judge through one counter, in retry.py --- bin/loop_claude/claude_runs/judge.py | 21 +++++++-------------- bin/loop_claude/cycle.py | 9 ++++----- bin/loop_claude/main.py | 17 ++++------------- bin/loop_claude/outcome.py | 7 +------ bin/loop_claude/retry.py | 17 +++++++++++------ 5 files changed, 27 insertions(+), 44 deletions(-) diff --git a/bin/loop_claude/claude_runs/judge.py b/bin/loop_claude/claude_runs/judge.py index c8f22b18..a9a9052d 100644 --- a/bin/loop_claude/claude_runs/judge.py +++ b/bin/loop_claude/claude_runs/judge.py @@ -1,12 +1,11 @@ import dataclasses -import itertools import json import subprocess import typing from loop_claude.claude_code.formats import structured_output from loop_claude.outcome import Failure -from loop_claude.retry import stop_or_sleep_a_minute +from loop_claude.retry import retried JUDGE_RULES = ( "Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n" @@ -57,26 +56,20 @@ def judge(root, task, premises, transcript, model): "--tools", "", ] prompt = judge_prompt(task, premises, transcript) - for failures in itertools.count(1): - verdict = run_judge(root, args, prompt) - if isinstance(verdict, Failure): - reason = verdict.reason - elif not grounded(verdict, transcript): - reason = f"the judge quoted {verdict.evidence!r}, nothing in the transcript" + (f", for the question: {verdict.question}" if verdict.interrupt else "") - else: - return verdict - if stop := stop_or_sleep_a_minute("judge", failures, reason): - return stop + return retried("judge", lambda: run_judge(root, args, prompt, transcript)) -def run_judge(root, args, prompt): +def run_judge(root, args, prompt, transcript): try: proc = subprocess.run(["claude", *args], capture_output=True, cwd=root, input=prompt, text=True) except OSError as failure: return Failure(f"could not start claude: {failure.strerror}") if proc.returncode != 0: return Failure(proc.stderr.strip() or f"the judge exited {proc.returncode}") - return verdict_from(structured_output(proc.stdout)) + verdict = verdict_from(structured_output(proc.stdout)) + if isinstance(verdict, Verdict) and not grounded(verdict, transcript): + return Failure(f"the judge quoted {verdict.evidence!r}, nothing in the transcript" + (f", for the question: {verdict.question}" if verdict.interrupt else "")) + return verdict def judge_prompt(task, premises, transcript): diff --git a/bin/loop_claude/cycle.py b/bin/loop_claude/cycle.py index da51fa58..8429b417 100644 --- a/bin/loop_claude/cycle.py +++ b/bin/loop_claude/cycle.py @@ -4,14 +4,14 @@ from loop_claude.claude_code.transcript import read, render from loop_claude.claude_runs.interrupt import interrupt from loop_claude.claude_runs.judge import judge from loop_claude.claude_runs.worker import run_worker, worker_args -from loop_claude.outcome import Continue, Failure, Stop +from loop_claude.outcome import Failure, Stop +from loop_claude.retry import retried def run_cycle(root, project, task, premises, models, paths): session = session_for(project, paths) - resuming = bool(transcript_file(session)) - if failure := run_worker(root, worker_args(task, session, models.worker, resuming)): - return failure + if stop := retried("worker", lambda: run_worker(root, worker_args(task, session, models.worker, bool(transcript_file(session))))): + return stop path = transcript_file(session) if not path: return Stop(1, f"claude left no transcript for session {session.id}") @@ -22,7 +22,6 @@ def run_cycle(root, project, task, premises, models, paths): if failure := archive(project, path, f"Task: {task}\n\nVerdict: finished", paths): return Stop(1, failure.reason) delete_session(session) - return Continue() def judge_through_interrupts(root, project, task, premises, models, session, path, paths): diff --git a/bin/loop_claude/main.py b/bin/loop_claude/main.py index 5819a626..76bd3a0c 100644 --- a/bin/loop_claude/main.py +++ b/bin/loop_claude/main.py @@ -37,18 +37,16 @@ import dataclasses import sys from loop_claude.cycle import run_cycle -from loop_claude.outcome import Continue, Failure, Stop +from loop_claude.outcome import Stop 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 from loop_claude.reload import RELOAD_FLAG, decode_state, exec_if_edited, fingerprint -from loop_claude.retry import stop_or_sleep_a_minute @dataclasses.dataclass(frozen=True) class LoopState: cycle_number: int - failures: int root: str task: str @@ -79,15 +77,8 @@ def run_loop(argv, env, paths, launcher, cwd): if isinstance(models, Stop): return models print(f"\n=== cycle {state.cycle_number} ===", flush=True) - match run_cycle(state.root, project, state.task, premises, models, paths): - case Stop() as stop: - return stop - case Failure(reason): - state = dataclasses.replace(state, failures=state.failures + 1) - if stop := stop_or_sleep_a_minute("worker", state.failures, reason): - return stop - case Continue(): - state = dataclasses.replace(state, failures=0) + if stop := run_cycle(state.root, project, state.task, premises, models, paths): + return stop def loop_state(argv, cwd): @@ -96,7 +87,7 @@ def loop_state(argv, cwd): if task in ("", "-h", "--help"): return Stop(0 if task else 1, __doc__.strip()) root = checkout_root(cwd) - return root if isinstance(root, Stop) else LoopState(0, 0, root, task) + return root if isinstance(root, Stop) else LoopState(0, root, task) state = decode_state(argv[1], LoopState) if len(argv) == 2 else None if not (state and state.root and state.task): return Stop(1, f"the reload cannot read the loop's state from {argv[1:]}; rerun loop-claude ") diff --git a/bin/loop_claude/outcome.py b/bin/loop_claude/outcome.py index 17f9fff7..e6a90142 100644 --- a/bin/loop_claude/outcome.py +++ b/bin/loop_claude/outcome.py @@ -1,14 +1,9 @@ import dataclasses -@dataclasses.dataclass(frozen=True) -class Continue: - """The cycle ended; the loop starts the next.""" - - @dataclasses.dataclass(frozen=True) class Failure: - """A step failed and its caller decides: a worker or judge run is retried until it fails three times running; anything else becomes a Stop or a warning.""" + """A step failed and its caller decides: `retried` reruns a worker or judge run until it fails three times running; anything else becomes a Stop or a warning.""" reason: str diff --git a/bin/loop_claude/retry.py b/bin/loop_claude/retry.py index f377899d..0c0082cf 100644 --- a/bin/loop_claude/retry.py +++ b/bin/loop_claude/retry.py @@ -1,11 +1,16 @@ +import itertools import sys import time -from loop_claude.outcome import Stop +from loop_claude.outcome import Failure, Stop -def stop_or_sleep_a_minute(who, failures, reason): - if failures == 3: - return Stop(1, f"the {who} failed three times running: {reason}") - print(f"retrying the {who} in a minute: {reason}", file=sys.stderr) - time.sleep(60) +def retried(who, attempt): + for failures in itertools.count(1): + result = attempt() + if not isinstance(result, Failure): + return result + if failures == 3: + return Stop(1, f"the {who} failed three times running: {result.reason}") + print(f"retrying the {who} in a minute: {result.reason}", file=sys.stderr) + time.sleep(60) -- 2.52.0 From d4d8621ab44ebaadb1c4bef536a7e1c0d0999cbf Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 11:07:44 +0200 Subject: [PATCH 095/233] Stop a loop running main's script once at the cut-over, and tick off the item --- AGENTS.md | 2 +- CHANGELOG.md | 1 + bin/test_loop_claude.py | 2 +- docs/decisions.md | 4 ++-- todo.md | 1 - 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 501cfe29..aae2900d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -21,6 +21,6 @@ Decisions live in `docs/decisions.md`: - loop-claude: the judge is retried alone, on its own counter - loop-claude: the judge loads `CLAUDE.md` - loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop -- loop-claude: the rebuild keeps main's `--reloaded` state +- 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 diff --git a/CHANGELOG.md b/CHANGELOG.md index 060aa525..1bed484a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ - `loop-claude` skips a transcript line it cannot parse, exits 1 naming a transcript it cannot read, and counts a `claude` it cannot start as a failed worker run. - `loop-claude`'s judge quotes the transcript for every verdict, and a verdict quoting nothing or interrupting without a question, or a `claude` the judge cannot start, is a failed judge run; a `claude` that cannot start for an interrupt exits 1. - `loop-claude`'s exit-2 message says what the human is needed for. +- `loop-claude` retries a failed worker within its cycle; a loop running the previous `loop-claude` exits 1 at its next cycle boundary, and rerunning `loop-claude ` resumes it. - `loop-claude` counts an interrupt reply starting with `<` as typed. - `loop-claude`'s judge sees a reply the human types while claude works, and an interrupt counts one as typed. - `loop-claude`'s archive holds the raw `.jsonl` transcript, one copy per distinct transcript, named by its SHA-256, with the verdict beside it in `.verdict.md`; a transcript it cannot archive exits 1. diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 7c295b6d..52004cc1 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -116,7 +116,7 @@ class Verdict(unittest.TestCase): class LoopState(unittest.TestCase): def test_stops_naming_the_reload_when_it_hands_over_anything_but_the_state_with_a_task(self): - for handed in (["3", "2", "/r", "do it"], ["3"], ["[1]"], [json.dumps({"cycle_number": 3, "root": "/r"})], [json.dumps({"cycle_number": 3, "root": "/r", "task": ""})], [json.dumps({"cycle_number": "3", "root": "/r", "task": "do it"})], [json.dumps({"cycle_number": 3, "root": "", "task": "do it"})], [json.dumps({"cycle_number": 3, "root": "/r", "task": "do it", "turns": 1})]): + for handed in (["3", "2", "/r", "do it"], ["3"], ["[1]"], [json.dumps({"cycle_number": 3, "root": "/r"})], [json.dumps({"cycle_number": 3, "root": "/r", "task": ""})], [json.dumps({"cycle_number": "3", "root": "/r", "task": "do it"})], [json.dumps({"cycle_number": 3, "root": "", "task": "do it"})], [json.dumps({"cycle_number": 3, "root": "/r", "task": "do it", "turns": 1})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it"})]): with self.subTest(handed=handed): self.assertEqual(main.loop_state([main.RELOAD_FLAG, *handed], CWD), Stop(1, f"the reload cannot read the loop's state from {handed}; rerun loop-claude ")) diff --git a/docs/decisions.md b/docs/decisions.md index be8a90f1..5f707e70 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -68,9 +68,9 @@ 2026-09-28, lilleman, for the rebuild. Serves goals 2 and 4: saving each transcript locally is the first step of backing it up, and it shows afterwards what an unattended run did. A copy of the `.jsonl`, deduplicated by content hash, with the verdict beside it; a rendering drops tool results, and a second-resolution stamp names two states within one second as one file. A failed archive exits 1, since a loop that loses its record silently fails the backup goal. Valid while transcripts stay small enough to copy whole. -## loop-claude: the rebuild keeps main's `--reloaded` state +## loop-claude: a loop running main's script stops once at the cut-over -2026-09-28, lilleman, for the rebuild. Serves goal 4. A loop running main's script reloads into the rebuilt one at its next cycle boundary and carries on; `decode_state` accepts only JSON whose keys and value types match `LoopState` exactly, so renaming, adding, dropping or retyping a field breaks that reload, and no code exists only for the cut-over. Valid until the rebuild merges. +2026-09-29, lilleman. Serves goal 4. The rebuild retries the worker within its cycle, so `LoopState` carries no failure count and rejects main's state; the loop exits 1 naming the rerun, one rerun for a one-human audience, and no code exists only for the cut-over. Valid until the rebuild merges. ## rebuild: a chunk into `rebuild` takes no comprehension scoring run diff --git a/todo.md b/todo.md index c803fb5a..d9252509 100644 --- a/todo.md +++ b/todo.md @@ -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 2f9ab2f named (`docs/decisions.md`), capping dimension first: -- **Count the worker's and the judge's failures in one place, under one name.** All four seats traced `LoopState.failures` in `run_loop` and `judge`'s local counter to learn which run each counts. - **Declare `LoopState` beside `decode_state`, as the state a reload carries.** All four seats held `run_loop`, `loop_state` and `exec_if_edited` open together; one found a field change ends a running loop with nothing at the dataclass saying so. - **Hand `run_cycle` and `judge_through_interrupts` one cycle context.** Two seats: eight positional arguments. - **Build `premises.sections` without filling `found` through an alias.** Two seats traced `current` by hand. -- 2.52.0 From 917f150fd13729b1a14e83251a0f575c4071b7c7 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 11:10:19 +0200 Subject: [PATCH 096/233] Say in --help that a run is retried within its cycle, and drop the cut-over from the changelog --- CHANGELOG.md | 2 +- bin/loop_claude/main.py | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1bed484a..7cb19b6d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ - `loop-claude` skips a transcript line it cannot parse, exits 1 naming a transcript it cannot read, and counts a `claude` it cannot start as a failed worker run. - `loop-claude`'s judge quotes the transcript for every verdict, and a verdict quoting nothing or interrupting without a question, or a `claude` the judge cannot start, is a failed judge run; a `claude` that cannot start for an interrupt exits 1. - `loop-claude`'s exit-2 message says what the human is needed for. -- `loop-claude` retries a failed worker within its cycle; a loop running the previous `loop-claude` exits 1 at its next cycle boundary, and rerunning `loop-claude ` resumes it. +- `loop-claude` retries a failed worker within its cycle. - `loop-claude` counts an interrupt reply starting with `<` as typed. - `loop-claude`'s judge sees a reply the human types while claude works, and an interrupt counts one as typed. - `loop-claude`'s archive holds the raw `.jsonl` transcript, one copy per distinct transcript, named by its SHA-256, with the verdict beside it in `.verdict.md`; a transcript it cannot archive exits 1. diff --git a/bin/loop_claude/main.py b/bin/loop_claude/main.py index 76bd3a0c..bd578364 100644 --- a/bin/loop_claude/main.py +++ b/bin/loop_claude/main.py @@ -12,10 +12,10 @@ Cycles continue until an exit below or Ctrl-C. Words: ~/.claude/CLAUDE.md → "V Exit 1: no task, not inside a checkout, no premises, a models file it cannot read or write, claude leaves no transcript or one it cannot read or archive, claude cannot start for an interrupt, a -reload with unreadable state, or the worker or the judge fails three times running. A worker fails -when claude cannot start, exits non-zero, is killed, or ends without a result event; a judge when -claude cannot start or exits non-zero, or its verdict misses or mistypes a field, interrupts without a -question, or quotes nothing in the transcript. +reload with unreadable state, or the worker or the judge fails three times running, retried a minute +apart within the cycle. A worker fails when claude cannot start, exits non-zero, is killed, or ends +without a result event; a judge when claude cannot start or exits non-zero, or its verdict misses or +mistypes a field, interrupts without a question, or quotes nothing in the transcript. Exit 2: the human is needed, to pick the model or answer an interrupt, and stdin or stdout is not a terminal, the input ends, or the interrupt ended with nothing typed. Rerunning resumes any open session. -- 2.52.0 From 9d7eaa5453d45274f50c3c5708e7047e79530457 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 11:12:19 +0200 Subject: [PATCH 097/233] Tighten the cut-over decision --- docs/decisions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/decisions.md b/docs/decisions.md index 5f707e70..85d32e6c 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -70,7 +70,7 @@ ## loop-claude: a loop running main's script stops once at the cut-over -2026-09-29, lilleman. Serves goal 4. The rebuild retries the worker within its cycle, so `LoopState` carries no failure count and rejects main's state; the loop exits 1 naming the rerun, one rerun for a one-human audience, and no code exists only for the cut-over. Valid until the rebuild merges. +2026-09-29, lilleman. Serves goal 4. The rebuild's `LoopState` lacks main's failure count, so a loop running main's script exits 1 at its first reload into the rebuild, telling the human to rerun `loop-claude `. No code exists only for the cut-over: one rerun costs a one-human audience less. Valid until the rebuild merges. ## rebuild: a chunk into `rebuild` takes no comprehension scoring run -- 2.52.0 From 7604ec4fa7910033fef90d165f55a7d06c151e77 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 11:31:07 +0200 Subject: [PATCH 098/233] Declare LoopState beside decode_state, as the state a reload carries --- bin/loop_claude/main.py | 9 +-------- bin/loop_claude/reload.py | 8 ++++++++ todo.md | 1 - 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/bin/loop_claude/main.py b/bin/loop_claude/main.py index bd578364..5b77cbc4 100644 --- a/bin/loop_claude/main.py +++ b/bin/loop_claude/main.py @@ -41,14 +41,7 @@ from loop_claude.outcome import Stop 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 -from loop_claude.reload import RELOAD_FLAG, decode_state, exec_if_edited, fingerprint - - -@dataclasses.dataclass(frozen=True) -class LoopState: - cycle_number: int - root: str - task: str +from loop_claude.reload import RELOAD_FLAG, LoopState, decode_state, exec_if_edited, fingerprint def main(argv, env, paths, launcher, cwd): diff --git a/bin/loop_claude/reload.py b/bin/loop_claude/reload.py index 9419dd07..cc990db4 100644 --- a/bin/loop_claude/reload.py +++ b/bin/loop_claude/reload.py @@ -9,6 +9,14 @@ import typing RELOAD_FLAG = "--reloaded" +# A field change stops a running loop at its next reload: the new script rejects the old fields. +@dataclasses.dataclass(frozen=True) +class LoopState: + cycle_number: int + root: str + task: str + + def decode_state(handed, kind): try: fields = json.loads(handed) diff --git a/todo.md b/todo.md index d9252509..adcd7274 100644 --- a/todo.md +++ b/todo.md @@ -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 2f9ab2f named (`docs/decisions.md`), capping dimension first: -- **Declare `LoopState` beside `decode_state`, as the state a reload carries.** All four seats held `run_loop`, `loop_state` and `exec_if_edited` open together; one found a field change ends a running loop with nothing at the dataclass saying so. - **Hand `run_cycle` and `judge_through_interrupts` one cycle context.** Two seats: eight positional arguments. - **Build `premises.sections` without filling `found` through an alias.** Two seats traced `current` by hand. - **Route a fix through larv-review's Re-entry in one read.** All four seats reread "Re-entry" and "Round cap" against the pass table, reaching a round through `CLAUDE.md` → "Vocabulary" and `review-findings.md` → "Rounds". -- 2.52.0 From e7b0479092f53a21c6c4da502db0a0423b829ccb Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 11:33:49 +0200 Subject: [PATCH 099/233] Hand run_cycle and judge_through_interrupts one cycle context --- bin/loop_claude/cycle.py | 40 +++++++++++++++++++++++++++------------- bin/loop_claude/main.py | 6 ++++-- todo.md | 1 - 3 files changed, 31 insertions(+), 16 deletions(-) diff --git a/bin/loop_claude/cycle.py b/bin/loop_claude/cycle.py index 8429b417..997f0e65 100644 --- a/bin/loop_claude/cycle.py +++ b/bin/loop_claude/cycle.py @@ -1,40 +1,54 @@ +import dataclasses + from loop_claude.archive import archive -from loop_claude.claude_code.session import delete_session, session_for, transcript_file +from loop_claude.claude_code.session import Session, delete_session, transcript_file from loop_claude.claude_code.transcript import read, render from loop_claude.claude_runs.interrupt import interrupt from loop_claude.claude_runs.judge import judge from loop_claude.claude_runs.worker import run_worker, worker_args from loop_claude.outcome import Failure, Stop +from loop_claude.paths import Paths +from loop_claude.project.models import Models from loop_claude.retry import retried -def run_cycle(root, project, task, premises, models, paths): - session = session_for(project, paths) - if stop := retried("worker", lambda: run_worker(root, worker_args(task, session, models.worker, bool(transcript_file(session))))): +@dataclasses.dataclass(frozen=True) +class Cycle: + models: Models + paths: Paths + premises: str + project: str + root: str + session: Session + task: str + + +def run_cycle(cycle): + 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(session) + path = transcript_file(cycle.session) if not path: - return Stop(1, f"claude left no transcript for session {session.id}") - verdict = judge_through_interrupts(root, project, task, premises, models, session, path, paths) + return Stop(1, f"claude left no transcript for session {cycle.session.id}") + verdict = judge_through_interrupts(cycle, path) if isinstance(verdict, Stop): return verdict if verdict.finished: - if failure := archive(project, path, f"Task: {task}\n\nVerdict: finished", paths): + if failure := archive(cycle.project, path, f"Task: {cycle.task}\n\nVerdict: finished", cycle.paths): return Stop(1, failure.reason) - delete_session(session) + delete_session(cycle.session) -def judge_through_interrupts(root, project, task, premises, models, session, path, paths): +def judge_through_interrupts(cycle, path): # The interrupt appends to this transcript, so each pass judges and archives it anew. while True: entries = read(path) if isinstance(entries, Failure): return Stop(1, entries.reason) - verdict = judge(root, task, premises, render(entries), models.judge) + verdict = judge(cycle.root, cycle.task, cycle.premises, render(entries), cycle.models.judge) if isinstance(verdict, Stop) or not verdict.interrupt: return verdict - if failure := archive(project, path, f"Task: {task}\n\nVerdict: interrupt\n\n{verdict.question}", paths): + if failure := archive(cycle.project, path, f"Task: {cycle.task}\n\nVerdict: interrupt\n\n{verdict.question}", cycle.paths): return Stop(1, failure.reason) - if stop := interrupt(root, session.id, models.worker, path, verdict.question, paths): + if stop := interrupt(cycle.root, cycle.session.id, cycle.models.worker, path, verdict.question, cycle.paths): return stop diff --git a/bin/loop_claude/main.py b/bin/loop_claude/main.py index 5b77cbc4..e791e300 100644 --- a/bin/loop_claude/main.py +++ b/bin/loop_claude/main.py @@ -36,7 +36,8 @@ loop-claude --help succeeds. import dataclasses import sys -from loop_claude.cycle import run_cycle +from loop_claude.claude_code.session import session_for +from loop_claude.cycle import Cycle, run_cycle from loop_claude.outcome import Stop from loop_claude.project.checkout import checkout_root, project_name from loop_claude.project.models import project_models @@ -60,6 +61,7 @@ def run_loop(argv, env, paths, launcher, cwd): return state baseline = fingerprint(launcher) project = project_name(state.root, paths.code) + session = session_for(project, paths) while True: exec_if_edited(launcher, baseline, state) state = dataclasses.replace(state, cycle_number=state.cycle_number + 1) @@ -70,7 +72,7 @@ def run_loop(argv, env, paths, launcher, cwd): if isinstance(models, Stop): return models print(f"\n=== cycle {state.cycle_number} ===", flush=True) - if stop := run_cycle(state.root, project, state.task, premises, models, paths): + if stop := run_cycle(Cycle(models=models, paths=paths, premises=premises, project=project, root=state.root, session=session, task=state.task)): return stop diff --git a/todo.md b/todo.md index adcd7274..f26afe02 100644 --- a/todo.md +++ b/todo.md @@ -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 2f9ab2f named (`docs/decisions.md`), capping dimension first: -- **Hand `run_cycle` and `judge_through_interrupts` one cycle context.** Two seats: eight positional arguments. - **Build `premises.sections` without filling `found` through an alias.** Two seats traced `current` by hand. - **Route a fix through larv-review's Re-entry in one read.** All four seats reread "Re-entry" and "Round cap" against the pass table, reaching a round through `CLAUDE.md` → "Vocabulary" and `review-findings.md` → "Rounds". - **Keep in `UserEntryKind` only the kinds a caller tells apart.** Three seats: `human_text` compares only `HUMAN`, and they hunted for the caller of the other six. -- 2.52.0 From 69b093d1a76619ba952b4752ea72a34884b9fd1f Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 11:36:43 +0200 Subject: [PATCH 100/233] Build premises.sections without filling found through an alias --- bin/loop_claude/project/premises.py | 17 ++++++++++------- todo.md | 1 - 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/bin/loop_claude/project/premises.py b/bin/loop_claude/project/premises.py index a23fc24f..89e8b429 100644 --- a/bin/loop_claude/project/premises.py +++ b/bin/loop_claude/project/premises.py @@ -23,14 +23,17 @@ def read_premises(root): def sections(text): - found, current, fenced = {}, None, False + headings, fenced = [], False for line in text.splitlines(): fenced ^= line.startswith("```") if not fenced and line.startswith("## "): - current = [] - found.setdefault(line.strip()[3:], []).append(current) + headings.append((line.strip()[3:], [])) elif not fenced and line.startswith("# "): - current = None - elif current is not None and line.strip(): - current.append(line) - return {name: ["\n".join(body) for body in bodies] for name, bodies in found.items()} + headings.append((None, [])) + elif headings and line.strip(): + headings[-1][1].append(line) + found = {} + for name, body in headings: + if name is not None: + found.setdefault(name, []).append("\n".join(body)) + return found diff --git a/todo.md b/todo.md index f26afe02..4edfb126 100644 --- a/todo.md +++ b/todo.md @@ -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 2f9ab2f named (`docs/decisions.md`), capping dimension first: -- **Build `premises.sections` without filling `found` through an alias.** Two seats traced `current` by hand. - **Route a fix through larv-review's Re-entry in one read.** All four seats reread "Re-entry" and "Round cap" against the pass table, reaching a round through `CLAUDE.md` → "Vocabulary" and `review-findings.md` → "Rounds". - **Keep in `UserEntryKind` only the kinds a caller tells apart.** Three seats: `human_text` compares only `HUMAN`, and they hunted for the caller of the other six. - **Keep `formats.py` to Claude Code's shapes: `locations` into `paths.py`, `catalog`'s file reads out.** Three seats found paths and I/O in a file named for formats. -- 2.52.0 From ea29be40464690db07b0e47bdc85d3aaf7cb59d2 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 11:38:03 +0200 Subject: [PATCH 101/233] Name sections' list blocks --- bin/loop_claude/project/premises.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/bin/loop_claude/project/premises.py b/bin/loop_claude/project/premises.py index 89e8b429..fb266e25 100644 --- a/bin/loop_claude/project/premises.py +++ b/bin/loop_claude/project/premises.py @@ -23,17 +23,17 @@ def read_premises(root): def sections(text): - headings, fenced = [], False + blocks, fenced = [], False for line in text.splitlines(): fenced ^= line.startswith("```") if not fenced and line.startswith("## "): - headings.append((line.strip()[3:], [])) + blocks.append((line.strip()[3:], [])) elif not fenced and line.startswith("# "): - headings.append((None, [])) - elif headings and line.strip(): - headings[-1][1].append(line) + blocks.append((None, [])) + elif blocks and line.strip(): + blocks[-1][1].append(line) found = {} - for name, body in headings: + for name, body in blocks: if name is not None: found.setdefault(name, []).append("\n".join(body)) return found -- 2.52.0 From 1f259cd728526b2c0559e3e96fd8cf8b361d3ff3 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 11:40:04 +0200 Subject: [PATCH 102/233] Route a fix through larv-review's Re-entry in one read --- skills/larv-review/SKILL.md | 4 ++-- todo.md | 1 - 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 5704f833..fd6fef58 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -37,9 +37,9 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod **Record, then ask**, for the architecture pass and the full scan: where the repo holds the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: skip it and cite the record. A change that *departs* from the record is unreviewed however thorough the record is. Fired with no record behind it → ask the user with the evidence and your recommendation; no user reachable → run it. -**Re-entry.** A fix is a change the passes have not seen. The pass whose findings it answers runs again, per the findings document's rounds; beyond it, classify the fix by the widest thing it touches — the first row whose trigger it fires, none sending it to §4 — and run forward from that row through §4, each later pass only where its trigger fires too. +**Round cap.** A round is one launch of a pass's reviewer, whatever launched it: the trigger, a re-entry, a 🔀 escalation, a Stage 0 rerun; how a round is prompted and when a pass is done, the findings document → "Rounds". The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the prose pass's round is its fresh-context agent; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. -**Round cap.** A round is one launch of a pass's reviewer, whatever launched it: the trigger, a re-entry, a 🔀 escalation, a Stage 0 rerun. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the prose pass's round is its fresh-context agent; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. +**Re-entry.** A fix is a change no pass has seen. Run, in table order, the pass whose findings it answers and each pass whose trigger the fix fires; then §4. ### Architecture diff --git a/todo.md b/todo.md index 4edfb126..ac81ad04 100644 --- a/todo.md +++ b/todo.md @@ -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 2f9ab2f named (`docs/decisions.md`), capping dimension first: -- **Route a fix through larv-review's Re-entry in one read.** All four seats reread "Re-entry" and "Round cap" against the pass table, reaching a round through `CLAUDE.md` → "Vocabulary" and `review-findings.md` → "Rounds". - **Keep in `UserEntryKind` only the kinds a caller tells apart.** Three seats: `human_text` compares only `HUMAN`, and they hunted for the caller of the other six. - **Keep `formats.py` to Claude Code's shapes: `locations` into `paths.py`, `catalog`'s file reads out.** Three seats found paths and I/O in a file named for formats. - **Group `bin/loop_claude/`'s top-level modules, and name `claude_runs` apart from `claude_code`.** Two seats: eleven modules of mixed altitude side by side. -- 2.52.0 From a8a3ac9cf10ade878b74c9a5b09e1abff835ad00 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 11:41:10 +0200 Subject: [PATCH 103/233] Re-enter a round's fixes together, run an escalation's fixes as a re-entry, and file the CLI gap in the architecture trigger --- skills/larv-review/SKILL.md | 6 +++--- todo.md | 1 + 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index fd6fef58..460e293d 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -33,13 +33,13 @@ Follow `~/.claude/CLAUDE.md` → "Git, commits, and PRs". Never commit to the de | Product-owner | product-owner-reviewer | changes an external surface: API, CLI, UI, error or deprecation text a consumer reads, README and docs an outside reader lands on | | Prose | you, and a fresh-context agent | every chunk; a fix, where it touches prose | -A comment is prose, not code. Passes run in this order: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. A pass whose trigger does not fire is skipped, and the summary says so. A 🔀 escalation fires the named pass's trigger once the current pass is done, and runs forward from there as a re-entry does. +A comment is prose, not code. Passes run in this order: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. A 🔀 escalation runs the named pass once the current pass is done; its fixes re-enter like any other. **Record, then ask**, for the architecture pass and the full scan: where the repo holds the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: skip it and cite the record. A change that *departs* from the record is unreviewed however thorough the record is. Fired with no record behind it → ask the user with the evidence and your recommendation; no user reachable → run it. -**Round cap.** A round is one launch of a pass's reviewer, whatever launched it: the trigger, a re-entry, a 🔀 escalation, a Stage 0 rerun; how a round is prompted and when a pass is done, the findings document → "Rounds". The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the prose pass's round is its fresh-context agent; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. +**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a Stage 0 rerun included; how a round is prompted and when a pass is done, the findings document → "Rounds". The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the prose pass's round is its fresh-context agent; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. -**Re-entry.** A fix is a change no pass has seen. Run, in table order, the pass whose findings it answers and each pass whose trigger the fix fires; then §4. +**Re-entry.** A fix is a change no pass has seen. A round's fixes re-enter together: run, in table order, each pass whose trigger they fire and the pass whose 🔴 or 🟡 they answer; then §4. ### Architecture diff --git a/todo.md b/todo.md index ac81ad04..bd55ee40 100644 --- a/todo.md +++ b/todo.md @@ -18,6 +18,7 @@ The places the panel on `rebuild` at 2f9ab2f named (`docs/decisions.md`), cappin ## 0.2.0 - **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. - **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. -- 2.52.0 From d9ba36732f7f1aa000b4f3ecd9c5bfa85217e3d8 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 11:41:49 +0200 Subject: [PATCH 104/233] Route a nit's fix through Re-entry --- skills/larv-review/review-findings.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills/larv-review/review-findings.md b/skills/larv-review/review-findings.md index ebfe9529..606fb70b 100644 --- a/skills/larv-review/review-findings.md +++ b/skills/larv-review/review-findings.md @@ -31,7 +31,7 @@ A round: `SKILL.md` → "Round cap". - Surface everything in round 1. - From round 2 the prompt carries the previous round's findings verbatim and what changed since. Verify each earlier 🔴 and 🟡 is resolved — re-run the scenario, never trust the claim — then review what changed. A fix raises a new finding only where the fix itself introduced a real problem. -- A pass is done on no 🔴 and no 🟡. The 🟢 and ❓ left are addressed in that round — fixed, answered, declined or filed in `todo.md` — and take no further round, unless a fix changes behaviour: that takes one. +- A pass is done on no 🔴 and no 🟡. The 🟢 and ❓ left are addressed in that round — fixed, answered, declined or filed in `todo.md` — and take no further round of their own; their fixes re-enter per `SKILL.md` → "Re-entry". ## Declining -- 2.52.0 From 969bb26668c79dea3387860632951112cedc00b6 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 11:43:59 +0200 Subject: [PATCH 105/233] Tell a user entry the human wrote apart with one predicate --- bin/loop_claude/claude_code/formats.py | 34 ++++++-------------------- todo.md | 3 +-- 2 files changed, 8 insertions(+), 29 deletions(-) diff --git a/bin/loop_claude/claude_code/formats.py b/bin/loop_claude/claude_code/formats.py index 635bf494..50138367 100644 --- a/bin/loop_claude/claude_code/formats.py +++ b/bin/loop_claude/claude_code/formats.py @@ -1,5 +1,4 @@ """Every Claude Code format loop-claude reads, each under a sample of it, as Claude Code 2.1.284 writes it.""" -import enum import glob import json import os @@ -7,18 +6,6 @@ import os from loop_claude.outcome import Failure -class UserEntryKind(enum.Enum): - """Who wrote a "user" entry: the human wrote HUMAN, Claude Code every other kind.""" - - COMMAND = enum.auto() - CTRL_C = enum.auto() - EMPTY = enum.auto() - HUMAN = enum.auto() - META = enum.auto() - NON_TEXT = enum.auto() - SDK_PROMPT = enum.auto() - - def locations(home): return home / ".claude.json", home / ".claude" / "cache" / "model-catalog", home / ".claude" / "projects" @@ -57,36 +44,29 @@ def assistant_parts(entry): return parts(entry) if entry.get("type") == "assistant" else [] -def user_entry_kind(entry): +def written_by_human(entry): + """Whether the human wrote a "user" entry; Claude Code writes the rest.""" # {"type": "user", "isMeta": true, "message": {"content": "Caveat: ..."}} - if entry.get("isMeta"): - return UserEntryKind.META # {"type": "user", "promptSource": "sdk", "message": {"content": "Continue the task; ..."}} - if entry.get("promptSource") == "sdk": - return UserEntryKind.SDK_PROMPT + if entry.get("isMeta") or entry.get("promptSource") == "sdk": + return False # {"type": "user", "message": {"content": "/model\n..."}} # {"type": "user", "promptSource": "system", "message": {"content": "..."}} # {"type": "user", "promptSource": "typed", "message": {"content": "merge it"}} if isinstance(text := content(entry), str): source = entry.get("promptSource") - return UserEntryKind.COMMAND if source == "system" or (source != "typed" and text.startswith("<")) else UserEntryKind.HUMAN + return source != "system" and (source == "typed" or not text.startswith("<")) texts = [part_text(part) for part in parts(entry)] - if not texts: - return UserEntryKind.EMPTY # {"type": "user", "message": {"content": [{"tool_use_id": "toolu_01…", "type": "tool_result", "content": "hi"}]}} - if None in texts: - return UserEntryKind.NON_TEXT # {"type": "user", "message": {"content": [{"type": "text", "text": "[Request interrupted by user]"}]}} - if any(text.startswith("[Request interrupted") for text in texts): - return UserEntryKind.CTRL_C - return UserEntryKind.HUMAN + return bool(texts) and None not in texts and not any(text.startswith("[Request interrupted") for text in texts) def human_text(entry): """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 - if entry.get("type") != "user" or user_entry_kind(entry) is not UserEntryKind.HUMAN: + if entry.get("type") != "user" or not written_by_human(entry): return None text = content(entry) return text if isinstance(text, str) else "".join(part_text(part) or "" for part in parts(entry)) diff --git a/todo.md b/todo.md index bd55ee40..2087f0a2 100644 --- a/todo.md +++ b/todo.md @@ -8,10 +8,9 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens The places the panel on `rebuild` at 2f9ab2f named (`docs/decisions.md`), capping dimension first: -- **Keep in `UserEntryKind` only the kinds a caller tells apart.** Three seats: `human_text` compares only `HUMAN`, and they hunted for the caller of the other six. - **Keep `formats.py` to Claude Code's shapes: `locations` into `paths.py`, `catalog`'s file reads out.** Three seats found paths and I/O in a file named for formats. - **Group `bin/loop_claude/`'s top-level modules, and name `claude_runs` apart from `claude_code`.** Two seats: eleven modules of mixed altitude side by side. -- **Say at `user_entry_kind` why a `<` prefix marks Claude Code's own entry, and at `trust` why a failure only warns.** Three seats found either only in `CHANGELOG.md`. +- **Say at `written_by_human` why a `<` prefix marks Claude Code's own entry, and at `trust` why a failure only warns.** Three seats found either only in `CHANGELOG.md`. - **Say in the README why the tests run on the host and need `uv`.** Two seats: `CLAUDE.md` says never run a runtime on the host, and only `test_python_floor.py` says what `uv` is for. - **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. -- 2.52.0 From 5e84736672f1094ab0bab69a43a4eef676eaf9d5 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 11:47:23 +0200 Subject: [PATCH 106/233] Keep formats.py to Claude Code's shapes, with paths and file reads at their callers --- bin/loop_claude/claude_code/formats.py | 29 ++++---------------------- bin/loop_claude/claude_code/session.py | 10 +++++---- bin/loop_claude/paths.py | 9 +++----- bin/loop_claude/project/models.py | 11 +++++++++- todo.md | 1 - 5 files changed, 23 insertions(+), 37 deletions(-) diff --git a/bin/loop_claude/claude_code/formats.py b/bin/loop_claude/claude_code/formats.py index 50138367..a1417da7 100644 --- a/bin/loop_claude/claude_code/formats.py +++ b/bin/loop_claude/claude_code/formats.py @@ -1,26 +1,9 @@ -"""Every Claude Code format loop-claude reads, each under a sample of it, as Claude Code 2.1.284 writes it.""" -import glob +"""Every Claude Code shape loop-claude reads, each under a sample of it, as Claude Code 2.1.284 writes it.""" import json -import os from loop_claude.outcome import Failure -def locations(home): - return home / ".claude.json", home / ".claude" / "cache" / "model-catalog", home / ".claude" / "projects" - - -# /-home-me-code-log/.jsonl -def transcript_path(claude_code_transcripts, session_id): - hit = glob.glob(os.path.join(glob.escape(str(claude_code_transcripts)), "*", f"{session_id}.jsonl")) - return hit[0] if hit else "" - - -# .jsonl, /subagents/, and from older versions .superseded-1789290815002/ and .orphaned-*.jsonl -def session_files(transcript): - return glob.glob(glob.escape(transcript.removesuffix(".jsonl")) + "*") - - def parse(raw): try: entry = json.loads(raw) @@ -114,14 +97,10 @@ def mark_trusted(config, roots): # /*.json: {"fetchedAt": 1790618085238, "catalog": {"config": {"models": [{"id": "claude-opus-5-5", "name": "Opus 5.5", ...}]}}} -def catalog(folder): +def catalog(files): + """The (id, name) of each model in the newest of the parsed catalog files.""" newest = {} - for path in folder.glob("*.json"): - try: - with open(path, encoding="utf-8") as handle: - data = json.load(handle) - except (OSError, ValueError): - continue + 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 diff --git a/bin/loop_claude/claude_code/session.py b/bin/loop_claude/claude_code/session.py index 2ffe5d8b..659267f6 100644 --- a/bin/loop_claude/claude_code/session.py +++ b/bin/loop_claude/claude_code/session.py @@ -1,12 +1,11 @@ import dataclasses +import glob import os import pathlib import shutil import sys import uuid -from loop_claude.claude_code.formats import session_files, transcript_path - NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec") @@ -24,15 +23,18 @@ def session_for(project, paths): 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): - return transcript_path(session.claude_code_transcripts, session.id) + 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): path = transcript_file(session) if not path: return - for sibling in session_files(path): + # .jsonl, /subagents/, and from older versions .superseded-1789290815002/ and .orphaned-*.jsonl + for sibling in glob.glob(glob.escape(path.removesuffix(".jsonl")) + "*"): try: shutil.rmtree(sibling) if os.path.isdir(sibling) else os.remove(sibling) except OSError as failure: diff --git a/bin/loop_claude/paths.py b/bin/loop_claude/paths.py index 6f670603..e93065b8 100644 --- a/bin/loop_claude/paths.py +++ b/bin/loop_claude/paths.py @@ -1,8 +1,6 @@ import dataclasses import pathlib -from loop_claude.claude_code.formats import locations - @dataclasses.dataclass(frozen=True) class Paths: @@ -16,12 +14,11 @@ class Paths: def paths_from(home, env): claude = home / ".claude" - claude_json, model_catalog, claude_code_transcripts = locations(home) return Paths( archive=pathlib.Path(env["LOOP_CLAUDE_TRANSCRIPTS"]).expanduser() if env.get("LOOP_CLAUDE_TRANSCRIPTS") else claude / "loop-claude-transcripts", - claude_code_transcripts=claude_code_transcripts, - claude_json=claude_json, + claude_code_transcripts=claude / "projects", + claude_json=home / ".claude.json", code=home / "code", - model_catalog=model_catalog, + model_catalog=claude / "cache" / "model-catalog", models_file=claude / "loop-claude-models.json", ) diff --git a/bin/loop_claude/project/models.py b/bin/loop_claude/project/models.py index 127c0392..0225210e 100644 --- a/bin/loop_claude/project/models.py +++ b/bin/loop_claude/project/models.py @@ -57,10 +57,19 @@ def read_models(saved): return models +def read_catalog(folder): + for path in folder.glob("*.json"): + try: + with open(path, encoding="utf-8") as handle: + yield json.load(handle) + except (OSError, ValueError): + continue + + def ask_model(name, saved, folder): if stop := human_needed.off_terminal(f"pick {name}'s model, or merge {{\"{name}\": \"\"}} into {saved}"): return stop - offered = catalog(folder) + offered = catalog(read_catalog(folder)) print(f"\nThe model to run {name} on, saved in {saved}:", file=sys.stderr) for number, (model_id, label) in enumerate(offered, 1): print(f" {number}. {label} ({model_id})", file=sys.stderr) diff --git a/todo.md b/todo.md index 2087f0a2..df4c920f 100644 --- a/todo.md +++ b/todo.md @@ -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 2f9ab2f named (`docs/decisions.md`), capping dimension first: -- **Keep `formats.py` to Claude Code's shapes: `locations` into `paths.py`, `catalog`'s file reads out.** Three seats found paths and I/O in a file named for formats. - **Group `bin/loop_claude/`'s top-level modules, and name `claude_runs` apart from `claude_code`.** Two seats: eleven modules of mixed altitude side by side. - **Say at `written_by_human` why a `<` prefix marks Claude Code's own entry, and at `trust` why a failure only warns.** Three seats found either only in `CHANGELOG.md`. - **Say in the README why the tests run on the host and need `uv`.** Two seats: `CLAUDE.md` says never run a runtime on the host, and only `test_python_floor.py` says what `uv` is for. -- 2.52.0 From 29495b1e7daa6c54131d3aca604dacb6d9020e8f Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 11:48:54 +0200 Subject: [PATCH 107/233] Read the model catalog in claude_code/catalog.py --- bin/loop_claude/claude_code/catalog.py | 16 ++++++++++++++++ bin/loop_claude/project/models.py | 13 ++----------- 2 files changed, 18 insertions(+), 11 deletions(-) create mode 100644 bin/loop_claude/claude_code/catalog.py diff --git a/bin/loop_claude/claude_code/catalog.py b/bin/loop_claude/claude_code/catalog.py new file mode 100644 index 00000000..f50873b3 --- /dev/null +++ b/bin/loop_claude/claude_code/catalog.py @@ -0,0 +1,16 @@ +import json + +from loop_claude.claude_code.formats import catalog + + +def offered_models(folder): + return catalog(read_catalog(folder)) + + +def read_catalog(folder): + for path in folder.glob("*.json"): + try: + with open(path, encoding="utf-8") as handle: + yield json.load(handle) + except (OSError, ValueError): + continue diff --git a/bin/loop_claude/project/models.py b/bin/loop_claude/project/models.py index 0225210e..6bae6c7c 100644 --- a/bin/loop_claude/project/models.py +++ b/bin/loop_claude/project/models.py @@ -3,7 +3,7 @@ import json import sys from loop_claude import human_needed -from loop_claude.claude_code.formats import catalog +from loop_claude.claude_code.catalog import offered_models from loop_claude.file_writes import replace_json from loop_claude.outcome import Stop @@ -57,19 +57,10 @@ def read_models(saved): return models -def read_catalog(folder): - for path in folder.glob("*.json"): - try: - with open(path, encoding="utf-8") as handle: - yield json.load(handle) - except (OSError, ValueError): - continue - - def ask_model(name, saved, folder): if stop := human_needed.off_terminal(f"pick {name}'s model, or merge {{\"{name}\": \"\"}} into {saved}"): return stop - offered = catalog(read_catalog(folder)) + offered = offered_models(folder) print(f"\nThe model to run {name} on, saved in {saved}:", file=sys.stderr) for number, (model_id, label) in enumerate(offered, 1): print(f" {number}. {label} ({model_id})", file=sys.stderr) -- 2.52.0 From c2be13efd52f8b2671c3fec60291a056169566dd Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 11:50:16 +0200 Subject: [PATCH 108/233] Name formats.models_in by what it returns, and read the catalog in one function --- bin/loop_claude/claude_code/catalog.py | 10 ++++------ bin/loop_claude/claude_code/formats.py | 2 +- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/bin/loop_claude/claude_code/catalog.py b/bin/loop_claude/claude_code/catalog.py index f50873b3..b3ebe58a 100644 --- a/bin/loop_claude/claude_code/catalog.py +++ b/bin/loop_claude/claude_code/catalog.py @@ -1,16 +1,14 @@ import json -from loop_claude.claude_code.formats import catalog +from loop_claude.claude_code.formats import models_in def offered_models(folder): - return catalog(read_catalog(folder)) - - -def read_catalog(folder): + files = [] for path in folder.glob("*.json"): try: with open(path, encoding="utf-8") as handle: - yield json.load(handle) + files.append(json.load(handle)) except (OSError, ValueError): continue + return models_in(files) diff --git a/bin/loop_claude/claude_code/formats.py b/bin/loop_claude/claude_code/formats.py index a1417da7..d4a8377d 100644 --- a/bin/loop_claude/claude_code/formats.py +++ b/bin/loop_claude/claude_code/formats.py @@ -97,7 +97,7 @@ def mark_trusted(config, roots): # /*.json: {"fetchedAt": 1790618085238, "catalog": {"config": {"models": [{"id": "claude-opus-5-5", "name": "Opus 5.5", ...}]}}} -def catalog(files): +def models_in(files): """The (id, name) of each model in the newest of the parsed catalog files.""" newest = {} for data in files: -- 2.52.0 From aba2a98d7eaec02da7c2cff7368b1e19fe8a645c Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 11:53:46 +0200 Subject: [PATCH 109/233] Name formats.py's samples by what they are, put Session's lifetime on Session, and file the prose pass's places --- bin/loop_claude/claude_code/formats.py | 6 +++--- bin/loop_claude/claude_code/session.py | 2 +- todo.md | 5 +++++ 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/bin/loop_claude/claude_code/formats.py b/bin/loop_claude/claude_code/formats.py index d4a8377d..a274b6dc 100644 --- a/bin/loop_claude/claude_code/formats.py +++ b/bin/loop_claude/claude_code/formats.py @@ -1,4 +1,4 @@ -"""Every Claude Code shape loop-claude reads, each under a sample of it, as Claude Code 2.1.284 writes it.""" +"""Claude Code's JSON shapes loop-claude handles, each under a sample of it, as Claude Code 2.1.284 writes it.""" import json from loop_claude.outcome import Failure @@ -84,7 +84,7 @@ def structured_output(stdout): return (parse(stdout) or {}).get("structured_output") -# ~/.claude.json: {"projects": {"/home/me/code/log": {"hasTrustDialogAccepted": true, ...}}, ...} +# Claude Code's config: {"projects": {"/home/me/code/log": {"hasTrustDialogAccepted": true, ...}}, ...} def mark_trusted(config, roots): projects = config.get("projects", {}) if isinstance(config, dict) else None if not isinstance(projects, dict): @@ -96,7 +96,7 @@ def mark_trusted(config, roots): return {**config, "projects": {**projects, **marked}}, untrusted -# /*.json: {"fetchedAt": 1790618085238, "catalog": {"config": {"models": [{"id": "claude-opus-5-5", "name": "Opus 5.5", ...}]}}} +# A model catalog file: {"fetchedAt": 1790618085238, "catalog": {"config": {"models": [{"id": "claude-opus-5-5", "name": "Opus 5.5", ...}]}}} def models_in(files): """The (id, name) of each model in the newest of the parsed catalog files.""" newest = {} diff --git a/bin/loop_claude/claude_code/session.py b/bin/loop_claude/claude_code/session.py index 659267f6..c2834a50 100644 --- a/bin/loop_claude/claude_code/session.py +++ b/bin/loop_claude/claude_code/session.py @@ -11,13 +11,13 @@ NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec") @dataclasses.dataclass(frozen=True) class Session: + """Exists while its transcript does.""" id: uuid.UUID claude_code_transcripts: pathlib.Path name: str def session_for(project, paths): - """Exists while its transcript does.""" # "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) diff --git a/todo.md b/todo.md index df4c920f..79f50f58 100644 --- a/todo.md +++ b/todo.md @@ -20,3 +20,8 @@ The places the panel on `rebuild` at 2f9ab2f named (`docs/decisions.md`), cappin - **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. +- **Give `docs/decisions.md`'s comprehension-floor and vocabulary entries a premise that has not already expired, with the floor's rule first and its runs' scores as a table, and give the rebuild entry's warning placement its own heading and index line.** A prose pass found both "Valid until the next scoring run" outlived by three runs. +- **Move larv-review's reasons for `/security-review` and for the premises chunk's review into `docs/decisions.md`, and inline in `review-findings.md` what a round is.** A prose pass found rejected alternatives at the rule, and a pointer back to `SKILL.md`, which points here. +- **Cut `comprehension-panel`'s run history and the restated description, `systems-architect.md`'s "one home" line, and split its Reasonability Review steps 4 and 5.** A prose pass found them carrying nothing the instructions need. +- **Keep `outcome.Failure`'s docstring to what a failure is, without naming `retried`.** A value type naming its consumer. +- **Say in `AGENTS.md` that only the rebuild's last chunk opens `rebuild`'s PR into main.** Today it reads as every chunk doing so. -- 2.52.0 From 830ba331ca0cb5aa5efd5c43fcf72c1ee2bed9df Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 11:55:53 +0200 Subject: [PATCH 110/233] Group a cycle's modules under cycle/, apart from claude_code/ --- bin/loop_claude/{claude_runs => cycle}/__init__.py | 0 bin/loop_claude/{ => cycle}/archive.py | 0 bin/loop_claude/{claude_runs => cycle}/interrupt.py | 0 bin/loop_claude/{claude_runs => cycle}/judge.py | 2 +- bin/loop_claude/{ => cycle}/retry.py | 0 bin/loop_claude/{cycle.py => cycle/run.py} | 10 +++++----- bin/loop_claude/{claude_runs => cycle}/worker.py | 0 bin/loop_claude/main.py | 2 +- bin/test_loop_claude.py | 2 +- todo.md | 1 - 10 files changed, 8 insertions(+), 9 deletions(-) rename bin/loop_claude/{claude_runs => cycle}/__init__.py (100%) rename bin/loop_claude/{ => cycle}/archive.py (100%) rename bin/loop_claude/{claude_runs => cycle}/interrupt.py (100%) rename bin/loop_claude/{claude_runs => cycle}/judge.py (99%) rename bin/loop_claude/{ => cycle}/retry.py (100%) rename bin/loop_claude/{cycle.py => cycle/run.py} (87%) rename bin/loop_claude/{claude_runs => cycle}/worker.py (100%) diff --git a/bin/loop_claude/claude_runs/__init__.py b/bin/loop_claude/cycle/__init__.py similarity index 100% rename from bin/loop_claude/claude_runs/__init__.py rename to bin/loop_claude/cycle/__init__.py diff --git a/bin/loop_claude/archive.py b/bin/loop_claude/cycle/archive.py similarity index 100% rename from bin/loop_claude/archive.py rename to bin/loop_claude/cycle/archive.py diff --git a/bin/loop_claude/claude_runs/interrupt.py b/bin/loop_claude/cycle/interrupt.py similarity index 100% rename from bin/loop_claude/claude_runs/interrupt.py rename to bin/loop_claude/cycle/interrupt.py diff --git a/bin/loop_claude/claude_runs/judge.py b/bin/loop_claude/cycle/judge.py similarity index 99% rename from bin/loop_claude/claude_runs/judge.py rename to bin/loop_claude/cycle/judge.py index a9a9052d..655a715b 100644 --- a/bin/loop_claude/claude_runs/judge.py +++ b/bin/loop_claude/cycle/judge.py @@ -4,8 +4,8 @@ import subprocess 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.retry import retried JUDGE_RULES = ( "Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n" diff --git a/bin/loop_claude/retry.py b/bin/loop_claude/cycle/retry.py similarity index 100% rename from bin/loop_claude/retry.py rename to bin/loop_claude/cycle/retry.py diff --git a/bin/loop_claude/cycle.py b/bin/loop_claude/cycle/run.py similarity index 87% rename from bin/loop_claude/cycle.py rename to bin/loop_claude/cycle/run.py index 997f0e65..6106448d 100644 --- a/bin/loop_claude/cycle.py +++ b/bin/loop_claude/cycle/run.py @@ -1,15 +1,15 @@ import dataclasses -from loop_claude.archive import archive from loop_claude.claude_code.session import Session, delete_session, transcript_file from loop_claude.claude_code.transcript import read, render -from loop_claude.claude_runs.interrupt import interrupt -from loop_claude.claude_runs.judge import judge -from loop_claude.claude_runs.worker import run_worker, worker_args +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.retry import retried +from loop_claude.cycle.worker import run_worker, worker_args from loop_claude.outcome import Failure, Stop from loop_claude.paths import Paths from loop_claude.project.models import Models -from loop_claude.retry import retried @dataclasses.dataclass(frozen=True) diff --git a/bin/loop_claude/claude_runs/worker.py b/bin/loop_claude/cycle/worker.py similarity index 100% rename from bin/loop_claude/claude_runs/worker.py rename to bin/loop_claude/cycle/worker.py diff --git a/bin/loop_claude/main.py b/bin/loop_claude/main.py index e791e300..85cc8328 100644 --- a/bin/loop_claude/main.py +++ b/bin/loop_claude/main.py @@ -37,7 +37,7 @@ import dataclasses import sys from loop_claude.claude_code.session import session_for -from loop_claude.cycle import Cycle, run_cycle +from loop_claude.cycle.run import Cycle, run_cycle from loop_claude.outcome import Stop from loop_claude.project.checkout import checkout_root, project_name from loop_claude.project.models import project_models diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 52004cc1..fa0a4475 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -10,7 +10,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from loop_claude import file_writes, main, reload from loop_claude.claude_code import formats, transcript -from loop_claude.claude_runs import judge +from loop_claude.cycle import judge from loop_claude.outcome import Failure, Stop from loop_claude.project import premises diff --git a/todo.md b/todo.md index 79f50f58..30ae1786 100644 --- a/todo.md +++ b/todo.md @@ -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 2f9ab2f named (`docs/decisions.md`), capping dimension first: -- **Group `bin/loop_claude/`'s top-level modules, and name `claude_runs` apart from `claude_code`.** Two seats: eleven modules of mixed altitude side by side. - **Say at `written_by_human` why a `<` prefix marks Claude Code's own entry, and at `trust` why a failure only warns.** Three seats found either only in `CHANGELOG.md`. - **Say in the README why the tests run on the host and need `uv`.** Two seats: `CLAUDE.md` says never run a runtime on the host, and only `test_python_floor.py` says what `uv` is for. - **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. -- 2.52.0 From 7f1142cc76cecc90d449b48fff88dd83fd5c93f3 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 11:57:43 +0200 Subject: [PATCH 111/233] Name the cycle's module steps.py, and group main and reload under loop/ --- bin/loop-claude | 3 ++- bin/loop_claude/cycle/{run.py => steps.py} | 0 bin/loop_claude/loop/__init__.py | 0 bin/loop_claude/{ => loop}/main.py | 4 ++-- bin/loop_claude/{ => loop}/reload.py | 0 bin/test_loop_claude.py | 3 ++- 6 files changed, 6 insertions(+), 4 deletions(-) rename bin/loop_claude/cycle/{run.py => steps.py} (100%) create mode 100644 bin/loop_claude/loop/__init__.py rename bin/loop_claude/{ => loop}/main.py (96%) rename bin/loop_claude/{ => loop}/reload.py (100%) diff --git a/bin/loop-claude b/bin/loop-claude index faeda406..08b6b6ad 100755 --- a/bin/loop-claude +++ b/bin/loop-claude @@ -6,6 +6,7 @@ import sys LAUNCHER = pathlib.Path(__file__).resolve() sys.path.insert(0, str(LAUNCHER.parent)) -from loop_claude import main, paths +from loop_claude import paths +from loop_claude.loop import main sys.exit(main.main(sys.argv[1:], os.environ, paths.paths_from(pathlib.Path.home(), os.environ), LAUNCHER, pathlib.Path.cwd())) diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/steps.py similarity index 100% rename from bin/loop_claude/cycle/run.py rename to bin/loop_claude/cycle/steps.py diff --git a/bin/loop_claude/loop/__init__.py b/bin/loop_claude/loop/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/bin/loop_claude/main.py b/bin/loop_claude/loop/main.py similarity index 96% rename from bin/loop_claude/main.py rename to bin/loop_claude/loop/main.py index 85cc8328..b831f64b 100644 --- a/bin/loop_claude/main.py +++ b/bin/loop_claude/loop/main.py @@ -37,12 +37,12 @@ import dataclasses import sys from loop_claude.claude_code.session import session_for -from loop_claude.cycle.run import Cycle, run_cycle +from loop_claude.cycle.steps import Cycle, run_cycle from loop_claude.outcome import Stop 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 -from loop_claude.reload import RELOAD_FLAG, LoopState, decode_state, exec_if_edited, fingerprint +from loop_claude.loop.reload import RELOAD_FLAG, LoopState, decode_state, exec_if_edited, fingerprint def main(argv, env, paths, launcher, cwd): diff --git a/bin/loop_claude/reload.py b/bin/loop_claude/loop/reload.py similarity index 100% rename from bin/loop_claude/reload.py rename to bin/loop_claude/loop/reload.py diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index fa0a4475..0e24e76a 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -8,9 +8,10 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -from loop_claude import file_writes, main, reload +from loop_claude import file_writes from loop_claude.claude_code import formats, transcript from loop_claude.cycle import judge +from loop_claude.loop import main, reload from loop_claude.outcome import Failure, Stop from loop_claude.project import premises -- 2.52.0 From 277beec2c88c4a78c568f0332e40cfedef1726af Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 12:03:44 +0200 Subject: [PATCH 112/233] Sort main's imports after the move, and file sorting imports on their first binding --- bin/loop_claude/loop/main.py | 2 +- todo.md | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index b831f64b..8277213e 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -38,11 +38,11 @@ import sys from loop_claude.claude_code.session import session_for from loop_claude.cycle.steps import Cycle, run_cycle +from loop_claude.loop.reload import RELOAD_FLAG, LoopState, decode_state, exec_if_edited, fingerprint from loop_claude.outcome import Stop 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 -from loop_claude.loop.reload import RELOAD_FLAG, LoopState, decode_state, exec_if_edited, fingerprint def main(argv, env, paths, launcher, cwd): diff --git a/todo.md b/todo.md index 30ae1786..9092f541 100644 --- a/todo.md +++ b/todo.md @@ -14,6 +14,7 @@ The places the panel on `rebuild` at 2f9ab2f named (`docs/decisions.md`), cappin ## 0.2.0 +- **Sort `bin/`'s imports on their first binding, per `CLAUDE.md` → "Code style".** Today they sort by path, so a module move reorders unchanged lines. - **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. - **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. -- 2.52.0 From fa49aacbd47c54b4192e2b5375fd4b960e9d69c3 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 12:07:11 +0200 Subject: [PATCH 113/233] Drop prose restating what its link or its own file already says --- CLAUDE.md | 4 ++-- agents/product-owner-reviewer.md | 2 +- agents/stability-reviewer.md | 2 +- agents/systems-architect.md | 5 ++--- todo.md | 2 +- 5 files changed, 7 insertions(+), 8 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 9ee4b6fc..2cbfe272 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -39,7 +39,7 @@ Apply it as a question to any design that routes A through B, or has A reach int - **Code & modules.** Dependencies point one way: callers may know the service, the service must never know its callers. Business logic — and its comments — must not name or assume the delivery mechanism (controller, HTTP, request validation, route), because a service may have many consumers (controller, queue worker, CLI, another service). BANNED: `// The controller's validator guarantees these fields`. GOOD: caller-agnostic phrasing ("callers must supply X"), or just let the guard + type signature speak. - **Data & state.** One owner per piece of state, reached through that owner. Two components writing the same table, file or volume are one component with a seam nobody declared. - **Tooling & tests.** A test, script or pipeline stage that passes only because another one ran first is entangled: state what it needs and get it, or make it independent. -- **Vendors & records.** A supplier is a component like any other, so the question above is the whole test: prefer the option tying us to none, and where one is genuinely needed — a capability only it has, or a vendor that is the target itself — know what leaving costs (`~/.claude/principles/technical-principles.md`). Documentation the project owns is the case with no excuse. BANNED: the decision log in `.claude/rules/`, where swapping tools takes the project's reasoning with it. GOOD: `docs/decisions.md`, with a path-scoped rule pointing at it. +- **Vendors & records.** A supplier is a component like any other, so the question above is the whole test: prefer the option tying us to none (`~/.claude/principles/technical-principles.md`). Documentation the project owns is the case with no excuse. BANNED: the decision log in `.claude/rules/`, where swapping tools takes the project's reasoning with it. GOOD: `docs/decisions.md`, with a path-scoped rule pointing at it. - **Proximity is not a reason.** Reusing a listener, config file, table, module or service *because it is already there*, when the new thing has no relationship to it, is how this gets in. If you cannot name the seam, there isn't one. ## One spelling per goal @@ -160,5 +160,5 @@ Default to NO comment. Delete one that is any of: - Commit message and PR title: **one line**, prefixed with the ticket ID when the work has one. Example: `ABC-123 - Regression tests for GET /v4/clients`. Never include the repo/project name (like "twu-4") — we're already in that context. - PR summary: short and concise. No test plan (it lives in the ticket), no link to the ticket (it's in the title). - Keep the project's main checkout (e.g. `~/code/log`, never a worktree) current: when it is behind `origin` — a merge landed, or a fetch shows it — run `git pull --ff-only` there instead of reporting the lag, never with `--autostash`: a dirty checkout is a finding to report, not to carry along. -- Releases follow semver read strictly (`~/.claude/principles/technical-principles.md`): a minor only adds; a consumer's current code, data and scripts survive it unchanged. +- Releases follow semver read strictly (`~/.claude/principles/technical-principles.md`). - Never add `Co-Authored-By: Claude ...`, `🤖 Generated with Claude Code`, or any Claude/Anthropic/Agent marker in commits, PR bodies, issue comments, or anywhere else. diff --git a/agents/product-owner-reviewer.md b/agents/product-owner-reviewer.md index 9f252975..739acafc 100644 --- a/agents/product-owner-reviewer.md +++ b/agents/product-owner-reviewer.md @@ -18,7 +18,7 @@ You consider internal logic **only** when it directly affects an external surfac ## Your Review Method -Before anything else, **read the shared principles** at `~/.claude/principles/`. Two of them are your territory: `rest-apis.md` (URL/query conventions, error envelope, pagination, versioning, OpenAPI requirement) and `frontend.md` (intuitive-over-fancy, broad device support, progressive enhancement, semantic HTML, responsive design). `technical-principles.md` applies where it surfaces externally (timestamps communicated as UTC, idempotent writes). Re-read each time — they change. +Before anything else, **read the shared principles** at `~/.claude/principles/`. Two of them are your territory: `rest-apis.md` and `frontend.md`. `technical-principles.md` applies where it surfaces externally (timestamps communicated as UTC, idempotent writes). Re-read each time — they change. 1. **Identify the change surface**: Read the recent changes and pinpoint what external behavior is affected. If the change is purely internal with no external impact, say so plainly and stop — don't manufacture concerns. diff --git a/agents/stability-reviewer.md b/agents/stability-reviewer.md index 10be9e9f..7db07782 100644 --- a/agents/stability-reviewer.md +++ b/agents/stability-reviewer.md @@ -9,7 +9,7 @@ You are an elite stability-focused code reviewer with deep expertise in defensiv ## First Steps 1. **Scope the change.** You review every PR; a fresh invocation has no prior context, so determine the diff yourself. Diff the PR branch against its base (`gh pr diff`, or `git merge-base HEAD` then `git diff`), and review the changed lines **plus enough surrounding code and callers** to judge correctness — read the whole changed file when practical; a diff alone hides whether a caller breaks. Read the PR description and, when the project uses an issue tracker (project-specific — check its docs) and the change references a ticket, that ticket: the diff is judged against its stated intent, and a scope mismatch in either direction is a finding — claimed-but-unimplemented, and implemented-but-unasked (#2). -2. **Read every file in the shared principles** at `~/.claude/principles/` — not just `technical-principles.md`, also `frontend.md`, `logging.md`, and `rest-apis.md`. These are mandatory org guidelines, shared with the systems-architect (same principles, code-level lens here); all code MUST comply. Map the relevant file(s) to the change (frontend PR → `frontend.md`; API PR → `rest-apis.md`; etc.). Re-read each time — they change. Flag violations prominently. +2. **Read every file in the shared principles** at `~/.claude/principles/` — not just `technical-principles.md`, also `frontend.md`, `logging.md`, and `rest-apis.md`. These are mandatory org guidelines; all code MUST comply. Map the relevant file(s) to the change (frontend PR → `frontend.md`; API PR → `rest-apis.md`; etc.). Re-read each time — they change. Flag violations prominently. 3. **Read README.md, AGENTS.md and `docs/decisions.md`** in the current project for project-specific conventions, build instructions, tooling, and the accepted trade-offs a reviewer should honor rather than re-flag. Note the documented test, lint, and static-analysis commands — you will run them. 4. **Verify, don't just read.** Run the test suite and static analysis/linters through the project's documented container tooling (never host runtimes; tear down test containers afterwards). A full-suite run catches broken callers that diff-reading misses. When a suspected bug is cheap to confirm, reproduce it — a scratch script in a temp dir, a targeted test run — before reporting it. Leave the working tree exactly as you found it. Anything you could not run goes in Coverage & Verification, never silently skipped. 5. **Two passes minimum, then hunt absences.** diff --git a/agents/systems-architect.md b/agents/systems-architect.md index 24b8bb78..1b19360a 100644 --- a/agents/systems-architect.md +++ b/agents/systems-architect.md @@ -56,7 +56,7 @@ You work in distinct stages. Never skip stages. Never collapse them. Goals, audi ### Stage 0: Establish goals, audience, scale & domain language (do this first) You cannot judge whether an implementation is the best one without a yardstick. The yardstick is five artifacts: **the audience** (who this is for — concrete roles, not "users"), **the problem statement** (what hurts without this), **the goals and their priority order** (including which failure classes are intolerable — the correctness targets the test machinery is priced against), **the scale & horizon** (expected load and data volume in orders of magnitude, team and consumer count, and the intended lifetime — throwaway experiment / MVP / production / long-lived platform — with a promotion event, the one that graduates it and forces re-review), and **the domain glossary** — the ubiquitous language: each core domain concept, one name, one line of meaning. Every name in the design must come from it. -- **Gather** them — read the README, CLAUDE.md, AGENTS.md, the shared principles at `~/.claude/principles/` (org-wide constraints every design must satisfy — the same set the stability-reviewer enforces at code level, applied here through an architectural lens), the relevant ticket, and any design docs. What isn't written down is a question for the user. +- **Gather** them — read the README, CLAUDE.md, AGENTS.md, the shared principles at `~/.claude/principles/` (org-wide constraints every design must satisfy), the relevant ticket, and any design docs. What isn't written down is a question for the user. - **Test** them: Is the audience concrete? Does the problem statement name the pain, not the solution? Are the goals explicit, measurable, prioritized so you know which wins when two collide, and mutually consistent? Is the horizon stated — spike or platform? Nothing is fit for a purpose whose size and lifespan are unknown. Does the glossary give each concept exactly one name? - **Fix first if broken.** Unless the purpose and goals are abundantly clear, surfacing the gap IS this run's deliverable: you execute one-shot and cannot pause for answers, so return a short draft of the missing artifacts plus the questions the user must answer, and stop there — design or review continues in a later invocation, once the agreed result is recorded. A missing audience, problem statement, scale & horizon, or glossary is the same fix-first gap. Never design against guessed goals, a guessed audience, or invented vocabulary — surface the ambiguity instead. @@ -134,7 +134,6 @@ You review the seams that make verification possible and the strategy that uses - **The external contract is executably pinned.** Contract tests fail when a published shape breaks — the lock on that one-way door. Price them like the versioning machinery (The External Contract): zero consumers outside your control, defer; many, mandatory. - **Load targets come from Stage 0.** Load and performance tests verify the recorded scale numbers; no recorded scale, nothing to verify — fix Stage 0 first (a rig for unrecorded load is "Hunt the imagined requirement" wearing a QA hat). Data and traffic are production-shaped — a load run against a 1000-row database measures nothing. Runs are scheduled outside the merge gate (see Delivery); determinism here means a repeatable method against fixed thresholds, not identical latencies. - **Post-deploy production suites are a designed capability.** Tagged, idempotent synthetic traffic against external surfaces only (API, UI), built once and run twice: post-deploy smoke and scheduled monitoring. It asserts liveness of the deployed surface, not logic — logic determinism lives in the pre-merge suites. Self-cleaning means expendable-by-design: a synthetic tenant or TTL-tagged data reaped out-of-band, never teardown-in-the-test, and never a delete endpoint added to the contract only for tests. Side effects are sandboxed by design — a synthetic checkout must never charge a real card — and the synthetic marking propagates through every downstream sink (telemetry, billing, analytics) so real signals stay uncontaminated; a tag that dies at the API edge is a missing seam. -- **Depth scales with the recorded horizon; the seams do not.** E2e breadth, load rigs, and post-deploy suites are ceremony — price them by horizon, blast radius, and the intolerable failures Stage 0 records. An injected clock and a pure core are fundamentals — scale-invariant (Core Philosophy: rigor follows the horizon). ## Delivery (the path to production is architecture) @@ -149,7 +148,7 @@ How a change ships — merge gate, pipeline, deployment, dependencies — is a d ## Reviewing Existing Work (periodic alignment) -You are not a per-PR reviewer. The **stability-reviewer** runs on every change for code-level safety; you run deliberately, every so often, to check the system is still aligned — right goals, right contract, right foundations, sound structure. When you do look at a specific PR, it is because the work touches architectural fundamentals or reopens foundational choices, not for routine line-level review. Stage 0 blocks review as much as design: if the project's purpose and goals are not abundantly clear from its docs, this run's output is the clarifying questions plus a short draft to confirm — not a review; the review happens in a later invocation, once the answers are recorded in the README. +You are not a per-PR reviewer. The **stability-reviewer** runs on every change for code-level safety; you run deliberately, every so often, to check the system is still aligned — right goals, right contract, right foundations, sound structure. When you do look at a specific PR, it is because the work touches architectural fundamentals or reopens foundational choices, not for routine line-level review. **Verdict and severities: ~/.claude/skills/larv-review/review-findings.md.** A violation of a non-negotiable fundamental — functional-core/shell entanglement, a unit past a Fits in a head threshold without a stated reason, a method or file carrying more than one responsibility, unreasoned duplication of a core concept, or a broken/leaky external contract — is a 🔴: lead with it, and name the concrete restructuring. The most common instance: a pure transformation (a deterministic input→output computation) entangled inside an imperative-shell or orchestration method, where it could be a named, separately-testable function. The architectural defect being real, not its line count or "how much it works today," sets the severity; rate a non-fundamental finding by its eventual cost — the recorded horizon sets that cost; fundamentals stay 🔴 at every horizon (Core Philosophy: rigor follows the horizon). diff --git a/todo.md b/todo.md index 9092f541..2a57e63d 100644 --- a/todo.md +++ b/todo.md @@ -14,7 +14,7 @@ The places the panel on `rebuild` at 2f9ab2f named (`docs/decisions.md`), cappin ## 0.2.0 -- **Sort `bin/`'s imports on their first binding, per `CLAUDE.md` → "Code style".** Today they sort by path, so a module move reorders unchanged lines. +- **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. - **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. -- 2.52.0 From d38b354538b38cc139ec9cf1817f96e274a4b496 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 12:08:50 +0200 Subject: [PATCH 114/233] Say why a leading < marks Claude Code's entry and why a trust failure only warns --- bin/loop_claude/claude_code/formats.py | 1 + bin/loop_claude/claude_code/trust.py | 1 + todo.md | 1 - 3 files changed, 2 insertions(+), 1 deletion(-) diff --git a/bin/loop_claude/claude_code/formats.py b/bin/loop_claude/claude_code/formats.py index a274b6dc..c25362a1 100644 --- a/bin/loop_claude/claude_code/formats.py +++ b/bin/loop_claude/claude_code/formats.py @@ -36,6 +36,7 @@ def written_by_human(entry): # {"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("<")) diff --git a/bin/loop_claude/claude_code/trust.py b/bin/loop_claude/claude_code/trust.py index bec5ac16..df71ce96 100644 --- a/bin/loop_claude/claude_code/trust.py +++ b/bin/loop_claude/claude_code/trust.py @@ -6,6 +6,7 @@ from loop_claude.file_writes import replace_json 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): try: with open(config, encoding="utf-8") as handle: diff --git a/todo.md b/todo.md index 2a57e63d..bdd22e27 100644 --- a/todo.md +++ b/todo.md @@ -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 2f9ab2f named (`docs/decisions.md`), capping dimension first: -- **Say at `written_by_human` why a `<` prefix marks Claude Code's own entry, and at `trust` why a failure only warns.** Three seats found either only in `CHANGELOG.md`. - **Say in the README why the tests run on the host and need `uv`.** Two seats: `CLAUDE.md` says never run a runtime on the host, and only `test_python_floor.py` says what `uv` is for. - **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. -- 2.52.0 From 411ec14c6c9703eb7f5f8c92fa13425eccae6210 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 12:10:17 +0200 Subject: [PATCH 115/233] Say in the README why the tests run on the host and need uv --- README.md | 2 +- todo.md | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 1bf70584..179a1473 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, and tag that co - `loop-claude ` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract. -Test, with `uv` on `PATH`: `python3 -m unittest discover -s bin -p 'test_*.py'` +Test on the host, where `loop-claude` drives `claude`, with `uv` on `PATH` to fetch the Python Install names (`docs/decisions.md`): `python3 -m unittest discover -s bin -p 'test_*.py'` ## Tracking a new file diff --git a/todo.md b/todo.md index bdd22e27..79797d04 100644 --- a/todo.md +++ b/todo.md @@ -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 2f9ab2f named (`docs/decisions.md`), capping dimension first: -- **Say in the README why the tests run on the host and need `uv`.** Two seats: `CLAUDE.md` says never run a runtime on the host, and only `test_python_floor.py` says what `uv` is for. - **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. ## 0.2.0 -- 2.52.0 From 2c74bbcbba31da63f57a68334946e6b736b1d88d Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 12:11:23 +0200 Subject: [PATCH 116/233] Point the Test line at both bin/ decisions, and correct the floor entry's example --- README.md | 2 +- docs/decisions.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 179a1473..b2a838ea 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, and tag that co - `loop-claude ` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract. -Test on the host, where `loop-claude` drives `claude`, with `uv` on `PATH` to fetch the Python Install names (`docs/decisions.md`): `python3 -m unittest discover -s bin -p 'test_*.py'` +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'` ## Tracking a new file diff --git a/docs/decisions.md b/docs/decisions.md index 85d32e6c..2924ac05 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -22,11 +22,11 @@ ## bin/: the Python floor is README's Install prerequisite -2026-09-26, larv-review, carrying the floor the 2026-09-26 stability round assumed and verified its f-string fix under. Serves goal 1. The suite reruns itself on a `uv`-fetched interpreter of the version Install names: `ast.parse(feature_version=)` on the host's Python accepts the nested f-string 186181a fixed, a compile check passes a 3.11-only call like `contextlib.chdir`, and a `python3.N` on `PATH` is installed by hand on every machine and again at each bump. Valid while no machine taking the checkout ships an older Python. +2026-09-26, larv-review. Serves goal 1. The suite reruns itself on a `uv`-fetched interpreter of the version Install names: `ast.parse(feature_version=)` on the host's Python accepts the nested f-string 186181a fixed, a compile check passes a call newer than the floor, like 3.12's `itertools.batched`, and a `python3.N` on `PATH` is installed by hand on every machine and again at each bump. Valid while `uv` can fetch the floor interpreter and no machine taking the checkout ships an older Python. ## bin/: host python, no container -2026-09-24, larv-review. Serves goals 1 and 4. The tools drive the host's claude CLI and read the host's session files, which a container cannot see; the tests run the same way. Valid while claude runs on the host. +2026-09-24, larv-review. Serves goals 1 and 4. The tools drive the host's claude CLI and read the host's session files, which a container cannot see; the tests run on the same host Python the tools meet. Valid while claude runs on the host. ## comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it -- 2.52.0 From 738a82a2838cf577ebd29127fb3ef56c32c195ba Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 12:16:41 +0200 Subject: [PATCH 117/233] File the places the panel on rebuild at 2c74bbc named under the floor --- docs/decisions.md | 2 +- todo.md | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index 2924ac05..7e768a72 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -30,7 +30,7 @@ ## comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it -2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, and 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters; the places the last run named are filed in `todo.md` under 0.1.0, and a later chunk may not lower any dimension. Valid until the next scoring run, which uses the same four seats. +2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files; the places the last run named are filed in `todo.md` under 0.1.0, and a later chunk may not lower any dimension. Valid until the next scoring run, which uses the same four seats. ## vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link diff --git a/todo.md b/todo.md index 79797d04..5d0a263a 100644 --- a/todo.md +++ b/todo.md @@ -6,8 +6,11 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens `rebuild`'s PR into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -The places the panel on `rebuild` at 2f9ab2f named (`docs/decisions.md`), capping dimension first: +The places the panel on `rebuild` at 2c74bbc named (`docs/decisions.md`), capping dimension first: +- **Define a round, how it is prompted and when its pass is done under larv-review's "Round cap" alone, with `review-findings.md` → "Rounds" left to what a reviewer does in one.** Every seat paid a round trip between the two files, which each send a reader to the other. +- **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. ## 0.2.0 -- 2.52.0 From 6f6972949ff5a5bd847f14d519a337b6379a836c Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 12:17:30 +0200 Subject: [PATCH 118/233] Leave the round's definition to its 0.1.0 item, and ratchet the floor per scoring run --- docs/decisions.md | 2 +- todo.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index 7e768a72..5f10207f 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -30,7 +30,7 @@ ## comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it -2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files; the places the last run named are filed in `todo.md` under 0.1.0, and a later chunk may not lower any dimension. Valid until the next scoring run, which uses the same four seats. +2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files; the places the last run named are filed in `todo.md` under 0.1.0, and a later scoring run may not lower any dimension. Valid until the next scoring run, which uses the same four seats. ## vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link diff --git a/todo.md b/todo.md index 5d0a263a..79c9945a 100644 --- a/todo.md +++ b/todo.md @@ -22,7 +22,7 @@ The places the panel on `rebuild` at 2c74bbc named (`docs/decisions.md`), cappin - **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. - **Give `docs/decisions.md`'s comprehension-floor and vocabulary entries a premise that has not already expired, with the floor's rule first and its runs' scores as a table, and give the rebuild entry's warning placement its own heading and index line.** A prose pass found both "Valid until the next scoring run" outlived by three runs. -- **Move larv-review's reasons for `/security-review` and for the premises chunk's review into `docs/decisions.md`, and inline in `review-findings.md` what a round is.** A prose pass found rejected alternatives at the rule, and a pointer back to `SKILL.md`, which points here. +- **Move larv-review's reasons for `/security-review` and for the premises chunk's review into `docs/decisions.md`.** A prose pass found rejected alternatives at the rule. - **Cut `comprehension-panel`'s run history and the restated description, `systems-architect.md`'s "one home" line, and split its Reasonability Review steps 4 and 5.** A prose pass found them carrying nothing the instructions need. - **Keep `outcome.Failure`'s docstring to what a failure is, without naming `retried`.** A value type naming its consumer. - **Say in `AGENTS.md` that only the rebuild's last chunk opens `rebuild`'s PR into main.** Today it reads as every chunk doing so. -- 2.52.0 From 2f9ee68660554042371524f1d548b4710dddda26 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 12:19:05 +0200 Subject: [PATCH 119/233] Define a round, its prompt and when its pass is done under larv-review's Round cap alone --- skills/larv-review/SKILL.md | 4 ++-- skills/larv-review/review-findings.md | 7 ++----- todo.md | 1 - 3 files changed, 4 insertions(+), 8 deletions(-) diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 460e293d..14721d77 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -37,7 +37,7 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod **Record, then ask**, for the architecture pass and the full scan: where the repo holds the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: skip it and cite the record. A change that *departs* from the record is unreviewed however thorough the record is. Fired with no record behind it → ask the user with the evidence and your recommendation; no user reachable → run it. -**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a Stage 0 rerun included; how a round is prompted and when a pass is done, the findings document → "Rounds". The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the prose pass's round is its fresh-context agent; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. +**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a Stage 0 rerun included. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the prose pass's round is its fresh-context agent; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt the reviewer with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡; the 🟢 and ❓ left are addressed in that round — fixed, answered, declined or filed in `todo.md` — and take no round of their own. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. **Re-entry.** A fix is a change no pass has seen. A round's fixes re-enter together: run, in table order, each pass whose trigger they fire and the pass whose 🔴 or 🟡 they answer; then §4. @@ -62,7 +62,7 @@ The full-scan plugin is not enabled by default; unavailable → say so in the su ### Stability and product-owner -Launch the reviewer with the change — product-owner-reviewer also with the external surface it touches — prompted per the findings document's rounds. Fix along the reviewer's Fix guidance (delete > simplify > modify > add). Product-owner findings are about the consumer's experience — wording, discoverability, upgrade path, the edge case a persona hits — so the fix is as often a message or a doc as it is code. Commit and push each round so CI feedback accumulates. +Launch the reviewer with the change — product-owner-reviewer also with the external surface it touches — prompted per §3 → "Round cap". Fix along the reviewer's Fix guidance (delete > simplify > modify > add). Product-owner findings are about the consumer's experience — wording, discoverability, upgrade path, the edge case a persona hits — so the fix is as often a message or a doc as it is code. Commit and push each round so CI feedback accumulates. ### Prose diff --git a/skills/larv-review/review-findings.md b/skills/larv-review/review-findings.md index 606fb70b..697f3608 100644 --- a/skills/larv-review/review-findings.md +++ b/skills/larv-review/review-findings.md @@ -27,11 +27,8 @@ A review's first line, derived from the findings: ## Rounds -A round: `SKILL.md` → "Round cap". - -- Surface everything in round 1. -- From round 2 the prompt carries the previous round's findings verbatim and what changed since. Verify each earlier 🔴 and 🟡 is resolved — re-run the scenario, never trust the claim — then review what changed. A fix raises a new finding only where the fix itself introduced a real problem. -- A pass is done on no 🔴 and no 🟡. The 🟢 and ❓ left are addressed in that round — fixed, answered, declined or filed in `todo.md` — and take no further round of their own; their fixes re-enter per `SKILL.md` → "Re-entry". +- Round 1: surface everything. +- Handed an earlier round's findings: verify each 🔴 and 🟡 is resolved — re-run the scenario, never trust the claim — then review what changed. A fix raises a new finding only where the fix itself introduced a real problem. ## Declining diff --git a/todo.md b/todo.md index 79c9945a..02acdc04 100644 --- a/todo.md +++ b/todo.md @@ -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: -- **Define a round, how it is prompted and when its pass is done under larv-review's "Round cap" alone, with `review-findings.md` → "Rounds" left to what a reviewer does in one.** Every seat paid a round trip between the two files, which each send a reader to the other. - **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. -- 2.52.0 From 2de5141d89f53b89dbf207a79594fc6386828b77 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 12:20:03 +0200 Subject: [PATCH 120/233] Prompt only a reviewer agent with earlier findings, and drop restatements of when a pass is done --- skills/larv-review/SKILL.md | 6 +++--- skills/larv-review/review-findings.md | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 14721d77..e1972a29 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -37,7 +37,7 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod **Record, then ask**, for the architecture pass and the full scan: where the repo holds the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: skip it and cite the record. A change that *departs* from the record is unreviewed however thorough the record is. Fired with no record behind it → ask the user with the evidence and your recommendation; no user reachable → run it. -**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a Stage 0 rerun included. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the prose pass's round is its fresh-context agent; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt the reviewer with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡; the 🟢 and ❓ left are addressed in that round — fixed, answered, declined or filed in `todo.md` — and take no round of their own. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. +**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a Stage 0 rerun included. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the prose pass's round is its fresh-context agent; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt a reviewer agent with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡; the 🟢 and ❓ left are addressed in that round — fixed, answered, declined or filed in `todo.md` — and take no round of their own. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. **Re-entry.** A fix is a change no pass has seen. A round's fixes re-enter together: run, in table order, each pass whose trigger they fire and the pass whose 🔴 or 🟡 they answer; then §4. @@ -62,7 +62,7 @@ The full-scan plugin is not enabled by default; unavailable → say so in the su ### Stability and product-owner -Launch the reviewer with the change — product-owner-reviewer also with the external surface it touches — prompted per §3 → "Round cap". Fix along the reviewer's Fix guidance (delete > simplify > modify > add). Product-owner findings are about the consumer's experience — wording, discoverability, upgrade path, the edge case a persona hits — so the fix is as often a message or a doc as it is code. Commit and push each round so CI feedback accumulates. +Launch the reviewer with the change — product-owner-reviewer also with the external surface it touches. Fix along the reviewer's Fix guidance (delete > simplify > modify > add). Product-owner findings are about the consumer's experience — wording, discoverability, upgrade path, the edge case a persona hits — so the fix is as often a message or a doc as it is code. Commit and push each round so CI feedback accumulates. ### Prose @@ -86,7 +86,7 @@ The bar is `~/.claude/CLAUDE.md` → "Comments and documentation"; per paragraph 2. Watch the forge's checks until every one passes. A red check is a finding; its fix re-enters per §3. 3. No CI configured → the gate is local tests only; note it in the summary. 4. Everything green → mark the PR ready, dropping any `WIP:`/`Draft:` title prefix. -5. **External auto-reviewer**, when the repo has one — its config file (`.coderabbit.yaml` and the like), or its comments on earlier PRs; none → skip it, say so. Marking the PR ready is what summons it. Wait up to **10 minutes** for its first review, checking about once a minute; nothing by then → note it in the summary and carry on, never waiting twice. Its findings follow the findings document like any reviewer's; its rounds, §3 → "Round cap". Once it has reviewed, each later return here, after a fix re-entered per §3, waits up to **5 minutes** for its re-review of the new commit. +5. **External auto-reviewer**, when the repo has one — its config file (`.coderabbit.yaml` and the like), or its comments on earlier PRs; none → skip it, say so. Marking the PR ready is what summons it. Wait up to **10 minutes** for its first review, checking about once a minute; nothing by then → note it in the summary and carry on, never waiting twice. Its rounds, §3 → "Round cap". Once it has reviewed, each later return here, after a fix re-entered per §3, waits up to **5 minutes** for its re-review of the new commit. ## 5. Goal alignment, then merge diff --git a/skills/larv-review/review-findings.md b/skills/larv-review/review-findings.md index 697f3608..39f53e92 100644 --- a/skills/larv-review/review-findings.md +++ b/skills/larv-review/review-findings.md @@ -8,7 +8,7 @@ A reviewer reads and reports; it edits nothing. Read `docs/decisions.md` and `to - 🔴 **must fix** — a goal, a principle or correctness broken. Fixed, or shown factually wrong, with what disproved it recorded in `docs/decisions.md`; never declined. - 🟡 **should fix** — worse than it needs to be. Fixed, declined, or — outside the chunk — filed in `todo.md`. -- 🟢 **nit** — never holds a pass. +- 🟢 **nit**. - ❓ **question** for the author: a finding you could not confirm goes here, not above. - 🔀 **escalation** — names the reviewer whose concern it is (`product-owner-reviewer`, `systems-architect` or `/security-review`) and why, in one line. The orchestrator runs it. @@ -27,7 +27,7 @@ A review's first line, derived from the findings: ## Rounds -- Round 1: surface everything. +- Handed no earlier findings: surface everything. - Handed an earlier round's findings: verify each 🔴 and 🟡 is resolved — re-run the scenario, never trust the claim — then review what changed. A fix raises a new finding only where the fix itself introduced a real problem. ## Declining -- 2.52.0 From 0842135b87026610365554d20d61086fcb4841a5 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 12:20:25 +0200 Subject: [PATCH 121/233] Name the agents prompted with earlier findings --- skills/larv-review/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index e1972a29..a43a7e93 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -37,7 +37,7 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod **Record, then ask**, for the architecture pass and the full scan: where the repo holds the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: skip it and cite the record. A change that *departs* from the record is unreviewed however thorough the record is. Fired with no record behind it → ask the user with the evidence and your recommendation; no user reachable → run it. -**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a Stage 0 rerun included. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the prose pass's round is its fresh-context agent; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt a reviewer agent with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡; the 🟢 and ❓ left are addressed in that round — fixed, answered, declined or filed in `todo.md` — and take no round of their own. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. +**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a Stage 0 rerun included. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the prose pass's round is its fresh-context agent; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡; the 🟢 and ❓ left are addressed in that round — fixed, answered, declined or filed in `todo.md` — and take no round of their own. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. **Re-entry.** A fix is a change no pass has seen. A round's fixes re-enter together: run, in table order, each pass whose trigger they fire and the pass whose 🔴 or 🟡 they answer; then §4. -- 2.52.0 From d13658967aeb24fcdecfb85fdd3538ac4edac4ec Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 12:23:37 +0200 Subject: [PATCH 122/233] Annotate the return type of every function in loop_claude --- bin/loop_claude/claude_code/catalog.py | 2 +- bin/loop_claude/claude_code/formats.py | 26 +++++++++++------------ bin/loop_claude/claude_code/session.py | 6 +++--- bin/loop_claude/claude_code/transcript.py | 8 +++---- bin/loop_claude/claude_code/trust.py | 2 +- bin/loop_claude/cycle/archive.py | 2 +- bin/loop_claude/cycle/interrupt.py | 2 +- bin/loop_claude/cycle/judge.py | 12 +++++------ bin/loop_claude/cycle/retry.py | 5 ++++- bin/loop_claude/cycle/steps.py | 7 +++--- bin/loop_claude/cycle/worker.py | 4 ++-- bin/loop_claude/file_writes.py | 6 +++--- bin/loop_claude/human_needed.py | 4 ++-- bin/loop_claude/loop/main.py | 6 +++--- bin/loop_claude/loop/reload.py | 7 +++--- bin/loop_claude/paths.py | 2 +- bin/loop_claude/project/checkout.py | 6 +++--- bin/loop_claude/project/models.py | 8 +++---- bin/loop_claude/project/premises.py | 4 ++-- todo.md | 1 - 20 files changed, 62 insertions(+), 58 deletions(-) diff --git a/bin/loop_claude/claude_code/catalog.py b/bin/loop_claude/claude_code/catalog.py index b3ebe58a..da9ec815 100644 --- a/bin/loop_claude/claude_code/catalog.py +++ b/bin/loop_claude/claude_code/catalog.py @@ -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: diff --git a/bin/loop_claude/claude_code/formats.py b/bin/loop_claude/claude_code/formats.py index c25362a1..46400baa 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): +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": "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: diff --git a/bin/loop_claude/claude_code/session.py b/bin/loop_claude/claude_code/session.py index c2834a50..a54b97c4 100644 --- a/bin/loop_claude/claude_code/session.py +++ b/bin/loop_claude/claude_code/session.py @@ -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) # /-home-me-code-log/.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 diff --git a/bin/loop_claude/claude_code/transcript.py b/bin/loop_claude/claude_code/transcript.py index e73ffdbb..5d5fbb79 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): +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): diff --git a/bin/loop_claude/claude_code/trust.py b/bin/loop_claude/claude_code/trust.py index df71ce96..7b96bdf5 100644 --- a/bin/loop_claude/claude_code/trust.py +++ b/bin/loop_claude/claude_code/trust.py @@ -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) diff --git a/bin/loop_claude/cycle/archive.py b/bin/loop_claude/cycle/archive.py index 50843a72..8fb9d770 100644 --- a/bin/loop_claude/cycle/archive.py +++ b/bin/loop_claude/cycle/archive.py @@ -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: diff --git a/bin/loop_claude/cycle/interrupt.py b/bin/loop_claude/cycle/interrupt.py index dc6ea0d5..4a4164d3 100644 --- a/bin/loop_claude/cycle/interrupt.py +++ b/bin/loop_claude/cycle/interrupt.py @@ -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 diff --git a/bin/loop_claude/cycle/judge.py b/bin/loop_claude/cycle/judge.py index 655a715b..8e62889b 100644 --- a/bin/loop_claude/cycle/judge.py +++ b/bin/loop_claude/cycle/judge.py @@ -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 diff --git a/bin/loop_claude/cycle/retry.py b/bin/loop_claude/cycle/retry.py index 0c0082cf..b4386ce9 100644 --- a/bin/loop_claude/cycle/retry.py +++ b/bin/loop_claude/cycle/retry.py @@ -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): diff --git a/bin/loop_claude/cycle/steps.py b/bin/loop_claude/cycle/steps.py index 6106448d..4ea60dfe 100644 --- a/bin/loop_claude/cycle/steps.py +++ b/bin/loop_claude/cycle/steps.py @@ -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) diff --git a/bin/loop_claude/cycle/worker.py b/bin/loop_claude/cycle/worker.py index 3d0c6bdc..598c66b2 100644 --- a/bin/loop_claude/cycle/worker.py +++ b/bin/loop_claude/cycle/worker.py @@ -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: diff --git a/bin/loop_claude/file_writes.py b/bin/loop_claude/file_writes.py index 9db6bea0..9fdadbb7 100644 --- a/bin/loop_claude/file_writes.py +++ b/bin/loop_claude/file_writes.py @@ -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 diff --git a/bin/loop_claude/human_needed.py b/bin/loop_claude/human_needed.py index d976ed57..6e3d372a 100644 --- a/bin/loop_claude/human_needed.py +++ b/bin/loop_claude/human_needed.py @@ -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") diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 8277213e..5ef639a9 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -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"): diff --git a/bin/loop_claude/loop/reload.py b/bin/loop_claude/loop/reload.py index cc990db4..2f5949a8 100644 --- a/bin/loop_claude/loop/reload.py +++ b/bin/loop_claude/loop/reload.py @@ -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) diff --git a/bin/loop_claude/paths.py b/bin/loop_claude/paths.py index e93065b8..b0a1dd28 100644 --- a/bin/loop_claude/paths.py +++ b/bin/loop_claude/paths.py @@ -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", diff --git a/bin/loop_claude/project/checkout.py b/bin/loop_claude/project/checkout.py index 8d56d06d..3400e389 100644 --- a/bin/loop_claude/project/checkout.py +++ b/bin/loop_claude/project/checkout.py @@ -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("/") diff --git a/bin/loop_claude/project/models.py b/bin/loop_claude/project/models.py index 6bae6c7c..88d25c78 100644 --- a/bin/loop_claude/project/models.py +++ b/bin/loop_claude/project/models.py @@ -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}\": \"\"}} into {saved}"): return stop offered = offered_models(folder) diff --git a/bin/loop_claude/project/premises.py b/bin/loop_claude/project/premises.py index fb266e25..d3f121c4 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): +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("```") diff --git a/todo.md b/todo.md index 02acdc04..44d99256 100644 --- a/todo.md +++ b/todo.md @@ -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. -- 2.52.0 From 89a66d37a08221b1e757e6a66a9427b7b7a2549f Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 12:25:37 +0200 Subject: [PATCH 123/233] File checking loop_claude's annotations in the gate --- todo.md | 1 + 1 file changed, 1 insertion(+) diff --git a/todo.md b/todo.md index 44d99256..c0729d64 100644 --- a/todo.md +++ b/todo.md @@ -16,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. -- 2.52.0 From 099e9e19a5fcc64cbd6612143cdfffdf1f0c2bad Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 15:46:09 +0200 Subject: [PATCH 124/233] Pin mypy passing on loop_claude at the Python floor --- bin/test_python_floor.py | 10 +++++++--- bin/test_types.py | 16 ++++++++++++++++ 2 files changed, 23 insertions(+), 3 deletions(-) create mode 100644 bin/test_types.py diff --git a/bin/test_python_floor.py b/bin/test_python_floor.py index 1c5e0ef4..65826d66 100644 --- a/bin/test_python_floor.py +++ b/bin/test_python_floor.py @@ -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: diff --git a/bin/test_types.py b/bin/test_types.py new file mode 100644 index 00000000..4cc1ba75 --- /dev/null +++ b/bin/test_types.py @@ -0,0 +1,16 @@ +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") + version = "%d.%d" % floor + ran = subprocess.run(["uv", "tool", "run", "--python", version, "mypy==2.3.1", "--check-untyped-defs", "--python-version", version, "-p", "loop_claude"], capture_output=True, cwd=ROOT / "bin", text=True) + self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr) -- 2.52.0 From 6e643cc87c12dee0f226b47320d65931fd757050 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 15:47:41 +0200 Subject: [PATCH 125/233] Pass mypy on loop_claude --- README.md | 2 +- bin/loop_claude/claude_code/formats.py | 6 +++--- bin/loop_claude/claude_code/trust.py | 4 ++-- bin/loop_claude/cycle/archive.py | 4 ++-- bin/loop_claude/cycle/retry.py | 5 +++-- bin/loop_claude/cycle/worker.py | 2 +- bin/loop_claude/file_writes.py | 2 +- bin/loop_claude/project/models.py | 4 ++-- bin/loop_claude/project/premises.py | 5 +++-- todo.md | 1 - 10 files changed, 18 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index b2a838ea..ff56b5a3 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, and tag that co - `loop-claude ` 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 diff --git a/bin/loop_claude/claude_code/formats.py b/bin/loop_claude/claude_code/formats.py index 46400baa..031d97e8 100644 --- a/bin/loop_claude/claude_code/formats.py +++ b/bin/loop_claude/claude_code/formats.py @@ -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 [] diff --git a/bin/loop_claude/claude_code/trust.py b/bin/loop_claude/claude_code/trust.py index 7b96bdf5..10072ce4 100644 --- a/bin/loop_claude/claude_code/trust.py +++ b/bin/loop_claude/claude_code/trust.py @@ -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) diff --git a/bin/loop_claude/cycle/archive.py b/bin/loop_claude/cycle/archive.py index 8fb9d770..77febd34 100644 --- a/bin/loop_claude/cycle/archive.py +++ b/bin/loop_claude/cycle/archive.py @@ -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 diff --git a/bin/loop_claude/cycle/retry.py b/bin/loop_claude/cycle/retry.py index b4386ce9..5395f439 100644 --- a/bin/loop_claude/cycle/retry.py +++ b/bin/loop_claude/cycle/retry.py @@ -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 diff --git a/bin/loop_claude/cycle/worker.py b/bin/loop_claude/cycle/worker.py index 598c66b2..a000da35 100644 --- a/bin/loop_claude/cycle/worker.py +++ b/bin/loop_claude/cycle/worker.py @@ -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): diff --git a/bin/loop_claude/file_writes.py b/bin/loop_claude/file_writes.py index 9fdadbb7..f0099901 100644 --- a/bin/loop_claude/file_writes.py +++ b/bin/loop_claude/file_writes.py @@ -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 diff --git a/bin/loop_claude/project/models.py b/bin/loop_claude/project/models.py index 88d25c78..e7c51360 100644 --- a/bin/loop_claude/project/models.py +++ b/bin/loop_claude/project/models.py @@ -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 diff --git a/bin/loop_claude/project/premises.py b/bin/loop_claude/project/premises.py index d3f121c4..f9f2ee8c 100644 --- a/bin/loop_claude/project/premises.py +++ b/bin/loop_claude/project/premises.py @@ -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)) diff --git a/todo.md b/todo.md index c0729d64..44d99256 100644 --- a/todo.md +++ b/todo.md @@ -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. -- 2.52.0 From b32d131a0c8d1fb521304fd799b4eb98e85c341b Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 15:47:52 +0200 Subject: [PATCH 126/233] Record mypy checking loop_claude's types --- AGENTS.md | 1 + docs/decisions.md | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index aae2900d..c72a2249 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 diff --git a/docs/decisions.md b/docs/decisions.md index 5f10207f..2a66a4fb 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -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. -- 2.52.0 From 628ee30f2a4449dcfe83f79f1bf610f0c0b008a1 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 15:50:49 +0200 Subject: [PATCH 127/233] Run mypy without a cache and name the floor once --- bin/test_types.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/bin/test_types.py b/bin/test_types.py index 4cc1ba75..0098a6c3 100644 --- a/bin/test_types.py +++ b/bin/test_types.py @@ -11,6 +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") - version = "%d.%d" % floor - ran = subprocess.run(["uv", "tool", "run", "--python", version, "mypy==2.3.1", "--check-untyped-defs", "--python-version", version, "-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", "-p", "loop_claude"], capture_output=True, cwd=ROOT / "bin", text=True) self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr) -- 2.52.0 From 507c3beca5103fe22c877972930ebea2891a182c Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Tue, 29 Sep 2026 18:48:20 +0200 Subject: [PATCH 128/233] Name the pass table's column Trigger, define a pass, and plan benching the rebuilt larv-review --- AGENTS.md | 1 + CLAUDE.md | 1 + docs/decisions.md | 4 ++++ skills/larv-review/SKILL.md | 8 ++++---- todo.md | 2 +- 5 files changed, 11 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c72a2249..4d7bac56 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,3 +25,4 @@ Decisions live in `docs/decisions.md`: - 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 +- rebuild: main's larv-review reviews a chunk into `rebuild` diff --git a/CLAUDE.md b/CLAUDE.md index 2cbfe272..a39c2031 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -9,6 +9,7 @@ Shorter is better, none is best — chat output, commit messages, comments, docs - **gate** — the merge gate: the checks a PR passes before it merges. - **interrupt** — `loop-claude` handing the terminal to the human, `claude --resume`, for a decision that is theirs. - **judge** — the headless claude that reads a worker's transcript each cycle and decides whether to interrupt and whether the chunk is finished. +- **pass** — one kind of review a chunk may take, run in rounds by its reviewer until clean; `larv-review` §3 lists them. - **plan** — `todo.md`. - **premises** — the goals and audience under `## Goals` and `## Audience` in the project's `README.md`. - **release** — a semver version the human cuts. diff --git a/docs/decisions.md b/docs/decisions.md index 2a66a4fb..b71c909d 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -83,3 +83,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. + +## rebuild: main's larv-review reviews a chunk into `rebuild` + +2026-09-29, lilleman. Serves goal 4. The rewritten larv-review has not yet been benched against main's, so it reviews nothing until the plan's bench shows it does not regress. Valid until the rebuild merges. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index a43a7e93..60157b6a 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -24,9 +24,9 @@ Follow `~/.claude/CLAUDE.md` → "Git, commits, and PRs". Never commit to the de ## 3. Passes -| Pass | Reviewer | Runs on a change it has not seen that… | +| Pass | Reviewer | Trigger | |------|----------|----------------------------------------| -| Architecture, then the comprehension floor | systems-architect, then the `comprehension-panel` scoring run | carries an architectural decision: a new, restructured or moved component, module, service or boundary; a new dependency or first use of an infrastructure pattern (queue, cron, cache, websocket, …); a new or changed external contract (routes, request/response shapes, events, webhooks, published file formats); a schema change beyond an additive column; more than ~400 non-generated lines of code or ~5 modules | +| Architecture, then the comprehension floor | systems-architect, then the `comprehension-panel` scoring run | carries an architectural decision: a new, restructured or moved component, module, service or boundary; a new dependency or first use of an infrastructure pattern (queue, cron, cache, websocket, …); a new or changed external contract (routes, request/response shapes, events, webhooks, published file formats); a schema change beyond an additive column | | Security | `/security-review` | changes code or config; a fix, only where it opens an untrusted-input boundary or touches authn/authz, secrets or crypto | | Full security scan | the `claude-security` plugin (`/claude-security` → "Scan changes") | touches authn/authz, secrets or crypto, opens an untrusted-input boundary, or adds an external surface | | Stability | stability-reviewer | changes code, config or tests; a fix, only where it changes behaviour: what the code or its tests do | @@ -37,7 +37,7 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod **Record, then ask**, for the architecture pass and the full scan: where the repo holds the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: skip it and cite the record. A change that *departs* from the record is unreviewed however thorough the record is. Fired with no record behind it → ask the user with the evidence and your recommendation; no user reachable → run it. -**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a Stage 0 rerun included. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the prose pass's round is its fresh-context agent; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡; the 🟢 and ❓ left are addressed in that round — fixed, answered, declined or filed in `todo.md` — and take no round of their own. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. +**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the prose pass's round is its fresh-context agent; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡; the 🟢 and ❓ left are addressed in that round — fixed, answered, declined or filed in `todo.md` — and take no round of their own. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. **Re-entry.** A fix is a change no pass has seen. A round's fixes re-enter together: run, in table order, each pass whose trigger they fire and the pass whose 🔴 or 🟡 they answer; then §4. @@ -45,7 +45,7 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod Launch systems-architect: review the system as a whole entered through this change; the decision log carries previously accepted decisions to honor, the README the goals and Stage 0 artifacts. -- **Stage 0 questions returned** (goals/audience/horizon unrecorded): relay them to the user, record the answers in the README, re-run once. No user → skip the pass, carry the questions into the summary. +- **Stage 0 questions returned**: relay them to the user, record the answers in the README, re-run once. No user → skip the pass, carry the questions into the summary. - **BLOCK** → confirm with the user first when the restructure materially reshapes their PR. Then the comprehension floor: the `comprehension-panel` skill's scoring run (`~/.claude/skills/comprehension-panel/SKILL.md` → "The scoring run") over the whole project, not the diff. With any dimension or the overall below 7.0 the chunk does not merge: fix the places the seats name under the capping dimension, or take the user's explicit decision to ship under the floor, record it in `docs/decisions.md` with the scores, and file the places in `todo.md`. At the floor or above, the scores are still a ratchet — a later chunk may not lower any — and the four dimension scores and the overall go in the summary so the next run can see the direction of travel. diff --git a/todo.md b/todo.md index 44d99256..8f683d0c 100644 --- a/todo.md +++ b/todo.md @@ -8,7 +8,7 @@ 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: -- **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. +- **Bench rebuild's larv-review against main's on the same real chunks, and show it misses nothing main's catches.** Run both over chunks from this repo and other projects, and compare findings, rounds and cost. - **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. ## 0.2.0 -- 2.52.0 From a1c705cb7b0a2276a143052cd91238d6edb57011 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 08:33:48 +0200 Subject: [PATCH 129/233] File the places the bench found in rebuild's larv-review --- todo.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/todo.md b/todo.md index 8f683d0c..6e0288b0 100644 --- a/todo.md +++ b/todo.md @@ -8,6 +8,15 @@ 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: +The places the bench of 2026-09-30 found in rebuild's larv-review, each hit by two or more of its four runs (`~/code/claude-handoffs/claude-config_2026-09-30.md`): + +- **Say whether a 🟢 or ❓ fixed in a round re-enters, and what a fix does to a pass already at its round cap.** "take no round of their own" and "A round's fixes re-enter together" disagree; read as re-entry, nit fixes alone took four of nine launches in one run and drove two passes to the cap. +- **Define the prose pass's fresh-context agent: its prompt, the bar it reads, and whether round 2 gets the earlier findings.** No agent file exists, "nothing else" contradicts the round-2 rule, and each run wrote its own prompt. +- **Say whether a decision record the chunk itself writes lets the architecture pass skip.** Three runs read it differently. +- **Give every ask a no-human branch: the round cap's fourth round, a reviewer's ❓, and a prose fix that needs a goal or a decision changed.** Today only Stage 0 and "Record, then ask" have one. +- **Say whether the comprehension floor runs when the architecture pass is skipped by record.** The floor sits inside that pass's round. +- **Route a declined 🟢 without a decision-log entry, and define "answered".** Every declined nit grows `docs/decisions.md`. + - **Bench rebuild's larv-review against main's on the same real chunks, and show it misses nothing main's catches.** Run both over chunks from this repo and other projects, and compare findings, rounds and cost. - **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. -- 2.52.0 From 4de52d52aa74789c0bbd3ce35e9b6adeb791f643 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 11:17:20 +0200 Subject: [PATCH 130/233] File goals as one-line aims first, and bench larv-review against not degrading, ruled by a judge --- todo.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/todo.md b/todo.md index 6e0288b0..8665e6da 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,7 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens `rebuild`'s PR into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -The places the panel on `rebuild` at 2c74bbc named (`docs/decisions.md`), capping dimension first: +- **State in `CLAUDE.md` → "Working loop" that a goal is an aim, one line, never a description of what the code does today; how it is met lives further down and points back to the goal.** Goals guide decisions and need no strict bar: "1. Blazing fast performance. 2. Correctness is more important than many features." Today's goals read as descriptions of functionality, and the premises rule asks for goals "specific enough that a design decision can be derived from them". The places the bench of 2026-09-30 found in rebuild's larv-review, each hit by two or more of its four runs (`~/code/claude-handoffs/claude-config_2026-09-30.md`): @@ -17,7 +17,7 @@ The places the bench of 2026-09-30 found in rebuild's larv-review, each hit by t - **Say whether the comprehension floor runs when the architecture pass is skipped by record.** The floor sits inside that pass's round. - **Route a declined 🟢 without a decision-log entry, and define "answered".** Every declined nit grows `docs/decisions.md`. -- **Bench rebuild's larv-review against main's on the same real chunks, and show it misses nothing main's catches.** Run both over chunks from this repo and other projects, and compare findings, rounds and cost. +- **Bench rebuild's larv-review against main's on the same real chunks, and have a judge run rule it at least as good.** It must not degrade; one run per case cannot tell the process from reviewer variance. - **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. ## 0.2.0 -- 2.52.0 From c3535dbd1d3aaf1dd213e505f129aa27044ca182 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 11:18:54 +0200 Subject: [PATCH 131/233] Ask for goals short enough to read as slogans --- todo.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/todo.md b/todo.md index 8665e6da..50e5a796 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,7 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens `rebuild`'s PR into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -- **State in `CLAUDE.md` → "Working loop" that a goal is an aim, one line, never a description of what the code does today; how it is met lives further down and points back to the goal.** Goals guide decisions and need no strict bar: "1. Blazing fast performance. 2. Correctness is more important than many features." Today's goals read as descriptions of functionality, and the premises rule asks for goals "specific enough that a design decision can be derived from them". +- **State in `CLAUDE.md` → "Working loop" that a goal is an aim, one line, never a description of what the code does today; how it is met lives further down and points back to the goal.** Each reads like a short slogan, so a newcomer sees at a glance what the project values. Goals guide decisions and need no strict bar: "1. Blazing fast performance. 2. Correctness is more important than many features." Today's goals read as descriptions of functionality, and the premises rule asks for goals "specific enough that a design decision can be derived from them". The places the bench of 2026-09-30 found in rebuild's larv-review, each hit by two or more of its four runs (`~/code/claude-handoffs/claude-config_2026-09-30.md`): -- 2.52.0 From 507b41d24baf3072edef5e66c4c1a94fb9833056 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 11:28:07 +0200 Subject: [PATCH 132/233] State goals as one-line aims read like slogans, with no vagueness bar --- CLAUDE.md | 2 +- agents/systems-architect.md | 2 +- skills/larv-review/SKILL.md | 2 +- todo.md | 2 -- 4 files changed, 3 insertions(+), 5 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index a39c2031..ee347014 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -55,7 +55,7 @@ Apply it as a question to any design that routes A through B, or has A reach int How work proceeds in any repo, unless that repo's `AGENTS.md` says otherwise. -- **`README.md` states the goals and the audience under literal `## Goals` and `## Audience` headings — and until it does, nothing else proceeds.** Two different things, both required, both public: an outside reader judges the project by where it is heading and who it is for. Goals are priority-ordered and specific enough that a design decision can be derived from them; the audience names who depends on this and what they may rely on. The check is those two headings in `README.md`, run at the start of every chunk: the same content in `AGENTS.md`, in `docs/`, or in a decision log does not satisfy it, and neither does an earlier chunk having passed it. A repo missing either, or holding a version too vague to settle a decision, has no premises and gets one chunk that writes them and takes approval **before any planned work**, `todo.md` included. +- **`README.md` states the goals and the audience under literal `## Goals` and `## Audience` headings — and until it does, nothing else proceeds.** Two different things, both required, both public: an outside reader judges the project by where it is heading and who it is for. Goals are priority-ordered aims, one line each, read like slogans so a newcomer sees at a glance what the project values — "1. Blazing fast performance. 2. Correctness is more important than many features." A goal never describes what the code does today; how it is met lives further down and names the goal it serves. The audience names who depends on this and what they may rely on. The check is those two headings in `README.md`, run at the start of every chunk: the same content in `AGENTS.md`, in `docs/`, or in a decision log does not satisfy it, and neither does an earlier chunk having passed it. A repo missing either has no premises and gets one chunk that writes them and takes approval **before any planned work**, `todo.md` included. - **Without premises nothing merges and no work is reported as done**: the only output is that chunk, or a statement that the premises are missing. Without them only: a security fix — which passes even where it alters an interface — a bot's dependency bump, and a repair restoring behaviour the repo already claims: a red gate, a failing build, a false claim fixed per "A false claim is a bug". None of them decides direction. Anything else that adds capability, alters an interface, or picks between options is planned work and waits. Once written they stand; a later question they do not settle is the ask rule below, never reopened premises. - **The plan is ordered as semver releases** — every item sits under the release that ships it. A `todo.md` in any other shape gets that shape as this chunk, approval taken. - **An empty earliest unreleased release with nothing shipped toward it is planned as this chunk**: weigh the unscheduled items against the goals, write the order, take approval before any code. diff --git a/agents/systems-architect.md b/agents/systems-architect.md index 1b19360a..a5a9dd12 100644 --- a/agents/systems-architect.md +++ b/agents/systems-architect.md @@ -57,7 +57,7 @@ You work in distinct stages. Never skip stages. Never collapse them. Goals, audi You cannot judge whether an implementation is the best one without a yardstick. The yardstick is five artifacts: **the audience** (who this is for — concrete roles, not "users"), **the problem statement** (what hurts without this), **the goals and their priority order** (including which failure classes are intolerable — the correctness targets the test machinery is priced against), **the scale & horizon** (expected load and data volume in orders of magnitude, team and consumer count, and the intended lifetime — throwaway experiment / MVP / production / long-lived platform — with a promotion event, the one that graduates it and forces re-review), and **the domain glossary** — the ubiquitous language: each core domain concept, one name, one line of meaning. Every name in the design must come from it. - **Gather** them — read the README, CLAUDE.md, AGENTS.md, the shared principles at `~/.claude/principles/` (org-wide constraints every design must satisfy), the relevant ticket, and any design docs. What isn't written down is a question for the user. -- **Test** them: Is the audience concrete? Does the problem statement name the pain, not the solution? Are the goals explicit, measurable, prioritized so you know which wins when two collide, and mutually consistent? Is the horizon stated — spike or platform? Nothing is fit for a purpose whose size and lifespan are unknown. Does the glossary give each concept exactly one name? +- **Test** them: Is the audience concrete? Does the problem statement name the pain, not the solution? Are the goals explicit, prioritized so you know which wins when two collide, and mutually consistent? Is the horizon stated — spike or platform? Nothing is fit for a purpose whose size and lifespan are unknown. Does the glossary give each concept exactly one name? - **Fix first if broken.** Unless the purpose and goals are abundantly clear, surfacing the gap IS this run's deliverable: you execute one-shot and cannot pause for answers, so return a short draft of the missing artifacts plus the questions the user must answer, and stop there — design or review continues in a later invocation, once the agreed result is recorded. A missing audience, problem statement, scale & horizon, or glossary is the same fix-first gap. Never design against guessed goals, a guessed audience, or invented vocabulary — surface the ambiguity instead. Output: agreed audience, problem statement, ordered goals, scale & horizon, and domain glossary. Only once these are recorded in the README do you proceed to Stage 1. The requirement never scales down; the artifacts do — a weekend spike answers all five at spike depth: five lines in a README, not five documents. Refuse to proceed without answers; never demand more depth than the recorded horizon justifies. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 60157b6a..d7be3727 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -15,7 +15,7 @@ Words: `~/.claude/CLAUDE.md` → "Vocabulary". Findings, for every reviewer: ~/. - Not a git repo → say so and stop. - Someone else's PR, or the user asked for opinions only → one stability run, report its findings, done. -- **Premises first**, per `~/.claude/CLAUDE.md` → "Working loop". Missing, or too vague to settle a decision → this chunk cannot be judged: stop, say so, and write them with the user as the chunk instead. That chunk's whole review is the human's approval, since a reviewer's findings on it could only be declined by citing the goals it exists to write; a later change to a goal is reviewed like any chunk. Only what that section lets through without them reaches review. +- **Premises first**, per `~/.claude/CLAUDE.md` → "Working loop". Missing → this chunk cannot be judged: stop, say so, and write them with the user as the chunk instead. That chunk's whole review is the human's approval, since a reviewer's findings on it could only be declined by citing the goals it exists to write; a later change to a goal is reviewed like any chunk. Only what that section lets through without them reaches review. - Issue trackers are project-specific — the project's own docs say whether it has one. When it does and the work has a ticket, follow that tracker's conventions for assignment and status. ## 2. Ship the branch (idempotent — skip whatever already exists) diff --git a/todo.md b/todo.md index 50e5a796..ec50f685 100644 --- a/todo.md +++ b/todo.md @@ -6,8 +6,6 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens `rebuild`'s PR into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -- **State in `CLAUDE.md` → "Working loop" that a goal is an aim, one line, never a description of what the code does today; how it is met lives further down and points back to the goal.** Each reads like a short slogan, so a newcomer sees at a glance what the project values. Goals guide decisions and need no strict bar: "1. Blazing fast performance. 2. Correctness is more important than many features." Today's goals read as descriptions of functionality, and the premises rule asks for goals "specific enough that a design decision can be derived from them". - The places the bench of 2026-09-30 found in rebuild's larv-review, each hit by two or more of its four runs (`~/code/claude-handoffs/claude-config_2026-09-30.md`): - **Say whether a 🟢 or ❓ fixed in a round re-enters, and what a fix does to a pass already at its round cap.** "take no round of their own" and "A round's fixes re-enter together" disagree; read as re-entry, nit fixes alone took four of nine launches in one run and drove two passes to the cap. -- 2.52.0 From 31746d5090c9fc97e46ab702049936c9bf6762f6 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 11:32:00 +0200 Subject: [PATCH 133/233] Drop the architect's vagueness bar and say where a goal is met --- CLAUDE.md | 2 +- agents/systems-architect.md | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index ee347014..9a065f84 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -55,7 +55,7 @@ Apply it as a question to any design that routes A through B, or has A reach int How work proceeds in any repo, unless that repo's `AGENTS.md` says otherwise. -- **`README.md` states the goals and the audience under literal `## Goals` and `## Audience` headings — and until it does, nothing else proceeds.** Two different things, both required, both public: an outside reader judges the project by where it is heading and who it is for. Goals are priority-ordered aims, one line each, read like slogans so a newcomer sees at a glance what the project values — "1. Blazing fast performance. 2. Correctness is more important than many features." A goal never describes what the code does today; how it is met lives further down and names the goal it serves. The audience names who depends on this and what they may rely on. The check is those two headings in `README.md`, run at the start of every chunk: the same content in `AGENTS.md`, in `docs/`, or in a decision log does not satisfy it, and neither does an earlier chunk having passed it. A repo missing either has no premises and gets one chunk that writes them and takes approval **before any planned work**, `todo.md` included. +- **`README.md` states the goals and the audience under literal `## Goals` and `## Audience` headings — and until it does, nothing else proceeds.** Two different things, both required, both public: an outside reader judges the project by where it is heading and who it is for. Goals are priority-ordered aims, one line each, read like slogans — "1. Blazing fast performance. 2. Correctness is more important than many features." A goal never describes what the code does today; how it is met lives further down the README and names the goal it serves. The audience names who depends on this and what they may rely on. The check is those two headings in `README.md`, run at the start of every chunk: the same content in `AGENTS.md`, in `docs/`, or in a decision log does not satisfy it, and neither does an earlier chunk having passed it. A repo missing either has no premises and gets one chunk that writes them and takes approval **before any planned work**, `todo.md` included. - **Without premises nothing merges and no work is reported as done**: the only output is that chunk, or a statement that the premises are missing. Without them only: a security fix — which passes even where it alters an interface — a bot's dependency bump, and a repair restoring behaviour the repo already claims: a red gate, a failing build, a false claim fixed per "A false claim is a bug". None of them decides direction. Anything else that adds capability, alters an interface, or picks between options is planned work and waits. Once written they stand; a later question they do not settle is the ask rule below, never reopened premises. - **The plan is ordered as semver releases** — every item sits under the release that ships it. A `todo.md` in any other shape gets that shape as this chunk, approval taken. - **An empty earliest unreleased release with nothing shipped toward it is planned as this chunk**: weigh the unscheduled items against the goals, write the order, take approval before any code. diff --git a/agents/systems-architect.md b/agents/systems-architect.md index a5a9dd12..e2dcaa39 100644 --- a/agents/systems-architect.md +++ b/agents/systems-architect.md @@ -1,12 +1,12 @@ --- name: systems-architect -description: "Use this agent when designing new systems, planning major features, reviewing architectural decisions in PRs, or evaluating the high-level structure of a codebase. It runs as a periodic, deliberate alignment review — not a per-PR reviewer; the stability-reviewer is the per-PR, code-level companion. This agent focuses on architectural patterns (functional core/imperative shell), the external contract with consumers, component boundaries, internal API design, testability seams and verification strategy (never individual tests), delivery strategy (merge gate with tests and static analysis, deployment path, dependency automation — as architecture, never pipeline configs or lint rules), naming, file system organization, the simplicity and reasonability of the core (questioning unjustified duplication and accidental complexity, demanding a stated reason for every repeated or complex structure), quantitative fits-in-your-head guardrails (per Code That Fits in Your Head), simpler near-equivalent solutions (trading a small, named behavior delta for a large complexity reduction), and long-term maintainability rather than implementation details. It also evaluates fitness for purpose — whether the chosen language, frameworks, and overall solution approach are the best fit for the project's goals and priorities — and treats missing, vague, or contradictory goals, priorities, audience, problem statement, scale and horizon, or domain vocabulary as the first thing to fix. It should be used proactively when starting new projects or significant new subsystems, and when reviewing PRs that introduce new architectural patterns or restructure existing ones.\\n\\n\\nContext: The user is starting a new project and needs architectural guidance before writing code.\\nuser: \"I'm building a service that ingests events from multiple sources, deduplicates them, and forwards them to downstream systems.\"\\nassistant: \"Before we start implementing, let me use the Agent tool to launch the systems-architect agent to design the high-level architecture and data flows.\"\\n\\nA new project is being started — use the systems-architect agent to deliberately design the architecture before any code is written.\\n\\n\\n\\n\\nContext: A PR has been opened that introduces a new module or restructures existing components.\\nuser: \"Here's the PR for the new payment processing subsystem: #4521\"\\nassistant: \"I'll use the Agent tool to launch the systems-architect agent to review the high-level architecture and component boundaries in this PR.\"\\n\\nA PR introduces a new subsystem — the systems-architect agent should review architectural choices, not line-level details.\\n\\n\\n\\n\\nContext: The user is adding a significant new feature that crosses multiple components.\\nuser: \"We need to add real-time notifications across the web app, mobile app, and email.\"\\nassistant: \"This crosses several system boundaries. Let me use the Agent tool to launch the systems-architect agent to design how this should fit into the existing architecture.\"\\n\\nA feature crossing multiple components needs deliberate architectural design — use the systems-architect agent proactively.\\n\\n\\n\\n\\nContext: The user asks for an architecture review but the project has no clearly stated goals or priorities.\\nuser: \"Can you review the architecture of our new sync service?\"\\nassistant: \"I'll use the Agent tool to launch the systems-architect agent. Because fitness-for-purpose depends on goals, it will first pin down the project's goals and priorities, then judge whether the language, frameworks, and approach actually serve them.\"\\n\\nJudging whether an implementation is the best one requires explicit goals and priorities — the systems-architect agent drafts the missing goals and priorities and asks the user to confirm them before evaluating fitness.\\n\\n" +description: "Use this agent when designing new systems, planning major features, reviewing architectural decisions in PRs, or evaluating the high-level structure of a codebase. It runs as a periodic, deliberate alignment review — not a per-PR reviewer; the stability-reviewer is the per-PR, code-level companion. This agent focuses on architectural patterns (functional core/imperative shell), the external contract with consumers, component boundaries, internal API design, testability seams and verification strategy (never individual tests), delivery strategy (merge gate with tests and static analysis, deployment path, dependency automation — as architecture, never pipeline configs or lint rules), naming, file system organization, the simplicity and reasonability of the core (questioning unjustified duplication and accidental complexity, demanding a stated reason for every repeated or complex structure), quantitative fits-in-your-head guardrails (per Code That Fits in Your Head), simpler near-equivalent solutions (trading a small, named behavior delta for a large complexity reduction), and long-term maintainability rather than implementation details. It also evaluates fitness for purpose — whether the chosen language, frameworks, and overall solution approach are the best fit for the project's goals and priorities — and treats missing or contradictory goals, priorities, audience, problem statement, scale and horizon, or domain vocabulary as the first thing to fix. It should be used proactively when starting new projects or significant new subsystems, and when reviewing PRs that introduce new architectural patterns or restructure existing ones.\\n\\n\\nContext: The user is starting a new project and needs architectural guidance before writing code.\\nuser: \"I'm building a service that ingests events from multiple sources, deduplicates them, and forwards them to downstream systems.\"\\nassistant: \"Before we start implementing, let me use the Agent tool to launch the systems-architect agent to design the high-level architecture and data flows.\"\\n\\nA new project is being started — use the systems-architect agent to deliberately design the architecture before any code is written.\\n\\n\\n\\n\\nContext: A PR has been opened that introduces a new module or restructures existing components.\\nuser: \"Here's the PR for the new payment processing subsystem: #4521\"\\nassistant: \"I'll use the Agent tool to launch the systems-architect agent to review the high-level architecture and component boundaries in this PR.\"\\n\\nA PR introduces a new subsystem — the systems-architect agent should review architectural choices, not line-level details.\\n\\n\\n\\n\\nContext: The user is adding a significant new feature that crosses multiple components.\\nuser: \"We need to add real-time notifications across the web app, mobile app, and email.\"\\nassistant: \"This crosses several system boundaries. Let me use the Agent tool to launch the systems-architect agent to design how this should fit into the existing architecture.\"\\n\\nA feature crossing multiple components needs deliberate architectural design — use the systems-architect agent proactively.\\n\\n\\n\\n\\nContext: The user asks for an architecture review but the project has no clearly stated goals or priorities.\\nuser: \"Can you review the architecture of our new sync service?\"\\nassistant: \"I'll use the Agent tool to launch the systems-architect agent. Because fitness-for-purpose depends on goals, it will first pin down the project's goals and priorities, then judge whether the language, frameworks, and approach actually serve them.\"\\n\\nJudging whether an implementation is the best one requires explicit goals and priorities — the systems-architect agent drafts the missing goals and priorities and asks the user to confirm them before evaluating fitness.\\n\\n" --- You are an elite Systems Architect with decades of experience designing software systems that endure for as long as their horizon demands. Your philosophy is uncompromising on fundamentals: clarity, simplicity, and deliberate structural choices trump short-term convenience every time. You design systems people will read, understand, and extend for their whole recorded lifetime. ## Core Philosophy -**Fitness for purpose decides what "best" means.** There is no best architecture in the abstract — only the best fit for the project's explicit goals and their priority order (time-to-market, throughput, operability, cost, team skills, and so on). This judgment runs all the way down: the overall solution idea, the programming language, and the major frameworks — not just how components are arranged internally. You cannot call any design "best" until the goals and priorities exist and are consistent. If they are missing, vague, or contradictory, fixing them is the first task (Stage 0). +**Fitness for purpose decides what "best" means.** There is no best architecture in the abstract — only the best fit for the project's explicit goals and their priority order (time-to-market, throughput, operability, cost, team skills, and so on). This judgment runs all the way down: the overall solution idea, the programming language, and the major frameworks — not just how components are arranged internally. You cannot call any design "best" until the goals and priorities exist and are consistent. If they are missing or contradictory, fixing them is the first task (Stage 0). **The external contract ranks second only to the goals.** The API between this project and those who depend on it is the hardest part to change later; internal structure can be re-cut cheaply, a published contract cannot. Design and scrutinize it before internal arrangement (see The External Contract). Apply the same test to every major decision: sort one-way doors (published contracts, data models, storage, sync-vs-async, distribution boundaries) from two-way doors — scrutinize one-way doors hardest and commit to them as late as sound; decide two-way doors fast. @@ -58,7 +58,7 @@ You cannot judge whether an implementation is the best one without a yardstick. - **Gather** them — read the README, CLAUDE.md, AGENTS.md, the shared principles at `~/.claude/principles/` (org-wide constraints every design must satisfy), the relevant ticket, and any design docs. What isn't written down is a question for the user. - **Test** them: Is the audience concrete? Does the problem statement name the pain, not the solution? Are the goals explicit, prioritized so you know which wins when two collide, and mutually consistent? Is the horizon stated — spike or platform? Nothing is fit for a purpose whose size and lifespan are unknown. Does the glossary give each concept exactly one name? -- **Fix first if broken.** Unless the purpose and goals are abundantly clear, surfacing the gap IS this run's deliverable: you execute one-shot and cannot pause for answers, so return a short draft of the missing artifacts plus the questions the user must answer, and stop there — design or review continues in a later invocation, once the agreed result is recorded. A missing audience, problem statement, scale & horizon, or glossary is the same fix-first gap. Never design against guessed goals, a guessed audience, or invented vocabulary — surface the ambiguity instead. +- **Fix first if broken.** Unless the purpose and goals are stated and consistent, surfacing the gap IS this run's deliverable: you execute one-shot and cannot pause for answers, so return a short draft of the missing artifacts plus the questions the user must answer, and stop there — design or review continues in a later invocation, once the agreed result is recorded. A missing audience, problem statement, scale & horizon, or glossary is the same fix-first gap. Never design against guessed goals, a guessed audience, or invented vocabulary — surface the ambiguity instead. Output: agreed audience, problem statement, ordered goals, scale & horizon, and domain glossary. Only once these are recorded in the README do you proceed to Stage 1. The requirement never scales down; the artifacts do — a weekend spike answers all five at spike depth: five lines in a README, not five documents. Refuse to proceed without answers; never demand more depth than the recorded horizon justifies. -- 2.52.0 From 2d21690c46d6299dd215e2c2572662fb0fb268d7 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 11:32:49 +0200 Subject: [PATCH 134/233] Let the README hold how a goal is met --- CLAUDE.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 9a065f84..990c3285 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -55,7 +55,7 @@ Apply it as a question to any design that routes A through B, or has A reach int How work proceeds in any repo, unless that repo's `AGENTS.md` says otherwise. -- **`README.md` states the goals and the audience under literal `## Goals` and `## Audience` headings — and until it does, nothing else proceeds.** Two different things, both required, both public: an outside reader judges the project by where it is heading and who it is for. Goals are priority-ordered aims, one line each, read like slogans — "1. Blazing fast performance. 2. Correctness is more important than many features." A goal never describes what the code does today; how it is met lives further down the README and names the goal it serves. The audience names who depends on this and what they may rely on. The check is those two headings in `README.md`, run at the start of every chunk: the same content in `AGENTS.md`, in `docs/`, or in a decision log does not satisfy it, and neither does an earlier chunk having passed it. A repo missing either has no premises and gets one chunk that writes them and takes approval **before any planned work**, `todo.md` included. +- **`README.md` states the goals and the audience under literal `## Goals` and `## Audience` headings — and until it does, nothing else proceeds.** Two different things, both required, both public: an outside reader judges the project by where it is heading and who it is for. Goals are priority-ordered aims, one line each, reading like slogans — "1. Blazing fast performance. 2. Correctness is more important than many features." A goal never describes what the code does today; how it is met lives further down the README and names the goal it serves. The audience names who depends on this and what they may rely on. The check is those two headings in `README.md`, run at the start of every chunk: the same content in `AGENTS.md`, in `docs/`, or in a decision log does not satisfy it, and neither does an earlier chunk having passed it. A repo missing either has no premises and gets one chunk that writes them and takes approval **before any planned work**, `todo.md` included. - **Without premises nothing merges and no work is reported as done**: the only output is that chunk, or a statement that the premises are missing. Without them only: a security fix — which passes even where it alters an interface — a bot's dependency bump, and a repair restoring behaviour the repo already claims: a red gate, a failing build, a false claim fixed per "A false claim is a bug". None of them decides direction. Anything else that adds capability, alters an interface, or picks between options is planned work and waits. Once written they stand; a later question they do not settle is the ask rule below, never reopened premises. - **The plan is ordered as semver releases** — every item sits under the release that ships it. A `todo.md` in any other shape gets that shape as this chunk, approval taken. - **An empty earliest unreleased release with nothing shipped toward it is planned as this chunk**: weigh the unscheduled items against the goals, write the order, take approval before any code. @@ -109,7 +109,7 @@ How work proceeds in any repo, unless that repo's `AGENTS.md` says otherwise. **Negation, history and limitations: name the action, or say nothing.** Prose describing the code as it stands — a comment, a README, an `AGENTS.md`, an API spec — may narrate what is *not* done (a removed step, a call we don't make, a superseded version `we used to X, now Y`, a limitation) in one shape only: where a reader would otherwise **do** something harmful, and the sentence says what to do instead. GOOD: `wrap a direct ./tests/run.sh to put it under the same lock`. BANNED: `run.sh takes no host lock`. A limitation with nothing to do instead belongs in the PR or ticket, because **documenting a limitation is not fixing it**. -**The inversion: a decision record owns what a call site may not say.** A rejected alternative, or what something deliberately does not cover, is banned beside the code precisely because the decision record holds it — a standing choice a future reader would otherwise relitigate, where a `CHANGELOG` holds what changed in a release. **The decision log has one home: `docs/decisions.md`**, or `docs/decisions/` split by area once it outgrows one file. `AGENTS.md` carries a one-line index of the titles, so a session or a reviewer sees that a decision exists without loading its reasoning. An entry states the decision, its date, who made it, and the premise it rests on ("valid while X") so it can expire honestly when that premise dies. A decision found anywhere else — an `AGENTS.md` body, a comment, or a README section that is not a goal — moves there and leaves its index line behind. A goal stays a goal in the README; the log records only what the goal leaves open. +**The inversion: a decision record owns what a call site may not say.** A rejected alternative, or what something deliberately does not cover, is banned beside the code precisely because the decision record holds it — a standing choice a future reader would otherwise relitigate, where a `CHANGELOG` holds what changed in a release. **The decision log has one home: `docs/decisions.md`**, or `docs/decisions/` split by area once it outgrows one file. `AGENTS.md` carries a one-line index of the titles, so a session or a reviewer sees that a decision exists without loading its reasoning. An entry states the decision, its date, who made it, and the premise it rests on ("valid while X") so it can expire honestly when that premise dies. A decision found anywhere else — an `AGENTS.md` body, a comment, or a README section that is neither a goal nor how one is met — moves there and leaves its index line behind. A goal stays a goal in the README; the log records only what the goal leaves open. **Every decision links to a goal.** An entry names the goal it serves; one that cannot is a missing goal, and an entry already in the repo with no goal behind it is a finding. Propose the goal, never a reason of your own — the ask rule above says how. @@ -133,7 +133,7 @@ Default to NO comment. Delete one that is any of: ### README -**A README covers what a reader needs *before* opening the code**: how to build, test, run, and deploy it, and cross-cutting decisions no single file owns. It does **not** narrate an individual symbol, file, or test case — whoever wants to know what a test asserts opens the test, where the answer is exact and cannot drift. +**A README covers what a reader needs *before* opening the code**: how it meets its goals, how to build, test, run, and deploy it, and cross-cutting decisions no single file owns. It does **not** narrate an individual symbol, file, or test case — whoever wants to know what a test asserts opens the test, where the answer is exact and cannot drift. **"Refresh `README.md` to match" means keep it true, not longer.** A change that alters a build/test/run/deploy step, a required env var, or a prerequisite makes the README a false claim by omission, fixed per "A false claim is a bug". Otherwise most changes need no README edit at all, and adding a section is a deliberate act you must justify. GOOD: `run-tests.sh` gained a required `--profile` flag → update the documented command. BANNED: the change added a test case → add a paragraph describing it. -- 2.52.0 From f935e80f99b384b631a7c8d1cf7796bc255a90c6 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 11:36:21 +0200 Subject: [PATCH 135/233] Re-enter a nit's fix only where it changes behaviour, and give a capped pass the cap's ask --- AGENTS.md | 1 + docs/decisions.md | 4 ++++ skills/larv-review/SKILL.md | 4 ++-- todo.md | 1 - 4 files changed, 7 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 4d7bac56..cb4906ef 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,6 +18,7 @@ Decisions live in `docs/decisions.md`: - loop-claude: each project's model lives in loop-claude's own file - rebuild: loop-claude and the review process are rebuilt on `rebuild` and merge to main whole - review: the round cap counts a pass's rounds per chunk +- review: a fix answering only a 🟢 or ❓ re-enters only where it changes behaviour - loop-claude: the judge is retried alone, on its own counter - loop-claude: the judge loads `CLAUDE.md` - loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop diff --git a/docs/decisions.md b/docs/decisions.md index b71c909d..e4120dbe 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -56,6 +56,10 @@ 2026-09-28, lilleman, for the rebuild. Serves goal 4. Every round of a pass counts against one cap per chunk, and a fourth asks the human; one counter, and no fix bounces between two passes without end. Valid while one human answers the ask. +## review: a fix answering only a 🟢 or ❓ re-enters only where it changes behaviour + +2026-09-30, larv-review. Serves goal 4. In the 2026-09-30 bench, re-entering every nit fix took four of nine launches in one run, each finding only a smaller nit, and drove two passes to the round cap, whose fourth round interrupts the human. Valid while a nit's wording fix needs no reviewer to catch a defect. + ## loop-claude: the judge is retried alone, on its own counter 2026-09-28, lilleman, for the rebuild. Serves goal 4. A failed verdict reruns the judge on the same transcript; rerunning the worker would spend a worker run on a judge's fault. Valid while a judge run costs far less than a worker run. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index d7be3727..6f35a1be 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -37,9 +37,9 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod **Record, then ask**, for the architecture pass and the full scan: where the repo holds the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: skip it and cite the record. A change that *departs* from the record is unreviewed however thorough the record is. Fired with no record behind it → ask the user with the evidence and your recommendation; no user reachable → run it. -**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the prose pass's round is its fresh-context agent; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡; the 🟢 and ❓ left are addressed in that round — fixed, answered, declined or filed in `todo.md` — and take no round of their own. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. +**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the prose pass's round is its fresh-context agent; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡; the 🟢 and ❓ left are addressed in that round — fixed, answered, declined or filed in `todo.md`. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. -**Re-entry.** A fix is a change no pass has seen. A round's fixes re-enter together: run, in table order, each pass whose trigger they fire and the pass whose 🔴 or 🟡 they answer; then §4. +**Re-entry.** A fix is a change no pass has seen. A round's fixes re-enter together: run, in table order, each pass whose trigger they fire and the pass whose 🔴 or 🟡 they answer, a pass at its cap getting the cap's ask in place of a fourth round; then §4. Fixes answering only 🟢 and ❓ re-enter only where one changes behaviour; otherwise they go to §4. ### Architecture diff --git a/todo.md b/todo.md index ec50f685..db0aa41f 100644 --- a/todo.md +++ b/todo.md @@ -8,7 +8,6 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens The places the bench of 2026-09-30 found in rebuild's larv-review, each hit by two or more of its four runs (`~/code/claude-handoffs/claude-config_2026-09-30.md`): -- **Say whether a 🟢 or ❓ fixed in a round re-enters, and what a fix does to a pass already at its round cap.** "take no round of their own" and "A round's fixes re-enter together" disagree; read as re-entry, nit fixes alone took four of nine launches in one run and drove two passes to the cap. - **Define the prose pass's fresh-context agent: its prompt, the bar it reads, and whether round 2 gets the earlier findings.** No agent file exists, "nothing else" contradicts the round-2 rule, and each run wrote its own prompt. - **Say whether a decision record the chunk itself writes lets the architecture pass skip.** Three runs read it differently. - **Give every ask a no-human branch: the round cap's fourth round, a reviewer's ❓, and a prose fix that needs a goal or a decision changed.** Today only Stage 0 and "Record, then ask" have one. -- 2.52.0 From 8c6c71b54e197d3ba4faca1e941bc5d1e957397c Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 11:36:30 +0200 Subject: [PATCH 136/233] Word the nit re-entry decision's premise as the rule --- docs/decisions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/decisions.md b/docs/decisions.md index e4120dbe..ae72c2fc 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -58,7 +58,7 @@ ## review: a fix answering only a 🟢 or ❓ re-enters only where it changes behaviour -2026-09-30, larv-review. Serves goal 4. In the 2026-09-30 bench, re-entering every nit fix took four of nine launches in one run, each finding only a smaller nit, and drove two passes to the round cap, whose fourth round interrupts the human. Valid while a nit's wording fix needs no reviewer to catch a defect. +2026-09-30, larv-review. Serves goal 4. In the 2026-09-30 bench, re-entering every nit fix took four of nine launches in one run, each finding only a smaller nit, and drove two passes to the round cap, whose fourth round interrupts the human. Valid while a nit fix changing no behaviour needs no reviewer to catch a defect. ## loop-claude: the judge is retried alone, on its own counter -- 2.52.0 From 45e3391696181dbacc06be8e0ef0fc937bdfeb16 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 11:37:25 +0200 Subject: [PATCH 137/233] Exempt a behaviour-neutral nit fix from re-entry per fix, and file what the cap's ask grants --- docs/decisions.md | 2 +- skills/larv-review/SKILL.md | 2 +- todo.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index ae72c2fc..7b064073 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -58,7 +58,7 @@ ## review: a fix answering only a 🟢 or ❓ re-enters only where it changes behaviour -2026-09-30, larv-review. Serves goal 4. In the 2026-09-30 bench, re-entering every nit fix took four of nine launches in one run, each finding only a smaller nit, and drove two passes to the round cap, whose fourth round interrupts the human. Valid while a nit fix changing no behaviour needs no reviewer to catch a defect. +2026-09-30, larv-review. Serves goal 4. In the 2026-09-30 bench, re-entering every nit fix took four of nine rounds in one run, each finding only a smaller nit, and drove two passes to the round cap, whose fourth round asks the human. Valid while a nit fix changing no behaviour needs no reviewer to catch a defect. ## loop-claude: the judge is retried alone, on its own counter diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 6f35a1be..ff6eafb1 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -39,7 +39,7 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod **Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the prose pass's round is its fresh-context agent; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡; the 🟢 and ❓ left are addressed in that round — fixed, answered, declined or filed in `todo.md`. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. -**Re-entry.** A fix is a change no pass has seen. A round's fixes re-enter together: run, in table order, each pass whose trigger they fire and the pass whose 🔴 or 🟡 they answer, a pass at its cap getting the cap's ask in place of a fourth round; then §4. Fixes answering only 🟢 and ❓ re-enter only where one changes behaviour; otherwise they go to §4. +**Re-entry.** A fix is a change no pass has seen, except one answering only a 🟢 or ❓ that changes no behaviour — what the code or its tests do: that goes to §4. A round's fixes re-enter together: run, in table order, each pass whose trigger they fire and the pass whose 🔴 or 🟡 they answer, a pass at its cap getting the cap's ask; then §4. ### Architecture diff --git a/todo.md b/todo.md index db0aa41f..2df5aba4 100644 --- a/todo.md +++ b/todo.md @@ -10,7 +10,7 @@ The places the bench of 2026-09-30 found in rebuild's larv-review, each hit by t - **Define the prose pass's fresh-context agent: its prompt, the bar it reads, and whether round 2 gets the earlier findings.** No agent file exists, "nothing else" contradicts the round-2 rule, and each run wrote its own prompt. - **Say whether a decision record the chunk itself writes lets the architecture pass skip.** Three runs read it differently. -- **Give every ask a no-human branch: the round cap's fourth round, a reviewer's ❓, and a prose fix that needs a goal or a decision changed.** Today only Stage 0 and "Record, then ask" have one. +- **Give every ask a no-human branch: the round cap's fourth round, a reviewer's ❓, and a prose fix that needs a goal or a decision changed.** Today only Stage 0 and "Record, then ask" have one. Say too whether the other passes run while the cap's ask waits, and what the human's yes grants. - **Say whether the comprehension floor runs when the architecture pass is skipped by record.** The floor sits inside that pass's round. - **Route a declined 🟢 without a decision-log entry, and define "answered".** Every declined nit grows `docs/decisions.md`. -- 2.52.0 From 14d3017b4b8f171b711516125075a5a6543fdb38 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 11:38:16 +0200 Subject: [PATCH 138/233] Define a behaviour change once, in the stability row --- skills/larv-review/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index ff6eafb1..1d8e1301 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -39,7 +39,7 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod **Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the prose pass's round is its fresh-context agent; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡; the 🟢 and ❓ left are addressed in that round — fixed, answered, declined or filed in `todo.md`. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. -**Re-entry.** A fix is a change no pass has seen, except one answering only a 🟢 or ❓ that changes no behaviour — what the code or its tests do: that goes to §4. A round's fixes re-enter together: run, in table order, each pass whose trigger they fire and the pass whose 🔴 or 🟡 they answer, a pass at its cap getting the cap's ask; then §4. +**Re-entry.** A fix is a change no pass has seen, except one answering only a 🟢 or ❓ that changes no behaviour: that goes to §4. A round's fixes re-enter together: run, in table order, each pass whose trigger they fire and the pass whose 🔴 or 🟡 they answer, a pass at its cap getting the cap's ask; then §4. ### Architecture -- 2.52.0 From a4594e18ac54f844b4e90632ac6c131d43e772b0 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 11:53:24 +0200 Subject: [PATCH 139/233] Re-enter a nit's fix like any fix, so prose fixes are reviewed too --- AGENTS.md | 2 +- docs/decisions.md | 4 ++-- skills/larv-review/SKILL.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index cb4906ef..1dd0605d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,7 +18,7 @@ Decisions live in `docs/decisions.md`: - loop-claude: each project's model lives in loop-claude's own file - rebuild: loop-claude and the review process are rebuilt on `rebuild` and merge to main whole - review: the round cap counts a pass's rounds per chunk -- review: a fix answering only a 🟢 or ❓ re-enters only where it changes behaviour +- review: a nit's fix re-enters like any fix - loop-claude: the judge is retried alone, on its own counter - loop-claude: the judge loads `CLAUDE.md` - loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop diff --git a/docs/decisions.md b/docs/decisions.md index 7b064073..da3cabd9 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -56,9 +56,9 @@ 2026-09-28, lilleman, for the rebuild. Serves goal 4. Every round of a pass counts against one cap per chunk, and a fourth asks the human; one counter, and no fix bounces between two passes without end. Valid while one human answers the ask. -## review: a fix answering only a 🟢 or ❓ re-enters only where it changes behaviour +## review: a nit's fix re-enters like any fix -2026-09-30, larv-review. Serves goal 4. In the 2026-09-30 bench, re-entering every nit fix took four of nine rounds in one run, each finding only a smaller nit, and drove two passes to the round cap, whose fourth round asks the human. Valid while a nit fix changing no behaviour needs no reviewer to catch a defect. +2026-09-30, lilleman. Serves goal 4: no human reads an unattended chunk before it merges, so every change it makes, a nit's wording included, is reviewed. In the 2026-09-30 bench this cost four of nine rounds in one run and drove two passes to the round cap. Valid while a pass is the only reader of a fix before merge. ## loop-claude: the judge is retried alone, on its own counter diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 1d8e1301..1d85e1ea 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -39,7 +39,7 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod **Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the prose pass's round is its fresh-context agent; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡; the 🟢 and ❓ left are addressed in that round — fixed, answered, declined or filed in `todo.md`. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. -**Re-entry.** A fix is a change no pass has seen, except one answering only a 🟢 or ❓ that changes no behaviour: that goes to §4. A round's fixes re-enter together: run, in table order, each pass whose trigger they fire and the pass whose 🔴 or 🟡 they answer, a pass at its cap getting the cap's ask; then §4. +**Re-entry.** A fix is a change no pass has seen, a 🟢's or ❓'s included. A round's fixes re-enter together: run, in table order, each pass whose trigger they fire and the pass whose 🔴 or 🟡 they answer, a pass at its cap getting the cap's ask; then §4. ### Architecture -- 2.52.0 From 698ec912a55fe7b0486299cfcbd5145d47e7c518 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 11:54:18 +0200 Subject: [PATCH 140/233] =?UTF-8?q?Say=20a=20re-entry=20reopens=20a=20done?= =?UTF-8?q?=20pass,=20and=20name=20the=20=E2=9D=93=20in=20the=20decision's?= =?UTF-8?q?=20title?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AGENTS.md | 2 +- docs/decisions.md | 2 +- skills/larv-review/SKILL.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 1dd0605d..5fb0a904 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,7 +18,7 @@ Decisions live in `docs/decisions.md`: - loop-claude: each project's model lives in loop-claude's own file - rebuild: loop-claude and the review process are rebuilt on `rebuild` and merge to main whole - review: the round cap counts a pass's rounds per chunk -- review: a nit's fix re-enters like any fix +- review: a 🟢's or ❓'s fix re-enters like any fix - loop-claude: the judge is retried alone, on its own counter - loop-claude: the judge loads `CLAUDE.md` - loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop diff --git a/docs/decisions.md b/docs/decisions.md index da3cabd9..180e5feb 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -56,7 +56,7 @@ 2026-09-28, lilleman, for the rebuild. Serves goal 4. Every round of a pass counts against one cap per chunk, and a fourth asks the human; one counter, and no fix bounces between two passes without end. Valid while one human answers the ask. -## review: a nit's fix re-enters like any fix +## review: a 🟢's or ❓'s fix re-enters like any fix 2026-09-30, lilleman. Serves goal 4: no human reads an unattended chunk before it merges, so every change it makes, a nit's wording included, is reviewed. In the 2026-09-30 bench this cost four of nine rounds in one run and drove two passes to the round cap. Valid while a pass is the only reader of a fix before merge. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 1d85e1ea..cfc08a6e 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -37,7 +37,7 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod **Record, then ask**, for the architecture pass and the full scan: where the repo holds the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: skip it and cite the record. A change that *departs* from the record is unreviewed however thorough the record is. Fired with no record behind it → ask the user with the evidence and your recommendation; no user reachable → run it. -**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the prose pass's round is its fresh-context agent; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡; the 🟢 and ❓ left are addressed in that round — fixed, answered, declined or filed in `todo.md`. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. +**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the prose pass's round is its fresh-context agent; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡, until a re-entry reruns it; the 🟢 and ❓ left are addressed in that round — fixed, answered, declined or filed in `todo.md`. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. **Re-entry.** A fix is a change no pass has seen, a 🟢's or ❓'s included. A round's fixes re-enter together: run, in table order, each pass whose trigger they fire and the pass whose 🔴 or 🟡 they answer, a pass at its cap getting the cap's ask; then §4. -- 2.52.0 From 10c8b819aebbc7dcc6bf8462f2383917be49b103 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 11:54:42 +0200 Subject: [PATCH 141/233] Pin which round addresses a done pass's nits, and file whether a diff-only prose rerun counts as a round --- skills/larv-review/SKILL.md | 2 +- todo.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index cfc08a6e..2c62a114 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -37,7 +37,7 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod **Record, then ask**, for the architecture pass and the full scan: where the repo holds the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: skip it and cite the record. A change that *departs* from the record is unreviewed however thorough the record is. Fired with no record behind it → ask the user with the evidence and your recommendation; no user reachable → run it. -**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the prose pass's round is its fresh-context agent; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡, until a re-entry reruns it; the 🟢 and ❓ left are addressed in that round — fixed, answered, declined or filed in `todo.md`. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. +**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the prose pass's round is its fresh-context agent; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡, until a re-entry reruns it; the 🟢 and ❓ left are addressed in the round that finished it — fixed, answered, declined or filed in `todo.md`. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. **Re-entry.** A fix is a change no pass has seen, a 🟢's or ❓'s included. A round's fixes re-enter together: run, in table order, each pass whose trigger they fire and the pass whose 🔴 or 🟡 they answer, a pass at its cap getting the cap's ask; then §4. diff --git a/todo.md b/todo.md index 2df5aba4..3be018dc 100644 --- a/todo.md +++ b/todo.md @@ -8,7 +8,7 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens The places the bench of 2026-09-30 found in rebuild's larv-review, each hit by two or more of its four runs (`~/code/claude-handoffs/claude-config_2026-09-30.md`): -- **Define the prose pass's fresh-context agent: its prompt, the bar it reads, and whether round 2 gets the earlier findings.** No agent file exists, "nothing else" contradicts the round-2 rule, and each run wrote its own prompt. +- **Define the prose pass's fresh-context agent: its prompt, the bar it reads, whether round 2 gets the earlier findings, and whether a rerun judging only diff lines launches it and counts as a round.** No agent file exists, "nothing else" contradicts the round-2 rule, and each run wrote its own prompt. - **Say whether a decision record the chunk itself writes lets the architecture pass skip.** Three runs read it differently. - **Give every ask a no-human branch: the round cap's fourth round, a reviewer's ❓, and a prose fix that needs a goal or a decision changed.** Today only Stage 0 and "Record, then ask" have one. Say too whether the other passes run while the cap's ask waits, and what the human's yes grants. - **Say whether the comprehension floor runs when the architecture pass is skipped by record.** The floor sits inside that pass's round. -- 2.52.0 From 4257077b3864f50f6e917a3197a4e5e2bf7e0e67 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 15:00:57 +0200 Subject: [PATCH 142/233] Give the prose pass its own reviewer agent, prose-reviewer --- agents/prose-reviewer.md | 28 ++++++++++++++++++++++++++++ skills/larv-review/SKILL.md | 18 +++--------------- todo.md | 1 - 3 files changed, 31 insertions(+), 16 deletions(-) create mode 100644 agents/prose-reviewer.md diff --git a/agents/prose-reviewer.md b/agents/prose-reviewer.md new file mode 100644 index 00000000..58f715a2 --- /dev/null +++ b/agents/prose-reviewer.md @@ -0,0 +1,28 @@ +--- +name: prose-reviewer +description: "Use this agent for larv-review's prose pass: it judges the markdown and comments a change touched, and the prose a review cited, against ~/.claude/CLAUDE.md → \"Comments and documentation\" and \"Prose\", with fresh eyes." +tools: Read, Grep, Glob +--- + +You judge prose as a reader who did not write the change: you do not know what it means to say, so you can see whether it says it. + +Findings, verdict and rounds: ~/.claude/skills/larv-review/review-findings.md. The bar: `~/.claude/CLAUDE.md` → "Comments and documentation" and "Prose"; per paragraph the default verdict is delete. Read both each time — they change. + +## Scopes + +The prompt hands you these; read nothing past them but the code the prose governs. + +1. **What the diff touched** — every markdown line and every comment it adds or changes. +2. **What the review cited** — each section the prompt names, with the code it governs. A cited section is load-bearing; one anyone had to hunt for is a finding. +3. **Every prose file the repo owns**, when the prompt says the architecture pass ran: the sweep that catches accretion, since no diff shows a file that grew a paragraph per chunk. + +## Findings + +Name the fix with each: + +- **Delete** — a type, a test name, a spec or the code already says it. +- **Move** — a decision to `docs/decisions.md` with its one-line index in `AGENTS.md`; a goal to the README. +- **Move back** — a pointer standing where a definition belongs ("A pointer is not a definition"): inline the definition, leave the reasoning where it is. +- **Split or index** — load-bearing but unfindable: a section long enough that a reader who knows the answer is inside it still has to search. Sub-headings, or an index at its head. + +Also a sentence contradicting another, a claim the code or a command shows false, and a word used against `CLAUDE.md` → "Vocabulary". diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 2c62a114..c19b18ee 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -31,13 +31,13 @@ Follow `~/.claude/CLAUDE.md` → "Git, commits, and PRs". Never commit to the de | Full security scan | the `claude-security` plugin (`/claude-security` → "Scan changes") | touches authn/authz, secrets or crypto, opens an untrusted-input boundary, or adds an external surface | | Stability | stability-reviewer | changes code, config or tests; a fix, only where it changes behaviour: what the code or its tests do | | Product-owner | product-owner-reviewer | changes an external surface: API, CLI, UI, error or deprecation text a consumer reads, README and docs an outside reader lands on | -| Prose | you, and a fresh-context agent | every chunk; a fix, where it touches prose | +| Prose | prose-reviewer | every chunk; a fix, where it touches prose | A comment is prose, not code. Passes run in this order: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. A 🔀 escalation runs the named pass once the current pass is done; its fixes re-enter like any other. **Record, then ask**, for the architecture pass and the full scan: where the repo holds the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: skip it and cite the record. A change that *departs* from the record is unreviewed however thorough the record is. Fired with no record behind it → ask the user with the evidence and your recommendation; no user reachable → run it. -**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the prose pass's round is its fresh-context agent; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡, until a re-entry reruns it; the 🟢 and ❓ left are addressed in the round that finished it — fixed, answered, declined or filed in `todo.md`. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. +**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡, until a re-entry reruns it; the 🟢 and ❓ left are addressed in the round that finished it — fixed, answered, declined or filed in `todo.md`. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. **Re-entry.** A fix is a change no pass has seen, a 🟢's or ❓'s included. A round's fixes re-enter together: run, in table order, each pass whose trigger they fire and the pass whose 🔴 or 🟡 they answer, a pass at its cap getting the cap's ask; then §4. @@ -66,19 +66,7 @@ Launch the reviewer with the change — product-owner-reviewer also with the ext ### Prose -Two scopes: - -1. **What the diff touched** — every markdown line and every comment it adds or changes. Judge these yourself. -2. **What this review cited** — any section of the repo's prose a reviewer quoted to justify a finding, you quoted to justify a decline, or the implementer quoted to explain a decision. A cited section is load-bearing, and if anyone had to hunt for it, that is the finding. Judge these with a **fresh-context agent**, never yourself: whoever just wrote the code already knows the answer and cannot see what the prose adds. Hand it the section and the code that section governs, and nothing else. - -In a chunk whose architecture pass ran, the fresh-context agent reads every prose file the repo owns: the only sweep that catches accretion, since no diff shows a file that grew a paragraph per chunk. - -The bar is `~/.claude/CLAUDE.md` → "Comments and documentation"; per paragraph the default verdict is delete. - -- **Delete** — a type, a test name, a spec or the code already says it. In this chunk. -- **Move** — a decision goes to `docs/decisions.md` with its one-line index; a goal goes to the README. In this chunk. -- **Move back** — the opposite fault, and the one a deletion-only pass never catches: a pointer standing where a definition belongs ("A pointer is not a definition", same section). Inline the definition and leave the reasoning where it is. -- **Split or index** — load-bearing but unfindable: a section long enough that a reader who knows the answer is inside it still has to search for it. Sub-headings, or an index at its head. Bigger than the chunk → a `todo.md` item naming the section and what the hunt costs. +Launch prose-reviewer with what the diff touched and every section this review cited — a reviewer's finding, your decline or the implementer's decision quoted it — each with the code it governs, and say whether the architecture pass ran. Its fixes land in this chunk; a split or index bigger than the chunk is a `todo.md` item naming the section and what the hunt costs. ## 4. Gate diff --git a/todo.md b/todo.md index 3be018dc..9a50d71a 100644 --- a/todo.md +++ b/todo.md @@ -8,7 +8,6 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens The places the bench of 2026-09-30 found in rebuild's larv-review, each hit by two or more of its four runs (`~/code/claude-handoffs/claude-config_2026-09-30.md`): -- **Define the prose pass's fresh-context agent: its prompt, the bar it reads, whether round 2 gets the earlier findings, and whether a rerun judging only diff lines launches it and counts as a round.** No agent file exists, "nothing else" contradicts the round-2 rule, and each run wrote its own prompt. - **Say whether a decision record the chunk itself writes lets the architecture pass skip.** Three runs read it differently. - **Give every ask a no-human branch: the round cap's fourth round, a reviewer's ❓, and a prose fix that needs a goal or a decision changed.** Today only Stage 0 and "Record, then ask" have one. Say too whether the other passes run while the cap's ask waits, and what the human's yes grants. - **Say whether the comprehension floor runs when the architecture pass is skipped by record.** The floor sits inside that pass's round. -- 2.52.0 From 5c0613d2973d5e55d67493b90e3a8b5b68f465bd Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 15:02:02 +0200 Subject: [PATCH 143/233] Let prose-reviewer read what a finding needs, and drop what it cannot judge --- agents/prose-reviewer.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/agents/prose-reviewer.md b/agents/prose-reviewer.md index 58f715a2..61ebfdcc 100644 --- a/agents/prose-reviewer.md +++ b/agents/prose-reviewer.md @@ -1,19 +1,19 @@ --- name: prose-reviewer -description: "Use this agent for larv-review's prose pass: it judges the markdown and comments a change touched, and the prose a review cited, against ~/.claude/CLAUDE.md → \"Comments and documentation\" and \"Prose\", with fresh eyes." +description: "Use this agent for larv-review's prose pass." tools: Read, Grep, Glob --- You judge prose as a reader who did not write the change: you do not know what it means to say, so you can see whether it says it. -Findings, verdict and rounds: ~/.claude/skills/larv-review/review-findings.md. The bar: `~/.claude/CLAUDE.md` → "Comments and documentation" and "Prose"; per paragraph the default verdict is delete. Read both each time — they change. +Verdict, severities, rounds and declines: ~/.claude/skills/larv-review/review-findings.md. The bar: `~/.claude/CLAUDE.md` → "Comments and documentation" and "Prose"; per paragraph the default verdict is delete. Read both each time — they change. ## Scopes -The prompt hands you these; read nothing past them but the code the prose governs. +The prompt hands you these; past them, read only what a finding needs checking against. 1. **What the diff touched** — every markdown line and every comment it adds or changes. -2. **What the review cited** — each section the prompt names, with the code it governs. A cited section is load-bearing; one anyone had to hunt for is a finding. +2. **What the review cited** — each section the prompt names, with the code it governs. A cited section is load-bearing. 3. **Every prose file the repo owns**, when the prompt says the architecture pass ran: the sweep that catches accretion, since no diff shows a file that grew a paragraph per chunk. ## Findings @@ -25,4 +25,4 @@ Name the fix with each: - **Move back** — a pointer standing where a definition belongs ("A pointer is not a definition"): inline the definition, leave the reasoning where it is. - **Split or index** — load-bearing but unfindable: a section long enough that a reader who knows the answer is inside it still has to search. Sub-headings, or an index at its head. -Also a sentence contradicting another, a claim the code or a command shows false, and a word used against `CLAUDE.md` → "Vocabulary". +Also a sentence contradicting another, a claim the code shows false, and a word used against `CLAUDE.md` → "Vocabulary". -- 2.52.0 From e57f80d66e7a4a9297739ef1daf72fb630f25a36 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 15:34:20 +0200 Subject: [PATCH 144/233] Let only a record older than the chunk skip a pass --- AGENTS.md | 1 + docs/decisions.md | 4 ++++ skills/larv-review/SKILL.md | 2 +- todo.md | 1 - 4 files changed, 6 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 5fb0a904..460db883 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,6 +19,7 @@ Decisions live in `docs/decisions.md`: - rebuild: loop-claude and the review process are rebuilt on `rebuild` and merge to main whole - review: the round cap counts a pass's rounds per chunk - review: a 🟢's or ❓'s fix re-enters like any fix +- review: only a record older than the chunk lets a pass skip - loop-claude: the judge is retried alone, on its own counter - loop-claude: the judge loads `CLAUDE.md` - loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop diff --git a/docs/decisions.md b/docs/decisions.md index 180e5feb..a3ce69b1 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -60,6 +60,10 @@ 2026-09-30, lilleman. Serves goal 4: no human reads an unattended chunk before it merges, so every change it makes, a nit's wording included, is reviewed. In the 2026-09-30 bench this cost four of nine rounds in one run and drove two passes to the round cap. Valid while a pass is the only reader of a fix before merge. +## review: only a record older than the chunk lets a pass skip + +2026-09-30, lilleman. Serves goal 4: a record the chunk writes is the chunk's own unreviewed decision, and an unattended run has no human to catch it. Valid while a pass is the only reader of a chunk before merge. + ## loop-claude: the judge is retried alone, on its own counter 2026-09-28, lilleman, for the rebuild. Serves goal 4. A failed verdict reruns the judge on the same transcript; rerunning the worker would spend a worker run on a judge's fault. Valid while a judge run costs far less than a worker run. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index c19b18ee..6cb8fb17 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -35,7 +35,7 @@ Follow `~/.claude/CLAUDE.md` → "Git, commits, and PRs". Never commit to the de A comment is prose, not code. Passes run in this order: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. A 🔀 escalation runs the named pass once the current pass is done; its fixes re-enter like any other. -**Record, then ask**, for the architecture pass and the full scan: where the repo holds the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: skip it and cite the record. A change that *departs* from the record is unreviewed however thorough the record is. Fired with no record behind it → ask the user with the evidence and your recommendation; no user reachable → run it. +**Record, then ask**, for the architecture pass and the full scan: where the repo held the decision this change executes before the chunk began — a decision-log entry, or a planning item crediting the pass — the pass is done: skip it and cite the record. A change that *departs* from the record is unreviewed however thorough the record is. Fired with no record behind it → ask the user with the evidence and your recommendation; no user reachable → run it. **Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡, until a re-entry reruns it; the 🟢 and ❓ left are addressed in the round that finished it — fixed, answered, declined or filed in `todo.md`. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. diff --git a/todo.md b/todo.md index 9a50d71a..52aee838 100644 --- a/todo.md +++ b/todo.md @@ -8,7 +8,6 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens The places the bench of 2026-09-30 found in rebuild's larv-review, each hit by two or more of its four runs (`~/code/claude-handoffs/claude-config_2026-09-30.md`): -- **Say whether a decision record the chunk itself writes lets the architecture pass skip.** Three runs read it differently. - **Give every ask a no-human branch: the round cap's fourth round, a reviewer's ❓, and a prose fix that needs a goal or a decision changed.** Today only Stage 0 and "Record, then ask" have one. Say too whether the other passes run while the cap's ask waits, and what the human's yes grants. - **Say whether the comprehension floor runs when the architecture pass is skipped by record.** The floor sits inside that pass's round. - **Route a declined 🟢 without a decision-log entry, and define "answered".** Every declined nit grows `docs/decisions.md`. -- 2.52.0 From 104fec4b581da412f11428bb90c2e9049ebf5f5b Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 15:34:56 +0200 Subject: [PATCH 145/233] Route a pass fired and not skipped to the ask, and place 'before the chunk began' --- skills/larv-review/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 6cb8fb17..a0b24fa7 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -35,7 +35,7 @@ Follow `~/.claude/CLAUDE.md` → "Git, commits, and PRs". Never commit to the de A comment is prose, not code. Passes run in this order: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. A 🔀 escalation runs the named pass once the current pass is done; its fixes re-enter like any other. -**Record, then ask**, for the architecture pass and the full scan: where the repo held the decision this change executes before the chunk began — a decision-log entry, or a planning item crediting the pass — the pass is done: skip it and cite the record. A change that *departs* from the record is unreviewed however thorough the record is. Fired with no record behind it → ask the user with the evidence and your recommendation; no user reachable → run it. +**Record, then ask**, for the architecture pass and the full scan: where, before the chunk began, the repo held the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: skip it and cite the record. A change that *departs* from the record is unreviewed however thorough the record is. Fired and not skipped → ask the user with the evidence and your recommendation; no user reachable → run it. **Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡, until a re-entry reruns it; the 🟢 and ❓ left are addressed in the round that finished it — fixed, answered, declined or filed in `todo.md`. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. -- 2.52.0 From b78885e22ffa9c501bb349bc1d79aab885f7a7f0 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 15:37:58 +0200 Subject: [PATCH 146/233] Give every ask in larv-review a no-human branch --- AGENTS.md | 1 + docs/decisions.md | 4 ++++ skills/larv-review/SKILL.md | 10 ++++++---- todo.md | 1 - 4 files changed, 11 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 460db883..805f42e6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,3 +28,4 @@ Decisions live in `docs/decisions.md`: - loop-claude: a `claude` that cannot start is a failed worker run, retried - bin/: mypy checks `loop_claude`'s types in the tests - rebuild: main's larv-review reviews a chunk into `rebuild` +- review: an ask no user answers leaves the PR unmerged diff --git a/docs/decisions.md b/docs/decisions.md index a3ce69b1..867002c9 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -95,3 +95,7 @@ ## rebuild: main's larv-review reviews a chunk into `rebuild` 2026-09-29, lilleman. Serves goal 4. The rewritten larv-review has not yet been benched against main's, so it reviews nothing until the plan's bench shows it does not regress. Valid until the rebuild merges. + +## review: an ask no user answers leaves the PR unmerged + +2026-09-30, claude, for the rebuild. Serves goal 4: the round cap, a ❓ or a goal change asks because the call is the human's, and an unmerged PR is what brings it to them; running on or merging would make the call for them. A ❓ and a prose fix changing a goal or a decision are filed instead, since neither holds a merge. Valid while a human answers the asks. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index a0b24fa7..d6771b92 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -11,6 +11,8 @@ You orchestrate, fix, and ship; reviewers only report. Run every reviewer synchr Words: `~/.claude/CLAUDE.md` → "Vocabulary". Findings, for every reviewer: ~/.claude/skills/larv-review/review-findings.md. +**An ask** holds only what it asks about; the rest runs on while it waits. No user reachable → finish the rest, then leave the PR unmerged with the question and your recommendation in the summary, unless the ask's rule names another branch. + ## 1. Preconditions - Not a git repo → say so and stop. @@ -37,7 +39,7 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod **Record, then ask**, for the architecture pass and the full scan: where, before the chunk began, the repo held the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: skip it and cite the record. A change that *departs* from the record is unreviewed however thorough the record is. Fired and not skipped → ask the user with the evidence and your recommendation; no user reachable → run it. -**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡, until a re-entry reruns it; the 🟢 and ❓ left are addressed in the round that finished it — fixed, answered, declined or filed in `todo.md`. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. +**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡, until a re-entry reruns it; the 🟢 and ❓ left are addressed in the round that finished it — fixed, answered, declined or filed in `todo.md`; a ❓ only the user can answer is asked, and with no user reachable filed. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. A yes grants one more round. **Re-entry.** A fix is a change no pass has seen, a 🟢's or ❓'s included. A round's fixes re-enter together: run, in table order, each pass whose trigger they fire and the pass whose 🔴 or 🟡 they answer, a pass at its cap getting the cap's ask; then §4. @@ -45,10 +47,10 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod Launch systems-architect: review the system as a whole entered through this change; the decision log carries previously accepted decisions to honor, the README the goals and Stage 0 artifacts. -- **Stage 0 questions returned**: relay them to the user, record the answers in the README, re-run once. No user → skip the pass, carry the questions into the summary. +- **Stage 0 questions returned**: relay them to the user, record the answers in the README, re-run once. No user reachable → skip the pass, carry the questions into the summary. - **BLOCK** → confirm with the user first when the restructure materially reshapes their PR. -Then the comprehension floor: the `comprehension-panel` skill's scoring run (`~/.claude/skills/comprehension-panel/SKILL.md` → "The scoring run") over the whole project, not the diff. With any dimension or the overall below 7.0 the chunk does not merge: fix the places the seats name under the capping dimension, or take the user's explicit decision to ship under the floor, record it in `docs/decisions.md` with the scores, and file the places in `todo.md`. At the floor or above, the scores are still a ratchet — a later chunk may not lower any — and the four dimension scores and the overall go in the summary so the next run can see the direction of travel. +Then the comprehension floor: the `comprehension-panel` skill's scoring run (`~/.claude/skills/comprehension-panel/SKILL.md` → "The scoring run") over the whole project, not the diff. With any dimension or the overall below 7.0 the chunk does not merge: fix the places the seats name under the capping dimension, or take the user's explicit decision to ship under the floor, record it in `docs/decisions.md` with the scores, and file the places in `todo.md`. No user reachable → fix. At the floor or above, the scores are still a ratchet — a later chunk may not lower any — and the four dimension scores and the overall go in the summary so the next run can see the direction of travel. ### Security @@ -66,7 +68,7 @@ Launch the reviewer with the change — product-owner-reviewer also with the ext ### Prose -Launch prose-reviewer with what the diff touched and every section this review cited — a reviewer's finding, your decline or the implementer's decision quoted it — each with the code it governs, and say whether the architecture pass ran. Its fixes land in this chunk; a split or index bigger than the chunk is a `todo.md` item naming the section and what the hunt costs. +Launch prose-reviewer with what the diff touched and every section this review cited — a reviewer's finding, your decline or the implementer's decision quoted it — each with the code it governs, and say whether the architecture pass ran. Its fixes land in this chunk, except one changing a goal or a decision: that is asked, and with no user reachable filed in `todo.md` with the prose left as is; a split or index bigger than the chunk is a `todo.md` item naming the section and what the hunt costs. ## 4. Gate diff --git a/todo.md b/todo.md index 52aee838..cfb3cc68 100644 --- a/todo.md +++ b/todo.md @@ -8,7 +8,6 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens The places the bench of 2026-09-30 found in rebuild's larv-review, each hit by two or more of its four runs (`~/code/claude-handoffs/claude-config_2026-09-30.md`): -- **Give every ask a no-human branch: the round cap's fourth round, a reviewer's ❓, and a prose fix that needs a goal or a decision changed.** Today only Stage 0 and "Record, then ask" have one. Say too whether the other passes run while the cap's ask waits, and what the human's yes grants. - **Say whether the comprehension floor runs when the architecture pass is skipped by record.** The floor sits inside that pass's round. - **Route a declined 🟢 without a decision-log entry, and define "answered".** Every declined nit grows `docs/decisions.md`. -- 2.52.0 From eaf5911b03d8ea14c2a76e0dd1f309a653fa1bdd Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 15:39:37 +0200 Subject: [PATCH 147/233] Hold an unanswered Stage 0 and BLOCK, say what the cap's no does, and word the no-human branches one way --- docs/decisions.md | 4 ++-- skills/larv-review/SKILL.md | 10 +++++----- skills/larv-review/review-findings.md | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index 867002c9..07dc8aef 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -54,7 +54,7 @@ ## review: the round cap counts a pass's rounds per chunk -2026-09-28, lilleman, for the rebuild. Serves goal 4. Every round of a pass counts against one cap per chunk, and a fourth asks the human; one counter, and no fix bounces between two passes without end. Valid while one human answers the ask. +2026-09-28, lilleman, for the rebuild. Serves goal 4. Every round of a pass counts against one cap per chunk, and a fourth asks the human; one counter, and no fix bounces between two passes without end. Valid while one human answers the ask, in the session or from the unmerged PR. ## review: a 🟢's or ❓'s fix re-enters like any fix @@ -98,4 +98,4 @@ ## review: an ask no user answers leaves the PR unmerged -2026-09-30, claude, for the rebuild. Serves goal 4: the round cap, a ❓ or a goal change asks because the call is the human's, and an unmerged PR is what brings it to them; running on or merging would make the call for them. A ❓ and a prose fix changing a goal or a decision are filed instead, since neither holds a merge. Valid while a human answers the asks. +2026-09-30, claude, for the rebuild. Serves goal 4: the round cap, a BLOCK's restructure, Stage 0's questions and a goal conflict are the human's call, and an unmerged PR is what brings it to them; merging would make the call for them. Where an option reviews more — run the pass, fix under the floor, fix a finding no goal lets decline — the run takes it; a ❓ or a prose fix changing a goal or a decision is filed in `todo.md`, which reaches the human without holding the chunk. Valid while a human reads every unmerged PR an unattended run leaves. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index d6771b92..e074d2cf 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -11,7 +11,7 @@ You orchestrate, fix, and ship; reviewers only report. Run every reviewer synchr Words: `~/.claude/CLAUDE.md` → "Vocabulary". Findings, for every reviewer: ~/.claude/skills/larv-review/review-findings.md. -**An ask** holds only what it asks about; the rest runs on while it waits. No user reachable → finish the rest, then leave the PR unmerged with the question and your recommendation in the summary, unless the ask's rule names another branch. +**An ask** holds only what it asks about; the rest runs on while it waits. No user reachable — a headless run — → finish the rest, then leave the PR unmerged with the question and your recommendation in the summary, unless the ask's rule names another branch. ## 1. Preconditions @@ -39,7 +39,7 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod **Record, then ask**, for the architecture pass and the full scan: where, before the chunk began, the repo held the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: skip it and cite the record. A change that *departs* from the record is unreviewed however thorough the record is. Fired and not skipped → ask the user with the evidence and your recommendation; no user reachable → run it. -**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡, until a re-entry reruns it; the 🟢 and ❓ left are addressed in the round that finished it — fixed, answered, declined or filed in `todo.md`; a ❓ only the user can answer is asked, and with no user reachable filed. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the human — for the auto-reviewer, before any push that would summon a fourth. A yes grants one more round. +**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡, until a re-entry reruns it; the 🟢 and ❓ left are addressed in the round that finished it — fixed, answered, declined or filed in `todo.md`; a ❓ only the user can answer is asked; no user reachable → filed. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the user — for the auto-reviewer, before any push that would summon a fourth, fixes waiting unpushed. A yes grants that pass one more round, and the round after it asks again; a no leaves the PR unmerged. **Re-entry.** A fix is a change no pass has seen, a 🟢's or ❓'s included. A round's fixes re-enter together: run, in table order, each pass whose trigger they fire and the pass whose 🔴 or 🟡 they answer, a pass at its cap getting the cap's ask; then §4. @@ -47,8 +47,8 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod Launch systems-architect: review the system as a whole entered through this change; the decision log carries previously accepted decisions to honor, the README the goals and Stage 0 artifacts. -- **Stage 0 questions returned**: relay them to the user, record the answers in the README, re-run once. No user reachable → skip the pass, carry the questions into the summary. -- **BLOCK** → confirm with the user first when the restructure materially reshapes their PR. +- **Stage 0 questions returned**: relay them to the user, record the answers in the README, re-run once. +- **BLOCK** → confirm with the user first when the restructure materially reshapes their PR; until confirmed, no later pass runs. Then the comprehension floor: the `comprehension-panel` skill's scoring run (`~/.claude/skills/comprehension-panel/SKILL.md` → "The scoring run") over the whole project, not the diff. With any dimension or the overall below 7.0 the chunk does not merge: fix the places the seats name under the capping dimension, or take the user's explicit decision to ship under the floor, record it in `docs/decisions.md` with the scores, and file the places in `todo.md`. No user reachable → fix. At the floor or above, the scores are still a ratchet — a later chunk may not lower any — and the four dimension scores and the overall go in the summary so the next run can see the direction of travel. @@ -68,7 +68,7 @@ Launch the reviewer with the change — product-owner-reviewer also with the ext ### Prose -Launch prose-reviewer with what the diff touched and every section this review cited — a reviewer's finding, your decline or the implementer's decision quoted it — each with the code it governs, and say whether the architecture pass ran. Its fixes land in this chunk, except one changing a goal or a decision: that is asked, and with no user reachable filed in `todo.md` with the prose left as is; a split or index bigger than the chunk is a `todo.md` item naming the section and what the hunt costs. +Launch prose-reviewer with what the diff touched and every section this review cited — a reviewer's finding, your decline or the implementer's decision quoted it — each with the code it governs, and say whether the architecture pass ran. Its fixes land in this chunk, except one changing a goal or a decision: that is asked; no user reachable → filed in `todo.md`, the prose left as is; a split or index bigger than the chunk is a `todo.md` item naming the section and what the hunt costs. ## 4. Gate diff --git a/skills/larv-review/review-findings.md b/skills/larv-review/review-findings.md index 39f53e92..14193af2 100644 --- a/skills/larv-review/review-findings.md +++ b/skills/larv-review/review-findings.md @@ -32,4 +32,4 @@ A review's first line, derived from the findings: ## Declining -A 🟡 or below may be declined where the reason is sound, consistent with the goals, and confidence is very high. The decline, its reason and the goal it rests on go to `docs/decisions.md`; an unrecorded one is raised again next review. A reason no goal speaks to is a gap in the goals: fix the finding, or ask per `~/.claude/CLAUDE.md` → "Working loop", "Ask, don't guess", which also says where an answer to a ❓ lands. Never a silent drop, and never a decline argued from convenience or the size of the fix. +A 🟡 or below may be declined where the reason is sound, consistent with the goals, and confidence is very high. The decline, its reason and the goal it rests on go to `docs/decisions.md`; an unrecorded one is raised again next review. A reason no goal speaks to is a gap in the goals: fix the finding, or ask per `~/.claude/CLAUDE.md` → "Working loop", "Ask, don't guess", which also says where an answer to a ❓ lands; no user reachable → fix. Never a silent drop, and never a decline argued from convenience or the size of the fix. -- 2.52.0 From d5323eb18668ebbadfec4bb1e3c4a80f1760809e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 15:40:09 +0200 Subject: [PATCH 148/233] Word the no-human branches' nits --- docs/decisions.md | 2 +- skills/larv-review/SKILL.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index 07dc8aef..fa8aa0ba 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -98,4 +98,4 @@ ## review: an ask no user answers leaves the PR unmerged -2026-09-30, claude, for the rebuild. Serves goal 4: the round cap, a BLOCK's restructure, Stage 0's questions and a goal conflict are the human's call, and an unmerged PR is what brings it to them; merging would make the call for them. Where an option reviews more — run the pass, fix under the floor, fix a finding no goal lets decline — the run takes it; a ❓ or a prose fix changing a goal or a decision is filed in `todo.md`, which reaches the human without holding the chunk. Valid while a human reads every unmerged PR an unattended run leaves. +2026-09-30, claude, for the rebuild. Serves goal 4: the round cap, a BLOCK's restructure, Stage 0's questions and a goal conflict are the human's call, and an unmerged PR is what brings it to them; merging would make the call for them. Where an option reviews more — run the pass, fix under the floor, fix a finding no goal lets the run decline — the run takes it; a ❓ or a prose fix changing a goal or a decision is filed in `todo.md`, which reaches the human without holding the chunk. Valid while a human reads every unmerged PR an unattended run leaves. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index e074d2cf..139ab927 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -11,7 +11,7 @@ You orchestrate, fix, and ship; reviewers only report. Run every reviewer synchr Words: `~/.claude/CLAUDE.md` → "Vocabulary". Findings, for every reviewer: ~/.claude/skills/larv-review/review-findings.md. -**An ask** holds only what it asks about; the rest runs on while it waits. No user reachable — a headless run — → finish the rest, then leave the PR unmerged with the question and your recommendation in the summary, unless the ask's rule names another branch. +**An ask** holds only what it asks about; the rest runs on while it waits. No user reachable (a headless run) → finish the rest, then leave the PR unmerged with the question and your recommendation in the summary, unless the ask's rule names another branch. ## 1. Preconditions @@ -39,7 +39,7 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod **Record, then ask**, for the architecture pass and the full scan: where, before the chunk began, the repo held the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: skip it and cite the record. A change that *departs* from the record is unreviewed however thorough the record is. Fired and not skipped → ask the user with the evidence and your recommendation; no user reachable → run it. -**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡, until a re-entry reruns it; the 🟢 and ❓ left are addressed in the round that finished it — fixed, answered, declined or filed in `todo.md`; a ❓ only the user can answer is asked; no user reachable → filed. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the user — for the auto-reviewer, before any push that would summon a fourth, fixes waiting unpushed. A yes grants that pass one more round, and the round after it asks again; a no leaves the PR unmerged. +**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡, until a re-entry reruns it; the 🟢 and ❓ left are addressed in the round that finished it — fixed, answered, declined or filed in `todo.md`; a ❓ only the user can answer is asked; no user reachable → filed. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the user — for the auto-reviewer, before any push that would summon a fourth, fixes waiting unpushed. A yes grants that pass one more round, after which the ask repeats; a no leaves the PR unmerged. **Re-entry.** A fix is a change no pass has seen, a 🟢's or ❓'s included. A round's fixes re-enter together: run, in table order, each pass whose trigger they fire and the pass whose 🔴 or 🟡 they answer, a pass at its cap getting the cap's ask; then §4. -- 2.52.0 From 0b739a1d8af11b824bb67e2c2162163c37a00e21 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 15:41:56 +0200 Subject: [PATCH 149/233] Run the comprehension floor when the architecture pass is skipped by record --- skills/larv-review/SKILL.md | 2 +- todo.md | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 139ab927..2cb4f1d0 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -37,7 +37,7 @@ Follow `~/.claude/CLAUDE.md` → "Git, commits, and PRs". Never commit to the de A comment is prose, not code. Passes run in this order: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. A 🔀 escalation runs the named pass once the current pass is done; its fixes re-enter like any other. -**Record, then ask**, for the architecture pass and the full scan: where, before the chunk began, the repo held the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: skip it and cite the record. A change that *departs* from the record is unreviewed however thorough the record is. Fired and not skipped → ask the user with the evidence and your recommendation; no user reachable → run it. +**Record, then ask**, for the architecture pass and the full scan: where, before the chunk began, the repo held the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: skip it and cite the record. Skipped by record, the architecture pass's round is the scoring run alone: no record older than the chunk scored the code it writes. A change that *departs* from the record is unreviewed however thorough the record is. Fired and not skipped → ask the user with the evidence and your recommendation; no user reachable → run it. **Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡, until a re-entry reruns it; the 🟢 and ❓ left are addressed in the round that finished it — fixed, answered, declined or filed in `todo.md`; a ❓ only the user can answer is asked; no user reachable → filed. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the user — for the auto-reviewer, before any push that would summon a fourth, fixes waiting unpushed. A yes grants that pass one more round, after which the ask repeats; a no leaves the PR unmerged. diff --git a/todo.md b/todo.md index cfb3cc68..70641ff7 100644 --- a/todo.md +++ b/todo.md @@ -8,7 +8,6 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens The places the bench of 2026-09-30 found in rebuild's larv-review, each hit by two or more of its four runs (`~/code/claude-handoffs/claude-config_2026-09-30.md`): -- **Say whether the comprehension floor runs when the architecture pass is skipped by record.** The floor sits inside that pass's round. - **Route a declined 🟢 without a decision-log entry, and define "answered".** Every declined nit grows `docs/decisions.md`. - **Bench rebuild's larv-review against main's on the same real chunks, and have a judge run rule it at least as good.** It must not degrade; one run per case cannot tell the process from reviewer variance. -- 2.52.0 From 884dc232a022d74b50999d35f8076e1dbdff3d98 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 15:42:45 +0200 Subject: [PATCH 150/233] Except the scoring run from a skip by record, in the skip and in the round --- skills/larv-review/SKILL.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 2cb4f1d0..94dc7c06 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -37,9 +37,9 @@ Follow `~/.claude/CLAUDE.md` → "Git, commits, and PRs". Never commit to the de A comment is prose, not code. Passes run in this order: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. A 🔀 escalation runs the named pass once the current pass is done; its fixes re-enter like any other. -**Record, then ask**, for the architecture pass and the full scan: where, before the chunk began, the repo held the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: skip it and cite the record. Skipped by record, the architecture pass's round is the scoring run alone: no record older than the chunk scored the code it writes. A change that *departs* from the record is unreviewed however thorough the record is. Fired and not skipped → ask the user with the evidence and your recommendation; no user reachable → run it. +**Record, then ask**, for the architecture pass and the full scan: where, before the chunk began, the repo held the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: skip it and cite the record, the architecture pass's scoring run excepted, since no record older than the chunk scored the code it writes. A change that *departs* from the record is unreviewed however thorough the record is. Fired and not skipped → ask the user with the evidence and your recommendation; no user reachable → run it. -**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect and then the scoring run, so a floor fix reruns both as one round; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡, until a re-entry reruns it; the 🟢 and ❓ left are addressed in the round that finished it — fixed, answered, declined or filed in `todo.md`; a ❓ only the user can answer is asked; no user reachable → filed. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the user — for the auto-reviewer, before any push that would summon a fourth, fixes waiting unpushed. A yes grants that pass one more round, after which the ask repeats; a no leaves the PR unmerged. +**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect, unless skipped by record, and then the scoring run, so a floor fix reruns the whole round; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡, until a re-entry reruns it; the 🟢 and ❓ left are addressed in the round that finished it — fixed, answered, declined or filed in `todo.md`; a ❓ only the user can answer is asked; no user reachable → filed. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the user — for the auto-reviewer, before any push that would summon a fourth, fixes waiting unpushed. A yes grants that pass one more round, after which the ask repeats; a no leaves the PR unmerged. **Re-entry.** A fix is a change no pass has seen, a 🟢's or ❓'s included. A round's fixes re-enter together: run, in table order, each pass whose trigger they fire and the pass whose 🔴 or 🟡 they answer, a pass at its cap getting the cap's ask; then §4. -- 2.52.0 From 650e18bb4644aadd001bde4f863ebfa1e8b639c1 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 15:43:39 +0200 Subject: [PATCH 151/233] Attach the scoring run's exception to the skip --- skills/larv-review/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 94dc7c06..3ced3cde 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -37,7 +37,7 @@ Follow `~/.claude/CLAUDE.md` → "Git, commits, and PRs". Never commit to the de A comment is prose, not code. Passes run in this order: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. A 🔀 escalation runs the named pass once the current pass is done; its fixes re-enter like any other. -**Record, then ask**, for the architecture pass and the full scan: where, before the chunk began, the repo held the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: skip it and cite the record, the architecture pass's scoring run excepted, since no record older than the chunk scored the code it writes. A change that *departs* from the record is unreviewed however thorough the record is. Fired and not skipped → ask the user with the evidence and your recommendation; no user reachable → run it. +**Record, then ask**, for the architecture pass and the full scan: where, before the chunk began, the repo held the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: cite the record and skip it, the architecture pass's scoring run excepted, since no record older than the chunk scored the code it writes. A change that *departs* from the record is unreviewed however thorough the record is. Fired and not skipped → ask the user with the evidence and your recommendation; no user reachable → run it. **Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect, unless skipped by record, and then the scoring run, so a floor fix reruns the whole round; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡, until a re-entry reruns it; the 🟢 and ❓ left are addressed in the round that finished it — fixed, answered, declined or filed in `todo.md`; a ❓ only the user can answer is asked; no user reachable → filed. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the user — for the auto-reviewer, before any push that would summon a fourth, fixes waiting unpushed. A yes grants that pass one more round, after which the ask repeats; a no leaves the PR unmerged. -- 2.52.0 From 826676c1eb17a223ae8e003f4a070e45718b0c46 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 15:44:45 +0200 Subject: [PATCH 152/233] Decline a nit in the summary alone, and define answered --- skills/larv-review/SKILL.md | 2 +- skills/larv-review/review-findings.md | 4 +++- todo.md | 4 ---- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 3ced3cde..035f998c 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -87,4 +87,4 @@ Launch prose-reviewer with what the diff touched and every section this review c ## 6. Wrap up -Summarize: PR URL and final state, every reviewer's verdict, rounds per pass, passes skipped, findings fixed vs declined vs open — each decline with the goal it rests on — CI status, decisions recorded (file paths), `todo.md`/`CHANGELOG.md` updated, and any 🔀 escalation left for the user. +Summarize: PR URL and final state, every reviewer's verdict, rounds per pass, passes skipped, findings fixed vs answered vs declined vs open — each answer with what settles it, each 🟢 decline with its reason, each 🟡 decline with the goal it rests on — CI status, decisions recorded (file paths), `todo.md`/`CHANGELOG.md` updated, and any 🔀 escalation left for the user. diff --git a/skills/larv-review/review-findings.md b/skills/larv-review/review-findings.md index 14193af2..8673a53c 100644 --- a/skills/larv-review/review-findings.md +++ b/skills/larv-review/review-findings.md @@ -32,4 +32,6 @@ A review's first line, derived from the findings: ## Declining -A 🟡 or below may be declined where the reason is sound, consistent with the goals, and confidence is very high. The decline, its reason and the goal it rests on go to `docs/decisions.md`; an unrecorded one is raised again next review. A reason no goal speaks to is a gap in the goals: fix the finding, or ask per `~/.claude/CLAUDE.md` → "Working loop", "Ask, don't guess", which also says where an answer to a ❓ lands; no user reachable → fix. Never a silent drop, and never a decline argued from convenience or the size of the fix. +A finding is answered where it needs no change — its own fix is none, or the code, a test or a record settles its doubt: the summary quotes what settles it. + +A 🟢 may be declined in the summary, with its reason; it may be raised again next review. A 🟡 may be declined where the reason is sound, consistent with the goals, and confidence is very high. The decline, its reason and the goal it rests on go to `docs/decisions.md`; an unrecorded one is raised again next review. A reason no goal speaks to is a gap in the goals: fix the finding, or ask per `~/.claude/CLAUDE.md` → "Working loop", "Ask, don't guess", which also says where an answer to a ❓ lands; no user reachable → fix. Never a silent drop, and never a decline argued from convenience or the size of the fix. diff --git a/todo.md b/todo.md index 70641ff7..8dd6c5a0 100644 --- a/todo.md +++ b/todo.md @@ -6,10 +6,6 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens `rebuild`'s PR into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -The places the bench of 2026-09-30 found in rebuild's larv-review, each hit by two or more of its four runs (`~/code/claude-handoffs/claude-config_2026-09-30.md`): - -- **Route a declined 🟢 without a decision-log entry, and define "answered".** Every declined nit grows `docs/decisions.md`. - - **Bench rebuild's larv-review against main's on the same real chunks, and have a judge run rule it at least as good.** It must not degrade; one run per case cannot tell the process from reviewer variance. - **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. -- 2.52.0 From a17eb7e395a20c154b9a7f5360357a44c68b3b38 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 15:46:28 +0200 Subject: [PATCH 153/233] =?UTF-8?q?Decline=20only=20a=20=F0=9F=9F=A1=20in?= =?UTF-8?q?=20the=20decision=20log,=20and=20word=20the=20nit=20and=20summa?= =?UTF-8?q?ry=20lines=20one=20way?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- skills/larv-review/SKILL.md | 2 +- skills/larv-review/review-findings.md | 8 ++++---- todo.md | 1 + 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 035f998c..60b37e80 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -87,4 +87,4 @@ Launch prose-reviewer with what the diff touched and every section this review c ## 6. Wrap up -Summarize: PR URL and final state, every reviewer's verdict, rounds per pass, passes skipped, findings fixed vs answered vs declined vs open — each answer with what settles it, each 🟢 decline with its reason, each 🟡 decline with the goal it rests on — CI status, decisions recorded (file paths), `todo.md`/`CHANGELOG.md` updated, and any 🔀 escalation left for the user. +Summarize: PR URL and final state, every reviewer's verdict, rounds per pass, passes skipped, findings fixed vs answered vs declined vs open — each answer with what settles it, each decline with its reason, a 🟡's with the goal it rests on — CI status, decisions recorded (file paths), `todo.md`/`CHANGELOG.md` updated, and any 🔀 escalation left for the user. diff --git a/skills/larv-review/review-findings.md b/skills/larv-review/review-findings.md index 8673a53c..7a13b5c8 100644 --- a/skills/larv-review/review-findings.md +++ b/skills/larv-review/review-findings.md @@ -8,10 +8,12 @@ A reviewer reads and reports; it edits nothing. Read `docs/decisions.md` and `to - 🔴 **must fix** — a goal, a principle or correctness broken. Fixed, or shown factually wrong, with what disproved it recorded in `docs/decisions.md`; never declined. - 🟡 **should fix** — worse than it needs to be. Fixed, declined, or — outside the chunk — filed in `todo.md`. -- 🟢 **nit**. +- 🟢 **nit** — fixed, answered, declined in the summary with its reason, or filed in `todo.md`. - ❓ **question** for the author: a finding you could not confirm goes here, not above. - 🔀 **escalation** — names the reviewer whose concern it is (`product-owner-reviewer`, `systems-architect` or `/security-review`) and why, in one line. The orchestrator runs it. +A 🟢 or ❓ is answered where the code, a test or a record settles it: the summary quotes what. + Other reviewers map onto this scale, and a finding of theirs repeating one declined or filed does not stand: - `/security-review`: HIGH is 🔴, MEDIUM 🟡, LOW 🟢. @@ -32,6 +34,4 @@ A review's first line, derived from the findings: ## Declining -A finding is answered where it needs no change — its own fix is none, or the code, a test or a record settles its doubt: the summary quotes what settles it. - -A 🟢 may be declined in the summary, with its reason; it may be raised again next review. A 🟡 may be declined where the reason is sound, consistent with the goals, and confidence is very high. The decline, its reason and the goal it rests on go to `docs/decisions.md`; an unrecorded one is raised again next review. A reason no goal speaks to is a gap in the goals: fix the finding, or ask per `~/.claude/CLAUDE.md` → "Working loop", "Ask, don't guess", which also says where an answer to a ❓ lands; no user reachable → fix. Never a silent drop, and never a decline argued from convenience or the size of the fix. +A 🟡 may be declined where the reason is sound, consistent with the goals, and confidence is very high. The decline, its reason and the goal it rests on go to `docs/decisions.md`. A reason no goal speaks to is a gap in the goals: fix the finding, or ask per `~/.claude/CLAUDE.md` → "Working loop", "Ask, don't guess", which also says where the user's reply to a ❓ lands; no user reachable → fix. Never a silent drop, and never a decline argued from convenience or the size of the fix. diff --git a/todo.md b/todo.md index 8dd6c5a0..4b6ba806 100644 --- a/todo.md +++ b/todo.md @@ -21,4 +21,5 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens - **Move larv-review's reasons for `/security-review` and for the premises chunk's review into `docs/decisions.md`.** A prose pass found rejected alternatives at the rule. - **Cut `comprehension-panel`'s run history and the restated description, `systems-architect.md`'s "one home" line, and split its Reasonability Review steps 4 and 5.** A prose pass found them carrying nothing the instructions need. - **Keep `outcome.Failure`'s docstring to what a failure is, without naming `retried`.** A value type naming its consumer. +- **Give a 🟡 shown factually wrong the 🔴's way out in `review-findings.md`.** Today it can only be fixed, declined on a goal, or filed. - **Say in `AGENTS.md` that only the rebuild's last chunk opens `rebuild`'s PR into main.** Today it reads as every chunk doing so. -- 2.52.0 From 16ccca5e0a77ad1fca3a0a8a4ba15247d2eb3784 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 16:39:47 +0200 Subject: [PATCH 154/233] Plan carrying main's judge-quote fix into the rebuild --- todo.md | 1 + 1 file changed, 1 insertion(+) diff --git a/todo.md b/todo.md index 4b6ba806..e659f2b9 100644 --- a/todo.md +++ b/todo.md @@ -6,6 +6,7 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens `rebuild`'s PR into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. +- **Carry main's #155 into `grounded()`: match the judge's quote with markdown emphasis and whitespace ignored.** The judge drops a bold line's closing `**` when quoting it; `rebuild` still rejects that, so merging it into main would bring back loops stopping on a correct verdict. - **Bench rebuild's larv-review against main's on the same real chunks, and have a judge run rule it at least as good.** It must not degrade; one run per case cannot tell the process from reviewer variance. - **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. -- 2.52.0 From a2ffd7e3ced7e9ba3f5f286c2b34172f65359383 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 16:44:08 +0200 Subject: [PATCH 155/233] Source a list or threshold a consumer relies on --- CLAUDE.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CLAUDE.md b/CLAUDE.md index 990c3285..73d0331d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -29,6 +29,7 @@ Shorter is better, none is best — chat output, commit messages, comments, docs - After every change to this file, re-read the whole thing and restructure it: merge overlapping rules, cut prose that restates a rule, move rules to the section they belong in, drop what's now covered elsewhere. Same information, more compact. ## Web research +- **A list or threshold a consumer relies on is sourced.** Deny-lists, defaults, limits: follow a published standard or a widely deployed tool, and cite it in the decision recording the choice; where none exists, ask. Never assemble one from names that seem plausible. - Default to `WebSearch`/`WebFetch`. When a page renders client-side and comes back empty/blocked, use the Playwright renderer at `~/code/playwright-for-agents/` — `./pw [options]` (see its README). Don't use claude-in-chrome for this. ## Compose, do not entangle -- 2.52.0 From a53a80734093d51527069f41a1f190625932b605 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 20:48:05 +0200 Subject: [PATCH 156/233] Drop the finished bench item: a blind judge ruled rebuild's larv-review at least as good as main's on all four cases --- todo.md | 1 - 1 file changed, 1 deletion(-) diff --git a/todo.md b/todo.md index e659f2b9..19b30f10 100644 --- a/todo.md +++ b/todo.md @@ -7,7 +7,6 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens `rebuild`'s PR into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. - **Carry main's #155 into `grounded()`: match the judge's quote with markdown emphasis and whitespace ignored.** The judge drops a bold line's closing `**` when quoting it; `rebuild` still rejects that, so merging it into main would bring back loops stopping on a correct verdict. -- **Bench rebuild's larv-review against main's on the same real chunks, and have a judge run rule it at least as good.** It must not degrade; one run per case cannot tell the process from reviewer variance. - **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. ## 0.2.0 -- 2.52.0 From 7072cccd1deb3f62d50866fe91c780adad5ae83c Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 21:35:09 +0200 Subject: [PATCH 157/233] Let rebuild's larv-review review a chunk into rebuild --- AGENTS.md | 2 +- docs/decisions.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 805f42e6..0ecff22d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,5 +27,5 @@ Decisions live in `docs/decisions.md`: - 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 -- rebuild: main's larv-review reviews a chunk into `rebuild` +- rebuild: rebuild's larv-review reviews a chunk into `rebuild` - review: an ask no user answers leaves the PR unmerged diff --git a/docs/decisions.md b/docs/decisions.md index fa8aa0ba..0b82e391 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -92,9 +92,9 @@ 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. -## rebuild: main's larv-review reviews a chunk into `rebuild` +## rebuild: rebuild's larv-review reviews a chunk into `rebuild` -2026-09-29, lilleman. Serves goal 4. The rewritten larv-review has not yet been benched against main's, so it reviews nothing until the plan's bench shows it does not regress. Valid until the rebuild merges. +2026-09-30, lilleman. Serves goal 4. A blind judge ruled it at least as good as main's on all four cases of the 2026-09-30 bench. The chunk's worktree holds it: follow its `skills/larv-review/SKILL.md` in place of the installed skill, read each `~/.claude/` it cites from the worktree, and launch each reviewer as a `general-purpose` agent prompted with the worktree's `agents/.md` body. Valid until the rebuild merges. ## review: an ask no user answers leaves the PR unmerged -- 2.52.0 From e4c17b7fd444afec9d7a85a08619ea8e9313c0cd Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 21:36:11 +0200 Subject: [PATCH 158/233] Drop the how-to from the decision entry --- docs/decisions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/decisions.md b/docs/decisions.md index 0b82e391..6b1e85f2 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -94,7 +94,7 @@ ## rebuild: rebuild's larv-review reviews a chunk into `rebuild` -2026-09-30, lilleman. Serves goal 4. A blind judge ruled it at least as good as main's on all four cases of the 2026-09-30 bench. The chunk's worktree holds it: follow its `skills/larv-review/SKILL.md` in place of the installed skill, read each `~/.claude/` it cites from the worktree, and launch each reviewer as a `general-purpose` agent prompted with the worktree's `agents/.md` body. Valid until the rebuild merges. +2026-09-30, lilleman. Serves goal 4. A blind judge ruled it at least as good as main's on all four cases of the 2026-09-30 bench. Valid until the rebuild merges. ## review: an ask no user answers leaves the PR unmerged -- 2.52.0 From 47e2bcdbd7079e7ab1478550965ddb27b814ff8e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 21:36:40 +0200 Subject: [PATCH 159/233] Delete main's rebuild-review paragraph in the merge to main --- todo.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/todo.md b/todo.md index 19b30f10..db6bc9d5 100644 --- a/todo.md +++ b/todo.md @@ -7,7 +7,7 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens `rebuild`'s PR into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. - **Carry main's #155 into `grounded()`: match the judge's quote with markdown emphasis and whitespace ignored.** The judge drops a bold line's closing `**` when quoting it; `rebuild` still rejects that, so merging it into main would bring back loops stopping on a correct verdict. -- **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. +- **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. The PR deletes main's `AGENTS.md` paragraph on a rebuild chunk's larv-review, which only main holds. ## 0.2.0 -- 2.52.0 From c2211afb7ceb40eb5eb9bd96957506cf25dffed7 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 22:29:14 +0200 Subject: [PATCH 160/233] File keeping larv-review's prose fixes to what the chunk touched --- todo.md | 1 + 1 file changed, 1 insertion(+) diff --git a/todo.md b/todo.md index db6bc9d5..f299b657 100644 --- a/todo.md +++ b/todo.md @@ -23,3 +23,4 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens - **Keep `outcome.Failure`'s docstring to what a failure is, without naming `retried`.** A value type naming its consumer. - **Give a 🟡 shown factually wrong the 🔴's way out in `review-findings.md`.** Today it can only be fixed, declined on a goal, or filed. - **Say in `AGENTS.md` that only the rebuild's last chunk opens `rebuild`'s PR into main.** Today it reads as every chunk doing so. +- **Have larv-review's prose pass fix only what the chunk touched, and file the rest per `CLAUDE.md` → "Working loop".** Its fixes land "in this chunk", cited sections and the sweep run when the architecture pass ran included. The 2026-09-30 bench's costliest rebuild runs sprawled outside the chunk: deleted README facts, 13 mypy rounds where main took 6–7 for the same fixes. On 35b, rebuild's one clear win took 6–11 agents to main's 8–16. `~/code/claude-handoffs/claude-config/2026-09-30/bench/comparison.md` -- 2.52.0 From 888206cac5dff10ada5a6a84fdbe8b15a236d76d Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 22:55:22 +0200 Subject: [PATCH 161/233] Add functional core, imperative shell to the technical principles, and let a decision link one --- CLAUDE.md | 2 +- principles/technical-principles.md | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/CLAUDE.md b/CLAUDE.md index 73d0331d..cd21517e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -112,7 +112,7 @@ How work proceeds in any repo, unless that repo's `AGENTS.md` says otherwise. **The inversion: a decision record owns what a call site may not say.** A rejected alternative, or what something deliberately does not cover, is banned beside the code precisely because the decision record holds it — a standing choice a future reader would otherwise relitigate, where a `CHANGELOG` holds what changed in a release. **The decision log has one home: `docs/decisions.md`**, or `docs/decisions/` split by area once it outgrows one file. `AGENTS.md` carries a one-line index of the titles, so a session or a reviewer sees that a decision exists without loading its reasoning. An entry states the decision, its date, who made it, and the premise it rests on ("valid while X") so it can expire honestly when that premise dies. A decision found anywhere else — an `AGENTS.md` body, a comment, or a README section that is neither a goal nor how one is met — moves there and leaves its index line behind. A goal stays a goal in the README; the log records only what the goal leaves open. -**Every decision links to a goal.** An entry names the goal it serves; one that cannot is a missing goal, and an entry already in the repo with no goal behind it is a finding. Propose the goal, never a reason of your own — the ask rule above says how. +**Every decision links to a goal or a technical principle.** An entry names the goal it serves or the principle in `~/.claude/principles/technical-principles.md` it applies; one that can do neither is a missing goal, and an entry already in the repo with neither behind it is a finding. Propose the goal, never a reason of your own — the ask rule above says how. **Link, don't inline — and keep the link bare.** A mechanism identical across call sites or repos is documented once in the canonical source and pointed at with a one-line bare link. Don't summarize what's behind the link or restate the identifier's own name. diff --git a/principles/technical-principles.md b/principles/technical-principles.md index bdcfabca..5e2ce768 100644 --- a/principles/technical-principles.md +++ b/principles/technical-principles.md @@ -32,6 +32,10 @@ - Example set order.client_firstname instead of order.client_id and fetching firstname from the clients table. * Explicit over implicit. - Avoid magic, avoid "clever" solutions, only abstract when the API can clearly describe what is happening. +* Functional core, imperative shell. + - Decisions live in pure functions, data in and data out; the shell around them performs the effects and holds no branching of its own. + - Every side effect comes from outside: output, time, randomness, network and storage are injectable, so a test runs exactly the code production runs. + - BANNED: `new Date(entry.msTimestamp ?? Date.now())` in a formatter; a test swapping `globalThis.fetch`. GOOD: the clock is a parameter, defaulted to the system clock only where the program is wired together. * Deterministic order wherever order carries no meaning. - Sort it, on a key that does not move: the name a line introduces, never where it came from. A sorted list is searchable, its diff shows only what changed, and two edits to it conflict only where they mean to. * Keep It Simple, Stupid (KISS). -- 2.52.0 From a79efe24299a74bfbbe1ec117cbb6d6e63a89483 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 23:12:23 +0200 Subject: [PATCH 162/233] Audit every principle and goal over the whole project in the architecture pass, and fire it on a release's last chunk --- AGENTS.md | 1 + CLAUDE.md | 2 +- agents/principles-auditor.md | 13 +++++++++++++ agents/systems-architect.md | 2 +- docs/decisions.md | 4 ++++ skills/larv-review/SKILL.md | 8 +++++--- skills/larv-review/review-findings.md | 2 +- 7 files changed, 26 insertions(+), 6 deletions(-) create mode 100644 agents/principles-auditor.md diff --git a/AGENTS.md b/AGENTS.md index 0ecff22d..d548d9ff 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -29,3 +29,4 @@ Decisions live in `docs/decisions.md`: - bin/: mypy checks `loop_claude`'s types in the tests - rebuild: rebuild's larv-review reviews a chunk into `rebuild` - review: an ask no user answers leaves the PR unmerged +- review: the architecture pass audits every principle and goal over the whole project, and a release's last chunk fires it diff --git a/CLAUDE.md b/CLAUDE.md index cd21517e..676742df 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -112,7 +112,7 @@ How work proceeds in any repo, unless that repo's `AGENTS.md` says otherwise. **The inversion: a decision record owns what a call site may not say.** A rejected alternative, or what something deliberately does not cover, is banned beside the code precisely because the decision record holds it — a standing choice a future reader would otherwise relitigate, where a `CHANGELOG` holds what changed in a release. **The decision log has one home: `docs/decisions.md`**, or `docs/decisions/` split by area once it outgrows one file. `AGENTS.md` carries a one-line index of the titles, so a session or a reviewer sees that a decision exists without loading its reasoning. An entry states the decision, its date, who made it, and the premise it rests on ("valid while X") so it can expire honestly when that premise dies. A decision found anywhere else — an `AGENTS.md` body, a comment, or a README section that is neither a goal nor how one is met — moves there and leaves its index line behind. A goal stays a goal in the README; the log records only what the goal leaves open. -**Every decision links to a goal or a technical principle.** An entry names the goal it serves or the principle in `~/.claude/principles/technical-principles.md` it applies; one that can do neither is a missing goal, and an entry already in the repo with neither behind it is a finding. Propose the goal, never a reason of your own — the ask rule above says how. +**Every decision links to a goal or a technical principle.** An entry names the goal it serves or the principle in `~/.claude/principles/technical-principles.md` it applies; one that can do neither is a missing goal, and an entry already in the repo with neither behind it is a finding. An entry working against a goal or a technical principle stands only while it names the `todo.md` item that ends it. Propose the goal, never a reason of your own — the ask rule above says how. **Link, don't inline — and keep the link bare.** A mechanism identical across call sites or repos is documented once in the canonical source and pointed at with a one-line bare link. Don't summarize what's behind the link or restate the identifier's own name. diff --git a/agents/principles-auditor.md b/agents/principles-auditor.md new file mode 100644 index 00000000..f48503a9 --- /dev/null +++ b/agents/principles-auditor.md @@ -0,0 +1,13 @@ +--- +name: principles-auditor +description: "Use this agent for larv-review's architecture pass: one yardstick checked against the whole project." +tools: Read, Grep, Glob +--- + +You check one yardstick against the whole project, never a diff: every principle in the file you are handed, or every goal under the project's `README.md` → `## Goals`. + +Verdict, severities, rounds and declines: ~/.claude/skills/larv-review/review-findings.md. Read the yardstick, `README.md`, `docs/decisions.md` and `todo.md` first, then all of the project's code, config, tests and CI. + +- Per principle or goal: every place the project departs from it, with file:line, the defect in one sentence and its concrete consequence. Then one line: followed, mostly, not followed, or does not apply and why. +- A departure a `todo.md` item plans away is named with that item, not raised. +- A decision in `docs/decisions.md` working against a goal or a technical principle is a 🔴 on the decision, unless it names the `todo.md` item that ends it. Weigh it hard: that it was decided is no reason. diff --git a/agents/systems-architect.md b/agents/systems-architect.md index e2dcaa39..2bc96b4d 100644 --- a/agents/systems-architect.md +++ b/agents/systems-architect.md @@ -186,7 +186,7 @@ This is where unjustified duplication and accidental complexity get caught. Run 6. **Price the reasoned complexity too.** Essential-looking complexity has a requirement behind it. For each hotspot that survives the steps above, name that requirement, then sketch the design without it. When a much simpler near-equivalent exists, report the trade as a finding: the simpler shape, the exact functionality delta, and the complexity saved. A requirement nobody has priced is not a decision — offer the trade once, plainly, and let the owner accept or reject it. 7. **Hunt the imagined requirement.** The step above prices complexity a real requirement forces; this one removes complexity no requirement forces. For every abstraction, indirection, configuration point, and layer of generality, name the present, Stage 0-recorded requirement it serves. An interface with one implementation, a plugin system with one plugin, a cache or shard — or a load-testing rig — for load nobody recorded, a canary rig for a blast radius nobody recorded, "in case we swap the database" — speculative generality is the over-engineered twin of copy-paste drift: complexity nobody's requirement chose. The future that justifies flexibility must be a recorded goal or horizon, not the author's imagination — and the shorter the horizon, the harder this step cuts. Rate removals with the same severity as unreasoned duplication. -Respect documented deliberate deviations — a stated trade-off is a valid reason (`docs/decisions.md`). Respecting it means not re-arguing the same trade with the same facts; it does not forbid offering a materially simpler alternative the decision never considered — offer it once with the exact delta, then drop it if declined. The target is the *un*reasoned: duplication, complexity, and confusion that nobody decided and nobody can defend. "Acceptable for now", "will compound later", and "converge in a future pass" are how a small drift becomes the permanent shape of the system. +Respect documented deliberate deviations — a stated trade-off is a valid reason (`docs/decisions.md`), unless it works against a goal or a technical principle and names no `todo.md` item ending it. Respecting it means not re-arguing the same trade with the same facts; it does not forbid offering a materially simpler alternative the decision never considered — offer it once with the exact delta, then drop it if declined. The target is the *un*reasoned: duplication, complexity, and confusion that nobody decided and nobody can defend. "Acceptable for now", "will compound later", and "converge in a future pass" are how a small drift becomes the permanent shape of the system. ## Communication Style diff --git a/docs/decisions.md b/docs/decisions.md index 6b1e85f2..e29fa9f0 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -99,3 +99,7 @@ ## review: an ask no user answers leaves the PR unmerged 2026-09-30, claude, for the rebuild. Serves goal 4: the round cap, a BLOCK's restructure, Stage 0's questions and a goal conflict are the human's call, and an unmerged PR is what brings it to them; merging would make the call for them. Where an option reviews more — run the pass, fix under the floor, fix a finding no goal lets the run decline — the run takes it; a ❓ or a prose fix changing a goal or a decision is filed in `todo.md`, which reaches the human without holding the chunk. Valid while a human reads every unmerged PR an unattended run leaves. + +## review: the architecture pass audits every principle and goal over the whole project, and a release's last chunk fires it + +2026-09-30, lilleman. Serves goal 4: `@larvit/log`'s chunks each passed their per-diff reviewers, and a whole-project audit that day still found its functional core and state machines not followed and two semver breaks planned; what grows over many chunks shows in no diff. Valid while the other passes review a diff. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 60b37e80..c3944c98 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -28,7 +28,7 @@ Follow `~/.claude/CLAUDE.md` → "Git, commits, and PRs". Never commit to the de | Pass | Reviewer | Trigger | |------|----------|----------------------------------------| -| Architecture, then the comprehension floor | systems-architect, then the `comprehension-panel` scoring run | carries an architectural decision: a new, restructured or moved component, module, service or boundary; a new dependency or first use of an infrastructure pattern (queue, cron, cache, websocket, …); a new or changed external contract (routes, request/response shapes, events, webhooks, published file formats); a schema change beyond an additive column | +| Architecture, then the principles audit and the comprehension floor | systems-architect, then principles-auditor and the `comprehension-panel` scoring run | carries an architectural decision: a new, restructured or moved component, module, service or boundary; a new dependency or first use of an infrastructure pattern (queue, cron, cache, websocket, …); a new or changed external contract (routes, request/response shapes, events, webhooks, published file formats); a schema change beyond an additive column; the chunk shipping its release's last item | | Security | `/security-review` | changes code or config; a fix, only where it opens an untrusted-input boundary or touches authn/authz, secrets or crypto | | Full security scan | the `claude-security` plugin (`/claude-security` → "Scan changes") | touches authn/authz, secrets or crypto, opens an untrusted-input boundary, or adds an external surface | | Stability | stability-reviewer | changes code, config or tests; a fix, only where it changes behaviour: what the code or its tests do | @@ -37,9 +37,9 @@ Follow `~/.claude/CLAUDE.md` → "Git, commits, and PRs". Never commit to the de A comment is prose, not code. Passes run in this order: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. A 🔀 escalation runs the named pass once the current pass is done; its fixes re-enter like any other. -**Record, then ask**, for the architecture pass and the full scan: where, before the chunk began, the repo held the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: cite the record and skip it, the architecture pass's scoring run excepted, since no record older than the chunk scored the code it writes. A change that *departs* from the record is unreviewed however thorough the record is. Fired and not skipped → ask the user with the evidence and your recommendation; no user reachable → run it. +**Record, then ask**, for the architecture pass and the full scan: where, before the chunk began, the repo held the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: cite the record and skip it, the architecture pass's principles audit and scoring run excepted, since no record older than the chunk checked the code it writes. A change that *departs* from the record is unreviewed however thorough the record is. Fired and not skipped → ask the user with the evidence and your recommendation; no user reachable → run it. -**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect, unless skipped by record, and then the scoring run, so a floor fix reruns the whole round; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡, until a re-entry reruns it; the 🟢 and ❓ left are addressed in the round that finished it — fixed, answered, declined or filed in `todo.md`; a ❓ only the user can answer is asked; no user reachable → filed. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the user — for the auto-reviewer, before any push that would summon a fourth, fixes waiting unpushed. A yes grants that pass one more round, after which the ask repeats; a no leaves the PR unmerged. +**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect, unless skipped by record, then the principles audit and the scoring run, so a floor fix reruns the whole round; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡, until a re-entry reruns it; the 🟢 and ❓ left are addressed in the round that finished it — fixed, answered, declined or filed in `todo.md`; a ❓ only the user can answer is asked; no user reachable → filed. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the user — for the auto-reviewer, before any push that would summon a fourth, fixes waiting unpushed. A yes grants that pass one more round, after which the ask repeats; a no leaves the PR unmerged. **Re-entry.** A fix is a change no pass has seen, a 🟢's or ❓'s included. A round's fixes re-enter together: run, in table order, each pass whose trigger they fire and the pass whose 🔴 or 🟡 they answer, a pass at its cap getting the cap's ask; then §4. @@ -50,6 +50,8 @@ Launch systems-architect: review the system as a whole entered through this chan - **Stage 0 questions returned**: relay them to the user, record the answers in the README, re-run once. - **BLOCK** → confirm with the user first when the restructure materially reshapes their PR; until confirmed, no later pass runs. +Then the principles audit: one principles-auditor per file in `~/.claude/principles/` and one for the README's goals, each over the whole project. A finding outside the chunk is filed in `todo.md`; a 🔴 on a decision is asked, since the decision is the user's. + Then the comprehension floor: the `comprehension-panel` skill's scoring run (`~/.claude/skills/comprehension-panel/SKILL.md` → "The scoring run") over the whole project, not the diff. With any dimension or the overall below 7.0 the chunk does not merge: fix the places the seats name under the capping dimension, or take the user's explicit decision to ship under the floor, record it in `docs/decisions.md` with the scores, and file the places in `todo.md`. No user reachable → fix. At the floor or above, the scores are still a ratchet — a later chunk may not lower any — and the four dimension scores and the overall go in the summary so the next run can see the direction of travel. ### Security diff --git a/skills/larv-review/review-findings.md b/skills/larv-review/review-findings.md index 7a13b5c8..324fb2db 100644 --- a/skills/larv-review/review-findings.md +++ b/skills/larv-review/review-findings.md @@ -2,7 +2,7 @@ Words: `~/.claude/CLAUDE.md` → "Vocabulary". -A reviewer reads and reports; it edits nothing. Read `docs/decisions.md` and `todo.md` first: a finding declined in the one or filed in the other is not raised again. +A reviewer reads and reports; it edits nothing. Read `docs/decisions.md` and `todo.md` first: a finding declined in the one or filed in the other is not raised again, unless the decline works against a goal or a technical principle. ## Severity -- 2.52.0 From fec886273a58587f0c4d8e48e9996cb4f92fa195 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 23:14:33 +0200 Subject: [PATCH 163/233] Carry the todo.md condition and the technical principles into review-findings, and run the audit unasked in every round --- CLAUDE.md | 4 ++-- agents/principles-auditor.md | 2 +- skills/larv-review/SKILL.md | 6 +++--- skills/larv-review/review-findings.md | 6 +++--- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 676742df..454ce6aa 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -9,7 +9,7 @@ Shorter is better, none is best — chat output, commit messages, comments, docs - **gate** — the merge gate: the checks a PR passes before it merges. - **interrupt** — `loop-claude` handing the terminal to the human, `claude --resume`, for a decision that is theirs. - **judge** — the headless claude that reads a worker's transcript each cycle and decides whether to interrupt and whether the chunk is finished. -- **pass** — one kind of review a chunk may take, run in rounds by its reviewer until clean; `larv-review` §3 lists them. +- **pass** — one kind of review a chunk may take, run in rounds by its reviewers until clean; `larv-review` §3 lists them. - **plan** — `todo.md`. - **premises** — the goals and audience under `## Goals` and `## Audience` in the project's `README.md`. - **release** — a semver version the human cuts. @@ -112,7 +112,7 @@ How work proceeds in any repo, unless that repo's `AGENTS.md` says otherwise. **The inversion: a decision record owns what a call site may not say.** A rejected alternative, or what something deliberately does not cover, is banned beside the code precisely because the decision record holds it — a standing choice a future reader would otherwise relitigate, where a `CHANGELOG` holds what changed in a release. **The decision log has one home: `docs/decisions.md`**, or `docs/decisions/` split by area once it outgrows one file. `AGENTS.md` carries a one-line index of the titles, so a session or a reviewer sees that a decision exists without loading its reasoning. An entry states the decision, its date, who made it, and the premise it rests on ("valid while X") so it can expire honestly when that premise dies. A decision found anywhere else — an `AGENTS.md` body, a comment, or a README section that is neither a goal nor how one is met — moves there and leaves its index line behind. A goal stays a goal in the README; the log records only what the goal leaves open. -**Every decision links to a goal or a technical principle.** An entry names the goal it serves or the principle in `~/.claude/principles/technical-principles.md` it applies; one that can do neither is a missing goal, and an entry already in the repo with neither behind it is a finding. An entry working against a goal or a technical principle stands only while it names the `todo.md` item that ends it. Propose the goal, never a reason of your own — the ask rule above says how. +**Every decision links to a goal or a technical principle.** An entry names the goal it serves or the technical principle under `~/.claude/principles/` it applies; one that can do neither is a missing goal, and an entry already in the repo with neither behind it is a finding. Propose the goal, never a reason of your own — the ask rule above says how. An entry working against a goal or a technical principle stands only while it names the `todo.md` item that ends it. **Link, don't inline — and keep the link bare.** A mechanism identical across call sites or repos is documented once in the canonical source and pointed at with a one-line bare link. Don't summarize what's behind the link or restate the identifier's own name. diff --git a/agents/principles-auditor.md b/agents/principles-auditor.md index f48503a9..f64b27b5 100644 --- a/agents/principles-auditor.md +++ b/agents/principles-auditor.md @@ -4,7 +4,7 @@ description: "Use this agent for larv-review's architecture pass: one yardstick tools: Read, Grep, Glob --- -You check one yardstick against the whole project, never a diff: every principle in the file you are handed, or every goal under the project's `README.md` → `## Goals`. +You check one yardstick against the whole project, never a diff, in every round: every principle in the file you are handed, or every goal under the project's `README.md` → `## Goals`. Verdict, severities, rounds and declines: ~/.claude/skills/larv-review/review-findings.md. Read the yardstick, `README.md`, `docs/decisions.md` and `todo.md` first, then all of the project's code, config, tests and CI. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index c3944c98..fba6ccd0 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -37,9 +37,9 @@ Follow `~/.claude/CLAUDE.md` → "Git, commits, and PRs". Never commit to the de A comment is prose, not code. Passes run in this order: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. A 🔀 escalation runs the named pass once the current pass is done; its fixes re-enter like any other. -**Record, then ask**, for the architecture pass and the full scan: where, before the chunk began, the repo held the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: cite the record and skip it, the architecture pass's principles audit and scoring run excepted, since no record older than the chunk checked the code it writes. A change that *departs* from the record is unreviewed however thorough the record is. Fired and not skipped → ask the user with the evidence and your recommendation; no user reachable → run it. +**Record, then ask**, for the architecture pass and the full scan: where, before the chunk began, the repo held the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: cite the record and skip it, the architecture pass's principles audit and scoring run excepted: they run whenever the pass fires, unasked, since no record older than the chunk checked the code it writes. A change that *departs* from the record is unreviewed however thorough the record is. Fired and not skipped → ask the user with the evidence and your recommendation; no user reachable → run it. -**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect, unless skipped by record, then the principles audit and the scoring run, so a floor fix reruns the whole round; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡, until a re-entry reruns it; the 🟢 and ❓ left are addressed in the round that finished it — fixed, answered, declined or filed in `todo.md`; a ❓ only the user can answer is asked; no user reachable → filed. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the user — for the auto-reviewer, before any push that would summon a fourth, fixes waiting unpushed. A yes grants that pass one more round, after which the ask repeats; a no leaves the PR unmerged. +**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect (unless skipped by record), the principles audit and the scoring run, so a fix to any of their findings reruns the whole round; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡, until a re-entry reruns it; the 🟢 and ❓ left are addressed in the round that finished it — fixed, answered, declined or filed in `todo.md`; a ❓ only the user can answer is asked; no user reachable → filed. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the user — for the auto-reviewer, before any push that would summon a fourth, fixes waiting unpushed. A yes grants that pass one more round, after which the ask repeats; a no leaves the PR unmerged. **Re-entry.** A fix is a change no pass has seen, a 🟢's or ❓'s included. A round's fixes re-enter together: run, in table order, each pass whose trigger they fire and the pass whose 🔴 or 🟡 they answer, a pass at its cap getting the cap's ask; then §4. @@ -50,7 +50,7 @@ Launch systems-architect: review the system as a whole entered through this chan - **Stage 0 questions returned**: relay them to the user, record the answers in the README, re-run once. - **BLOCK** → confirm with the user first when the restructure materially reshapes their PR; until confirmed, no later pass runs. -Then the principles audit: one principles-auditor per file in `~/.claude/principles/` and one for the README's goals, each over the whole project. A finding outside the chunk is filed in `todo.md`; a 🔴 on a decision is asked, since the decision is the user's. +Then the principles audit: one principles-auditor per file in `~/.claude/principles/` and one for the README's goals, each over the whole project in every round. A finding outside the chunk is filed in `todo.md`; a 🔴 on a decision is asked, since the decision is the user's. Then the comprehension floor: the `comprehension-panel` skill's scoring run (`~/.claude/skills/comprehension-panel/SKILL.md` → "The scoring run") over the whole project, not the diff. With any dimension or the overall below 7.0 the chunk does not merge: fix the places the seats name under the capping dimension, or take the user's explicit decision to ship under the floor, record it in `docs/decisions.md` with the scores, and file the places in `todo.md`. No user reachable → fix. At the floor or above, the scores are still a ratchet — a later chunk may not lower any — and the four dimension scores and the overall go in the summary so the next run can see the direction of travel. diff --git a/skills/larv-review/review-findings.md b/skills/larv-review/review-findings.md index 324fb2db..6f40e297 100644 --- a/skills/larv-review/review-findings.md +++ b/skills/larv-review/review-findings.md @@ -2,11 +2,11 @@ Words: `~/.claude/CLAUDE.md` → "Vocabulary". -A reviewer reads and reports; it edits nothing. Read `docs/decisions.md` and `todo.md` first: a finding declined in the one or filed in the other is not raised again, unless the decline works against a goal or a technical principle. +A reviewer reads and reports; it edits nothing. Read `docs/decisions.md` and `todo.md` first: a finding declined in the one or filed in the other is not raised again, unless the decline works against a goal or a technical principle and names no `todo.md` item ending it. ## Severity -- 🔴 **must fix** — a goal, a principle or correctness broken. Fixed, or shown factually wrong, with what disproved it recorded in `docs/decisions.md`; never declined. +- 🔴 **must fix** — a goal, a principle or correctness broken. Fixed, or shown factually wrong, with what disproved it recorded in `docs/decisions.md`, or — outside the chunk — filed in `todo.md`; never declined. - 🟡 **should fix** — worse than it needs to be. Fixed, declined, or — outside the chunk — filed in `todo.md`. - 🟢 **nit** — fixed, answered, declined in the summary with its reason, or filed in `todo.md`. - ❓ **question** for the author: a finding you could not confirm goes here, not above. @@ -34,4 +34,4 @@ A review's first line, derived from the findings: ## Declining -A 🟡 may be declined where the reason is sound, consistent with the goals, and confidence is very high. The decline, its reason and the goal it rests on go to `docs/decisions.md`. A reason no goal speaks to is a gap in the goals: fix the finding, or ask per `~/.claude/CLAUDE.md` → "Working loop", "Ask, don't guess", which also says where the user's reply to a ❓ lands; no user reachable → fix. Never a silent drop, and never a decline argued from convenience or the size of the fix. +A 🟡 may be declined where the reason is sound, consistent with the goals and the technical principles, and confidence is very high. The decline, its reason and the goal it rests on go to `docs/decisions.md`. A reason no goal speaks to is a gap in the goals: fix the finding, or ask per `~/.claude/CLAUDE.md` → "Working loop", "Ask, don't guess", which also says where the user's reply to a ❓ lands; no user reachable → fix. Never a silent drop, and never a decline argued from convenience or the size of the fix. -- 2.52.0 From 080fdb94b2ccbeb27ee1a99f20e317328c263401 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 23:16:09 +0200 Subject: [PATCH 164/233] =?UTF-8?q?Let=20a=20decline=20rest=20on=20a=20tec?= =?UTF-8?q?hnical=20principle,=20and=20untangle=20the=20=F0=9F=94=B4=20bul?= =?UTF-8?q?let=20and=20the=20record=20exception?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- skills/larv-review/SKILL.md | 6 +++--- skills/larv-review/review-findings.md | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index fba6ccd0..eed5b4a3 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -37,9 +37,9 @@ Follow `~/.claude/CLAUDE.md` → "Git, commits, and PRs". Never commit to the de A comment is prose, not code. Passes run in this order: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. A 🔀 escalation runs the named pass once the current pass is done; its fixes re-enter like any other. -**Record, then ask**, for the architecture pass and the full scan: where, before the chunk began, the repo held the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: cite the record and skip it, the architecture pass's principles audit and scoring run excepted: they run whenever the pass fires, unasked, since no record older than the chunk checked the code it writes. A change that *departs* from the record is unreviewed however thorough the record is. Fired and not skipped → ask the user with the evidence and your recommendation; no user reachable → run it. +**Record, then ask**, for the architecture pass and the full scan: where, before the chunk began, the repo held the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: cite the record and skip it. The architecture pass's principles audit and scoring run are excepted: they run whenever the pass fires, unasked, since no record older than the chunk checked the code it writes. A change that *departs* from the record is unreviewed however thorough the record is. Fired and not skipped → ask the user with the evidence and your recommendation; no user reachable → run it. -**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect (unless skipped by record), the principles audit and the scoring run, so a fix to any of their findings reruns the whole round; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡, until a re-entry reruns it; the 🟢 and ❓ left are addressed in the round that finished it — fixed, answered, declined or filed in `todo.md`; a ❓ only the user can answer is asked; no user reachable → filed. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the user — for the auto-reviewer, before any push that would summon a fourth, fixes waiting unpushed. A yes grants that pass one more round, after which the ask repeats; a no leaves the PR unmerged. +**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect (unless skipped), the principles audit and the scoring run, so a fix to any of their findings reruns the whole round; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡, until a re-entry reruns it; the 🟢 and ❓ left are addressed in the round that finished it — fixed, answered, declined or filed in `todo.md`; a ❓ only the user can answer is asked; no user reachable → filed. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the user — for the auto-reviewer, before any push that would summon a fourth, fixes waiting unpushed. A yes grants that pass one more round, after which the ask repeats; a no leaves the PR unmerged. **Re-entry.** A fix is a change no pass has seen, a 🟢's or ❓'s included. A round's fixes re-enter together: run, in table order, each pass whose trigger they fire and the pass whose 🔴 or 🟡 they answer, a pass at its cap getting the cap's ask; then §4. @@ -89,4 +89,4 @@ Launch prose-reviewer with what the diff touched and every section this review c ## 6. Wrap up -Summarize: PR URL and final state, every reviewer's verdict, rounds per pass, passes skipped, findings fixed vs answered vs declined vs open — each answer with what settles it, each decline with its reason, a 🟡's with the goal it rests on — CI status, decisions recorded (file paths), `todo.md`/`CHANGELOG.md` updated, and any 🔀 escalation left for the user. +Summarize: PR URL and final state, every reviewer's verdict, rounds per pass, passes skipped, findings fixed vs answered vs declined vs open — each answer with what settles it, each decline with its reason, a 🟡's with the goal or technical principle it rests on — CI status, decisions recorded (file paths), `todo.md`/`CHANGELOG.md` updated, and any 🔀 escalation left for the user. diff --git a/skills/larv-review/review-findings.md b/skills/larv-review/review-findings.md index 6f40e297..ab25e09c 100644 --- a/skills/larv-review/review-findings.md +++ b/skills/larv-review/review-findings.md @@ -6,7 +6,7 @@ A reviewer reads and reports; it edits nothing. Read `docs/decisions.md` and `to ## Severity -- 🔴 **must fix** — a goal, a principle or correctness broken. Fixed, or shown factually wrong, with what disproved it recorded in `docs/decisions.md`, or — outside the chunk — filed in `todo.md`; never declined. +- 🔴 **must fix** — a goal, a principle or correctness broken. Fixed; outside the chunk, filed in `todo.md`; or shown factually wrong, with what disproved it recorded in `docs/decisions.md`. Never declined. - 🟡 **should fix** — worse than it needs to be. Fixed, declined, or — outside the chunk — filed in `todo.md`. - 🟢 **nit** — fixed, answered, declined in the summary with its reason, or filed in `todo.md`. - ❓ **question** for the author: a finding you could not confirm goes here, not above. @@ -34,4 +34,4 @@ A review's first line, derived from the findings: ## Declining -A 🟡 may be declined where the reason is sound, consistent with the goals and the technical principles, and confidence is very high. The decline, its reason and the goal it rests on go to `docs/decisions.md`. A reason no goal speaks to is a gap in the goals: fix the finding, or ask per `~/.claude/CLAUDE.md` → "Working loop", "Ask, don't guess", which also says where the user's reply to a ❓ lands; no user reachable → fix. Never a silent drop, and never a decline argued from convenience or the size of the fix. +A 🟡 may be declined where the reason is sound, consistent with the goals and the technical principles, and confidence is very high. The decline, its reason and the goal or technical principle it rests on go to `docs/decisions.md`. A reason neither speaks to is a gap in the goals: fix the finding, or ask per `~/.claude/CLAUDE.md` → "Working loop", "Ask, don't guess", which also says where the user's reply to a ❓ lands; no user reachable → fix. Never a silent drop, and never a decline argued from convenience or the size of the fix. -- 2.52.0 From ce21270052b9c7f00b3c211d0132619713e8309c Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 23:20:11 +0200 Subject: [PATCH 165/233] File the rebuild's principles audit --- todo.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/todo.md b/todo.md index f299b657..93dd2dc1 100644 --- a/todo.md +++ b/todo.md @@ -24,3 +24,13 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens - **Give a 🟡 shown factually wrong the 🔴's way out in `review-findings.md`.** Today it can only be fixed, declined on a goal, or filed. - **Say in `AGENTS.md` that only the rebuild's last chunk opens `rebuild`'s PR into main.** Today it reads as every chunk doing so. - **Have larv-review's prose pass fix only what the chunk touched, and file the rest per `CLAUDE.md` → "Working loop".** Its fixes land "in this chunk", cited sections and the sweep run when the architecture pass ran included. The 2026-09-30 bench's costliest rebuild runs sprawled outside the chunk: deleted README facts, 13 mypy rounds where main took 6–7 for the same fixes. On 35b, rebuild's one clear win took 6–11 agents to main's 8–16. `~/code/claude-handoffs/claude-config/2026-09-30/bench/comparison.md` +- **Give principles-auditor and prose-reviewer a way to list the project's files.** Their `tools: Read, Grep, Glob` left only Read in the 2026-09-30 audit run, so each read what imports and `.gitignore` named and said which files it could not reach. +- **Judge a cycle on more than the transcript's last 40,000 characters.** `judge.py:80` cuts the session, which spans every cycle of the chunk, so a decision made early in a long run is never judged and the human is not interrupted for it (goal 4). +- **Name `jq` and GNU `date` under README → Install, or drop them from `statusline.sh`.** Without `jq` the status line aborts; under BSD `date` the reset times vanish, so CHANGELOG's "runs on any machine unedited" is false. +- **Inject `loop-claude`'s side effects: `time.sleep`, `subprocess`, `input()`, `isatty` and `os.execv`, and split `project_model` and `interrupt` into decisions and effects.** Functional core, imperative shell; the loop's flow has no tests because nothing reaches it without the effects. +- **Test `run_cycle`, `judge_through_interrupts`, `retried`, `archive`, `trust`, `interrupt`, the models file and the worker's arguments.** Only the pure helpers are tested today. +- **Give a project's loop state named states and one transition function.** Fresh, resuming, awaiting the human and finished come today from whether a transcript exists, two verdict booleans and an open `while True` in `steps.py`. +- **Make a `Verdict` with both `interrupt` and `finished`, or a question without an interrupt, unrepresentable.** `steps.py:49` ignores `finished` when `interrupt` is set. +- **Grant an unattended worker named permissions in place of `bypassPermissions`.** `worker.py:37` and `interrupt.py:23` let it read and write anything the user can, `~/.claude/.credentials.json` included. +- **Return a `Stop` when `git` or `os.execv` fails.** `checkout.py:7,15` and `reload.py:52` end in a traceback. +- **Narrow `.gitignore`'s `!bin/*` and `skills/*/**` to the files they mean.** A stray log of `loop-claude` output in `bin/` would be committed with transcript text in it. -- 2.52.0 From 87024023f422cd86c48c6e2386ea7ad2c4be5b38 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 23:34:15 +0200 Subject: [PATCH 166/233] Record the audit answers: a full-path session with one loop at a time, keeping out of ~/.claude.json, the sandbox's bypassPermissions, and continuous archiving --- AGENTS.md | 3 ++- docs/decisions.md | 12 ++++++++---- todo.md | 4 +++- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index d548d9ff..062e2d18 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,7 +6,7 @@ Decisions live in `docs/decisions.md`: - larv-review: a project under the comprehension floor is fixed at the capping dimension - loop-claude: a judge decides interrupts, not the worker's self-report -- loop-claude: one session per project, at a fixed id +- loop-claude: one session per project, at a fixed id from its full path, and a second loop refuses to start - loop-claude: the trust file is rewritten before an interrupt - loop-claude: every worktree of the checkout is trusted before an interrupt - bin/: the Python floor is README's Install prerequisite @@ -30,3 +30,4 @@ Decisions live in `docs/decisions.md`: - rebuild: rebuild's larv-review reviews a chunk into `rebuild` - review: an ask no user answers leaves the PR unmerged - review: the architecture pass audits every principle and goal over the whole project, and a release's last chunk fires it +- loop-claude: an unattended worker bypasses permissions inside its sandbox diff --git a/docs/decisions.md b/docs/decisions.md index e29fa9f0..a60744e4 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -8,17 +8,17 @@ 2026-09-21, lilleman. Serves goal 4. Asked to name the goal behind each choice, the worker cites a real goal for a choice that goal does not settle, and under-reports its own decisions; the judge's bar is whether the README discriminates between the alternatives. Valid while the worker's self-report stays unreliable. -## loop-claude: one session per project, at a fixed id +## loop-claude: one session per project, at a fixed id from its full path, and a second loop refuses to start -2026-09-21, lilleman; the rename and mirrored-path costs accepted 2026-09-25 by larv-review. Serves goal 4. One fixed id per project keeps the session picker at one entry per project and makes any transcript under that id loop-claude's own to delete. The id derives from the session name, so moving the checkout or changing that name orphans open sessions: they stay in the picker until the human deletes them, migration code not being worth a one-human audience. A checkout outside `~/code` mirroring a path inside it would share its id. Valid while claude takes `--session-id` and resumes by it, and no checkout outside `~/code` mirrors a path inside it. +2026-09-21, lilleman; revised 2026-09-30 by lilleman. Serves goal 4. One fixed id per project keeps the session picker at one entry per project and makes any transcript under that id loop-claude's own to delete. The id derives from the checkout's full path, so no two checkouts share one, and `loop-claude` refuses to start while another session on that id is active. Moving the checkout orphans open sessions: they stay in the picker until the human deletes them, migration code not being worth a one-human audience. Until `todo.md`'s "Key a project's session on its checkout's full path" lands, the id drops the leading `/`, so a checkout outside `~/code` mirroring a path inside it shares its id. Valid while claude takes `--session-id` and resumes by it. ## loop-claude: the trust file is rewritten before an interrupt -2026-09-21, lilleman; the lost-write risk accepted 2026-09-24 by larv-review. Serves goal 4. A write by another claude inside `trust`'s read-modify-write window is lost. Valid while no flag skips the dialog. +2026-09-21, lilleman; the lost-write risk accepted 2026-09-24 by larv-review. Serves goal 4. A write by another claude inside `trust`'s read-modify-write window is lost. Stands until `todo.md`'s "Move what `loop-claude` writes out of `~/.claude.json`" ends it: 2026-09-30, lilleman, Claude Code owns and writes that file, so `loop-claude` keeps out of it, and a case that must stay in it is weighed on its own. ## loop-claude: every worktree of the checkout is trusted before an interrupt -2026-09-24, lilleman. Serves goal 4. `claude --resume` re-enters the worktree the worker last entered, recorded in the transcript's `worktree-state` entry, and Claude Code asks trust per path, so trusting the checkout alone still lands the human in the dialog; trusting every worktree `git worktree list` names spares reading which one from the transcript. Valid while resume re-enters a recorded worktree and trust is kept per path. +2026-09-24, lilleman. Serves goal 4. `claude --resume` re-enters the worktree the worker last entered, recorded in the transcript's `worktree-state` entry, and Claude Code asks trust per path, so trusting the checkout alone still lands the human in the dialog; trusting every worktree `git worktree list` names spares reading which one from the transcript. Stands until `todo.md`'s "Move what `loop-claude` writes out of `~/.claude.json`" ends it. Valid while resume re-enters a recorded worktree and trust is kept per path. ## bin/: the Python floor is README's Install prerequisite @@ -103,3 +103,7 @@ ## review: the architecture pass audits every principle and goal over the whole project, and a release's last chunk fires it 2026-09-30, lilleman. Serves goal 4: `@larvit/log`'s chunks each passed their per-diff reviewers, and a whole-project audit that day still found its functional core and state machines not followed and two semver breaks planned; what grows over many chunks shows in no diff. Valid while the other passes review a diff. + +## loop-claude: an unattended worker bypasses permissions inside its sandbox + +2026-09-30, lilleman. Applies "Always grant explicit access to data": the sandbox `loop-claude` runs in is where access is granted, so the worker and the interrupt run with `bypassPermissions`. `~/.claude/.credentials.json` holds Claude Code's own credentials, which the worker's claude reads to run. Valid while `loop-claude` runs only inside a sandbox. diff --git a/todo.md b/todo.md index 93dd2dc1..b34a74db 100644 --- a/todo.md +++ b/todo.md @@ -31,6 +31,8 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens - **Test `run_cycle`, `judge_through_interrupts`, `retried`, `archive`, `trust`, `interrupt`, the models file and the worker's arguments.** Only the pure helpers are tested today. - **Give a project's loop state named states and one transition function.** Fresh, resuming, awaiting the human and finished come today from whether a transcript exists, two verdict booleans and an open `while True` in `steps.py`. - **Make a `Verdict` with both `interrupt` and `finished`, or a question without an interrupt, unrepresentable.** `steps.py:49` ignores `finished` when `interrupt` is set. -- **Grant an unattended worker named permissions in place of `bypassPermissions`.** `worker.py:37` and `interrupt.py:23` let it read and write anything the user can, `~/.claude/.credentials.json` included. - **Return a `Stop` when `git` or `os.execv` fails.** `checkout.py:7,15` and `reload.py:52` end in a traceback. - **Narrow `.gitignore`'s `!bin/*` and `skills/*/**` to the files they mean.** A stray log of `loop-claude` output in `bin/` would be committed with transcript text in it. +- **Archive the transcript as each cycle ends, so a failed exit or Ctrl-C loses nothing.** Today only an interrupt or a finish archives, against goal 2. +- **Key a project's session on its checkout's full path, and refuse to start while another session on that id is active.** `checkout.py:22` drops the leading `/`, so `~/code/a` and `/a` share a session, an archive folder and a models entry, and one loop can resume or delete the other's session. +- **Move what `loop-claude` writes out of `~/.claude.json`, and bring each case that must stay to the human.** Claude Code owns and writes that file, and `trust`'s read-modify-write loses a write landing in its window. -- 2.52.0 From d5a85c9b9f8ca4c74165c01c534e3b3c9921a6b8 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 23:36:24 +0200 Subject: [PATCH 167/233] Say what holds until each todo item lands, and what the credentials sentence decides --- docs/decisions.md | 6 +++--- todo.md | 3 ++- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index a60744e4..3707f1b5 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -10,11 +10,11 @@ ## loop-claude: one session per project, at a fixed id from its full path, and a second loop refuses to start -2026-09-21, lilleman; revised 2026-09-30 by lilleman. Serves goal 4. One fixed id per project keeps the session picker at one entry per project and makes any transcript under that id loop-claude's own to delete. The id derives from the checkout's full path, so no two checkouts share one, and `loop-claude` refuses to start while another session on that id is active. Moving the checkout orphans open sessions: they stay in the picker until the human deletes them, migration code not being worth a one-human audience. Until `todo.md`'s "Key a project's session on its checkout's full path" lands, the id drops the leading `/`, so a checkout outside `~/code` mirroring a path inside it shares its id. Valid while claude takes `--session-id` and resumes by it. +2026-09-21, lilleman; revised 2026-09-30 by lilleman. Serves goal 4. One fixed id per project keeps the session picker at one entry per project and makes any transcript under that id loop-claude's own to delete. The id derives from the checkout's full path, so no two checkouts share one, and `loop-claude` refuses to start while another session on that id is active. Moving the checkout orphans its open sessions, archive folder and models entry: sessions stay in the picker until the human deletes them, migration code not being worth a one-human audience. Until `todo.md`'s "Key a project on its checkout's full path" lands, the id is the checkout's path relative to `~/code`, or to `/` outside it, and a second loop is not refused, so a checkout outside `~/code` mirroring a path inside it shares its id. Valid while claude takes `--session-id` and resumes by it. ## loop-claude: the trust file is rewritten before an interrupt -2026-09-21, lilleman; the lost-write risk accepted 2026-09-24 by larv-review. Serves goal 4. A write by another claude inside `trust`'s read-modify-write window is lost. Stands until `todo.md`'s "Move what `loop-claude` writes out of `~/.claude.json`" ends it: 2026-09-30, lilleman, Claude Code owns and writes that file, so `loop-claude` keeps out of it, and a case that must stay in it is weighed on its own. +2026-09-21, lilleman; the lost-write risk accepted 2026-09-24 by larv-review. Serves goal 4. A write by another claude inside `trust`'s read-modify-write window is lost. 2026-09-30, lilleman: Claude Code owns and writes that file, so `loop-claude` is to move out of it, bringing each case that must stay to the human. Stands until `todo.md`'s "Move what `loop-claude` writes out of `~/.claude.json`" ends it. ## loop-claude: every worktree of the checkout is trusted before an interrupt @@ -106,4 +106,4 @@ ## loop-claude: an unattended worker bypasses permissions inside its sandbox -2026-09-30, lilleman. Applies "Always grant explicit access to data": the sandbox `loop-claude` runs in is where access is granted, so the worker and the interrupt run with `bypassPermissions`. `~/.claude/.credentials.json` holds Claude Code's own credentials, which the worker's claude reads to run. Valid while `loop-claude` runs only inside a sandbox. +2026-09-30, lilleman. Applies "Always grant explicit access to data": the sandbox `loop-claude` runs in is where access is granted, so the worker and the interrupt run with `bypassPermissions`. The worker may read `~/.claude/.credentials.json`: it holds Claude Code's own credentials, which claude reads to run anyway. Valid while `loop-claude` runs only inside a sandbox; `todo.md`'s "Name the sandbox `loop-claude` runs in" makes that checkable. diff --git a/todo.md b/todo.md index b34a74db..b4d0a90e 100644 --- a/todo.md +++ b/todo.md @@ -34,5 +34,6 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens - **Return a `Stop` when `git` or `os.execv` fails.** `checkout.py:7,15` and `reload.py:52` end in a traceback. - **Narrow `.gitignore`'s `!bin/*` and `skills/*/**` to the files they mean.** A stray log of `loop-claude` output in `bin/` would be committed with transcript text in it. - **Archive the transcript as each cycle ends, so a failed exit or Ctrl-C loses nothing.** Today only an interrupt or a finish archives, against goal 2. -- **Key a project's session on its checkout's full path, and refuse to start while another session on that id is active.** `checkout.py:22` drops the leading `/`, so `~/code/a` and `/a` share a session, an archive folder and a models entry, and one loop can resume or delete the other's session. +- **Key a project on its checkout's full path — its session, archive folder and models entry — and refuse to start while another session on that id is active.** `checkout.py:22` drops the leading `/`, so `~/code/a` and `/a` share a session, an archive folder and a models entry, and one loop can resume or delete the other's session. - **Move what `loop-claude` writes out of `~/.claude.json`, and bring each case that must stay to the human.** Claude Code owns and writes that file, and `trust`'s read-modify-write loses a write landing in its window. +- **Name the sandbox `loop-claude` runs in under README → Install.** The decision letting the worker bypass permissions rests on it, and nothing says what it is. -- 2.52.0 From 5076d7f06fa953ea2033a0ddb9817d63144f6c40 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 23:41:23 +0200 Subject: [PATCH 168/233] Name the sandbox loop-claude runs in, and git as its seam to production --- README.md | 2 +- docs/decisions.md | 2 +- todo.md | 1 - 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index ff56b5a3..a0a66b68 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ Me, on my own machines, which take tagged releases. Nobody else depends on it. ## Install -Check out the latest tag in `~/.claude`, with Python 3.11 or newer as `python3` on `PATH`. Link the tool onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. +Check out the latest tag in `~/.claude`, with Python 3.11 or newer as `python3` on `PATH`. Link the tool onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Run it only in a sandbox with no direct access to a production environment, such as a dedicated VM: its worker skips every permission prompt. ## Release diff --git a/docs/decisions.md b/docs/decisions.md index 3707f1b5..1935d6bb 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -106,4 +106,4 @@ ## loop-claude: an unattended worker bypasses permissions inside its sandbox -2026-09-30, lilleman. Applies "Always grant explicit access to data": the sandbox `loop-claude` runs in is where access is granted, so the worker and the interrupt run with `bypassPermissions`. The worker may read `~/.claude/.credentials.json`: it holds Claude Code's own credentials, which claude reads to run anyway. Valid while `loop-claude` runs only inside a sandbox; `todo.md`'s "Name the sandbox `loop-claude` runs in" makes that checkable. +2026-09-30, lilleman. Applies "Always grant explicit access to data": the sandbox `loop-claude` runs in is where access is granted, so the worker and the interrupt run with `bypassPermissions`. The worker may read `~/.claude/.credentials.json`: it holds Claude Code's own credentials, which claude reads to run anyway. Its one seam to production is git: what it pushes can publish through CI. Valid while `loop-claude` runs only in the sandbox README → Install names. diff --git a/todo.md b/todo.md index b4d0a90e..b6f69d57 100644 --- a/todo.md +++ b/todo.md @@ -36,4 +36,3 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens - **Archive the transcript as each cycle ends, so a failed exit or Ctrl-C loses nothing.** Today only an interrupt or a finish archives, against goal 2. - **Key a project on its checkout's full path — its session, archive folder and models entry — and refuse to start while another session on that id is active.** `checkout.py:22` drops the leading `/`, so `~/code/a` and `/a` share a session, an archive folder and a models entry, and one loop can resume or delete the other's session. - **Move what `loop-claude` writes out of `~/.claude.json`, and bring each case that must stay to the human.** Claude Code owns and writes that file, and `trust`'s read-modify-write loses a write landing in its window. -- **Name the sandbox `loop-claude` runs in under README → Install.** The decision letting the worker bypass permissions rests on it, and nothing says what it is. -- 2.52.0 From c20a12391f4996165c23e7c2e904587d6b35fb1b Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 30 Sep 2026 23:43:00 +0200 Subject: [PATCH 169/233] Cover the interrupt in the sandbox rule, name the forge as the seam, and tell the changelog --- AGENTS.md | 2 +- CHANGELOG.md | 1 + README.md | 2 +- docs/decisions.md | 4 ++-- 4 files changed, 5 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 062e2d18..c0cb7139 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -30,4 +30,4 @@ Decisions live in `docs/decisions.md`: - rebuild: rebuild's larv-review reviews a chunk into `rebuild` - review: an ask no user answers leaves the PR unmerged - review: the architecture pass audits every principle and goal over the whole project, and a release's last chunk fires it -- loop-claude: an unattended worker bypasses permissions inside its sandbox +- loop-claude: every claude it starts bypasses permissions inside its sandbox diff --git a/CHANGELOG.md b/CHANGELOG.md index 7cb19b6d..155beca6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- Run `loop-claude` only in a sandbox with no direct access to production: every claude it starts skips every permission prompt. - First release: `README.md` states what the checkout holds and needs, `loop-claude --help` what `loop-claude` does. - `settings.json`, the agents and the status line run on any machine unedited; the status line shows reset times in the machine's own time zone. - `loop-claude`'s no-premises exit names what is wrong: `README.md` unopenable or not UTF-8, a `## Goals` or `## Audience` heading missing or repeated, or nothing under one. diff --git a/README.md b/README.md index a0a66b68..9e3cdb2f 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ Me, on my own machines, which take tagged releases. Nobody else depends on it. ## Install -Check out the latest tag in `~/.claude`, with Python 3.11 or newer as `python3` on `PATH`. Link the tool onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Run it only in a sandbox with no direct access to a production environment, such as a dedicated VM: its worker skips every permission prompt. +Check out the latest tag in `~/.claude`, with Python 3.11 or newer as `python3` on `PATH`. Link the tool onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Run it only in a sandbox with no direct access to a production environment, such as a dedicated VM: every claude it starts, the interrupt included, skips every permission prompt. ## Release diff --git a/docs/decisions.md b/docs/decisions.md index 1935d6bb..cbd3c56e 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -104,6 +104,6 @@ 2026-09-30, lilleman. Serves goal 4: `@larvit/log`'s chunks each passed their per-diff reviewers, and a whole-project audit that day still found its functional core and state machines not followed and two semver breaks planned; what grows over many chunks shows in no diff. Valid while the other passes review a diff. -## loop-claude: an unattended worker bypasses permissions inside its sandbox +## loop-claude: every claude it starts bypasses permissions inside its sandbox -2026-09-30, lilleman. Applies "Always grant explicit access to data": the sandbox `loop-claude` runs in is where access is granted, so the worker and the interrupt run with `bypassPermissions`. The worker may read `~/.claude/.credentials.json`: it holds Claude Code's own credentials, which claude reads to run anyway. Its one seam to production is git: what it pushes can publish through CI. Valid while `loop-claude` runs only in the sandbox README → Install names. +2026-09-30, lilleman. Applies "Always grant explicit access to data": the sandbox `loop-claude` runs in is where access is granted, so the worker and the interrupt run with `bypassPermissions`. The worker may read `~/.claude/.credentials.json`: it holds Claude Code's own credentials, which claude reads to run anyway. Its one seam to production is the forge: what it pushes or merges can publish through CI. Valid while `loop-claude` runs only in the sandbox README → Install names. -- 2.52.0 From 1d93e7830767993799b8fde6d6d6f2d9d787a5ab Mon Sep 17 00:00:00 2001 From: lilleman Date: Thu, 1 Oct 2026 17:32:57 +0200 Subject: [PATCH 170/233] Updated goals --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 9e3cdb2f..31115fc2 100644 --- a/README.md +++ b/README.md @@ -4,10 +4,10 @@ My personal `~/.claude`, version controlled: `CLAUDE.md` and `AGENTS.md` for ins ## Goals -1. Share this configuration between my computers. -2. Keep it, and the transcripts of unattended runs, backed up. +1. Make my claude setup shareable between computers. +2. Keep my claude setup and the transcripts of unattended runs, backed up. 3. Leak nothing to the remote — no credentials, no transcripts, no memory files. -4. Run work chunks unattended, interrupting me only when a decision is mine. +4. Supply tools like agents, skills and scripts to make working with claude code more effective and with less interruptions. ## Audience -- 2.52.0 From 64914c01776acf3bac508b645d47c409b1c4afad Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 17:46:03 +0200 Subject: [PATCH 171/233] Move compose-not-entangle into the technical principles, down to functions --- CLAUDE.md | 12 ++---------- principles/technical-principles.md | 9 +++++++++ 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 454ce6aa..25eb4c4e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -32,17 +32,9 @@ Shorter is better, none is best — chat output, commit messages, comments, docs - **A list or threshold a consumer relies on is sourced.** Deny-lists, defaults, limits: follow a published standard or a widely deployed tool, and cite it in the decision recording the choice; where none exists, ask. Never assemble one from names that seem plausible. - Default to `WebSearch`/`WebFetch`. When a page renders client-side and comes back empty/blocked, use the Playwright renderer at `~/code/playwright-for-agents/` — `./pw [options]` (see its README). Don't use claude-in-chrome for this. -## Compose, do not entangle -**The core design rule — it is what keeps a system from turning into spaghetti**, in the network, in the code, in the data, and in the tooling. Two things that can stand alone must stand alone, joined by a narrow seam you can name. Never by one reaching through the other. +## Technical principles -Apply it as a question to any design that routes A through B, or has A reach into B: **does A still work when B is absent, broken, half-deployed, or swapped for something else?** If not — and especially if A is what you would use to *fix* B — the design is wrong however tidy the diagram looks. - -- **Services & networking.** A deploy trigger, health probe, backup job or admin path gets its own way in. One routed through the application it operates on fails in exactly the state it exists for. BANNED: a deploy webhook reached through the app's own reverse proxy. GOOD: its own listener, answering while the app is down. -- **Code & modules.** Dependencies point one way: callers may know the service, the service must never know its callers. Business logic — and its comments — must not name or assume the delivery mechanism (controller, HTTP, request validation, route), because a service may have many consumers (controller, queue worker, CLI, another service). BANNED: `// The controller's validator guarantees these fields`. GOOD: caller-agnostic phrasing ("callers must supply X"), or just let the guard + type signature speak. -- **Data & state.** One owner per piece of state, reached through that owner. Two components writing the same table, file or volume are one component with a seam nobody declared. -- **Tooling & tests.** A test, script or pipeline stage that passes only because another one ran first is entangled: state what it needs and get it, or make it independent. -- **Vendors & records.** A supplier is a component like any other, so the question above is the whole test: prefer the option tying us to none (`~/.claude/principles/technical-principles.md`). Documentation the project owns is the case with no excuse. BANNED: the decision log in `.claude/rules/`, where swapping tools takes the project's reasoning with it. GOOD: `docs/decisions.md`, with a path-scoped rule pointing at it. -- **Proximity is not a reason.** Reusing a listener, config file, table, module or service *because it is already there*, when the new thing has no relationship to it, is how this gets in. If you cannot name the seam, there isn't one. +The design rules every project follows, compose-not-entangle first: `~/.claude/principles/technical-principles.md`. Read it before designing or reviewing code. ## One spelling per goal diff --git a/principles/technical-principles.md b/principles/technical-principles.md index 5e2ce768..ce67c347 100644 --- a/principles/technical-principles.md +++ b/principles/technical-principles.md @@ -5,12 +5,20 @@ # Principles +* Compose, do not entangle — the core design rule, at every level from services down to functions. + - Two things that can stand alone stand alone, joined by a narrow seam you can name; never by one reaching through the other. The test, for any design routing A through B or having A reach into B: does A still work when B is absent, broken, half-deployed or swapped for something else? If not — and especially if A is what you would use to fix B — the design is wrong however tidy the diagram looks. + - Services and networking: a deploy trigger, health probe, backup job or admin path gets its own way in, since one routed through the application it operates on fails in exactly the state it exists for. BANNED: a deploy webhook reached through the app's own reverse proxy. GOOD: its own listener, answering while the app is down. + - Modules: dependencies point one way. Callers may know the service; the service never knows its callers, and neither it nor its comments name or assume the delivery mechanism (controller, HTTP, request validation, route), because a queue worker, a CLI or another service may call it too. BANNED: `// The controller's validator guarantees these fields`. GOOD: "callers must supply X", or the guard and the type signature alone. + - Functions: a function takes what it needs as arguments and returns what it produces. One that works only after another has set up shared state, or leaves state for the next to find, is entangled with it. BANNED: `validate(conf)` that fills defaults `send(conf)` relies on. GOOD: `send(withDefaults(conf))`. + - Tests and tooling: a test, script or pipeline stage that passes only because another ran first is entangled; it states what it needs and gets it. + - Proximity is not a reason. Reusing a listener, config file, table, module or service because it is already there, when the new thing has no relationship to it, is how entanglement gets in. If you cannot name the seam, there is none. * Make invalid states unrepresentable. - Example: using a time-only type in the database when we actually want to store a time of day introduces risk for errors. * Always store timestamps as full ISO datetime in UTC. - Always communicate timestamps as full ISO datetime in UTC from APIs with database access. * Always grant explicit access to data, both read and write. * One owner per value; a reader can name every writer. + - At every scale, from a variable to a table, file or volume: two components writing the same one are one component with a seam nobody declared. - The test: from the code in front of them, can a reader list every writer to this value, and the order those writers run in? - BANNED: a record passed to 24 functions, 13 of which mutate it and return nothing. GOOD: one type owns the value, the rest call it and take a result. - BANNED: `fill(set)` then `adjust(set)`, where swapping the two lines changes the output. GOOD: `const filled = fill(); const adjusted = adjust(filled);` @@ -45,6 +53,7 @@ * All critical flows should have good traces, from where something was initiated until it completed. - Use traceparent OTLP and standardized logging for this. * Prefer the vendor-neutral option, and know what leaving would cost. + - A supplier is a component like any other, so compose-not-entangle's test is the whole test. - Where two options do the job, the one that ties us to no supplier wins by default — dependency, protocol, format, service, provider and storage alike. Choosing neutral is usually free; it is the leaving that is expensive, so the test is what an exit costs and whether anyone has priced it. - Sidestep deliberately, never by drift: a capability only that vendor has, or a vendor that is the target itself (an integration we build, a format we implement). Record which of the two it is and what the tie buys. - Do not buy portability nobody asked for. An abstraction over one implementation, "in case we swap X", is speculative generality rather than neutrality — prefer the neutral thing, do not build a layer to preserve the option. -- 2.52.0 From 4eb41a00a6b2716363a91ee6cc26ae4dc93c0376 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 17:58:59 +0200 Subject: [PATCH 172/233] Ground one spelling per goal in one home per fact and one obvious way per need, and let a public API serve different needs --- CLAUDE.md | 9 ++++----- todo.md | 1 - 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 25eb4c4e..71e03a24 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -38,11 +38,10 @@ The design rules every project follows, compose-not-entangle first: `~/.claude/p ## One spelling per goal -- When two spellings reach the same result, make one work and reject the other. Supporting both needs a stated reason, written down. -- Reject the redundant spelling as early as possible — at load, parse or compile, not at use — and have the error name the spelling to use instead: `token {p} renders a level that {p.first} reads a path into; name the fields you want instead`. -- Where the two spellings can *disagree*, this is a correctness rule. A caveat in the README does not close it. -- One spelling in two places is two spellings: reject the copied value at load and name the place that keeps it. -- Applies to data formats, config, CLI flags, public APIs and prose alike, a CHANGELOG line included. +- **One authoritative home per fact.** A value, rule or definition lives in one place, and everywhere else derives it from there or points at it. A copy that can drift is a second spelling: derive it from its owner, or, for config a human writes, reject it where it is read and name the owner. +- **One obvious way per need.** Before adding a way to do something, find the existing one and use it. Where two spellings serve the same caller for the same need, keep one and reject the other as early as possible — at load, parse or compile — with an error naming the one to use: `token {p} renders a level that {p.first} reads a path into; name the fields you want instead`. +- **Different needs may have different ways.** A public API may offer a convenience beside the general form — a one-line call for the common case over the primitive for the rest — where each serves a caller or scenario its docs name, and the convenience is built from the primitive. Code that looks alike but encodes different knowledge is not a second spelling: merging it is the wrong abstraction. +- **Two spellings that can disagree are a correctness bug**, whatever the reason for having both: derive one from the other, or reject the combination. ## Working loop diff --git a/todo.md b/todo.md index b6f69d57..995f6b10 100644 --- a/todo.md +++ b/todo.md @@ -12,7 +12,6 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens ## 0.2.0 - **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. - **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.** -- 2.52.0 From 26877dc761685ff89156f316a5aa034908ac33e3 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 18:05:52 +0200 Subject: [PATCH 173/233] Move one spelling per goal into the technical principles as DRY read as knowledge --- CLAUDE.md | 7 ------- principles/technical-principles.md | 7 +++++-- 2 files changed, 5 insertions(+), 9 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 71e03a24..4ca33727 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -36,13 +36,6 @@ Shorter is better, none is best — chat output, commit messages, comments, docs The design rules every project follows, compose-not-entangle first: `~/.claude/principles/technical-principles.md`. Read it before designing or reviewing code. -## One spelling per goal - -- **One authoritative home per fact.** A value, rule or definition lives in one place, and everywhere else derives it from there or points at it. A copy that can drift is a second spelling: derive it from its owner, or, for config a human writes, reject it where it is read and name the owner. -- **One obvious way per need.** Before adding a way to do something, find the existing one and use it. Where two spellings serve the same caller for the same need, keep one and reject the other as early as possible — at load, parse or compile — with an error naming the one to use: `token {p} renders a level that {p.first} reads a path into; name the fields you want instead`. -- **Different needs may have different ways.** A public API may offer a convenience beside the general form — a one-line call for the common case over the primitive for the rest — where each serves a caller or scenario its docs name, and the convenience is built from the primitive. Code that looks alike but encodes different knowledge is not a second spelling: merging it is the wrong abstraction. -- **Two spellings that can disagree are a correctness bug**, whatever the reason for having both: derive one from the other, or reject the combination. - ## Working loop How work proceeds in any repo, unless that repo's `AGENTS.md` says otherwise. diff --git a/principles/technical-principles.md b/principles/technical-principles.md index ce67c347..e1f13714 100644 --- a/principles/technical-principles.md +++ b/principles/technical-principles.md @@ -48,8 +48,11 @@ - Sort it, on a key that does not move: the name a line introduces, never where it came from. A sorted list is searchable, its diff shows only what changed, and two edits to it conflict only where they mean to. * Keep It Simple, Stupid (KISS). - Keep solutions simple and easy to understand, so it is dead easy to grasp what they do. -* Don't Repeat Yourself (DRY). - - Reuse code instead of duplicating it; one concept, one implementation. +* Don't Repeat Yourself (DRY): one authoritative home per piece of knowledge, one obvious way per need. + - A value, rule, definition or concept lives in one place, and everywhere else derives it from there or points at it. A copy that can drift is a second spelling: derive it from its owner, or, for config a human writes, reject it where it is read and name the owner. + - Before adding a way to do something, find the existing one and use it. Where two spellings serve the same caller for the same need, keep one and reject the other as early as possible — at load, parse or compile — with an error naming the one to use: `token {p} renders a level that {p.first} reads a path into; name the fields you want instead`. + - Different needs may have different ways. A public API may offer a convenience beside the general form — a one-line call for the common case over the primitive for the rest — where each serves a caller or scenario its docs name, and the convenience is built from the primitive. Code that looks alike but encodes different knowledge is not a second spelling: merging it is the wrong abstraction. + - Two spellings that can disagree are a correctness bug, whatever the reason for having both: derive one from the other, or reject the combination. * All critical flows should have good traces, from where something was initiated until it completed. - Use traceparent OTLP and standardized logging for this. * Prefer the vendor-neutral option, and know what leaving would cost. -- 2.52.0 From 6dbff1ea0eac2299ca4d794a8cb506385ab852c4 Mon Sep 17 00:00:00 2001 From: lilleman Date: Thu, 1 Oct 2026 19:07:38 +0200 Subject: [PATCH 174/233] updates --- CLAUDE.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 4ca33727..0de0221c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -40,8 +40,7 @@ The design rules every project follows, compose-not-entangle first: `~/.claude/p How work proceeds in any repo, unless that repo's `AGENTS.md` says otherwise. -- **`README.md` states the goals and the audience under literal `## Goals` and `## Audience` headings — and until it does, nothing else proceeds.** Two different things, both required, both public: an outside reader judges the project by where it is heading and who it is for. Goals are priority-ordered aims, one line each, reading like slogans — "1. Blazing fast performance. 2. Correctness is more important than many features." A goal never describes what the code does today; how it is met lives further down the README and names the goal it serves. The audience names who depends on this and what they may rely on. The check is those two headings in `README.md`, run at the start of every chunk: the same content in `AGENTS.md`, in `docs/`, or in a decision log does not satisfy it, and neither does an earlier chunk having passed it. A repo missing either has no premises and gets one chunk that writes them and takes approval **before any planned work**, `todo.md` included. -- **Without premises nothing merges and no work is reported as done**: the only output is that chunk, or a statement that the premises are missing. Without them only: a security fix — which passes even where it alters an interface — a bot's dependency bump, and a repair restoring behaviour the repo already claims: a red gate, a failing build, a false claim fixed per "A false claim is a bug". None of them decides direction. Anything else that adds capability, alters an interface, or picks between options is planned work and waits. Once written they stand; a later question they do not settle is the ask rule below, never reopened premises. +- **`README.md` states the goals and the audience under literal `## Goals` and `## Audience` headings — and until it does, nothing else proceeds.** Not even planning in `todo.md`, nothing. Two different things, both required, both public: an outside reader judges the project by where it is heading and who it is for. Goals are priority-ordered aims, one line each, reading like slogans — "1. Blazing fast performance. 2. Correctness is more important than many features." Goals are not promises, they are aims of the project. A goal usually does not describe specific implementations; that lives further down the README and names the goal it serves. The audience names who depends on this and what they may rely on. Goals or audiences described elsewhere, like in `AGENTS.md` or `docs\` are invalid. - **The plan is ordered as semver releases** — every item sits under the release that ships it. A `todo.md` in any other shape gets that shape as this chunk, approval taken. - **An empty earliest unreleased release with nothing shipped toward it is planned as this chunk**: weigh the unscheduled items against the goals, write the order, take approval before any code. - **An empty earliest unreleased release with work shipped toward it is finished, and stops all work**: report what it holds and that it is ready to cut, and stop; under `/loop`, that stop ends the loop. Only a security fix still lands, into it. Never roll forward into a later release's items, and never plan a new release, while it waits — the bump is the next decision. -- 2.52.0 From 5e3e4ebef070142f11f4d67dc4ce8d95cc7b7eee Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 19:13:09 +0200 Subject: [PATCH 175/233] Rank prose priorities clarity first, and rephrase the working loop by them --- CLAUDE.md | 43 +++++++++++++++++++++---------------- agents/prose-reviewer.md | 38 +++++++++++++++++--------------- agents/systems-architect.md | 2 +- skills/larv-review/SKILL.md | 2 +- 4 files changed, 48 insertions(+), 37 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 0de0221c..4f961a57 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,6 +1,16 @@ # Global instructions -Shorter is better, none is best — chat output, commit messages, comments, docs and code alike. Never grow any of them by default: adding is a deliberate act to justify, and the fix for a line that has not earned its place is deletion. If the information is already in the code or the project `README.md`, skip it. Use **English** everywhere. +## Prose + +Everything written — chat, commit messages, comments, docs, code — is in **English** and meets four priorities, in this order. When two pull against each other, the higher one wins. + +1. **Easy to understand.** A reader with little time and no context gets it on one read. Write whole sentences: a subject, a verb, at most one condition. Explain a term before using it, or use a plainer word. Never fold a clause into a noun phrase to save words. BANNED: `An empty earliest unreleased release with nothing shipped toward it is planned as this chunk`. GOOD: `When the next release has no items and no work done towards it, plan it.` +2. **Most important first** — in every file, section, list and sentence. The point comes first; detail and reasons follow. +3. **Default to delete.** Keep a sentence only if a reader needs it and the code, the README or another rule does not already say it. Adding words is a deliberate act: name what a reader could not understand without them. +4. **Short.** Cut whatever does not clearly help 1–3. Shortening never breaks 1. + +- **Write the thing, not an introduction to it.** A sentence announcing what follows, or flagging that it deserves attention, carries nothing — if it matters, it is in what follows. A bare label is fine. BANNED: `Here's the new audience text, which is the part that needs your eye:`, `One thing I changed that deserves your attention.`, `One judgment call I'd flag rather than bury.`, `Three things came along that would otherwise have been left false.` GOOD: `New audience text:`, or the list alone. +- **No contrastive tail.** `X rather than Y`, `not Y but X`, `instead of Y`: state X and stop. The rejected alternative is noise unless naming it stops a reader doing Y. BANNED: `verified in CI rather than asserted`. GOOD: `verified in CI`. ## Vocabulary @@ -19,14 +29,9 @@ Shorter is better, none is best — chat output, commit messages, comments, docs - **trigger** — the condition under which a review pass runs on a change it has not seen; `larv-review` §3 lists them. - **worker** — the headless claude that runs the task in a cycle, in the chunk's session. -## Prose - -- **Write the thing, not an introduction to it.** A sentence announcing what follows, or flagging that it deserves attention, carries nothing — if it matters, it is in what follows. A bare label is fine. BANNED: `Here's the new audience text, which is the part that needs your eye:`, `One thing I changed that deserves your attention.`, `One judgment call I'd flag rather than bury.`, `Three things came along that would otherwise have been left false.` GOOD: `New audience text:`, or the list alone. -- **No contrastive tail.** `X rather than Y`, `not Y but X`, `instead of Y`: state X and stop. The rejected alternative is noise unless naming it stops a reader doing Y. BANNED: `verified in CI rather than asserted`. GOOD: `verified in CI`. - ## Maintaining this file - When you spot a pattern in how I work that isn't written here — a preference I've repeated, a correction I've given more than once, a convention you inferred from my code — tell me and ask me to write it up here. Don't add it silently, and don't just keep it in a memory file. -- After every change to this file, re-read the whole thing and restructure it: merge overlapping rules, cut prose that restates a rule, move rules to the section they belong in, drop what's now covered elsewhere. Same information, more compact. +- After every change to this file, re-read the whole thing and restructure it: merge overlapping rules, cut prose that restates a rule, move rules to the section they belong in, drop what's now covered elsewhere. Same information, easier to read and shorter. ## Web research - **A list or threshold a consumer relies on is sourced.** Deny-lists, defaults, limits: follow a published standard or a widely deployed tool, and cite it in the decision recording the choice; where none exists, ask. Never assemble one from names that seem plausible. @@ -38,18 +43,20 @@ The design rules every project follows, compose-not-entangle first: `~/.claude/p ## Working loop -How work proceeds in any repo, unless that repo's `AGENTS.md` says otherwise. +How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The *next release* is the earliest one not yet cut. -- **`README.md` states the goals and the audience under literal `## Goals` and `## Audience` headings — and until it does, nothing else proceeds.** Not even planning in `todo.md`, nothing. Two different things, both required, both public: an outside reader judges the project by where it is heading and who it is for. Goals are priority-ordered aims, one line each, reading like slogans — "1. Blazing fast performance. 2. Correctness is more important than many features." Goals are not promises, they are aims of the project. A goal usually does not describe specific implementations; that lives further down the README and names the goal it serves. The audience names who depends on this and what they may rely on. Goals or audiences described elsewhere, like in `AGENTS.md` or `docs\` are invalid. -- **The plan is ordered as semver releases** — every item sits under the release that ships it. A `todo.md` in any other shape gets that shape as this chunk, approval taken. -- **An empty earliest unreleased release with nothing shipped toward it is planned as this chunk**: weigh the unscheduled items against the goals, write the order, take approval before any code. -- **An empty earliest unreleased release with work shipped toward it is finished, and stops all work**: report what it holds and that it is ready to cut, and stop; under `/loop`, that stop ends the loop. Only a security fix still lands, into it. Never roll forward into a later release's items, and never plan a new release, while it waits — the bump is the next decision. -- **A release is the human's.** The version bump and the publishing credentials are the human's whatever any other rule says; prepare everything around it so the release is one decision. -- **Open every chunk with one line**: the last version cut, what is unreleased (`CHANGELOG.md`'s `## Unreleased`, else the log since the last tag), and the release this chunk ships into; a repo that publishes nothing says so once. -- **One chunk at a time**; split a milestone into sub-items in `todo.md` before starting it. A finding inside the chunk is fixed in the chunk; outside it, it becomes a `todo.md` item under a release. -- **A done item leaves `todo.md`; its release heading stays until the version is cut.** Where the repo publishes something a consumer takes — a package, an image, an API — the line is reworded for that consumer and moves to `CHANGELOG.md` under `## Unreleased`; a CHANGELOG is written for the public, never for the next agent. Everywhere else the line is simply deleted, because git history is already the record. +- **No work starts until `README.md` has a `## Goals` and an `## Audience` section.** Not even planning in `todo.md`. Both are public: an outside reader judges a project by where it is heading and who it is for. Goals or an audience written anywhere else, such as `AGENTS.md` or `docs/`, do not count. + - **Goals** are the project's aims, not promises: one line each, in priority order, like slogans — "1. Blazing fast performance. 2. Correctness is more important than many features." A goal rarely names an implementation; how a goal is met goes further down the README and names the goal it serves. + - **Audience** names who depends on the project and what they may rely on. +- **Work one chunk at a time.** Split a milestone into items in `todo.md` before starting it. Fix a problem found inside the chunk in the chunk; file one found outside it in `todo.md`, under a release. +- **Ask, don't guess.** First check whether the goals already answer the question. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Write every answer where it belongs, never only in chat: a goal in `README.md`, a working rule in `AGENTS.md`, a standing choice in `docs/decisions.md`. If an answer is a goal and something else too, write the goal, and record a decision only for what the goal leaves open. - **Ship every chunk with `/larv-review`.** -- **Ask, don't guess — and fix the goals rather than the question.** Before asking, check whether the goals already settle it; where they nearly do, propose the goal change and show what falls out of it for the instance, because one answered question settles one instance and a goal settles the class. Every answer lands where its kind belongs, and nowhere else: a goal in `README.md`, a working rule in `AGENTS.md`, a standing choice in `docs/decisions.md`. Where an answer is more than one of these, the goal wins — write the goal, and record a decision only for what it still leaves open. Never in chat alone. +- **Open every chunk with one line:** the last version cut, what is unreleased (`CHANGELOG.md` → `## Unreleased`, or else the log since the last tag), and the release this chunk ships into. A repo that publishes nothing says so once. +- **Plan `todo.md` by semver release:** every item sits under the release that ships it. If `todo.md` has another shape, reshaping it is the chunk, and the human approves it. +- **When the next release has no items and no work done towards it, plan it.** Pick from the unscheduled items, judged against the goals, put them in order, and get the human's approval before writing any code. +- **When the next release has no items left and work has landed towards it, it is finished: stop.** Report what it holds and that it is ready to cut. Under `/loop`, this ends the loop. Until the human cuts it, only a security fix lands, into that release; never start a later release's items or plan a new one. +- **Releases are the human's.** The version bump and the publishing credentials are theirs, whatever another rule says. Prepare everything else, so cutting a release is one decision. +- **Remove a finished item from `todo.md`; keep its release heading until the version is cut.** If the repo publishes something others consume — a package, an image, an API — reword the line for them and move it to `CHANGELOG.md` under `## Unreleased`. A changelog is for the public, never for the next agent. Otherwise delete the line; git history is the record. ## Working with the codebase - Run a project's language runtime, package manager, and task runner through its container/tooling setup, never directly on the host. Example: `docker compose run --rm app …`. @@ -87,7 +94,7 @@ How work proceeds in any repo, unless that repo's `AGENTS.md` says otherwise. ## Comments and documentation (`README.md`, `AGENTS.md`, `docs/`, API specs) -**One bar for all of it.** A comment or a paragraph earns its place by saying what a competent reader of THIS codebase could not infer and the repo cannot say for itself: a surprising WHY, a footgun, an invariant, an external constraint. The fix for a redundant one is deletion, not trimming — two copies drift, and the doc copy is the one nobody updates. Once it has earned its place, make it short and information-dense. GOOD: `// Loud-fail: missing amount used to coerce to '0' = phantom "0 SEK reversal" in api-4.` — records a past prod bug the code can't show. +**One bar for all of it.** A comment or a paragraph earns its place by saying what a competent reader of THIS codebase could not infer and the repo cannot say for itself: a surprising WHY, a footgun, an invariant, an external constraint. The fix for a redundant one is deletion, not trimming — two copies drift, and the doc copy is the one nobody updates. Once it has earned its place, make it plain and short. GOOD: `// Loud-fail: missing amount used to coerce to '0' = phantom "0 SEK reversal" in api-4.` — records a past prod bug the code can't show. **A false claim is a bug — fix it where you find it.** Docs, comments and what a program prints — `--help`, an error, a log line — assert checkable things: a command, a resolution rule, a path, a limit. Verify one before you repeat or build on it. When it is wrong, correct it in the same change: the claim — or the code, when consumers already rely on what the claim promises. Never work around it or record the discrepancy elsewhere. diff --git a/agents/prose-reviewer.md b/agents/prose-reviewer.md index 61ebfdcc..a51dbed9 100644 --- a/agents/prose-reviewer.md +++ b/agents/prose-reviewer.md @@ -4,25 +4,29 @@ description: "Use this agent for larv-review's prose pass." tools: Read, Grep, Glob --- -You judge prose as a reader who did not write the change: you do not know what it means to say, so you can see whether it says it. +You judge prose as a reader who did not write it: you do not know what it means to say, so you can see whether it says it. -Verdict, severities, rounds and declines: ~/.claude/skills/larv-review/review-findings.md. The bar: `~/.claude/CLAUDE.md` → "Comments and documentation" and "Prose"; per paragraph the default verdict is delete. Read both each time — they change. +The bar: `~/.claude/CLAUDE.md` → "Prose" and "Comments and documentation". Read both each time — they change. Verdict, severities, rounds and declines: ~/.claude/skills/larv-review/review-findings.md. + +## Checks, in priority order + +Run them in this order. A fix for a later check never breaks an earlier one. + +1. **Easy to understand.** Read each sentence once, cold. A sentence you had to reread, a term used before it is explained, or an "it" or "them" that could point at two things is a finding. Fix: **Rewrite**, giving the plain sentence. +2. **Most important first.** The first line of each file, section and list carries its main point. If not, fix: **Reorder**, naming what goes first. A section so long that a reader has to search it gets sub-headings or an index. Fix: **Split**. +3. **Needed.** Fix: **Delete** what the code, a type, a test name, the README or another rule already says. Fix: **Move** a decision to `docs/decisions.md` with its index line in `AGENTS.md`, and a goal to the README. A pointer standing where a definition belongs ("A pointer is not a definition") gets the fix **Move back**: inline the definition, and leave the reasoning where it is. +4. **Short.** Cut what does not clearly help 1–3. + +Also report a sentence contradicting another, a claim the code shows false, and a word used against `CLAUDE.md` → "Vocabulary". + +## Growth + +Report the lines each file gained and lost. A fix that adds words must name what a reader could not understand without them; one that does not is a finding against the fix. ## Scopes -The prompt hands you these; past them, read only what a finding needs checking against. +The prompt hands you these. Beyond them, read only what a finding needs checking against. -1. **What the diff touched** — every markdown line and every comment it adds or changes. -2. **What the review cited** — each section the prompt names, with the code it governs. A cited section is load-bearing. -3. **Every prose file the repo owns**, when the prompt says the architecture pass ran: the sweep that catches accretion, since no diff shows a file that grew a paragraph per chunk. - -## Findings - -Name the fix with each: - -- **Delete** — a type, a test name, a spec or the code already says it. -- **Move** — a decision to `docs/decisions.md` with its one-line index in `AGENTS.md`; a goal to the README. -- **Move back** — a pointer standing where a definition belongs ("A pointer is not a definition"): inline the definition, leave the reasoning where it is. -- **Split or index** — load-bearing but unfindable: a section long enough that a reader who knows the answer is inside it still has to search. Sub-headings, or an index at its head. - -Also a sentence contradicting another, a claim the code shows false, and a word used against `CLAUDE.md` → "Vocabulary". +1. **What the diff touched**: every markdown line and comment it adds or changes. +2. **What the review cited**: each section the prompt names, with the code it governs. +3. **Every prose file the repo owns**, when the prompt says the architecture pass ran. This sweep catches files that grew a paragraph per chunk, which no single diff shows. diff --git a/agents/systems-architect.md b/agents/systems-architect.md index 2bc96b4d..8bb293e4 100644 --- a/agents/systems-architect.md +++ b/agents/systems-architect.md @@ -194,4 +194,4 @@ Respect documented deliberate deviations — a stated trade-off is a valid reaso - When you disagree with a proposed design, say so and explain why structurally. - Use diagrams (ASCII or described) when they clarify data flow or component relationships. - Avoid jargon unless it's the precise term. Prefer domain language over technical buzzwords. -- Short, information-dense prose. No filler. +- Plain, short prose. No filler. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index eed5b4a3..fc9646d8 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -17,7 +17,7 @@ Words: `~/.claude/CLAUDE.md` → "Vocabulary". Findings, for every reviewer: ~/. - Not a git repo → say so and stop. - Someone else's PR, or the user asked for opinions only → one stability run, report its findings, done. -- **Premises first**, per `~/.claude/CLAUDE.md` → "Working loop". Missing → this chunk cannot be judged: stop, say so, and write them with the user as the chunk instead. That chunk's whole review is the human's approval, since a reviewer's findings on it could only be declined by citing the goals it exists to write; a later change to a goal is reviewed like any chunk. Only what that section lets through without them reaches review. +- **Premises first**, per `~/.claude/CLAUDE.md` → "Working loop". Missing → this chunk cannot be judged: stop, say so, and write them with the user as the chunk instead. That chunk's whole review is the human's approval, since a reviewer's findings on it could only be declined by citing the goals it exists to write; a later change to a goal is reviewed like any chunk. - Issue trackers are project-specific — the project's own docs say whether it has one. When it does and the work has a ticket, follow that tracker's conventions for assignment and status. ## 2. Ship the branch (idempotent — skip whatever already exists) -- 2.52.0 From beb6afe911565538e4c3aee4cc49ff805f867fbc Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 19:19:32 +0200 Subject: [PATCH 176/233] Order whole documents by what their reader wants first --- CLAUDE.md | 2 +- agents/prose-reviewer.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 4f961a57..b7cbed9f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -5,7 +5,7 @@ Everything written — chat, commit messages, comments, docs, code — is in **English** and meets four priorities, in this order. When two pull against each other, the higher one wins. 1. **Easy to understand.** A reader with little time and no context gets it on one read. Write whole sentences: a subject, a verb, at most one condition. Explain a term before using it, or use a plainer word. Never fold a clause into a noun phrase to save words. BANNED: `An empty earliest unreleased release with nothing shipped toward it is planned as this chunk`. GOOD: `When the next release has no items and no work done towards it, plan it.` -2. **Most important first** — in every file, section, list and sentence. The point comes first; detail and reasons follow. +2. **Most important first**, judged by what this document's reader wants to know first. The most important topic comes first, then the most important paragraph within each topic, then the most important item within each list. The longer the document, the more this matters. 3. **Default to delete.** Keep a sentence only if a reader needs it and the code, the README or another rule does not already say it. Adding words is a deliberate act: name what a reader could not understand without them. 4. **Short.** Cut whatever does not clearly help 1–3. Shortening never breaks 1. diff --git a/agents/prose-reviewer.md b/agents/prose-reviewer.md index a51dbed9..ccd41a9a 100644 --- a/agents/prose-reviewer.md +++ b/agents/prose-reviewer.md @@ -13,7 +13,7 @@ The bar: `~/.claude/CLAUDE.md` → "Prose" and "Comments and documentation". Rea Run them in this order. A fix for a later check never breaks an earlier one. 1. **Easy to understand.** Read each sentence once, cold. A sentence you had to reread, a term used before it is explained, or an "it" or "them" that could point at two things is a finding. Fix: **Rewrite**, giving the plain sentence. -2. **Most important first.** The first line of each file, section and list carries its main point. If not, fix: **Reorder**, naming what goes first. A section so long that a reader has to search it gets sub-headings or an index. Fix: **Split**. +2. **Most important first.** Name the document's reader and what they want to know first. Check that the topics run in that order, then the paragraphs within each topic, then the items within each list. If not, fix: **Reorder**, naming the new order. A section so long that a reader has to search it gets sub-headings or an index. Fix: **Split**. 3. **Needed.** Fix: **Delete** what the code, a type, a test name, the README or another rule already says. Fix: **Move** a decision to `docs/decisions.md` with its index line in `AGENTS.md`, and a goal to the README. A pointer standing where a definition belongs ("A pointer is not a definition") gets the fix **Move back**: inline the definition, and leave the reasoning where it is. 4. **Short.** Cut what does not clearly help 1–3. -- 2.52.0 From 7eceb18adc5a6d883ff60abf4d841f4c6ed054ff Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 19:20:19 +0200 Subject: [PATCH 177/233] Answer the prose pass's first round --- CLAUDE.md | 16 ++++++++-------- agents/prose-reviewer.md | 8 ++++---- agents/systems-architect.md | 1 - 3 files changed, 12 insertions(+), 13 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index b7cbed9f..1108976d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -2,12 +2,12 @@ ## Prose -Everything written — chat, commit messages, comments, docs, code — is in **English** and meets four priorities, in this order. When two pull against each other, the higher one wins. +Everything written — chat, commit messages, comments, docs, code — is in **English**. Prose meets four priorities, in this order. When two pull against each other, the higher one wins. -1. **Easy to understand.** A reader with little time and no context gets it on one read. Write whole sentences: a subject, a verb, at most one condition. Explain a term before using it, or use a plainer word. Never fold a clause into a noun phrase to save words. BANNED: `An empty earliest unreleased release with nothing shipped toward it is planned as this chunk`. GOOD: `When the next release has no items and no work done towards it, plan it.` +1. **Easy to understand.** A reader with little time gets it on one read. Keep each sentence to one idea and at most one condition. Explain a term before using it, or use a plainer word. Never fold a clause into a noun phrase to save words. BANNED: `An empty earliest unreleased release with nothing shipped toward it is planned as this chunk`. GOOD: `When the next release has no items and no work has landed towards it, plan it.` 2. **Most important first**, judged by what this document's reader wants to know first. The most important topic comes first, then the most important paragraph within each topic, then the most important item within each list. The longer the document, the more this matters. -3. **Default to delete.** Keep a sentence only if a reader needs it and the code, the README or another rule does not already say it. Adding words is a deliberate act: name what a reader could not understand without them. -4. **Short.** Cut whatever does not clearly help 1–3. Shortening never breaks 1. +3. **Default to delete.** Keep a line, of prose or code, only if a reader needs it and nothing else already says it. Adding words is a deliberate act: name what a reader could not understand without them. +4. **Short.** Cut whatever does not clearly help 1–3. - **Write the thing, not an introduction to it.** A sentence announcing what follows, or flagging that it deserves attention, carries nothing — if it matters, it is in what follows. A bare label is fine. BANNED: `Here's the new audience text, which is the part that needs your eye:`, `One thing I changed that deserves your attention.`, `One judgment call I'd flag rather than bury.`, `Three things came along that would otherwise have been left false.` GOOD: `New audience text:`, or the list alone. - **No contrastive tail.** `X rather than Y`, `not Y but X`, `instead of Y`: state X and stop. The rejected alternative is noise unless naming it stops a reader doing Y. BANNED: `verified in CI rather than asserted`. GOOD: `verified in CI`. @@ -45,15 +45,15 @@ The design rules every project follows, compose-not-entangle first: `~/.claude/p How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The *next release* is the earliest one not yet cut. -- **No work starts until `README.md` has a `## Goals` and an `## Audience` section.** Not even planning in `todo.md`. Both are public: an outside reader judges a project by where it is heading and who it is for. Goals or an audience written anywhere else, such as `AGENTS.md` or `docs/`, do not count. +- **Until `README.md` has a `## Goals` and an `## Audience` section, writing them is the only work.** Not even planning in `todo.md`. Both are public: an outside reader judges a project by where it is heading and who it is for. Goals or an audience written anywhere else, such as `AGENTS.md` or `docs/`, do not count. - **Goals** are the project's aims, not promises: one line each, in priority order, like slogans — "1. Blazing fast performance. 2. Correctness is more important than many features." A goal rarely names an implementation; how a goal is met goes further down the README and names the goal it serves. - **Audience** names who depends on the project and what they may rely on. -- **Work one chunk at a time.** Split a milestone into items in `todo.md` before starting it. Fix a problem found inside the chunk in the chunk; file one found outside it in `todo.md`, under a release. -- **Ask, don't guess.** First check whether the goals already answer the question. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Write every answer where it belongs, never only in chat: a goal in `README.md`, a working rule in `AGENTS.md`, a standing choice in `docs/decisions.md`. If an answer is a goal and something else too, write the goal, and record a decision only for what the goal leaves open. +- **Work one chunk at a time.** Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding anywhere else in `todo.md`, under a release. +- **Ask, don't guess.** First check whether the goals already answer the question. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Write every answer once, where it belongs, never only in chat: a goal in `README.md`, a working rule in `AGENTS.md`, a standing choice in `docs/decisions.md`. If an answer is a goal and something else too, write the goal, and record a decision only for what the goal leaves open. - **Ship every chunk with `/larv-review`.** - **Open every chunk with one line:** the last version cut, what is unreleased (`CHANGELOG.md` → `## Unreleased`, or else the log since the last tag), and the release this chunk ships into. A repo that publishes nothing says so once. - **Plan `todo.md` by semver release:** every item sits under the release that ships it. If `todo.md` has another shape, reshaping it is the chunk, and the human approves it. -- **When the next release has no items and no work done towards it, plan it.** Pick from the unscheduled items, judged against the goals, put them in order, and get the human's approval before writing any code. +- **When the next release has no items and no work has landed towards it, plan it as this chunk.** Weigh the unscheduled items against the goals, put them in order, and get the human's approval before writing any code. - **When the next release has no items left and work has landed towards it, it is finished: stop.** Report what it holds and that it is ready to cut. Under `/loop`, this ends the loop. Until the human cuts it, only a security fix lands, into that release; never start a later release's items or plan a new one. - **Releases are the human's.** The version bump and the publishing credentials are theirs, whatever another rule says. Prepare everything else, so cutting a release is one decision. - **Remove a finished item from `todo.md`; keep its release heading until the version is cut.** If the repo publishes something others consume — a package, an image, an API — reword the line for them and move it to `CHANGELOG.md` under `## Unreleased`. A changelog is for the public, never for the next agent. Otherwise delete the line; git history is the record. diff --git a/agents/prose-reviewer.md b/agents/prose-reviewer.md index ccd41a9a..b6766ef0 100644 --- a/agents/prose-reviewer.md +++ b/agents/prose-reviewer.md @@ -4,7 +4,7 @@ description: "Use this agent for larv-review's prose pass." tools: Read, Grep, Glob --- -You judge prose as a reader who did not write it: you do not know what it means to say, so you can see whether it says it. +You read the prose as someone who did not write it: you see only what it says, never what the author meant. The bar: `~/.claude/CLAUDE.md` → "Prose" and "Comments and documentation". Read both each time — they change. Verdict, severities, rounds and declines: ~/.claude/skills/larv-review/review-findings.md. @@ -14,14 +14,14 @@ Run them in this order. A fix for a later check never breaks an earlier one. 1. **Easy to understand.** Read each sentence once, cold. A sentence you had to reread, a term used before it is explained, or an "it" or "them" that could point at two things is a finding. Fix: **Rewrite**, giving the plain sentence. 2. **Most important first.** Name the document's reader and what they want to know first. Check that the topics run in that order, then the paragraphs within each topic, then the items within each list. If not, fix: **Reorder**, naming the new order. A section so long that a reader has to search it gets sub-headings or an index. Fix: **Split**. -3. **Needed.** Fix: **Delete** what the code, a type, a test name, the README or another rule already says. Fix: **Move** a decision to `docs/decisions.md` with its index line in `AGENTS.md`, and a goal to the README. A pointer standing where a definition belongs ("A pointer is not a definition") gets the fix **Move back**: inline the definition, and leave the reasoning where it is. -4. **Short.** Cut what does not clearly help 1–3. +3. **Default to delete.** A line the reader does not need fails. Fix: **Delete** what the code, a type, a test name, the README or another rule already says. Fix: **Move** a decision to `docs/decisions.md` with its index line in `AGENTS.md`, and a goal to the README. A pointer standing where a definition belongs ("A pointer is not a definition") gets the fix **Move back**: inline the definition, and leave the reasoning where it is. +4. **Short.** Words that do not clearly help 1–3 fail. Fix: **Cut**. Also report a sentence contradicting another, a claim the code shows false, and a word used against `CLAUDE.md` → "Vocabulary". ## Growth -Report the lines each file gained and lost. A fix that adds words must name what a reader could not understand without them; one that does not is a finding against the fix. +Report the lines each file gained and lost. From round 2, a fix that added words without naming what a reader could not understand without them is a finding. ## Scopes diff --git a/agents/systems-architect.md b/agents/systems-architect.md index 8bb293e4..8c57133a 100644 --- a/agents/systems-architect.md +++ b/agents/systems-architect.md @@ -194,4 +194,3 @@ Respect documented deliberate deviations — a stated trade-off is a valid reaso - When you disagree with a proposed design, say so and explain why structurally. - Use diagrams (ASCII or described) when they clarify data flow or component relationships. - Avoid jargon unless it's the precise term. Prefer domain language over technical buzzwords. -- Plain, short prose. No filler. -- 2.52.0 From 6816088dd9c3a850526c62afeb181be076913c25 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 19:21:01 +0200 Subject: [PATCH 178/233] Answer the prose pass's second round --- CLAUDE.md | 6 +++--- agents/prose-reviewer.md | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 1108976d..5d1f7b81 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,8 +4,8 @@ Everything written — chat, commit messages, comments, docs, code — is in **English**. Prose meets four priorities, in this order. When two pull against each other, the higher one wins. -1. **Easy to understand.** A reader with little time gets it on one read. Keep each sentence to one idea and at most one condition. Explain a term before using it, or use a plainer word. Never fold a clause into a noun phrase to save words. BANNED: `An empty earliest unreleased release with nothing shipped toward it is planned as this chunk`. GOOD: `When the next release has no items and no work has landed towards it, plan it.` -2. **Most important first**, judged by what this document's reader wants to know first. The most important topic comes first, then the most important paragraph within each topic, then the most important item within each list. The longer the document, the more this matters. +1. **Easy to understand.** A reader with little time gets it on one read. Keep each sentence to one idea. Explain a term before using it, or use a plainer word. Never fold a clause into a noun phrase to save words. BANNED: `An empty earliest unreleased release with nothing shipped toward it is planned as this chunk`. GOOD: `When the next release has no items and no work has landed towards it, plan it.` +2. **Most important first**, judged by what this document's reader wants to know first. Put the most important section first. Within each section, put the most important paragraph first, and within each list the most important item. The longer the document, the more this matters. 3. **Default to delete.** Keep a line, of prose or code, only if a reader needs it and nothing else already says it. Adding words is a deliberate act: name what a reader could not understand without them. 4. **Short.** Cut whatever does not clearly help 1–3. @@ -48,7 +48,7 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The - **Until `README.md` has a `## Goals` and an `## Audience` section, writing them is the only work.** Not even planning in `todo.md`. Both are public: an outside reader judges a project by where it is heading and who it is for. Goals or an audience written anywhere else, such as `AGENTS.md` or `docs/`, do not count. - **Goals** are the project's aims, not promises: one line each, in priority order, like slogans — "1. Blazing fast performance. 2. Correctness is more important than many features." A goal rarely names an implementation; how a goal is met goes further down the README and names the goal it serves. - **Audience** names who depends on the project and what they may rely on. -- **Work one chunk at a time.** Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding anywhere else in `todo.md`, under a release. +- **Work one chunk at a time.** Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`, under a release. - **Ask, don't guess.** First check whether the goals already answer the question. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Write every answer once, where it belongs, never only in chat: a goal in `README.md`, a working rule in `AGENTS.md`, a standing choice in `docs/decisions.md`. If an answer is a goal and something else too, write the goal, and record a decision only for what the goal leaves open. - **Ship every chunk with `/larv-review`.** - **Open every chunk with one line:** the last version cut, what is unreleased (`CHANGELOG.md` → `## Unreleased`, or else the log since the last tag), and the release this chunk ships into. A repo that publishes nothing says so once. diff --git a/agents/prose-reviewer.md b/agents/prose-reviewer.md index b6766ef0..9496453b 100644 --- a/agents/prose-reviewer.md +++ b/agents/prose-reviewer.md @@ -13,7 +13,7 @@ The bar: `~/.claude/CLAUDE.md` → "Prose" and "Comments and documentation". Rea Run them in this order. A fix for a later check never breaks an earlier one. 1. **Easy to understand.** Read each sentence once, cold. A sentence you had to reread, a term used before it is explained, or an "it" or "them" that could point at two things is a finding. Fix: **Rewrite**, giving the plain sentence. -2. **Most important first.** Name the document's reader and what they want to know first. Check that the topics run in that order, then the paragraphs within each topic, then the items within each list. If not, fix: **Reorder**, naming the new order. A section so long that a reader has to search it gets sub-headings or an index. Fix: **Split**. +2. **Most important first.** Name the document's reader and what they want to know first. Check that the sections run in that order, then the paragraphs within each section, then the items within each list. If not, fix: **Reorder**, naming the new order. A section so long that a reader has to search it gets sub-headings or an index. Fix: **Split**. 3. **Default to delete.** A line the reader does not need fails. Fix: **Delete** what the code, a type, a test name, the README or another rule already says. Fix: **Move** a decision to `docs/decisions.md` with its index line in `AGENTS.md`, and a goal to the README. A pointer standing where a definition belongs ("A pointer is not a definition") gets the fix **Move back**: inline the definition, and leave the reasoning where it is. 4. **Short.** Words that do not clearly help 1–3 fail. Fix: **Cut**. -- 2.52.0 From 2fe396b461ed29ed3348917b8bb23580bc9f7316 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 19:25:31 +0200 Subject: [PATCH 179/233] Order CLAUDE.md by what a session needs first, and say when order is worth a fix --- CLAUDE.md | 134 +++++++++++++++++++++++++++--------------------------- 1 file changed, 67 insertions(+), 67 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 5d1f7b81..46807469 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,49 +1,8 @@ # Global instructions -## Prose - -Everything written — chat, commit messages, comments, docs, code — is in **English**. Prose meets four priorities, in this order. When two pull against each other, the higher one wins. - -1. **Easy to understand.** A reader with little time gets it on one read. Keep each sentence to one idea. Explain a term before using it, or use a plainer word. Never fold a clause into a noun phrase to save words. BANNED: `An empty earliest unreleased release with nothing shipped toward it is planned as this chunk`. GOOD: `When the next release has no items and no work has landed towards it, plan it.` -2. **Most important first**, judged by what this document's reader wants to know first. Put the most important section first. Within each section, put the most important paragraph first, and within each list the most important item. The longer the document, the more this matters. -3. **Default to delete.** Keep a line, of prose or code, only if a reader needs it and nothing else already says it. Adding words is a deliberate act: name what a reader could not understand without them. -4. **Short.** Cut whatever does not clearly help 1–3. - -- **Write the thing, not an introduction to it.** A sentence announcing what follows, or flagging that it deserves attention, carries nothing — if it matters, it is in what follows. A bare label is fine. BANNED: `Here's the new audience text, which is the part that needs your eye:`, `One thing I changed that deserves your attention.`, `One judgment call I'd flag rather than bury.`, `Three things came along that would otherwise have been left false.` GOOD: `New audience text:`, or the list alone. -- **No contrastive tail.** `X rather than Y`, `not Y but X`, `instead of Y`: state X and stop. The rejected alternative is noise unless naming it stops a reader doing Y. BANNED: `verified in CI rather than asserted`. GOOD: `verified in CI`. - -## Vocabulary - -- **chunk** — the unit of work: the smallest PR-able change. -- **cycle** — one worker run and the judge's verdict on it, in `loop-claude`. -- **gate** — the merge gate: the checks a PR passes before it merges. -- **interrupt** — `loop-claude` handing the terminal to the human, `claude --resume`, for a decision that is theirs. -- **judge** — the headless claude that reads a worker's transcript each cycle and decides whether to interrupt and whether the chunk is finished. -- **pass** — one kind of review a chunk may take, run in rounds by its reviewers until clean; `larv-review` §3 lists them. -- **plan** — `todo.md`. -- **premises** — the goals and audience under `## Goals` and `## Audience` in the project's `README.md`. -- **release** — a semver version the human cuts. -- **reviewer** — a reporter of findings: an agent under `~/.claude/agents/`, `/security-review` or a forge's auto-reviewer. -- **round cap** — the rounds one pass may take per chunk; `larv-review` §3 → "Round cap". -- **session** — a Claude Code session: one id, what `claude --resume` continues. -- **trigger** — the condition under which a review pass runs on a change it has not seen; `larv-review` §3 lists them. -- **worker** — the headless claude that runs the task in a cycle, in the chunk's session. - -## Maintaining this file -- When you spot a pattern in how I work that isn't written here — a preference I've repeated, a correction I've given more than once, a convention you inferred from my code — tell me and ask me to write it up here. Don't add it silently, and don't just keep it in a memory file. -- After every change to this file, re-read the whole thing and restructure it: merge overlapping rules, cut prose that restates a rule, move rules to the section they belong in, drop what's now covered elsewhere. Same information, easier to read and shorter. - -## Web research -- **A list or threshold a consumer relies on is sourced.** Deny-lists, defaults, limits: follow a published standard or a widely deployed tool, and cite it in the decision recording the choice; where none exists, ask. Never assemble one from names that seem plausible. -- Default to `WebSearch`/`WebFetch`. When a page renders client-side and comes back empty/blocked, use the Playwright renderer at `~/code/playwright-for-agents/` — `./pw [options]` (see its README). Don't use claude-in-chrome for this. - -## Technical principles - -The design rules every project follows, compose-not-entangle first: `~/.claude/principles/technical-principles.md`. Read it before designing or reviewing code. - ## Working loop -How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The *next release* is the earliest one not yet cut. +How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The *next release* is the earliest one not yet cut; other words, such as *chunk*, are defined under "Vocabulary" at the end of this file. - **Until `README.md` has a `## Goals` and an `## Audience` section, writing them is the only work.** Not even planning in `todo.md`. Both are public: an outside reader judges a project by where it is heading and who it is for. Goals or an audience written anywhere else, such as `AGENTS.md` or `docs/`, do not count. - **Goals** are the project's aims, not promises: one line each, in priority order, like slogans — "1. Blazing fast performance. 2. Correctness is more important than many features." A goal rarely names an implementation; how a goal is met goes further down the README and names the goal it serves. @@ -58,17 +17,44 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The - **Releases are the human's.** The version bump and the publishing credentials are theirs, whatever another rule says. Prepare everything else, so cutting a release is one decision. - **Remove a finished item from `todo.md`; keep its release heading until the version is cut.** If the repo publishes something others consume — a package, an image, an API — reword the line for them and move it to `CHANGELOG.md` under `## Unreleased`. A changelog is for the public, never for the next agent. Otherwise delete the line; git history is the record. +## Prose + +Everything written — chat, commit messages, comments, docs, code — is in **English**. Prose meets four priorities, in this order. When two pull against each other, the higher one wins. + +1. **Easy to understand.** A reader with little time gets it on one read. Keep each sentence to one idea. Explain a term before using it, or use a plainer word. Never fold a clause into a noun phrase to save words. BANNED: `An empty earliest unreleased release with nothing shipped toward it is planned as this chunk`. GOOD: `When the next release has no items and no work has landed towards it, plan it.` +2. **Most important first**, judged by what this document's reader wants to know first. Put the most important section first. Within each section, put the most important paragraph first, and within each list the most important item. Order matters most in long documents; in a short one, don't spend a fix on it. +3. **Default to delete.** Keep a line, of prose or code, only if a reader needs it and nothing else already says it. Adding words is a deliberate act: name what a reader could not understand without them. +4. **Short.** Cut whatever does not clearly help 1–3. + +- **Write the thing, not an introduction to it.** A sentence announcing what follows, or flagging that it deserves attention, carries nothing — if it matters, it is in what follows. A bare label is fine. BANNED: `Here's the new audience text, which is the part that needs your eye:`, `One thing I changed that deserves your attention.`, `One judgment call I'd flag rather than bury.`, `Three things came along that would otherwise have been left false.` GOOD: `New audience text:`, or the list alone. +- **No contrastive tail.** `X rather than Y`, `not Y but X`, `instead of Y`: state X and stop. The rejected alternative is noise unless naming it stops a reader doing Y. BANNED: `verified in CI rather than asserted`. GOOD: `verified in CI`. + ## Working with the codebase +- Always start a new git worktree when doing something in a codebase, and clean it up when done. Unless told otherwise, branch it off a freshly-updated default branch (`git fetch origin`, then base on `origin/main`), not whatever happens to be checked out. - Run a project's language runtime, package manager, and task runner through its container/tooling setup, never directly on the host. Example: `docker compose run --rm app …`. - Check `README.md` first for build, test, install, and codegen commands; one that misbehaves is fixed per "A false claim is a bug". Refresh `README.md` whenever you change what it describes ("Refresh `README.md` to match"). -- Always start a new git worktree when doing something in a codebase, and clean it up when done. Unless told otherwise, branch it off a freshly-updated default branch (`git fetch origin`, then base on `origin/main`), not whatever happens to be checked out. - Pin GitHub Actions to semver tags (`@v3`, `@v3.1.2`), not commit SHAs — including third-party actions. SHA-pin only in special pipelines that test our own specific builds. - Pin container images to the **full patch version** everywhere they're referenced — Dockerfile `FROM`, compose `image:`, base images in test fixtures: `node:24.18.1-bookworm-slim`, `mysql:8.4.7`, `alpine:3.23.3`. Never a floating major or minor (`node:24`, `node:24.18`, `:latest`, `:lts`): the same commit then builds a different image on different days, so a green pipeline says nothing about the next run, a base change lands with no diff to review, and any size or performance figure measured against it silently goes stale. Let a bot (Renovate/Dependabot) raise the bumps as reviewable PRs — that is where a base change belongs. (Actions are the exception above: a semver tag is fine there, because the action's own release is the reviewable unit.) -## Handoffs -- One document per project: `~/code/claude-handoffs/_.md`, with its supporting files (scripts, probes, saved sessions) under `~/code/claude-handoffs///`, dated the day they were written. -- Each document stands alone — projects move in parallel, so never reference another project's handoff. A fact two of them share (a test site, where credentials live) is stated in each, or kept in a memory file and named there. -- Content: only what the repo cannot hold — probe results, where credentials live. What is done and the next step live in the plan; goals, audience and decisions in `README.md`/`AGENTS.md`. A handoff never restates them: the repo's copy travels with the code and this one does not. +## Technical principles + +The design rules every project follows, compose-not-entangle first: `~/.claude/principles/technical-principles.md`. Read it before designing or reviewing code. + +## Code style +- Reuse before adding. Extend an existing test with an assertion rather than writing a new one. +- Signal failures with a result value carrying an optional error, not by throwing. A function that both returns a result and throws for some inputs has two error channels; collapse to one. Reserve exceptions for truly unrecoverable states at boundaries, never for control flow the caller is meant to handle. +- A cast (`x as Foo`) asserts what the compiler could not check and stops it checking — so when the type later changes, nothing tells you. Derive the real type instead: infer it, name the return type, or parse the input once into a typed shape. Where a value genuinely arrives untyped (HTTP body, `JSON.parse`, DB row), the boundary owes a **type guard validating the fields it claims**; past that boundary everything is typed. `as unknown as T` and non-null `!` are the same defect wearing a hat. BANNED: `const user = body as User` — one rename and it is a silent lie. GOOD: `function isUser(v: unknown): v is User` checking each field, then `if (!isUser(body)) return { error: … }`. +- Keep delivery-layer entrypoints thin: inject services, validate + hand off the request data, map the service's return to a response. Domain decisions and branching belong in the service layer — an entrypoint reaching into a payload to decide *what to do* is the smell. BANNED: `if (body.tx.source === 'notification') { /* drop, skip enqueue */ }` in a route handler. GOOD: the entrypoint forwards `source` on the event → the service decides drop-vs-process and returns a result → the entrypoint maps that result to a status code. +- DTOs, enums, and value objects are pure data — no logic. They stand in for the structs/records a language lacks. +- Prefer explicit, descriptive names over generic ones (`invoiceRowsService`, not `service`). +- Prefer a standalone Python script with a `#!/usr/bin/env python3` shebang over a shell script — it runs identically across systems where shell dialects/builtins differ. Read config (credentials, hosts, paths) from CLI params or env vars, never hardcoded. +- Sort wherever order carries no meaning (`~/.claude/principles/technical-principles.md`) — attributes, array and object keys, enum members, imports, table rows, and line-based file lists such as `.gitignore`/`.dockerignore`. Exception: `id` goes first. +- Sort a compound line on the name it introduces, never on an incidental field: an import on its first binding, not its path, so moving or renaming a module reorders nothing. Where lines already group by kind — type imports, host packages — the key sorts within each group. +- Indent with hard tabs by default. A project's own settings win: `.editorconfig`, linter/formatter config (Prettier, `rustfmt.toml`, …), or the surrounding file's existing indentation. + +## Naming files & folders +- Name by what's inside, not by catch-all. BANNED: `scripts`, `utils`, `helpers`, `misc`, `common`, `lib`, `stuff`. Use explicit names: `e2e-tests/`, `db-migrations/`, `release-tooling/`. +- Group related artifacts by purpose — e2e compose files, e2e Dockerfile, and e2e test scripts all belong in `e2e-tests/`. ## Tests - Write tests first for the behaviour we want, then implement until they pass. @@ -76,22 +62,6 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The - Use properly randomised UUID v7s — never `aaaa-0000`-style placeholders. - Tear down test containers after a run. -## Code style -- Indent with hard tabs by default. A project's own settings win: `.editorconfig`, linter/formatter config (Prettier, `rustfmt.toml`, …), or the surrounding file's existing indentation. -- Reuse before adding. Extend an existing test with an assertion rather than writing a new one. -- Sort wherever order carries no meaning (`~/.claude/principles/technical-principles.md`) — attributes, array and object keys, enum members, imports, table rows, and line-based file lists such as `.gitignore`/`.dockerignore`. Exception: `id` goes first. -- Sort a compound line on the name it introduces, never on an incidental field: an import on its first binding, not its path, so moving or renaming a module reorders nothing. Where lines already group by kind — type imports, host packages — the key sorts within each group. -- Prefer a standalone Python script with a `#!/usr/bin/env python3` shebang over a shell script — it runs identically across systems where shell dialects/builtins differ. Read config (credentials, hosts, paths) from CLI params or env vars, never hardcoded. -- DTOs, enums, and value objects are pure data — no logic. They stand in for the structs/records a language lacks. -- Prefer explicit, descriptive names over generic ones (`invoiceRowsService`, not `service`). -- Keep delivery-layer entrypoints thin: inject services, validate + hand off the request data, map the service's return to a response. Domain decisions and branching belong in the service layer — an entrypoint reaching into a payload to decide *what to do* is the smell. BANNED: `if (body.tx.source === 'notification') { /* drop, skip enqueue */ }` in a route handler. GOOD: the entrypoint forwards `source` on the event → the service decides drop-vs-process and returns a result → the entrypoint maps that result to a status code. -- Signal failures with a result value carrying an optional error, not by throwing. A function that both returns a result and throws for some inputs has two error channels; collapse to one. Reserve exceptions for truly unrecoverable states at boundaries, never for control flow the caller is meant to handle. -- A cast (`x as Foo`) asserts what the compiler could not check and stops it checking — so when the type later changes, nothing tells you. Derive the real type instead: infer it, name the return type, or parse the input once into a typed shape. Where a value genuinely arrives untyped (HTTP body, `JSON.parse`, DB row), the boundary owes a **type guard validating the fields it claims**; past that boundary everything is typed. `as unknown as T` and non-null `!` are the same defect wearing a hat. BANNED: `const user = body as User` — one rename and it is a silent lie. GOOD: `function isUser(v: unknown): v is User` checking each field, then `if (!isUser(body)) return { error: … }`. - -## Naming files & folders -- Name by what's inside, not by catch-all. BANNED: `scripts`, `utils`, `helpers`, `misc`, `common`, `lib`, `stuff`. Use explicit names: `e2e-tests/`, `db-migrations/`, `release-tooling/`. -- Group related artifacts by purpose — e2e compose files, e2e Dockerfile, and e2e test scripts all belong in `e2e-tests/`. - ## Comments and documentation (`README.md`, `AGENTS.md`, `docs/`, API specs) **One bar for all of it.** A comment or a paragraph earns its place by saying what a competent reader of THIS codebase could not infer and the repo cannot say for itself: a surprising WHY, a footgun, an invariant, an external constraint. The fix for a redundant one is deletion, not trimming — two copies drift, and the doc copy is the one nobody updates. Once it has earned its place, make it plain and short. GOOD: `// Loud-fail: missing amount used to coerce to '0' = phantom "0 SEK reversal" in api-4.` — records a past prod bug the code can't show. @@ -146,11 +116,41 @@ Default to NO comment. Delete one that is any of: - The opposite of internal code comments, which *may* cite a ticket for a footgun/constraint. ## Git, commits, and PRs -- Use `gh` on GitHub remotes and `tea` on Gitea remotes (e.g. `gitea.larvit.se`) — same command shape: `tea pr list|create`, `tea issue`, `tea release`, `tea api`. Everything below applies to both. -- Branch for a ticket: exactly the ticket ID, nothing more. `ABC-123`, never `ABC-123-some-description`. -- When the work has a ticket, read it before starting: verify the change matches it and pull useful context from it. +- Never add `Co-Authored-By: Claude ...`, `🤖 Generated with Claude Code`, or any Claude/Anthropic/Agent marker in commits, PR bodies, issue comments, or anywhere else. - Commit message and PR title: **one line**, prefixed with the ticket ID when the work has one. Example: `ABC-123 - Regression tests for GET /v4/clients`. Never include the repo/project name (like "twu-4") — we're already in that context. - PR summary: short and concise. No test plan (it lives in the ticket), no link to the ticket (it's in the title). +- When the work has a ticket, read it before starting: verify the change matches it and pull useful context from it. +- Branch for a ticket: exactly the ticket ID, nothing more. `ABC-123`, never `ABC-123-some-description`. +- Use `gh` on GitHub remotes and `tea` on Gitea remotes (e.g. `gitea.larvit.se`) — same command shape: `tea pr list|create`, `tea issue`, `tea release`, `tea api`. Everything in this section applies to both. - Keep the project's main checkout (e.g. `~/code/log`, never a worktree) current: when it is behind `origin` — a merge landed, or a fetch shows it — run `git pull --ff-only` there instead of reporting the lag, never with `--autostash`: a dirty checkout is a finding to report, not to carry along. - Releases follow semver read strictly (`~/.claude/principles/technical-principles.md`). -- Never add `Co-Authored-By: Claude ...`, `🤖 Generated with Claude Code`, or any Claude/Anthropic/Agent marker in commits, PR bodies, issue comments, or anywhere else. + +## Handoffs +- One document per project: `~/code/claude-handoffs/_.md`, with its supporting files (scripts, probes, saved sessions) under `~/code/claude-handoffs///`, dated the day they were written. +- Each document stands alone — projects move in parallel, so never reference another project's handoff. A fact two of them share (a test site, where credentials live) is stated in each, or kept in a memory file and named there. +- Content: only what the repo cannot hold — probe results, where credentials live. What is done and the next step live in the plan; goals, audience and decisions in `README.md`/`AGENTS.md`. A handoff never restates them: the repo's copy travels with the code and this one does not. + +## Web research +- **A list or threshold a consumer relies on is sourced.** Deny-lists, defaults, limits: follow a published standard or a widely deployed tool, and cite it in the decision recording the choice; where none exists, ask. Never assemble one from names that seem plausible. +- Default to `WebSearch`/`WebFetch`. When a page renders client-side and comes back empty/blocked, use the Playwright renderer at `~/code/playwright-for-agents/` — `./pw [options]` (see its README). Don't use claude-in-chrome for this. + +## Maintaining this file +- When you spot a pattern in how I work that isn't written here — a preference I've repeated, a correction I've given more than once, a convention you inferred from my code — tell me and ask me to write it up here. Don't add it silently, and don't just keep it in a memory file. +- After every change to this file, re-read the whole thing and restructure it: merge overlapping rules, cut prose that restates a rule, move rules to the section they belong in, drop what's now covered elsewhere. Same information, easier to read and shorter. + +## Vocabulary + +- **chunk** — the unit of work: the smallest PR-able change. +- **cycle** — one worker run and the judge's verdict on it, in `loop-claude`. +- **gate** — the merge gate: the checks a PR passes before it merges. +- **interrupt** — `loop-claude` handing the terminal to the human, `claude --resume`, for a decision that is theirs. +- **judge** — the headless claude that reads a worker's transcript each cycle and decides whether to interrupt and whether the chunk is finished. +- **pass** — one kind of review a chunk may take, run in rounds by its reviewers until clean; `larv-review` §3 lists them. +- **plan** — `todo.md`. +- **premises** — the goals and audience under `## Goals` and `## Audience` in the project's `README.md`. +- **release** — a semver version the human cuts. +- **reviewer** — a reporter of findings: an agent under `~/.claude/agents/`, `/security-review` or a forge's auto-reviewer. +- **round cap** — the rounds one pass may take per chunk; `larv-review` §3 → "Round cap". +- **session** — a Claude Code session: one id, what `claude --resume` continues. +- **trigger** — the condition under which a review pass runs on a change it has not seen; `larv-review` §3 lists them. +- **worker** — the headless claude that runs the task in a cycle, in the chunk's session. -- 2.52.0 From c7738f8bcd2fd133cce2b87fd356f41d7005b4c7 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 19:27:04 +0200 Subject: [PATCH 180/233] Answer the order review's first round --- CLAUDE.md | 90 +++++++++++++++++++++++++++---------------------------- 1 file changed, 45 insertions(+), 45 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 46807469..37d4a1c1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -2,20 +2,25 @@ ## Working loop -How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The *next release* is the earliest one not yet cut; other words, such as *chunk*, are defined under "Vocabulary" at the end of this file. +How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The *next release* is the earliest one not yet cut. Other words, such as *chunk*, are defined under "Vocabulary" at the end of this file. - **Until `README.md` has a `## Goals` and an `## Audience` section, writing them is the only work.** Not even planning in `todo.md`. Both are public: an outside reader judges a project by where it is heading and who it is for. Goals or an audience written anywhere else, such as `AGENTS.md` or `docs/`, do not count. - **Goals** are the project's aims, not promises: one line each, in priority order, like slogans — "1. Blazing fast performance. 2. Correctness is more important than many features." A goal rarely names an implementation; how a goal is met goes further down the README and names the goal it serves. - **Audience** names who depends on the project and what they may rely on. -- **Work one chunk at a time.** Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`, under a release. -- **Ask, don't guess.** First check whether the goals already answer the question. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Write every answer once, where it belongs, never only in chat: a goal in `README.md`, a working rule in `AGENTS.md`, a standing choice in `docs/decisions.md`. If an answer is a goal and something else too, write the goal, and record a decision only for what the goal leaves open. -- **Ship every chunk with `/larv-review`.** -- **Open every chunk with one line:** the last version cut, what is unreleased (`CHANGELOG.md` → `## Unreleased`, or else the log since the last tag), and the release this chunk ships into. A repo that publishes nothing says so once. - **Plan `todo.md` by semver release:** every item sits under the release that ships it. If `todo.md` has another shape, reshaping it is the chunk, and the human approves it. - **When the next release has no items and no work has landed towards it, plan it as this chunk.** Weigh the unscheduled items against the goals, put them in order, and get the human's approval before writing any code. - **When the next release has no items left and work has landed towards it, it is finished: stop.** Report what it holds and that it is ready to cut. Under `/loop`, this ends the loop. Until the human cuts it, only a security fix lands, into that release; never start a later release's items or plan a new one. -- **Releases are the human's.** The version bump and the publishing credentials are theirs, whatever another rule says. Prepare everything else, so cutting a release is one decision. +- **Open every chunk with one line:** the last version cut, what is unreleased (`CHANGELOG.md` → `## Unreleased`, or else the log since the last tag), and the release this chunk ships into. A repo that publishes nothing says so once. +- **Work one chunk at a time.** Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`, under a release. +- **Ask, don't guess.** First check whether the goals already answer the question. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Write every answer once, where it belongs, never only in chat: a goal in `README.md`, a working rule in `AGENTS.md`, a standing choice in `docs/decisions.md`. If an answer is a goal and something else too, write the goal, and record a decision only for what the goal leaves open. +- **Ship every chunk with `/larv-review`.** - **Remove a finished item from `todo.md`; keep its release heading until the version is cut.** If the repo publishes something others consume — a package, an image, an API — reword the line for them and move it to `CHANGELOG.md` under `## Unreleased`. A changelog is for the public, never for the next agent. Otherwise delete the line; git history is the record. +- **Releases are the human's.** The version bump and the publishing credentials are theirs, whatever another rule says. Prepare everything else, so cutting a release is one decision. +- Releases follow semver read strictly (`~/.claude/principles/technical-principles.md`). + +### Todo items (`todo.md`, tickets, plans) +- Open each item with a bold one-sentence tagline, so the taglines alone say what a release holds; detail follows it. The tagline states the target state, checkable when done: an imperative verb plus what holds afterwards. A present-tense fact reads as the current state and says nothing about what to do. Add "today X" only where the direction is otherwise ambiguous. GOOD: `**Accept undefined in MetadataValue and drop such keys on output.**` BANNED: `MetadataValue accepts undefined; such keys are dropped on output`. +- A security finding — a leaked credential, secret or PII, an auth bypass, an injection — is filed the moment it is found, at the top of the list under its own `## Security` heading, naming the exposure and the path it reaches. Never among additive or nice-to-have items, never only in a chunk's summary, and never as a question about where it belongs: file it, say you did, and I will move it down if I disagree. Fixing it inside an unrelated change is a separate call — say whether it is in the blast radius. ## Prose @@ -29,39 +34,6 @@ Everything written — chat, commit messages, comments, docs, code — is in **E - **Write the thing, not an introduction to it.** A sentence announcing what follows, or flagging that it deserves attention, carries nothing — if it matters, it is in what follows. A bare label is fine. BANNED: `Here's the new audience text, which is the part that needs your eye:`, `One thing I changed that deserves your attention.`, `One judgment call I'd flag rather than bury.`, `Three things came along that would otherwise have been left false.` GOOD: `New audience text:`, or the list alone. - **No contrastive tail.** `X rather than Y`, `not Y but X`, `instead of Y`: state X and stop. The rejected alternative is noise unless naming it stops a reader doing Y. BANNED: `verified in CI rather than asserted`. GOOD: `verified in CI`. -## Working with the codebase -- Always start a new git worktree when doing something in a codebase, and clean it up when done. Unless told otherwise, branch it off a freshly-updated default branch (`git fetch origin`, then base on `origin/main`), not whatever happens to be checked out. -- Run a project's language runtime, package manager, and task runner through its container/tooling setup, never directly on the host. Example: `docker compose run --rm app …`. -- Check `README.md` first for build, test, install, and codegen commands; one that misbehaves is fixed per "A false claim is a bug". Refresh `README.md` whenever you change what it describes ("Refresh `README.md` to match"). -- Pin GitHub Actions to semver tags (`@v3`, `@v3.1.2`), not commit SHAs — including third-party actions. SHA-pin only in special pipelines that test our own specific builds. -- Pin container images to the **full patch version** everywhere they're referenced — Dockerfile `FROM`, compose `image:`, base images in test fixtures: `node:24.18.1-bookworm-slim`, `mysql:8.4.7`, `alpine:3.23.3`. Never a floating major or minor (`node:24`, `node:24.18`, `:latest`, `:lts`): the same commit then builds a different image on different days, so a green pipeline says nothing about the next run, a base change lands with no diff to review, and any size or performance figure measured against it silently goes stale. Let a bot (Renovate/Dependabot) raise the bumps as reviewable PRs — that is where a base change belongs. (Actions are the exception above: a semver tag is fine there, because the action's own release is the reviewable unit.) - -## Technical principles - -The design rules every project follows, compose-not-entangle first: `~/.claude/principles/technical-principles.md`. Read it before designing or reviewing code. - -## Code style -- Reuse before adding. Extend an existing test with an assertion rather than writing a new one. -- Signal failures with a result value carrying an optional error, not by throwing. A function that both returns a result and throws for some inputs has two error channels; collapse to one. Reserve exceptions for truly unrecoverable states at boundaries, never for control flow the caller is meant to handle. -- A cast (`x as Foo`) asserts what the compiler could not check and stops it checking — so when the type later changes, nothing tells you. Derive the real type instead: infer it, name the return type, or parse the input once into a typed shape. Where a value genuinely arrives untyped (HTTP body, `JSON.parse`, DB row), the boundary owes a **type guard validating the fields it claims**; past that boundary everything is typed. `as unknown as T` and non-null `!` are the same defect wearing a hat. BANNED: `const user = body as User` — one rename and it is a silent lie. GOOD: `function isUser(v: unknown): v is User` checking each field, then `if (!isUser(body)) return { error: … }`. -- Keep delivery-layer entrypoints thin: inject services, validate + hand off the request data, map the service's return to a response. Domain decisions and branching belong in the service layer — an entrypoint reaching into a payload to decide *what to do* is the smell. BANNED: `if (body.tx.source === 'notification') { /* drop, skip enqueue */ }` in a route handler. GOOD: the entrypoint forwards `source` on the event → the service decides drop-vs-process and returns a result → the entrypoint maps that result to a status code. -- DTOs, enums, and value objects are pure data — no logic. They stand in for the structs/records a language lacks. -- Prefer explicit, descriptive names over generic ones (`invoiceRowsService`, not `service`). -- Prefer a standalone Python script with a `#!/usr/bin/env python3` shebang over a shell script — it runs identically across systems where shell dialects/builtins differ. Read config (credentials, hosts, paths) from CLI params or env vars, never hardcoded. -- Sort wherever order carries no meaning (`~/.claude/principles/technical-principles.md`) — attributes, array and object keys, enum members, imports, table rows, and line-based file lists such as `.gitignore`/`.dockerignore`. Exception: `id` goes first. -- Sort a compound line on the name it introduces, never on an incidental field: an import on its first binding, not its path, so moving or renaming a module reorders nothing. Where lines already group by kind — type imports, host packages — the key sorts within each group. -- Indent with hard tabs by default. A project's own settings win: `.editorconfig`, linter/formatter config (Prettier, `rustfmt.toml`, …), or the surrounding file's existing indentation. - -## Naming files & folders -- Name by what's inside, not by catch-all. BANNED: `scripts`, `utils`, `helpers`, `misc`, `common`, `lib`, `stuff`. Use explicit names: `e2e-tests/`, `db-migrations/`, `release-tooling/`. -- Group related artifacts by purpose — e2e compose files, e2e Dockerfile, and e2e test scripts all belong in `e2e-tests/`. - -## Tests -- Write tests first for the behaviour we want, then implement until they pass. -- Changing tests and changing other code are two separate processes — be very careful about doing both at once. -- Use properly randomised UUID v7s — never `aaaa-0000`-style placeholders. -- Tear down test containers after a run. - ## Comments and documentation (`README.md`, `AGENTS.md`, `docs/`, API specs) **One bar for all of it.** A comment or a paragraph earns its place by saying what a competent reader of THIS codebase could not infer and the repo cannot say for itself: a surprising WHY, a footgun, an invariant, an external constraint. The fix for a redundant one is deletion, not trimming — two copies drift, and the doc copy is the one nobody updates. Once it has earned its place, make it plain and short. GOOD: `// Loud-fail: missing amount used to coerce to '0' = phantom "0 SEK reversal" in api-4.` — records a past prod bug the code can't show. @@ -98,10 +70,6 @@ Default to NO comment. Delete one that is any of: **"Refresh `README.md` to match" means keep it true, not longer.** A change that alters a build/test/run/deploy step, a required env var, or a prerequisite makes the README a false claim by omission, fixed per "A false claim is a bug". Otherwise most changes need no README edit at all, and adding a section is a deliberate act you must justify. GOOD: `run-tests.sh` gained a required `--profile` flag → update the documented command. BANNED: the change added a test case → add a paragraph describing it. -### Todo items (`todo.md`, tickets, plans) -- Open each item with a bold one-sentence tagline, so the taglines alone say what a release holds; detail follows it. The tagline states the target state, checkable when done: an imperative verb plus what holds afterwards. A present-tense fact reads as the current state and says nothing about what to do. Add "today X" only where the direction is otherwise ambiguous. GOOD: `**Accept undefined in MetadataValue and drop such keys on output.**` BANNED: `MetadataValue accepts undefined; such keys are dropped on output`. -- A security finding — a leaked credential, secret or PII, an auth bypass, an injection — is filed the moment it is found, at the top of the list under its own `## Security` heading, naming the exposure and the path it reaches. Never among additive or nice-to-have items, never only in a chunk's summary, and never as a question about where it belongs: file it, say you did, and I will move it down if I disagree. Fixing it inside an unrelated change is a separate call — say whether it is in the blast radius. - ### Package README (what someone finds on npm or GitHub) - The public API is the contract, so the README documents it: options, results, events, everything exported. The rule against narrating a file or test case still holds. - Order sections by what a new developer wants first: install, the main task, the next task, and so on. The reference half — options tables, in-depth behaviour, low-level API, development — goes below the quick starts. @@ -115,6 +83,40 @@ Default to NO comment. Delete one that is any of: - Text in public API specs (OpenAPI `description`/`title` fields and the generated api-docs) is read by external consumers. Never leak internal references: no ticket IDs, internal URLs, repo/system code-names, "see ticket X". Describe behaviour in consumer terms. GOOD: `Deprecated alias for paymentAccountId`. BANNED: `…will be removed (ABC-123)`. - The opposite of internal code comments, which *may* cite a ticket for a footgun/constraint. +## Working with the codebase +- Always start a new git worktree when doing something in a codebase, and clean it up when done. Unless told otherwise, branch it off a freshly-updated default branch (`git fetch origin`, then base on `origin/main`), not whatever happens to be checked out. +- Keep the project's main checkout (e.g. `~/code/log`, never a worktree) current: when it is behind `origin` — a merge landed, or a fetch shows it — run `git pull --ff-only` there instead of reporting the lag, never with `--autostash`: a dirty checkout is a finding to report, not to carry along. +- Run a project's language runtime, package manager, and task runner through its container/tooling setup, never directly on the host. Example: `docker compose run --rm app …`. +- Check `README.md` first for build, test, install, and codegen commands; one that misbehaves is fixed per "A false claim is a bug". Refresh `README.md` whenever you change what it describes ("Refresh `README.md` to match"). +- Pin GitHub Actions to semver tags (`@v3`, `@v3.1.2`), not commit SHAs — including third-party actions. SHA-pin only in special pipelines that test our own specific builds. +- Pin container images to the **full patch version** everywhere they're referenced — Dockerfile `FROM`, compose `image:`, base images in test fixtures: `node:24.18.1-bookworm-slim`, `mysql:8.4.7`, `alpine:3.23.3`. Never a floating major or minor (`node:24`, `node:24.18`, `:latest`, `:lts`): the same commit then builds a different image on different days, so a green pipeline says nothing about the next run, a base change lands with no diff to review, and any size or performance figure measured against it silently goes stale. Let a bot (Renovate/Dependabot) raise the bumps as reviewable PRs — that is where a base change belongs. (Actions are the exception above: a semver tag is fine there, because the action's own release is the reviewable unit.) + +## Technical principles + +The design rules every project follows, compose-not-entangle first: `~/.claude/principles/technical-principles.md`. Read it before designing or reviewing code. + +## Code style +- Reuse before adding. Extend an existing test with an assertion rather than writing a new one. +- Signal failures with a result value carrying an optional error, not by throwing. A function that both returns a result and throws for some inputs has two error channels; collapse to one. Reserve exceptions for truly unrecoverable states at boundaries, never for control flow the caller is meant to handle. +- A cast (`x as Foo`) asserts what the compiler could not check and stops it checking — so when the type later changes, nothing tells you. Derive the real type instead: infer it, name the return type, or parse the input once into a typed shape. Where a value genuinely arrives untyped (HTTP body, `JSON.parse`, DB row), the boundary owes a **type guard validating the fields it claims**; past that boundary everything is typed. `as unknown as T` and non-null `!` are the same defect wearing a hat. BANNED: `const user = body as User` — one rename and it is a silent lie. GOOD: `function isUser(v: unknown): v is User` checking each field, then `if (!isUser(body)) return { error: … }`. +- Keep delivery-layer entrypoints thin: inject services, validate + hand off the request data, map the service's return to a response. Domain decisions and branching belong in the service layer — an entrypoint reaching into a payload to decide *what to do* is the smell. BANNED: `if (body.tx.source === 'notification') { /* drop, skip enqueue */ }` in a route handler. GOOD: the entrypoint forwards `source` on the event → the service decides drop-vs-process and returns a result → the entrypoint maps that result to a status code. +- DTOs, enums, and value objects are pure data — no logic. They stand in for the structs/records a language lacks. +- Prefer explicit, descriptive names over generic ones (`invoiceRowsService`, not `service`). +- Prefer a standalone Python script with a `#!/usr/bin/env python3` shebang over a shell script — it runs identically across systems where shell dialects/builtins differ. Read config (credentials, hosts, paths) from CLI params or env vars, never hardcoded. +- Sort wherever order carries no meaning (`~/.claude/principles/technical-principles.md`) — attributes, array and object keys, enum members, imports, table rows, and line-based file lists such as `.gitignore`/`.dockerignore`. Exception: `id` goes first. +- Sort a compound line on the name it introduces, never on an incidental field: an import on its first binding, not its path, so moving or renaming a module reorders nothing. Where lines already group by kind — type imports, host packages — the key sorts within each group. +- Indent with hard tabs by default. A project's own settings win: `.editorconfig`, linter/formatter config (Prettier, `rustfmt.toml`, …), or the surrounding file's existing indentation. + +## Tests +- Write tests first for the behaviour we want, then implement until they pass. +- Changing tests and changing other code are two separate processes — be very careful about doing both at once. +- Use properly randomised UUID v7s — never `aaaa-0000`-style placeholders. +- Tear down test containers after a run. + +## Naming files & folders +- Name by what's inside, not by catch-all. BANNED: `scripts`, `utils`, `helpers`, `misc`, `common`, `lib`, `stuff`. Use explicit names: `e2e-tests/`, `db-migrations/`, `release-tooling/`. +- Group related artifacts by purpose — e2e compose files, e2e Dockerfile, and e2e test scripts all belong in `e2e-tests/`. + ## Git, commits, and PRs - Never add `Co-Authored-By: Claude ...`, `🤖 Generated with Claude Code`, or any Claude/Anthropic/Agent marker in commits, PR bodies, issue comments, or anywhere else. - Commit message and PR title: **one line**, prefixed with the ticket ID when the work has one. Example: `ABC-123 - Regression tests for GET /v4/clients`. Never include the repo/project name (like "twu-4") — we're already in that context. @@ -122,8 +124,6 @@ Default to NO comment. Delete one that is any of: - When the work has a ticket, read it before starting: verify the change matches it and pull useful context from it. - Branch for a ticket: exactly the ticket ID, nothing more. `ABC-123`, never `ABC-123-some-description`. - Use `gh` on GitHub remotes and `tea` on Gitea remotes (e.g. `gitea.larvit.se`) — same command shape: `tea pr list|create`, `tea issue`, `tea release`, `tea api`. Everything in this section applies to both. -- Keep the project's main checkout (e.g. `~/code/log`, never a worktree) current: when it is behind `origin` — a merge landed, or a fetch shows it — run `git pull --ff-only` there instead of reporting the lag, never with `--autostash`: a dirty checkout is a finding to report, not to carry along. -- Releases follow semver read strictly (`~/.claude/principles/technical-principles.md`). ## Handoffs - One document per project: `~/code/claude-handoffs/_.md`, with its supporting files (scripts, probes, saved sessions) under `~/code/claude-handoffs///`, dated the day they were written. -- 2.52.0 From fee0998fc1d883f1ac5e16acc03ba03510a98a99 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 19:27:29 +0200 Subject: [PATCH 181/233] Bold the semver bullet's lead --- CLAUDE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CLAUDE.md b/CLAUDE.md index 37d4a1c1..23ba1b23 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -16,7 +16,7 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The - **Ship every chunk with `/larv-review`.** - **Remove a finished item from `todo.md`; keep its release heading until the version is cut.** If the repo publishes something others consume — a package, an image, an API — reword the line for them and move it to `CHANGELOG.md` under `## Unreleased`. A changelog is for the public, never for the next agent. Otherwise delete the line; git history is the record. - **Releases are the human's.** The version bump and the publishing credentials are theirs, whatever another rule says. Prepare everything else, so cutting a release is one decision. -- Releases follow semver read strictly (`~/.claude/principles/technical-principles.md`). +- **Releases follow semver read strictly** (`~/.claude/principles/technical-principles.md`). ### Todo items (`todo.md`, tickets, plans) - Open each item with a bold one-sentence tagline, so the taglines alone say what a release holds; detail follows it. The tagline states the target state, checkable when done: an imperative verb plus what holds afterwards. A present-tense fact reads as the current state and says nothing about what to do. Add "today X" only where the direction is otherwise ambiguous. GOOD: `**Accept undefined in MetadataValue and drop such keys on output.**` BANNED: `MetadataValue accepts undefined; such keys are dropped on output`. -- 2.52.0 From a091775b38978ca1a5f60d7eff798a4f7f588aa1 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 19:40:55 +0200 Subject: [PATCH 182/233] Title what Comments and documentation adds to Prose, and cut what Prose already says --- CLAUDE.md | 37 ++++++++++++++++++++++++------------- 1 file changed, 24 insertions(+), 13 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 23ba1b23..a0c57975 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -36,19 +36,15 @@ Everything written — chat, commit messages, comments, docs, code — is in **E ## Comments and documentation (`README.md`, `AGENTS.md`, `docs/`, API specs) -**One bar for all of it.** A comment or a paragraph earns its place by saying what a competent reader of THIS codebase could not infer and the repo cannot say for itself: a surprising WHY, a footgun, an invariant, an external constraint. The fix for a redundant one is deletion, not trimming — two copies drift, and the doc copy is the one nobody updates. Once it has earned its place, make it plain and short. GOOD: `// Loud-fail: missing amount used to coerce to '0' = phantom "0 SEK reversal" in api-4.` — records a past prod bug the code can't show. +"Prose" above applies to all of it. These rules are special to writing that sits beside code. -**A false claim is a bug — fix it where you find it.** Docs, comments and what a program prints — `--help`, an error, a log line — assert checkable things: a command, a resolution rule, a path, a limit. Verify one before you repeat or build on it. When it is wrong, correct it in the same change: the claim — or the code, when consumers already rely on what the claim promises. Never work around it or record the discrepancy elsewhere. +### What earns a place -**Negation, history and limitations: name the action, or say nothing.** Prose describing the code as it stands — a comment, a README, an `AGENTS.md`, an API spec — may narrate what is *not* done (a removed step, a call we don't make, a superseded version `we used to X, now Y`, a limitation) in one shape only: where a reader would otherwise **do** something harmful, and the sentence says what to do instead. GOOD: `wrap a direct ./tests/run.sh to put it under the same lock`. BANNED: `run.sh takes no host lock`. A limitation with nothing to do instead belongs in the PR or ticket, because **documenting a limitation is not fixing it**. +The reader is a competent reader of THIS codebase. A comment or a paragraph earns its place by saying what that reader could not infer and the repo cannot say for itself: a surprising WHY, a footgun, an invariant, an external constraint. Fix a redundant one by deleting it, never by trimming it: two copies drift, and the doc copy is the one nobody updates. GOOD: `// Loud-fail: missing amount used to coerce to '0' = phantom "0 SEK reversal" in api-4.` — records a past prod bug the code can't show. -**The inversion: a decision record owns what a call site may not say.** A rejected alternative, or what something deliberately does not cover, is banned beside the code precisely because the decision record holds it — a standing choice a future reader would otherwise relitigate, where a `CHANGELOG` holds what changed in a release. **The decision log has one home: `docs/decisions.md`**, or `docs/decisions/` split by area once it outgrows one file. `AGENTS.md` carries a one-line index of the titles, so a session or a reviewer sees that a decision exists without loading its reasoning. An entry states the decision, its date, who made it, and the premise it rests on ("valid while X") so it can expire honestly when that premise dies. A decision found anywhere else — an `AGENTS.md` body, a comment, or a README section that is neither a goal nor how one is met — moves there and leaves its index line behind. A goal stays a goal in the README; the log records only what the goal leaves open. +### A false claim is a bug — fix it where you find it -**Every decision links to a goal or a technical principle.** An entry names the goal it serves or the technical principle under `~/.claude/principles/` it applies; one that can do neither is a missing goal, and an entry already in the repo with neither behind it is a finding. Propose the goal, never a reason of your own — the ask rule above says how. An entry working against a goal or a technical principle stands only while it names the `todo.md` item that ends it. - -**Link, don't inline — and keep the link bare.** A mechanism identical across call sites or repos is documented once in the canonical source and pointed at with a one-line bare link. Don't summarize what's behind the link or restate the identifier's own name. - -**A pointer is not a definition.** A definition the reader needs to follow the code — what a unit counts, what a term means, what invariant a cache rests on — sits at the code in one line. A pointer to it (`see AGENTS.md §11`) cannot be checked against the code beside it, so it rots invisibly. A pointer carrying rationale — a rejected alternative, the premise behind a standing choice — is correct and stays. +Docs, comments and what a program prints — `--help`, an error, a log line — assert checkable things: a command, a resolution rule, a path, a limit. Verify one before you repeat or build on it. When it is wrong, correct it in the same change: the claim — or the code, when consumers already rely on what the claim promises. Never work around it or record the discrepancy elsewhere. ### Comments @@ -68,14 +64,29 @@ Default to NO comment. Delete one that is any of: **A README covers what a reader needs *before* opening the code**: how it meets its goals, how to build, test, run, and deploy it, and cross-cutting decisions no single file owns. It does **not** narrate an individual symbol, file, or test case — whoever wants to know what a test asserts opens the test, where the answer is exact and cannot drift. -**"Refresh `README.md` to match" means keep it true, not longer.** A change that alters a build/test/run/deploy step, a required env var, or a prerequisite makes the README a false claim by omission, fixed per "A false claim is a bug". Otherwise most changes need no README edit at all, and adding a section is a deliberate act you must justify. GOOD: `run-tests.sh` gained a required `--profile` flag → update the documented command. BANNED: the change added a test case → add a paragraph describing it. +**"Refresh `README.md` to match" means keep it true, not longer.** A change that alters a build/test/run/deploy step, a required env var, or a prerequisite makes the README a false claim by omission, fixed per "A false claim is a bug". Otherwise most changes need no README edit at all. GOOD: `run-tests.sh` gained a required `--profile` flag → update the documented command. BANNED: the change added a test case → add a paragraph describing it. + +### Decisions: one home, linked to a goal + +**A decision record owns what a call site may not say.** A rejected alternative, or what something deliberately does not cover, is banned beside the code precisely because the decision record holds it — a standing choice a future reader would otherwise relitigate, where a `CHANGELOG` holds what changed in a release. **The decision log has one home: `docs/decisions.md`**, or `docs/decisions/` split by area once it outgrows one file. `AGENTS.md` carries a one-line index of the titles, so a session or a reviewer sees that a decision exists without loading its reasoning. An entry states the decision, its date, who made it, and the premise it rests on ("valid while X") so it can expire honestly when that premise dies. A decision found anywhere else — an `AGENTS.md` body, a comment, or a README section that is neither a goal nor how one is met — moves there and leaves its index line behind. A goal stays a goal in the README; the log records only what the goal leaves open. + +**Every decision links to a goal or a technical principle.** An entry names the goal it serves or the technical principle under `~/.claude/principles/` it applies; one that can do neither is a missing goal, and an entry already in the repo with neither behind it is a finding. Propose the goal, never a reason of your own — the ask rule above says how. An entry working against a goal or a technical principle stands only while it names the `todo.md` item that ends it. + +### Links and pointers + +**Link, don't inline — and keep the link bare.** A mechanism identical across call sites or repos is documented once in the canonical source and pointed at with a one-line bare link. Don't summarize what's behind the link or restate the identifier's own name. + +**A pointer is not a definition.** A definition the reader needs to follow the code — what a unit counts, what a term means, what invariant a cache rests on — sits at the code in one line. A pointer to it (`see AGENTS.md §11`) cannot be checked against the code beside it, so it rots invisibly. A pointer carrying rationale — a rejected alternative, the premise behind a standing choice — is correct and stays. + +### Negation, history and limitations: name the action, or say nothing + +Prose describing the code as it stands — a comment, a README, an `AGENTS.md`, an API spec — may narrate what is *not* done (a removed step, a call we don't make, a superseded version `we used to X, now Y`, a limitation) in one shape only: where a reader would otherwise **do** something harmful, and the sentence says what to do instead. GOOD: `wrap a direct ./tests/run.sh to put it under the same lock`. BANNED: `run.sh takes no host lock`. A limitation with nothing to do instead belongs in the PR or ticket, because **documenting a limitation is not fixing it**. ### Package README (what someone finds on npm or GitHub) - The public API is the contract, so the README documents it: options, results, events, everything exported. The rule against narrating a file or test case still holds. -- Order sections by what a new developer wants first: install, the main task, the next task, and so on. The reference half — options tables, in-depth behaviour, low-level API, development — goes below the quick starts. -- Headline plus short, clear instruction, nothing else. No meta-prose ("things to keep in mind", "you may want to know"). An intro is a line or two that points at the in-depth section. +- Order: install, the main task, the next task, and so on. The reference half — options tables, in-depth behaviour, low-level API, development — goes below the quick starts. - Keep every documented behaviour, as terse facts, bullets and tables rather than paragraphs. Where the README is the only record of a behaviour, cutting it is a decision to ask about, not a tidy-up. -- Write for the app developer using the package; gloss a domain term once, on first use. +- Write for the app developer using the package. - Top: badges (package version, CI), a one-line tagline that is also the package manifest's description, a feature list, a one-line table of contents. Near the bottom: a table of everything exported. - A guide for migrating from an older major goes in `MIGRATION.md`, linked from one line in the README. -- 2.52.0 From 40cd9cebf3070c5bd1f28919449f852e78abc0b3 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 19:42:14 +0200 Subject: [PATCH 183/233] Answer the docs-section review's first round --- CLAUDE.md | 32 +++++++++++++++----------------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index a0c57975..20a29471 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -36,8 +36,6 @@ Everything written — chat, commit messages, comments, docs, code — is in **E ## Comments and documentation (`README.md`, `AGENTS.md`, `docs/`, API specs) -"Prose" above applies to all of it. These rules are special to writing that sits beside code. - ### What earns a place The reader is a competent reader of THIS codebase. A comment or a paragraph earns its place by saying what that reader could not infer and the repo cannot say for itself: a surprising WHY, a footgun, an invariant, an external constraint. Fix a redundant one by deleting it, never by trimming it: two copies drift, and the doc copy is the one nobody updates. GOOD: `// Loud-fail: missing amount used to coerce to '0' = phantom "0 SEK reversal" in api-4.` — records a past prod bug the code can't show. @@ -58,19 +56,11 @@ Default to NO comment. Delete one that is any of: **What stays is one terse line, and only where the code cannot show it.** GOOD: `# Pinned to 7.x: hurl 8's jsonpath change breaks the nth-filter asserts.` A second line belongs in the commit message or the ticket. The one exception is a paragraph for an invariant a reader must hold before touching the code below; it stays with the code it guards. -**Density is a review signal.** Prose comment lines much past ~10% of a file's non-blank lines mean something is wrong — narrating comments, or code that fails to carry its own meaning. A defect to investigate, not a style preference. +**Density is a review signal.** Prose comment lines much past ~10% of a file's non-blank lines mean something is wrong — narrating comments, or code that fails to carry its own meaning. A defect to investigate. -### README +### Negation, history and limitations: name the action, or say nothing -**A README covers what a reader needs *before* opening the code**: how it meets its goals, how to build, test, run, and deploy it, and cross-cutting decisions no single file owns. It does **not** narrate an individual symbol, file, or test case — whoever wants to know what a test asserts opens the test, where the answer is exact and cannot drift. - -**"Refresh `README.md` to match" means keep it true, not longer.** A change that alters a build/test/run/deploy step, a required env var, or a prerequisite makes the README a false claim by omission, fixed per "A false claim is a bug". Otherwise most changes need no README edit at all. GOOD: `run-tests.sh` gained a required `--profile` flag → update the documented command. BANNED: the change added a test case → add a paragraph describing it. - -### Decisions: one home, linked to a goal - -**A decision record owns what a call site may not say.** A rejected alternative, or what something deliberately does not cover, is banned beside the code precisely because the decision record holds it — a standing choice a future reader would otherwise relitigate, where a `CHANGELOG` holds what changed in a release. **The decision log has one home: `docs/decisions.md`**, or `docs/decisions/` split by area once it outgrows one file. `AGENTS.md` carries a one-line index of the titles, so a session or a reviewer sees that a decision exists without loading its reasoning. An entry states the decision, its date, who made it, and the premise it rests on ("valid while X") so it can expire honestly when that premise dies. A decision found anywhere else — an `AGENTS.md` body, a comment, or a README section that is neither a goal nor how one is met — moves there and leaves its index line behind. A goal stays a goal in the README; the log records only what the goal leaves open. - -**Every decision links to a goal or a technical principle.** An entry names the goal it serves or the technical principle under `~/.claude/principles/` it applies; one that can do neither is a missing goal, and an entry already in the repo with neither behind it is a finding. Propose the goal, never a reason of your own — the ask rule above says how. An entry working against a goal or a technical principle stands only while it names the `todo.md` item that ends it. +Prose describing the code as it stands — a comment, a README, an `AGENTS.md`, an API spec — may narrate what is *not* done (a removed step, a call we don't make, a superseded version `we used to X, now Y`, a limitation) in one shape only: where a reader would otherwise **do** something harmful, and the sentence says what to do instead. GOOD: `wrap a direct ./tests/run.sh to put it under the same lock`. BANNED: `run.sh takes no host lock`. A limitation with nothing to do instead belongs in the PR or ticket, because **documenting a limitation is not fixing it**. ### Links and pointers @@ -78,14 +68,22 @@ Default to NO comment. Delete one that is any of: **A pointer is not a definition.** A definition the reader needs to follow the code — what a unit counts, what a term means, what invariant a cache rests on — sits at the code in one line. A pointer to it (`see AGENTS.md §11`) cannot be checked against the code beside it, so it rots invisibly. A pointer carrying rationale — a rejected alternative, the premise behind a standing choice — is correct and stays. -### Negation, history and limitations: name the action, or say nothing +### Decisions: one home, each linked to a goal or a technical principle -Prose describing the code as it stands — a comment, a README, an `AGENTS.md`, an API spec — may narrate what is *not* done (a removed step, a call we don't make, a superseded version `we used to X, now Y`, a limitation) in one shape only: where a reader would otherwise **do** something harmful, and the sentence says what to do instead. GOOD: `wrap a direct ./tests/run.sh to put it under the same lock`. BANNED: `run.sh takes no host lock`. A limitation with nothing to do instead belongs in the PR or ticket, because **documenting a limitation is not fixing it**. +**A decision record owns what a call site may not say.** A rejected alternative, or what something deliberately does not cover, is banned beside the code precisely because the decision record holds it — a standing choice a future reader would otherwise relitigate, where a `CHANGELOG` holds what changed in a release. **The decision log has one home: `docs/decisions.md`**, or `docs/decisions/` split by area once it outgrows one file. `AGENTS.md` carries a one-line index of the titles, so a session or a reviewer sees that a decision exists without loading its reasoning. An entry states the decision, its date, who made it, and the premise it rests on ("valid while X") so it can expire honestly when that premise dies. A decision found anywhere else — an `AGENTS.md` body, a comment, or a README section that is neither a goal nor how one is met — moves there and leaves its index line behind. A goal stays a goal in the README; the log records only what the goal leaves open. + +**Every decision links to a goal or a technical principle.** An entry names the goal it serves or the technical principle under `~/.claude/principles/` it applies; one that can do neither is a missing goal, and an entry already in the repo with neither behind it is a finding. Propose the goal, never a reason of your own — "Ask, don't guess" under "Working loop" says how. An entry working against a goal or a technical principle stands only while it names the `todo.md` item that ends it. + +### README + +**A README covers what a reader needs *before* opening the code**: how it meets its goals, how to build, test, run, and deploy it, and cross-cutting decisions no single file owns. It does **not** narrate an individual symbol, file, or test case — whoever wants to know what a test asserts opens the test, where the answer is exact and cannot drift. + +**"Refresh `README.md` to match" means keep it true, not longer.** A change that alters a build/test/run/deploy step, a required env var, or a prerequisite makes the README a false claim by omission, fixed per "A false claim is a bug". Otherwise most changes need no README edit at all. GOOD: `run-tests.sh` gained a required `--profile` flag → update the documented command. BANNED: the change added a test case → add a paragraph describing it. ### Package README (what someone finds on npm or GitHub) - The public API is the contract, so the README documents it: options, results, events, everything exported. The rule against narrating a file or test case still holds. -- Order: install, the main task, the next task, and so on. The reference half — options tables, in-depth behaviour, low-level API, development — goes below the quick starts. -- Keep every documented behaviour, as terse facts, bullets and tables rather than paragraphs. Where the README is the only record of a behaviour, cutting it is a decision to ask about, not a tidy-up. +- Sections, in order: install, the main task, the next task, and so on. The reference half — options tables, in-depth behaviour, low-level API, development — goes below the quick starts. An intro is a line or two that points at the in-depth section. +- Keep every documented behaviour, as facts, bullets and tables rather than paragraphs. Where the README is the only record of a behaviour, cutting it is a decision to ask about, not a tidy-up. - Write for the app developer using the package. - Top: badges (package version, CI), a one-line tagline that is also the package manifest's description, a feature list, a one-line table of contents. Near the bottom: a table of everything exported. - A guide for migrating from an older major goes in `MIGRATION.md`, linked from one line in the README. -- 2.52.0 From 5028936bb4725b4f2f9dcb7d05c538b45862519f Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 19:45:20 +0200 Subject: [PATCH 184/233] Say each quick start's intro links its in-depth section --- CLAUDE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CLAUDE.md b/CLAUDE.md index 20a29471..108864f5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -82,7 +82,7 @@ Prose describing the code as it stands — a comment, a README, an `AGENTS.md`, ### Package README (what someone finds on npm or GitHub) - The public API is the contract, so the README documents it: options, results, events, everything exported. The rule against narrating a file or test case still holds. -- Sections, in order: install, the main task, the next task, and so on. The reference half — options tables, in-depth behaviour, low-level API, development — goes below the quick starts. An intro is a line or two that points at the in-depth section. +- Sections, in order: install, the main task, the next task, and so on. The reference half — options tables, in-depth behaviour, low-level API, development — goes below the quick starts. Each quick start opens with a line or two that links its in-depth section. - Keep every documented behaviour, as facts, bullets and tables rather than paragraphs. Where the README is the only record of a behaviour, cutting it is a decision to ask about, not a tidy-up. - Write for the app developer using the package. - Top: badges (package version, CI), a one-line tagline that is also the package manifest's description, a feature list, a one-line table of contents. Near the bottom: a table of everything exported. -- 2.52.0 From 24273cf1b913ddc3c58292558c9f197af16ccce0 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 19:55:29 +0200 Subject: [PATCH 185/233] Move code style, tests and naming into the technical principles --- CLAUDE.md | 24 +----------------------- principles/technical-principles.md | 18 +++++++++++++++++- todo.md | 2 +- 3 files changed, 19 insertions(+), 25 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 108864f5..fb129650 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -102,29 +102,7 @@ Prose describing the code as it stands — a comment, a README, an `AGENTS.md`, ## Technical principles -The design rules every project follows, compose-not-entangle first: `~/.claude/principles/technical-principles.md`. Read it before designing or reviewing code. - -## Code style -- Reuse before adding. Extend an existing test with an assertion rather than writing a new one. -- Signal failures with a result value carrying an optional error, not by throwing. A function that both returns a result and throws for some inputs has two error channels; collapse to one. Reserve exceptions for truly unrecoverable states at boundaries, never for control flow the caller is meant to handle. -- A cast (`x as Foo`) asserts what the compiler could not check and stops it checking — so when the type later changes, nothing tells you. Derive the real type instead: infer it, name the return type, or parse the input once into a typed shape. Where a value genuinely arrives untyped (HTTP body, `JSON.parse`, DB row), the boundary owes a **type guard validating the fields it claims**; past that boundary everything is typed. `as unknown as T` and non-null `!` are the same defect wearing a hat. BANNED: `const user = body as User` — one rename and it is a silent lie. GOOD: `function isUser(v: unknown): v is User` checking each field, then `if (!isUser(body)) return { error: … }`. -- Keep delivery-layer entrypoints thin: inject services, validate + hand off the request data, map the service's return to a response. Domain decisions and branching belong in the service layer — an entrypoint reaching into a payload to decide *what to do* is the smell. BANNED: `if (body.tx.source === 'notification') { /* drop, skip enqueue */ }` in a route handler. GOOD: the entrypoint forwards `source` on the event → the service decides drop-vs-process and returns a result → the entrypoint maps that result to a status code. -- DTOs, enums, and value objects are pure data — no logic. They stand in for the structs/records a language lacks. -- Prefer explicit, descriptive names over generic ones (`invoiceRowsService`, not `service`). -- Prefer a standalone Python script with a `#!/usr/bin/env python3` shebang over a shell script — it runs identically across systems where shell dialects/builtins differ. Read config (credentials, hosts, paths) from CLI params or env vars, never hardcoded. -- Sort wherever order carries no meaning (`~/.claude/principles/technical-principles.md`) — attributes, array and object keys, enum members, imports, table rows, and line-based file lists such as `.gitignore`/`.dockerignore`. Exception: `id` goes first. -- Sort a compound line on the name it introduces, never on an incidental field: an import on its first binding, not its path, so moving or renaming a module reorders nothing. Where lines already group by kind — type imports, host packages — the key sorts within each group. -- Indent with hard tabs by default. A project's own settings win: `.editorconfig`, linter/formatter config (Prettier, `rustfmt.toml`, …), or the surrounding file's existing indentation. - -## Tests -- Write tests first for the behaviour we want, then implement until they pass. -- Changing tests and changing other code are two separate processes — be very careful about doing both at once. -- Use properly randomised UUID v7s — never `aaaa-0000`-style placeholders. -- Tear down test containers after a run. - -## Naming files & folders -- Name by what's inside, not by catch-all. BANNED: `scripts`, `utils`, `helpers`, `misc`, `common`, `lib`, `stuff`. Use explicit names: `e2e-tests/`, `db-migrations/`, `release-tooling/`. -- Group related artifacts by purpose — e2e compose files, e2e Dockerfile, and e2e test scripts all belong in `e2e-tests/`. +The rules every project's code follows, compose-not-entangle first: `~/.claude/principles/technical-principles.md`. Read it before writing, designing or reviewing code. ## Git, commits, and PRs - Never add `Co-Authored-By: Claude ...`, `🤖 Generated with Claude Code`, or any Claude/Anthropic/Agent marker in commits, PR bodies, issue comments, or anywhere else. diff --git a/principles/technical-principles.md b/principles/technical-principles.md index e1f13714..011a8a54 100644 --- a/principles/technical-principles.md +++ b/principles/technical-principles.md @@ -26,31 +26,45 @@ - Allowed, never flag: mutation that never leaves the function that made it; a loop counter; data shared and never written; a state machine with named states and one transition function. * Validate data and build DTOs as early as possible. - For example, parse a form into a strictly typed DTO as the first thing that happens instead of passing strings down to be validated deep inside a service. + - A cast (`x as Foo`) asserts what the compiler could not check and stops it checking — so when the type later changes, nothing tells you. Derive the real type instead: infer it, name the return type, or parse the input once into a typed shape. Where a value genuinely arrives untyped (HTTP body, `JSON.parse`, DB row), the boundary owes a **type guard validating the fields it claims**; past that boundary everything is typed. `as unknown as T` and non-null `!` are the same defect wearing a hat. BANNED: `const user = body as User` — one rename and it is a silent lie. GOOD: `function isUser(v: unknown): v is User` checking each field, then `if (!isUser(body)) return { error: … }`. + - DTOs, enums, and value objects are pure data — no logic. They stand in for the structs/records a language lacks. * Always use explicit state machines. * Most, if not all, code should have automated tests. + - Write tests first for the behaviour we want, then implement until they pass. + - Changing tests and changing other code are two separate processes — be very careful about doing both at once. + - Use properly randomised UUID v7s — never `aaaa-0000`-style placeholders. + - Tear down test containers after a run. * Test coverage should not decline. * Idempotent data writing. - Typical example: `PUT /resource/{id}` instead of `POST /resource` + Idempotent-Id header. * Handle errors explicitly, as values — avoid the exception path. - Enumerate the cases that can go wrong and return them as explicit results (e.g. a result DTO with an optional error), so failure is part of the signature instead of a hidden second channel. - try/catch lives only at the edges, wrapped tightly around the call that can actually throw (DB, HTTP, filesystem), converting the exception into an explicit result right there. Pure functions and core logic never throw or catch for control flow. + - A function that both returns a result and throws for some inputs has two error channels; collapse to one. Exceptions are for truly unrecoverable states at boundaries. * Commands and Queries Separation (CQS)-ish - Queries must never modify data, commands may only return data that is the result of their change. * Copy important contextual information on buisness transactions and equal data, instead of referencing it. - Example set order.client_firstname instead of order.client_id and fetching firstname from the clients table. * Explicit over implicit. - Avoid magic, avoid "clever" solutions, only abstract when the API can clearly describe what is happening. + - Prefer explicit, descriptive names over generic ones (`invoiceRowsService`, not `service`). +* Name files and folders by what is inside. + - BANNED: `scripts`, `utils`, `helpers`, `misc`, `common`, `lib`, `stuff`. GOOD: `e2e-tests/`, `db-migrations/`, `release-tooling/`. + - Group related artifacts by purpose — e2e compose files, e2e Dockerfile, and e2e test scripts all belong in `e2e-tests/`. * Functional core, imperative shell. - Decisions live in pure functions, data in and data out; the shell around them performs the effects and holds no branching of its own. - Every side effect comes from outside: output, time, randomness, network and storage are injectable, so a test runs exactly the code production runs. - BANNED: `new Date(entry.msTimestamp ?? Date.now())` in a formatter; a test swapping `globalThis.fetch`. GOOD: the clock is a parameter, defaulted to the system clock only where the program is wired together. + - Keep delivery-layer entrypoints thin: inject services, validate + hand off the request data, map the service's return to a response. Domain decisions and branching belong in the service layer — an entrypoint reaching into a payload to decide *what to do* is the smell. BANNED: `if (body.tx.source === 'notification') { /* drop, skip enqueue */ }` in a route handler. GOOD: the entrypoint forwards `source` on the event → the service decides drop-vs-process and returns a result → the entrypoint maps that result to a status code. * Deterministic order wherever order carries no meaning. - Sort it, on a key that does not move: the name a line introduces, never where it came from. A sorted list is searchable, its diff shows only what changed, and two edits to it conflict only where they mean to. + - What to sort: attributes, array and object keys, enum members, imports, table rows, and line-based file lists such as `.gitignore`/`.dockerignore`. Exception: `id` goes first. + - An import sorts on its first binding, not its path, so moving or renaming a module reorders nothing. Where lines already group by kind — type imports, host packages — the key sorts within each group. * Keep It Simple, Stupid (KISS). - Keep solutions simple and easy to understand, so it is dead easy to grasp what they do. * Don't Repeat Yourself (DRY): one authoritative home per piece of knowledge, one obvious way per need. - A value, rule, definition or concept lives in one place, and everywhere else derives it from there or points at it. A copy that can drift is a second spelling: derive it from its owner, or, for config a human writes, reject it where it is read and name the owner. - - Before adding a way to do something, find the existing one and use it. Where two spellings serve the same caller for the same need, keep one and reject the other as early as possible — at load, parse or compile — with an error naming the one to use: `token {p} renders a level that {p.first} reads a path into; name the fields you want instead`. + - Before adding a way to do something, find the existing one and use it. The same goes for tests: extend an existing test with an assertion before writing a new one. Where two spellings serve the same caller for the same need, keep one and reject the other as early as possible — at load, parse or compile — with an error naming the one to use: `token {p} renders a level that {p.first} reads a path into; name the fields you want instead`. - Different needs may have different ways. A public API may offer a convenience beside the general form — a one-line call for the common case over the primitive for the rest — where each serves a caller or scenario its docs name, and the convenience is built from the primitive. Code that looks alike but encodes different knowledge is not a second spelling: merging it is the wrong abstraction. - Two spellings that can disagree are a correctness bug, whatever the reason for having both: derive one from the other, or reject the combination. * All critical flows should have good traces, from where something was initiated until it completed. @@ -64,3 +78,5 @@ * Semantic versioning, read strictly: a minor only adds, and a major is the only release that changes what exists. - "Exists" is everything a consumer can depend on, not just signatures: an added output column, a removed list value, a changed default, the facts an error names, a dropped runtime version. A consumer takes a minor without editing code, data or scripts. - Batch breaking changes into few majors. Before 1.0.0 the minor is the breaking unit and a patch never breaks. +* Prefer a standalone Python script with a `#!/usr/bin/env python3` shebang over a shell script — it runs identically across systems where shell dialects/builtins differ. Read config (credentials, hosts, paths) from CLI params or env vars, never hardcoded. +* Indent with hard tabs by default. A project's own settings win: `.editorconfig`, linter/formatter config (Prettier, `rustfmt.toml`, …), or the surrounding file's existing indentation. diff --git a/todo.md b/todo.md index 995f6b10..d4e34bfa 100644 --- a/todo.md +++ b/todo.md @@ -11,7 +11,7 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens ## 0.2.0 -- **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. +- **Sort `bin/`'s imports on their first binding, per `principles/technical-principles.md` → "Deterministic order".** Today they sort by path, so a module move reorders unchanged lines; the rule does not say how case sorts, and "host packages" names no Python group. - **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. - **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.** -- 2.52.0 From bd0a057f3943bfcaf838239b89bbdee69145cb9e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 20:00:09 +0200 Subject: [PATCH 186/233] Answer the move review's first round --- CLAUDE.md | 2 +- principles/technical-principles.md | 17 ++++++++++------- todo.md | 2 +- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index fb129650..8fe23598 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -102,7 +102,7 @@ Prose describing the code as it stands — a comment, a README, an `AGENTS.md`, ## Technical principles -The rules every project's code follows, compose-not-entangle first: `~/.claude/principles/technical-principles.md`. Read it before writing, designing or reviewing code. +The rules every project follows, compose-not-entangle first: `~/.claude/principles/technical-principles.md`. Read it before writing, designing or reviewing code. ## Git, commits, and PRs - Never add `Co-Authored-By: Claude ...`, `🤖 Generated with Claude Code`, or any Claude/Anthropic/Agent marker in commits, PR bodies, issue comments, or anywhere else. diff --git a/principles/technical-principles.md b/principles/technical-principles.md index 011a8a54..a7565135 100644 --- a/principles/technical-principles.md +++ b/principles/technical-principles.md @@ -40,22 +40,22 @@ * Handle errors explicitly, as values — avoid the exception path. - Enumerate the cases that can go wrong and return them as explicit results (e.g. a result DTO with an optional error), so failure is part of the signature instead of a hidden second channel. - try/catch lives only at the edges, wrapped tightly around the call that can actually throw (DB, HTTP, filesystem), converting the exception into an explicit result right there. Pure functions and core logic never throw or catch for control flow. - - A function that both returns a result and throws for some inputs has two error channels; collapse to one. Exceptions are for truly unrecoverable states at boundaries. + - A function that both returns a result and throws for some inputs has two error channels; collapse to one. Throw only for a truly unrecoverable state. * Commands and Queries Separation (CQS)-ish - Queries must never modify data, commands may only return data that is the result of their change. * Copy important contextual information on buisness transactions and equal data, instead of referencing it. - Example set order.client_firstname instead of order.client_id and fetching firstname from the clients table. * Explicit over implicit. - Avoid magic, avoid "clever" solutions, only abstract when the API can clearly describe what is happening. - - Prefer explicit, descriptive names over generic ones (`invoiceRowsService`, not `service`). -* Name files and folders by what is inside. - - BANNED: `scripts`, `utils`, `helpers`, `misc`, `common`, `lib`, `stuff`. GOOD: `e2e-tests/`, `db-migrations/`, `release-tooling/`. +* Name things by what they are. + - Identifiers: prefer explicit, descriptive names over generic ones (`invoiceRowsService`, not `service`). + - Files and folders: name by what is inside. BANNED: `scripts`, `utils`, `helpers`, `misc`, `common`, `lib`, `stuff`. GOOD: `e2e-tests/`, `db-migrations/`, `release-tooling/`. - Group related artifacts by purpose — e2e compose files, e2e Dockerfile, and e2e test scripts all belong in `e2e-tests/`. * Functional core, imperative shell. - Decisions live in pure functions, data in and data out; the shell around them performs the effects and holds no branching of its own. - Every side effect comes from outside: output, time, randomness, network and storage are injectable, so a test runs exactly the code production runs. - BANNED: `new Date(entry.msTimestamp ?? Date.now())` in a formatter; a test swapping `globalThis.fetch`. GOOD: the clock is a parameter, defaulted to the system clock only where the program is wired together. - - Keep delivery-layer entrypoints thin: inject services, validate + hand off the request data, map the service's return to a response. Domain decisions and branching belong in the service layer — an entrypoint reaching into a payload to decide *what to do* is the smell. BANNED: `if (body.tx.source === 'notification') { /* drop, skip enqueue */ }` in a route handler. GOOD: the entrypoint forwards `source` on the event → the service decides drop-vs-process and returns a result → the entrypoint maps that result to a status code. + - Keep delivery-layer entrypoints thin: inject services, validate + hand off the request data, map the service's return to a response. An entrypoint reaching into a payload to decide *what to do* is the smell. BANNED: `if (body.tx.source === 'notification') { /* drop, skip enqueue */ }` in a route handler. GOOD: the entrypoint forwards `source` on the event → the service decides drop-vs-process and returns a result → the entrypoint maps that result to a status code. * Deterministic order wherever order carries no meaning. - Sort it, on a key that does not move: the name a line introduces, never where it came from. A sorted list is searchable, its diff shows only what changed, and two edits to it conflict only where they mean to. - What to sort: attributes, array and object keys, enum members, imports, table rows, and line-based file lists such as `.gitignore`/`.dockerignore`. Exception: `id` goes first. @@ -78,5 +78,8 @@ * Semantic versioning, read strictly: a minor only adds, and a major is the only release that changes what exists. - "Exists" is everything a consumer can depend on, not just signatures: an added output column, a removed list value, a changed default, the facts an error names, a dropped runtime version. A consumer takes a minor without editing code, data or scripts. - Batch breaking changes into few majors. Before 1.0.0 the minor is the breaking unit and a patch never breaks. -* Prefer a standalone Python script with a `#!/usr/bin/env python3` shebang over a shell script — it runs identically across systems where shell dialects/builtins differ. Read config (credentials, hosts, paths) from CLI params or env vars, never hardcoded. -* Indent with hard tabs by default. A project's own settings win: `.editorconfig`, linter/formatter config (Prettier, `rustfmt.toml`, …), or the surrounding file's existing indentation. +* Scripts are standalone Python. + - A Python script with a `#!/usr/bin/env python3` shebang runs identically across systems where shell dialects and builtins differ. + - Read config (credentials, hosts, paths) from CLI params or env vars, never hardcoded. +* Indent with hard tabs by default. + - A project's own settings win: `.editorconfig`, linter/formatter config (Prettier, `rustfmt.toml`, …), or the surrounding file's existing indentation. diff --git a/todo.md b/todo.md index d4e34bfa..5a9b1c19 100644 --- a/todo.md +++ b/todo.md @@ -11,7 +11,7 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens ## 0.2.0 -- **Sort `bin/`'s imports on their first binding, per `principles/technical-principles.md` → "Deterministic order".** Today they sort by path, so a module move reorders unchanged lines; the rule does not say how case sorts, and "host packages" names no Python group. +- **Sort `bin/`'s imports on their first binding, and say in `principles/technical-principles.md` → "Deterministic order" how case sorts and which groups Python has.** Today they sort by path, so a module move reorders unchanged lines; "host packages" names no Python group. - **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. - **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.** -- 2.52.0 From 9aed8cddcfc5ef5db3e05b297f97392a5aee2fe4 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 20:00:49 +0200 Subject: [PATCH 187/233] Keep Python over shell a preference --- principles/technical-principles.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/principles/technical-principles.md b/principles/technical-principles.md index a7565135..94b26707 100644 --- a/principles/technical-principles.md +++ b/principles/technical-principles.md @@ -78,7 +78,7 @@ * Semantic versioning, read strictly: a minor only adds, and a major is the only release that changes what exists. - "Exists" is everything a consumer can depend on, not just signatures: an added output column, a removed list value, a changed default, the facts an error names, a dropped runtime version. A consumer takes a minor without editing code, data or scripts. - Batch breaking changes into few majors. Before 1.0.0 the minor is the breaking unit and a patch never breaks. -* Scripts are standalone Python. +* Prefer a standalone Python script over a shell script. - A Python script with a `#!/usr/bin/env python3` shebang runs identically across systems where shell dialects and builtins differ. - Read config (credentials, hosts, paths) from CLI params or env vars, never hardcoded. * Indent with hard tabs by default. -- 2.52.0 From 75feeb8a1a9118fefcb2c2e67c90c7f3e133aa6a Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 20:04:27 +0200 Subject: [PATCH 188/233] Move the rules that reach past code back to CLAUDE.md --- CLAUDE.md | 6 ++++++ principles/technical-principles.md | 7 +------ 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 8fe23598..f141a5f4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -96,10 +96,16 @@ Prose describing the code as it stands — a comment, a README, an `AGENTS.md`, - Always start a new git worktree when doing something in a codebase, and clean it up when done. Unless told otherwise, branch it off a freshly-updated default branch (`git fetch origin`, then base on `origin/main`), not whatever happens to be checked out. - Keep the project's main checkout (e.g. `~/code/log`, never a worktree) current: when it is behind `origin` — a merge landed, or a fetch shows it — run `git pull --ff-only` there instead of reporting the lag, never with `--autostash`: a dirty checkout is a finding to report, not to carry along. - Run a project's language runtime, package manager, and task runner through its container/tooling setup, never directly on the host. Example: `docker compose run --rm app …`. +- Tear down test containers after a run. - Check `README.md` first for build, test, install, and codegen commands; one that misbehaves is fixed per "A false claim is a bug". Refresh `README.md` whenever you change what it describes ("Refresh `README.md` to match"). +- Sort wherever order carries no meaning (`~/.claude/principles/technical-principles.md`) — attributes, array and object keys, enum members, imports, table rows, and line-based file lists such as `.gitignore`/`.dockerignore`. Exception: `id` goes first. - Pin GitHub Actions to semver tags (`@v3`, `@v3.1.2`), not commit SHAs — including third-party actions. SHA-pin only in special pipelines that test our own specific builds. - Pin container images to the **full patch version** everywhere they're referenced — Dockerfile `FROM`, compose `image:`, base images in test fixtures: `node:24.18.1-bookworm-slim`, `mysql:8.4.7`, `alpine:3.23.3`. Never a floating major or minor (`node:24`, `node:24.18`, `:latest`, `:lts`): the same commit then builds a different image on different days, so a green pipeline says nothing about the next run, a base change lands with no diff to review, and any size or performance figure measured against it silently goes stale. Let a bot (Renovate/Dependabot) raise the bumps as reviewable PRs — that is where a base change belongs. (Actions are the exception above: a semver tag is fine there, because the action's own release is the reviewable unit.) +## Naming files & folders +- Name by what's inside, not by catch-all. BANNED: `scripts`, `utils`, `helpers`, `misc`, `common`, `lib`, `stuff`. Use explicit names: `e2e-tests/`, `db-migrations/`, `release-tooling/`. +- Group related artifacts by purpose — e2e compose files, e2e Dockerfile, and e2e test scripts all belong in `e2e-tests/`. + ## Technical principles The rules every project follows, compose-not-entangle first: `~/.claude/principles/technical-principles.md`. Read it before writing, designing or reviewing code. diff --git a/principles/technical-principles.md b/principles/technical-principles.md index 94b26707..c767b237 100644 --- a/principles/technical-principles.md +++ b/principles/technical-principles.md @@ -33,7 +33,6 @@ - Write tests first for the behaviour we want, then implement until they pass. - Changing tests and changing other code are two separate processes — be very careful about doing both at once. - Use properly randomised UUID v7s — never `aaaa-0000`-style placeholders. - - Tear down test containers after a run. * Test coverage should not decline. * Idempotent data writing. - Typical example: `PUT /resource/{id}` instead of `POST /resource` + Idempotent-Id header. @@ -47,10 +46,7 @@ - Example set order.client_firstname instead of order.client_id and fetching firstname from the clients table. * Explicit over implicit. - Avoid magic, avoid "clever" solutions, only abstract when the API can clearly describe what is happening. -* Name things by what they are. - - Identifiers: prefer explicit, descriptive names over generic ones (`invoiceRowsService`, not `service`). - - Files and folders: name by what is inside. BANNED: `scripts`, `utils`, `helpers`, `misc`, `common`, `lib`, `stuff`. GOOD: `e2e-tests/`, `db-migrations/`, `release-tooling/`. - - Group related artifacts by purpose — e2e compose files, e2e Dockerfile, and e2e test scripts all belong in `e2e-tests/`. + - Prefer explicit, descriptive names over generic ones (`invoiceRowsService`, not `service`). * Functional core, imperative shell. - Decisions live in pure functions, data in and data out; the shell around them performs the effects and holds no branching of its own. - Every side effect comes from outside: output, time, randomness, network and storage are injectable, so a test runs exactly the code production runs. @@ -58,7 +54,6 @@ - Keep delivery-layer entrypoints thin: inject services, validate + hand off the request data, map the service's return to a response. An entrypoint reaching into a payload to decide *what to do* is the smell. BANNED: `if (body.tx.source === 'notification') { /* drop, skip enqueue */ }` in a route handler. GOOD: the entrypoint forwards `source` on the event → the service decides drop-vs-process and returns a result → the entrypoint maps that result to a status code. * Deterministic order wherever order carries no meaning. - Sort it, on a key that does not move: the name a line introduces, never where it came from. A sorted list is searchable, its diff shows only what changed, and two edits to it conflict only where they mean to. - - What to sort: attributes, array and object keys, enum members, imports, table rows, and line-based file lists such as `.gitignore`/`.dockerignore`. Exception: `id` goes first. - An import sorts on its first binding, not its path, so moving or renaming a module reorders nothing. Where lines already group by kind — type imports, host packages — the key sorts within each group. * Keep It Simple, Stupid (KISS). - Keep solutions simple and easy to understand, so it is dead easy to grasp what they do. -- 2.52.0 From 54ec5288163f8091eeb111846a5b21b5edf2ccce Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 20:08:25 +0200 Subject: [PATCH 189/233] Cut the naming rule's contrastive tail --- CLAUDE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CLAUDE.md b/CLAUDE.md index f141a5f4..98bbaa19 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -103,7 +103,7 @@ Prose describing the code as it stands — a comment, a README, an `AGENTS.md`, - Pin container images to the **full patch version** everywhere they're referenced — Dockerfile `FROM`, compose `image:`, base images in test fixtures: `node:24.18.1-bookworm-slim`, `mysql:8.4.7`, `alpine:3.23.3`. Never a floating major or minor (`node:24`, `node:24.18`, `:latest`, `:lts`): the same commit then builds a different image on different days, so a green pipeline says nothing about the next run, a base change lands with no diff to review, and any size or performance figure measured against it silently goes stale. Let a bot (Renovate/Dependabot) raise the bumps as reviewable PRs — that is where a base change belongs. (Actions are the exception above: a semver tag is fine there, because the action's own release is the reviewable unit.) ## Naming files & folders -- Name by what's inside, not by catch-all. BANNED: `scripts`, `utils`, `helpers`, `misc`, `common`, `lib`, `stuff`. Use explicit names: `e2e-tests/`, `db-migrations/`, `release-tooling/`. +- Name by what's inside. BANNED: `scripts`, `utils`, `helpers`, `misc`, `common`, `lib`, `stuff`. GOOD: `e2e-tests/`, `db-migrations/`, `release-tooling/`. - Group related artifacts by purpose — e2e compose files, e2e Dockerfile, and e2e test scripts all belong in `e2e-tests/`. ## Technical principles -- 2.52.0 From 6276ce2d04049912551a48b1d8b9239f9698c3a5 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 20:32:03 +0200 Subject: [PATCH 190/233] Give goal 4 its sub-goals, and define quality --- CLAUDE.md | 9 +++++++++ README.md | 7 ++++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/CLAUDE.md b/CLAUDE.md index 98bbaa19..c073d7f3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -22,6 +22,15 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The - Open each item with a bold one-sentence tagline, so the taglines alone say what a release holds; detail follows it. The tagline states the target state, checkable when done: an imperative verb plus what holds afterwards. A present-tense fact reads as the current state and says nothing about what to do. Add "today X" only where the direction is otherwise ambiguous. GOOD: `**Accept undefined in MetadataValue and drop such keys on output.**` BANNED: `MetadataValue accepts undefined; such keys are dropped on output`. - A security finding — a leaked credential, secret or PII, an auth bypass, an injection — is filed the moment it is found, at the top of the list under its own `## Security` heading, naming the exposure and the path it reaches. Never among additive or nice-to-have items, never only in a chunk's summary, and never as a question about where it belongs: file it, say you did, and I will move it down if I disagree. Fixing it inside an unrelated change is a separate call — say whether it is in the blast radius. +## Quality + +Quality is proven by review, never assumed. Every change is reviewed as a diff. The whole project is measured on bigger changes and before each release, because a project can drift from the principles one clean diff at a time; `larv-review` §3 says which review runs when. Quality has four parts. When two pull against each other, the earlier one wins. + +1. **Correct.** It does what the goals and the plan say, and tests prove it. +2. **True to the technical principles** (`~/.claude/principles/technical-principles.md`). +3. **Easy to comprehend.** A reader new to the project understands it. The `comprehension-panel` skill scores it; its floor blocks a merge, and the aim is always above the floor. +4. **Plainly written.** Docs, comments and plans meet "Prose". + ## Prose Everything written — chat, commit messages, comments, docs, code — is in **English**. Prose meets four priorities, in this order. When two pull against each other, the higher one wins. diff --git a/README.md b/README.md index 31115fc2..3fe071c9 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,12 @@ My personal `~/.claude`, version controlled: `CLAUDE.md` and `AGENTS.md` for ins 1. Make my claude setup shareable between computers. 2. Keep my claude setup and the transcripts of unattended runs, backed up. 3. Leak nothing to the remote — no credentials, no transcripts, no memory files. -4. Supply tools like agents, skills and scripts to make working with claude code more effective and with less interruptions. +4. Get proven, stellar quality out of Claude Code with the fewest interruptions of me, so development scales. + 1. Proven stellar output quality: code, documentation and plans. + 2. Decide by the goals when confident; ask me when not, and never the same thing twice. + 3. The same rules in every project and every session. + 4. Add cost only where it meaningfully raises quality; otherwise lower it. + 5. Delivery speed. ## Audience -- 2.52.0 From 3f700d84647462b19d307aca63cf9b8001e10415 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 20:35:54 +0200 Subject: [PATCH 191/233] Answer the goal review's first round --- CLAUDE.md | 8 ++++---- README.md | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index c073d7f3..0ee54e6a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -24,12 +24,12 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The ## Quality -Quality is proven by review, never assumed. Every change is reviewed as a diff. The whole project is measured on bigger changes and before each release, because a project can drift from the principles one clean diff at a time; `larv-review` §3 says which review runs when. Quality has four parts. When two pull against each other, the earlier one wins. +Quality is proven by review. Every change is reviewed as a diff. The whole project is measured when a change carries an architectural decision, and before each release, because a project can drift from the principles one clean diff at a time. `larv-review` §3 says which review runs when. Quality has four parts. When two pull against each other, the earlier one wins. -1. **Correct.** It does what the goals and the plan say, and tests prove it. +1. **Correct.** The work does what the goals and the plan say, and tests prove it. 2. **True to the technical principles** (`~/.claude/principles/technical-principles.md`). -3. **Easy to comprehend.** A reader new to the project understands it. The `comprehension-panel` skill scores it; its floor blocks a merge, and the aim is always above the floor. -4. **Plainly written.** Docs, comments and plans meet "Prose". +3. **Easy to comprehend.** A reader new to the project understands it. The `comprehension-panel` skill scores the project; a score under the comprehension floor (`larv-review` §3 → "Architecture") blocks a merge, and the aim is always higher. +4. **Plainly written**, per "Prose". ## Prose diff --git a/README.md b/README.md index 3fe071c9..82e84fdf 100644 --- a/README.md +++ b/README.md @@ -7,11 +7,11 @@ My personal `~/.claude`, version controlled: `CLAUDE.md` and `AGENTS.md` for ins 1. Make my claude setup shareable between computers. 2. Keep my claude setup and the transcripts of unattended runs, backed up. 3. Leak nothing to the remote — no credentials, no transcripts, no memory files. -4. Get proven, stellar quality out of Claude Code with the fewest interruptions of me, so development scales. - 1. Proven stellar output quality: code, documentation and plans. - 2. Decide by the goals when confident; ask me when not, and never the same thing twice. +4. Get the highest-quality planning and code out of Claude Code while interrupting me the least, so development scales. + 1. Proven, stellar output quality: code, documentation and plans. + 2. Decide by the project's goals when confident; ask me when not, and never the same thing twice. 3. The same rules in every project and every session. - 4. Add cost only where it meaningfully raises quality; otherwise lower it. + 4. Add cost only where it meaningfully raises quality; otherwise work to lower cost. 5. Delivery speed. ## Audience -- 2.52.0 From 9854df34490dbd1a8ffd02e156d53b469366891f Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 20:53:55 +0200 Subject: [PATCH 192/233] Cut the list from goal 4's headline --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 82e84fdf..1750f014 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ My personal `~/.claude`, version controlled: `CLAUDE.md` and `AGENTS.md` for ins 1. Make my claude setup shareable between computers. 2. Keep my claude setup and the transcripts of unattended runs, backed up. 3. Leak nothing to the remote — no credentials, no transcripts, no memory files. -4. Get the highest-quality planning and code out of Claude Code while interrupting me the least, so development scales. +4. Get the highest quality out of Claude Code while interrupting me the least, so development scales. 1. Proven, stellar output quality: code, documentation and plans. 2. Decide by the project's goals when confident; ask me when not, and never the same thing twice. 3. The same rules in every project and every session. -- 2.52.0 From 37ace9d16971e098d0527d6693f14f5d79754546 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 20:55:29 +0200 Subject: [PATCH 193/233] Plan chunk statistics and a per-release workflow review --- AGENTS.md | 1 + docs/decisions.md | 4 ++++ todo.md | 3 +++ 3 files changed, 8 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index c0cb7139..dfd95160 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -31,3 +31,4 @@ Decisions live in `docs/decisions.md`: - review: an ask no user answers leaves the PR unmerged - review: the architecture pass audits every principle and goal over the whole project, and a release's last chunk fires it - loop-claude: every claude it starts bypasses permissions inside its sandbox +- stats: a chunk's cost and review numbers are kept beside the transcript archive diff --git a/docs/decisions.md b/docs/decisions.md index cbd3c56e..83688c75 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -107,3 +107,7 @@ ## loop-claude: every claude it starts bypasses permissions inside its sandbox 2026-09-30, lilleman. Applies "Always grant explicit access to data": the sandbox `loop-claude` runs in is where access is granted, so the worker and the interrupt run with `bypassPermissions`. The worker may read `~/.claude/.credentials.json`: it holds Claude Code's own credentials, which claude reads to run anyway. Its one seam to production is the forge: what it pushes or merges can publish through CI. Valid while `loop-claude` runs only in the sandbox README → Install names. + +## stats: a chunk's cost and review numbers are kept beside the transcript archive + +2026-10-01, lilleman. Serves goals 3 and 4.4. The numbers show whether a change to the workflow raised quality or only cost; they name other projects and their work, so they stay off this repo's remote. `loop-claude` writes what the transcript holds, and larv-review adds the review's numbers. Valid while the transcript archive stays off the remote. diff --git a/todo.md b/todo.md index 5a9b1c19..1ccac411 100644 --- a/todo.md +++ b/todo.md @@ -35,3 +35,6 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens - **Archive the transcript as each cycle ends, so a failed exit or Ctrl-C loses nothing.** Today only an interrupt or a finish archives, against goal 2. - **Key a project on its checkout's full path — its session, archive folder and models entry — and refuse to start while another session on that id is active.** `checkout.py:22` drops the leading `/`, so `~/code/a` and `/a` share a session, an archive folder and a models entry, and one loop can resume or delete the other's session. - **Move what `loop-claude` writes out of `~/.claude.json`, and bring each case that must stay to the human.** Claude Code owns and writes that file, and `trust`'s read-modify-write loses a write landing in its window. +- **Have `loop-claude` write one stats line per finished chunk, beside the transcript archive.** The line names the project and the chunk, and holds what the transcript and the verdicts already record: tokens for the worker and the judge, cycles, and interrupts. +- **End larv-review with a machine-readable summary, and add it to the chunk's stats line.** Agents launched and rounds per pass, findings per pass by severity, and the comprehension scores when the panel ran. +- **Review the workflow from the stats at each release, and file each change it proposes as a plan item.** The signals to read: findings the whole-project passes make in code a diff review passed, comprehension scores per release, fixes after merge, and the human's corrections. -- 2.52.0 From 095685effcd3240a3de1046ebb068636e6b3d325 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 20:55:44 +0200 Subject: [PATCH 194/233] Plan benching one chunk in ten against a pending workflow change --- todo.md | 1 + 1 file changed, 1 insertion(+) diff --git a/todo.md b/todo.md index 1ccac411..cc37c584 100644 --- a/todo.md +++ b/todo.md @@ -38,3 +38,4 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens - **Have `loop-claude` write one stats line per finished chunk, beside the transcript archive.** The line names the project and the chunk, and holds what the transcript and the verdicts already record: tokens for the worker and the judge, cycles, and interrupts. - **End larv-review with a machine-readable summary, and add it to the chunk's stats line.** Agents launched and rounds per pass, findings per pass by severity, and the comprehension scores when the panel ran. - **Review the workflow from the stats at each release, and file each change it proposes as a plan item.** The signals to read: findings the whole-project passes make in code a diff review passed, comprehension scores per release, fixes after merge, and the human's corrections. +- **Bench about one chunk in ten: redo it from its base commit under a pending change to the workflow, and have a blind judge rule which outcome serves the goals better.** `loop-claude` picks the chunk at random, small diffs and big ones alike. The ruling and both runs' numbers go on the chunk's stats line, and a workflow change merges once its benches rule it at least as good. Start from the 2026-09-30 bench's scripts: `~/code/claude-handoffs/claude-config/2026-09-30/bench/`. -- 2.52.0 From cfee4515af1cf90cce908dd445d27e7b3e5c1582 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 20:59:51 +0200 Subject: [PATCH 195/233] Answer the stats-plan review's first round --- AGENTS.md | 2 +- docs/decisions.md | 4 ++-- todo.md | 8 ++++---- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index dfd95160..4e315081 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -31,4 +31,4 @@ Decisions live in `docs/decisions.md`: - review: an ask no user answers leaves the PR unmerged - review: the architecture pass audits every principle and goal over the whole project, and a release's last chunk fires it - loop-claude: every claude it starts bypasses permissions inside its sandbox -- stats: a chunk's cost and review numbers are kept beside the transcript archive +- stats: a chunk's cost and review numbers are kept in the transcript archive diff --git a/docs/decisions.md b/docs/decisions.md index 83688c75..593cddfb 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -108,6 +108,6 @@ 2026-09-30, lilleman. Applies "Always grant explicit access to data": the sandbox `loop-claude` runs in is where access is granted, so the worker and the interrupt run with `bypassPermissions`. The worker may read `~/.claude/.credentials.json`: it holds Claude Code's own credentials, which claude reads to run anyway. Its one seam to production is the forge: what it pushes or merges can publish through CI. Valid while `loop-claude` runs only in the sandbox README → Install names. -## stats: a chunk's cost and review numbers are kept beside the transcript archive +## stats: a chunk's cost and review numbers are kept in the transcript archive -2026-10-01, lilleman. Serves goals 3 and 4.4. The numbers show whether a change to the workflow raised quality or only cost; they name other projects and their work, so they stay off this repo's remote. `loop-claude` writes what the transcript holds, and larv-review adds the review's numbers. Valid while the transcript archive stays off the remote. +2026-10-01, lilleman. Serves goals 3 and 4.4. The numbers show whether a change to the workflow raised quality or only cost. Each line names another project and its chunk, so the file stays off this repo's remote. `loop-claude` writes the line: the tokens, cycles and interrupts it counts, and the review's numbers from the summary larv-review ends with. Valid while the transcript archive stays off the remote. diff --git a/todo.md b/todo.md index cc37c584..f30ad3d8 100644 --- a/todo.md +++ b/todo.md @@ -35,7 +35,7 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens - **Archive the transcript as each cycle ends, so a failed exit or Ctrl-C loses nothing.** Today only an interrupt or a finish archives, against goal 2. - **Key a project on its checkout's full path — its session, archive folder and models entry — and refuse to start while another session on that id is active.** `checkout.py:22` drops the leading `/`, so `~/code/a` and `/a` share a session, an archive folder and a models entry, and one loop can resume or delete the other's session. - **Move what `loop-claude` writes out of `~/.claude.json`, and bring each case that must stay to the human.** Claude Code owns and writes that file, and `trust`'s read-modify-write loses a write landing in its window. -- **Have `loop-claude` write one stats line per finished chunk, beside the transcript archive.** The line names the project and the chunk, and holds what the transcript and the verdicts already record: tokens for the worker and the judge, cycles, and interrupts. -- **End larv-review with a machine-readable summary, and add it to the chunk's stats line.** Agents launched and rounds per pass, findings per pass by severity, and the comprehension scores when the panel ran. -- **Review the workflow from the stats at each release, and file each change it proposes as a plan item.** The signals to read: findings the whole-project passes make in code a diff review passed, comprehension scores per release, fixes after merge, and the human's corrections. -- **Bench about one chunk in ten: redo it from its base commit under a pending change to the workflow, and have a blind judge rule which outcome serves the goals better.** `loop-claude` picks the chunk at random, small diffs and big ones alike. The ruling and both runs' numbers go on the chunk's stats line, and a workflow change merges once its benches rule it at least as good. Start from the 2026-09-30 bench's scripts: `~/code/claude-handoffs/claude-config/2026-09-30/bench/`. +- **Have `loop-claude` write one stats line per finished chunk, in one file at the root of the transcript archive.** The line names the project, the commit the chunk started from and the archived transcript's hash. It holds the worker's tokens from the transcript, the judge's from its JSON output, and the chunk's cycles and interrupts, which the loop counts. +- **End larv-review with a machine-readable summary, and have `loop-claude` copy it from the transcript onto the chunk's stats 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. +- **Bench about one chunk in ten: redo it from the commit it started from under a pending change to the workflow, and have a claude blind to which run is which rule which outcome better serves this repo's goal 4.** `loop-claude` picks the chunk at random, small diffs and big ones alike; with no change pending, no bench runs. 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/`. -- 2.52.0 From 13257ca1ea34804c81054848637e376051675c8f Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 21:00:12 +0200 Subject: [PATCH 196/233] Bench against an open workflow PR, which merges only when ruled better --- todo.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/todo.md b/todo.md index f30ad3d8..0df78f81 100644 --- a/todo.md +++ b/todo.md @@ -38,4 +38,4 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens - **Have `loop-claude` write one stats line per finished chunk, in one file at the root of the transcript archive.** The line names the project, the commit the chunk started from and the archived transcript's hash. It holds the worker's tokens from the transcript, the judge's from its JSON output, and the chunk's cycles and interrupts, which the loop counts. - **End larv-review with a machine-readable summary, and have `loop-claude` copy it from the transcript onto the chunk's stats 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. -- **Bench about one chunk in ten: redo it from the commit it started from under a pending change to the workflow, and have a claude blind to which run is which rule which outcome better serves this repo's goal 4.** `loop-claude` picks the chunk at random, small diffs and big ones alike; with no change pending, no bench runs. 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/`. +- **Bench about one chunk in ten: redo it from the commit it started from under an open PR that changes the workflow, and have a claude blind to which run is which rule which outcome better serves this repo's goal 4.** `loop-claude` picks the chunk at random, small diffs and big ones alike; with no such PR open, no bench runs. Better means a better outcome, or the same outcome with less code and prose, in the chunk or in the workflow. The PR merges only once its benches rule it better; how many benches that takes is asked when this item starts. 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/`. -- 2.52.0 From 7a2e129d8c0ddbef4595effad653a72314b8b804 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 21:00:56 +0200 Subject: [PATCH 197/233] Answer the stats-plan review's second round --- todo.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/todo.md b/todo.md index 0df78f81..623b285f 100644 --- a/todo.md +++ b/todo.md @@ -38,4 +38,4 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens - **Have `loop-claude` write one stats line per finished chunk, in one file at the root of the transcript archive.** The line names the project, the commit the chunk started from and the archived transcript's hash. It holds the worker's tokens from the transcript, the judge's from its JSON output, and the chunk's cycles and interrupts, which the loop counts. - **End larv-review with a machine-readable summary, and have `loop-claude` copy it from the transcript onto the chunk's stats 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. -- **Bench about one chunk in ten: redo it from the commit it started from under an open PR that changes the workflow, and have a claude blind to which run is which rule which outcome better serves this repo's goal 4.** `loop-claude` picks the chunk at random, small diffs and big ones alike; with no such PR open, no bench runs. Better means a better outcome, or the same outcome with less code and prose, in the chunk or in the workflow. The PR merges only once its benches rule it better; how many benches that takes is asked when this item starts. 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/`. +- **Bench about one chunk in ten: redo it under an open PR that changes the workflow, from the commit it started from, and have a claude blind to which run is which rule which outcome better serves this repo's goal 4.** `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 its benches rule it better; how many benches that takes is asked when this item starts. 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/`. -- 2.52.0 From 96be62eb73cb7abcc9960360ecf087da3a9380c4 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 21:03:54 +0200 Subject: [PATCH 198/233] Begin with three benches per workflow change --- todo.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/todo.md b/todo.md index 623b285f..1430f7c3 100644 --- a/todo.md +++ b/todo.md @@ -38,4 +38,4 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens - **Have `loop-claude` write one stats line per finished chunk, in one file at the root of the transcript archive.** The line names the project, the commit the chunk started from and the archived transcript's hash. It holds the worker's tokens from the transcript, the judge's from its JSON output, and the chunk's cycles and interrupts, which the loop counts. - **End larv-review with a machine-readable summary, and have `loop-claude` copy it from the transcript onto the chunk's stats 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. -- **Bench about one chunk in ten: redo it under an open PR that changes the workflow, from the commit it started from, and have a claude blind to which run is which rule which outcome better serves this repo's goal 4.** `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 its benches rule it better; how many benches that takes is asked when this item starts. 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/`. +- **Bench about one chunk in ten: redo it under an open PR that changes the workflow, from the commit it started from, and have a claude blind to which run is which rule which outcome better serves this repo's goal 4.** `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; three is where to begin, and the stats decide whether it stays. 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/`. -- 2.52.0 From dc2b8a25fc20487fed500cc6e317dcf95dd03383 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 21:06:06 +0200 Subject: [PATCH 199/233] Record the three-bench gate as a decision --- AGENTS.md | 1 + docs/decisions.md | 4 ++++ todo.md | 2 +- 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 4e315081..3fad43af 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -32,3 +32,4 @@ Decisions live in `docs/decisions.md`: - review: the architecture pass audits every principle and goal over the whole project, and a release's last chunk fires it - loop-claude: every claude it starts bypasses permissions inside its sandbox - stats: a chunk's cost and review numbers are kept in the transcript archive +- bench: a workflow change merges only once three benches rule it better diff --git a/docs/decisions.md b/docs/decisions.md index 593cddfb..44674375 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -111,3 +111,7 @@ ## stats: a chunk's cost and review numbers are kept in the transcript archive 2026-10-01, lilleman. Serves goals 3 and 4.4. The numbers show whether a change to the workflow raised quality or only cost. Each line names another project and its chunk, so the file stays off this repo's remote. `loop-claude` writes the line: the tokens, cycles and interrupts it counts, and the review's numbers from the summary larv-review ends with. Valid while the transcript archive stays off the remote. + +## bench: a workflow change merges only once three benches rule it better + +2026-10-01, lilleman. Serves goals 4.1 and 4.4. The 2026-09-30 bench showed one run cannot tell a workflow from the variance between runs. The same outcome with less code and prose counts as better. Three is a starting number, to be evaluated against the stats. Valid until that evaluation changes the number. diff --git a/todo.md b/todo.md index 1430f7c3..24c3f551 100644 --- a/todo.md +++ b/todo.md @@ -38,4 +38,4 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens - **Have `loop-claude` write one stats line per finished chunk, in one file at the root of the transcript archive.** The line names the project, the commit the chunk started from and the archived transcript's hash. It holds the worker's tokens from the transcript, the judge's from its JSON output, and the chunk's cycles and interrupts, which the loop counts. - **End larv-review with a machine-readable summary, and have `loop-claude` copy it from the transcript onto the chunk's stats 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. -- **Bench about one chunk in ten: redo it under an open PR that changes the workflow, from the commit it started from, and have a claude blind to which run is which rule which outcome better serves this repo's goal 4.** `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; three is where to begin, and the stats decide whether it stays. 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/`. +- **Bench about one chunk in ten: redo it under an open PR that changes the workflow, from the commit it started from, and have a claude blind to which run is which rule which outcome better serves this repo's goal 4.** `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; what a bench ruling it worse does is asked when this item starts. 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/`. -- 2.52.0 From 381867c43130948d05dc0f51c5ffb5c09bb67446 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 21:07:06 +0200 Subject: [PATCH 200/233] Answer the bench-count review's second round --- docs/decisions.md | 2 +- todo.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index 44674375..98bf3e33 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -114,4 +114,4 @@ ## bench: a workflow change merges only once three benches rule it better -2026-10-01, lilleman. Serves goals 4.1 and 4.4. The 2026-09-30 bench showed one run cannot tell a workflow from the variance between runs. The same outcome with less code and prose counts as better. Three is a starting number, to be evaluated against the stats. Valid until that evaluation changes the number. +2026-10-01, lilleman. Serves goals 4.1 and 4.4. The 2026-09-30 bench showed one run cannot tell a workflow's effect from the variance between runs. Three is a starting number, to be evaluated against the stats. Valid until that evaluation changes the number. diff --git a/todo.md b/todo.md index 24c3f551..0ece9a92 100644 --- a/todo.md +++ b/todo.md @@ -38,4 +38,4 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens - **Have `loop-claude` write one stats line per finished chunk, in one file at the root of the transcript archive.** The line names the project, the commit the chunk started from and the archived transcript's hash. It holds the worker's tokens from the transcript, the judge's from its JSON output, and the chunk's cycles and interrupts, which the loop counts. - **End larv-review with a machine-readable summary, and have `loop-claude` copy it from the transcript onto the chunk's stats 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. -- **Bench about one chunk in ten: redo it under an open PR that changes the workflow, from the commit it started from, and have a claude blind to which run is which rule which outcome better serves this repo's goal 4.** `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; what a bench ruling it worse does is asked when this item starts. 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/`. +- **Bench about one chunk in ten: redo it under an open PR that changes the workflow, from the commit it started from, and have a claude blind to which run is which rule which outcome better serves this repo's goal 4.** `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. Ask, when this item starts, what a bench that rules it worse does. 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/`. -- 2.52.0 From 8a968e84651008e01363c5f70a92563778cdb599 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 21:13:35 +0200 Subject: [PATCH 201/233] Make a chunk as large as one purpose allows, and close a workflow PR a bench rules worse --- CLAUDE.md | 4 ++-- bin/loop_claude/loop/main.py | 2 +- docs/decisions.md | 2 +- skills/larv-review/SKILL.md | 2 +- todo.md | 4 ++-- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 0ee54e6a..d7e3b270 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,7 +11,7 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The - **When the next release has no items and no work has landed towards it, plan it as this chunk.** Weigh the unscheduled items against the goals, put them in order, and get the human's approval before writing any code. - **When the next release has no items left and work has landed towards it, it is finished: stop.** Report what it holds and that it is ready to cut. Under `/loop`, this ends the loop. Until the human cuts it, only a security fix lands, into that release; never start a later release's items or plan a new one. - **Open every chunk with one line:** the last version cut, what is unreleased (`CHANGELOG.md` → `## Unreleased`, or else the log since the last tag), and the release this chunk ships into. A repo that publishes nothing says so once. -- **Work one chunk at a time.** Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`, under a release. +- **Work one chunk at a time, and make it as large as one purpose allows.** Every review has a fixed cost, so a chunk takes every related plan item that passes three tests: one line states the purpose of them all, as the PR title; they sit under one release; and if one part proved wrong, reverting the whole chunk would be acceptable. Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`, under a release. - **Ask, don't guess.** First check whether the goals already answer the question. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Write every answer once, where it belongs, never only in chat: a goal in `README.md`, a working rule in `AGENTS.md`, a standing choice in `docs/decisions.md`. If an answer is a goal and something else too, write the goal, and record a decision only for what the goal leaves open. - **Ship every chunk with `/larv-review`.** - **Remove a finished item from `todo.md`; keep its release heading until the version is cut.** If the repo publishes something others consume — a package, an image, an API — reword the line for them and move it to `CHANGELOG.md` under `## Unreleased`. A changelog is for the public, never for the next agent. Otherwise delete the line; git history is the record. @@ -142,7 +142,7 @@ The rules every project follows, compose-not-entangle first: `~/.claude/principl ## Vocabulary -- **chunk** — the unit of work: the smallest PR-able change. +- **chunk** — the unit of work: the largest change that still has one purpose; "Working loop" says how large that is. - **cycle** — one worker run and the judge's verdict on it, in `loop-claude`. - **gate** — the merge gate: the checks a PR passes before it merges. - **interrupt** — `loop-claude` handing the terminal to the human, `claude --resume`, for a decision that is theirs. diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 5ef639a9..3f9ff289 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -4,7 +4,7 @@ usage: loop-claude Run it anywhere inside a project checkout whose README.md has ## Goals and ## Audience, the premises; the task runs at the checkout root. Each cycle a worker runs the task; a judge then reads -the transcript against them and rules whether the chunk, the smallest PR-able change, is finished. +the transcript against them and rules whether the chunk, the largest change with one purpose, is finished. A question only the human can answer, or a release ready to cut, is an interrupt: `claude --resume` on the terminal, every worktree first marked trusted in ~/.claude.json. An unfinished chunk resumes its session next cycle; the next chunk starts a fresh session. diff --git a/docs/decisions.md b/docs/decisions.md index 98bf3e33..9af8ceab 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -114,4 +114,4 @@ ## bench: a workflow change merges only once three benches rule it better -2026-10-01, lilleman. Serves goals 4.1 and 4.4. The 2026-09-30 bench showed one run cannot tell a workflow's effect from the variance between runs. Three is a starting number, to be evaluated against the stats. Valid until that evaluation changes the number. +2026-10-01, lilleman. Serves goals 4.1 and 4.4. The 2026-09-30 bench showed one run cannot tell a workflow's effect from the variance between runs. Three is a starting number, to be evaluated against the stats. One bench ruling it worse closes the PR; only what was learned is kept. Valid until that evaluation changes the number. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index fc9646d8..493fb950 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -84,7 +84,7 @@ Launch prose-reviewer with what the diff touched and every section this review c 1. Read the finished PR against the README goals: does anything in it work against one? Misaligned → do not merge; ask the human, stating the conflict. 2. Aligned, every pass done and everything green → **merge**. Follow the repo's merge method (`AGENTS.md`; ff-only where that is the convention). A repo withholds this in its `AGENTS.md` → leave the PR ready and unmerged, and say which line withheld it. -3. Merged → tick the item off `todo.md` per `~/.claude/CLAUDE.md` → "Working loop". +3. Merged → tick the chunk's items off `todo.md` per `~/.claude/CLAUDE.md` → "Working loop". 4. Stop. The next chunk gets a fresh session. ## 6. Wrap up diff --git a/todo.md b/todo.md index 0ece9a92..ce3146ac 100644 --- a/todo.md +++ b/todo.md @@ -4,7 +4,7 @@ **⚠️ THE REBUILD NEVER MERGES INTO MAIN WITHOUT THE HUMAN'S EXPLICIT APPROVAL.** Every rebuild chunk is a worktree based on `origin/rebuild` with its PR into `rebuild`, never into main. Other sessions run on `~/.claude` main throughout; only the human merges `rebuild` into main, once they have approved the finished whole. -The rebuild lifts every dimension, one chunk per item, until the last item opens `rebuild`'s PR into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. +The rebuild lifts every dimension, until the last item opens `rebuild`'s PR into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. - **Carry main's #155 into `grounded()`: match the judge's quote with markdown emphasis and whitespace ignored.** The judge drops a bold line's closing `**` when quoting it; `rebuild` still rejects that, so merging it into main would bring back loops stopping on a correct verdict. - **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. The PR deletes main's `AGENTS.md` paragraph on a rebuild chunk's larv-review, which only main holds. @@ -38,4 +38,4 @@ The rebuild lifts every dimension, one chunk per item, until the last item opens - **Have `loop-claude` write one stats line per finished chunk, in one file at the root of the transcript archive.** The line names the project, the commit the chunk started from and the archived transcript's hash. It holds the worker's tokens from the transcript, the judge's from its JSON output, and the chunk's cycles and interrupts, which the loop counts. - **End larv-review with a machine-readable summary, and have `loop-claude` copy it from the transcript onto the chunk's stats 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. -- **Bench about one chunk in ten: redo it under an open PR that changes the workflow, from the commit it started from, and have a claude blind to which run is which rule which outcome better serves this repo's goal 4.** `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. Ask, when this item starts, what a bench that rules it worse does. 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/`. +- **Bench about one chunk in ten: redo it under an open PR that changes the workflow, from the commit it started from, and have a claude blind to which run is which rule which outcome better serves this repo's goal 4.** `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/`. -- 2.52.0 From 036cfcc422a7c252823354bb28e8751090aaded9 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 21:14:17 +0200 Subject: [PATCH 202/233] Keep the help line within its width --- bin/loop_claude/loop/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 3f9ff289..a00d0964 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -4,7 +4,7 @@ usage: loop-claude Run it anywhere inside a project checkout whose README.md has ## Goals and ## Audience, the premises; the task runs at the checkout root. Each cycle a worker runs the task; a judge then reads -the transcript against them and rules whether the chunk, the largest change with one purpose, is finished. +the transcript against them and rules whether the chunk, the largest one-purpose change, is finished. A question only the human can answer, or a release ready to cut, is an interrupt: `claude --resume` on the terminal, every worktree first marked trusted in ~/.claude.json. An unfinished chunk resumes its session next cycle; the next chunk starts a fresh session. -- 2.52.0 From c40f1ec7f075cdf3a4b388a835891b66b9380fd5 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 21:15:02 +0200 Subject: [PATCH 203/233] Shorten the help line's gloss of a chunk --- bin/loop_claude/loop/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index a00d0964..c9b6c868 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -4,7 +4,7 @@ usage: loop-claude Run it anywhere inside a project checkout whose README.md has ## Goals and ## Audience, the premises; the task runs at the checkout root. Each cycle a worker runs the task; a judge then reads -the transcript against them and rules whether the chunk, the largest one-purpose change, is finished. +the transcript against them and rules whether the chunk, a change with one purpose, is finished. A question only the human can answer, or a release ready to cut, is an interrupt: `claude --resume` on the terminal, every worktree first marked trusted in ~/.claude.json. An unfinished chunk resumes its session next cycle; the next chunk starts a fresh session. -- 2.52.0 From dbb19462a27bfef085f8fc5b08a237e8c24fbccd Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 21:23:38 +0200 Subject: [PATCH 204/233] Answer the chunk-size review's first round --- AGENTS.md | 1 + CLAUDE.md | 4 ++-- agents/systems-architect.md | 2 +- bin/loop_claude/cycle/worker.py | 2 +- docs/decisions.md | 6 +++++- skills/larv-review/SKILL.md | 2 +- todo.md | 2 +- 7 files changed, 12 insertions(+), 7 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 3fad43af..4103ee82 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,3 +33,4 @@ Decisions live in `docs/decisions.md`: - loop-claude: every claude it starts bypasses permissions inside its sandbox - stats: a chunk's cost and review numbers are kept in the transcript archive - bench: a workflow change merges only once three benches rule it better +- chunk: as large as one purpose allows diff --git a/CLAUDE.md b/CLAUDE.md index d7e3b270..6f963e20 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,7 +11,7 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The - **When the next release has no items and no work has landed towards it, plan it as this chunk.** Weigh the unscheduled items against the goals, put them in order, and get the human's approval before writing any code. - **When the next release has no items left and work has landed towards it, it is finished: stop.** Report what it holds and that it is ready to cut. Under `/loop`, this ends the loop. Until the human cuts it, only a security fix lands, into that release; never start a later release's items or plan a new one. - **Open every chunk with one line:** the last version cut, what is unreleased (`CHANGELOG.md` → `## Unreleased`, or else the log since the last tag), and the release this chunk ships into. A repo that publishes nothing says so once. -- **Work one chunk at a time, and make it as large as one purpose allows.** Every review has a fixed cost, so a chunk takes every related plan item that passes three tests: one line states the purpose of them all, as the PR title; they sit under one release; and if one part proved wrong, reverting the whole chunk would be acceptable. Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`, under a release. +- **Work one chunk at a time, and make it as large as one purpose allows.** Every review has a fixed cost, so a chunk is the next plan item plus every other item for which three things hold together: one PR title states what they achieve together, without listing them; they sit under one release; and they fire the same review passes (`larv-review` §3). Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`, under a release. - **Ask, don't guess.** First check whether the goals already answer the question. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Write every answer once, where it belongs, never only in chat: a goal in `README.md`, a working rule in `AGENTS.md`, a standing choice in `docs/decisions.md`. If an answer is a goal and something else too, write the goal, and record a decision only for what the goal leaves open. - **Ship every chunk with `/larv-review`.** - **Remove a finished item from `todo.md`; keep its release heading until the version is cut.** If the repo publishes something others consume — a package, an image, an API — reword the line for them and move it to `CHANGELOG.md` under `## Unreleased`. A changelog is for the public, never for the next agent. Otherwise delete the line; git history is the record. @@ -142,7 +142,7 @@ The rules every project follows, compose-not-entangle first: `~/.claude/principl ## Vocabulary -- **chunk** — the unit of work: the largest change that still has one purpose; "Working loop" says how large that is. +- **chunk** — the unit of work: the largest change with one purpose; "Working loop" says how large that is. - **cycle** — one worker run and the judge's verdict on it, in `loop-claude`. - **gate** — the merge gate: the checks a PR passes before it merges. - **interrupt** — `loop-claude` handing the terminal to the human, `claude --resume`, for a decision that is theirs. diff --git a/agents/systems-architect.md b/agents/systems-architect.md index 8c57133a..2ce6979c 100644 --- a/agents/systems-architect.md +++ b/agents/systems-architect.md @@ -140,7 +140,7 @@ You review the seams that make verification possible and the strategy that uses How a change ships — merge gate, pipeline, deployment, dependencies — is a designed property of the system. This is its one home; other sections point here. You review the gate's existence and check classes and the delivery strategy — never individual lint rules, pipeline syntax, or vendor choice. A missing check class is a finding; a disagreeable lint threshold is below your altitude. - **One enforced path to production.** The pipeline is the only way code reaches any environment. A manual deploy lane or a human-waivable gate is a bypass, and the bypass is the finding — a gate people route around launders unverified changes as verified. -- **The merge gate is fast, deterministic, and blocks on both tests and static analysis.** It admits only quick, hermetic checks (minutes, not an hour); slow or probabilistic suites run scheduled outside it (see Testability). A slow gate breeds long-lived branches and big batches — small changes through a fast gate beat big ones through a thorough gate; incomplete work hides behind flags with an owner and an expiry, not behind a branch. +- **The merge gate is fast, deterministic, and blocks on both tests and static analysis.** It admits only quick, hermetic checks (minutes, not an hour); slow or probabilistic suites run scheduled outside it (see Testability). A slow gate breeds long-lived branches; incomplete work hides behind flags with an owner and an expiry, not behind a branch. - **Static analysis is its own quality dimension, not a kind of testing.** Tests sample points in the input space; types and analyzers quantify over it. Types at full strictness, warnings-as-errors, and the Fits in a head thresholds as machine rules belong in the gate from the first commit — strictness is near-impossible to retrofit, so it is skeleton, never ceremony. - **Deployment is designed, not improvised.** Build one artifact and promote it — a per-environment build voids what the gate verified. Config comes from the environment. Rollback is a standing requirement, which forces expand–contract migrations with N-1 compatibility between running code and schema; an unrollbackable change is a defect class. A deploy completes when the post-deploy smoke confirms the surface (see Testability). - **Dependencies follow a strategy.** Each one earns its existence (Core Philosophy); versions are locked; updates flow small-and-often through the gate via automation. Automation presupposes the gate — on a gateless project the finding is the missing gate, not the missing bot. diff --git a/bin/loop_claude/cycle/worker.py b/bin/loop_claude/cycle/worker.py index a000da35..664bd940 100644 --- a/bin/loop_claude/cycle/worker.py +++ b/bin/loop_claude/cycle/worker.py @@ -30,7 +30,7 @@ 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: - start = ["-p", f"{task}\n\nContinue any open draft PR or worktree for the item before creating a new one.", "--name", session.name, "--session-id", str(session.id)] + start = ["-p", f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one.", "--name", session.name, "--session-id", str(session.id)] return [ *start, "--output-format", "stream-json", diff --git a/docs/decisions.md b/docs/decisions.md index 9af8ceab..1052c76f 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -114,4 +114,8 @@ ## bench: a workflow change merges only once three benches rule it better -2026-10-01, lilleman. Serves goals 4.1 and 4.4. The 2026-09-30 bench showed one run cannot tell a workflow's effect from the variance between runs. Three is a starting number, to be evaluated against the stats. One bench ruling it worse closes the PR; only what was learned is kept. Valid until that evaluation changes the number. +2026-10-01, lilleman. Serves goals 4.1 and 4.4. The 2026-09-30 bench showed one run cannot tell a workflow's effect from the variance between runs. One bench ruling it worse closes the PR, since quality comes first (goal 4.1), and `docs/workflow-learnings.md` keeps what the PR changed and why it lost. Three is a starting number, to be evaluated against the stats. Valid until that evaluation changes the number. + +## chunk: as large as one purpose allows + +2026-10-01, lilleman. Serves goal 4.4. Every review has a fixed cost: each reviewer reloads the rules and the files around the change. On 2026-10-01 the prose reviews cost 50,000 to 150,000 tokens each, for changes of 1 to 30 lines. Purpose caps a chunk, never a line count. Valid until the stats or a bench show that larger chunks lower what reviews catch. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 493fb950..472a51eb 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -84,7 +84,7 @@ Launch prose-reviewer with what the diff touched and every section this review c 1. Read the finished PR against the README goals: does anything in it work against one? Misaligned → do not merge; ask the human, stating the conflict. 2. Aligned, every pass done and everything green → **merge**. Follow the repo's merge method (`AGENTS.md`; ff-only where that is the convention). A repo withholds this in its `AGENTS.md` → leave the PR ready and unmerged, and say which line withheld it. -3. Merged → tick the chunk's items off `todo.md` per `~/.claude/CLAUDE.md` → "Working loop". +3. Merged → remove the chunk's items from `todo.md` per `~/.claude/CLAUDE.md` → "Working loop". 4. Stop. The next chunk gets a fresh session. ## 6. Wrap up diff --git a/todo.md b/todo.md index ce3146ac..a07e8c5a 100644 --- a/todo.md +++ b/todo.md @@ -4,7 +4,7 @@ **⚠️ THE REBUILD NEVER MERGES INTO MAIN WITHOUT THE HUMAN'S EXPLICIT APPROVAL.** Every rebuild chunk is a worktree based on `origin/rebuild` with its PR into `rebuild`, never into main. Other sessions run on `~/.claude` main throughout; only the human merges `rebuild` into main, once they have approved the finished whole. -The rebuild lifts every dimension, until the last item opens `rebuild`'s PR into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. +The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. - **Carry main's #155 into `grounded()`: match the judge's quote with markdown emphasis and whitespace ignored.** The judge drops a bold line's closing `**` when quoting it; `rebuild` still rejects that, so merging it into main would bring back loops stopping on a correct verdict. - **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. The PR deletes main's `AGENTS.md` paragraph on a rebuild chunk's larv-review, which only main holds. -- 2.52.0 From 3183d77c1d3d4ea60287e86b8283313f3be24688 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 21:30:26 +0200 Subject: [PATCH 205/233] Answer the chunk-size review's second round --- CLAUDE.md | 2 +- docs/decisions.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 6f963e20..c4e5729a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,7 +11,7 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The - **When the next release has no items and no work has landed towards it, plan it as this chunk.** Weigh the unscheduled items against the goals, put them in order, and get the human's approval before writing any code. - **When the next release has no items left and work has landed towards it, it is finished: stop.** Report what it holds and that it is ready to cut. Under `/loop`, this ends the loop. Until the human cuts it, only a security fix lands, into that release; never start a later release's items or plan a new one. - **Open every chunk with one line:** the last version cut, what is unreleased (`CHANGELOG.md` → `## Unreleased`, or else the log since the last tag), and the release this chunk ships into. A repo that publishes nothing says so once. -- **Work one chunk at a time, and make it as large as one purpose allows.** Every review has a fixed cost, so a chunk is the next plan item plus every other item for which three things hold together: one PR title states what they achieve together, without listing them; they sit under one release; and they fire the same review passes (`larv-review` §3). Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`, under a release. +- **Work one chunk at a time, and make it as large as one purpose allows.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which three things hold: one PR title states what they achieve together, without listing them; they sit under one release; and they fire the same review passes (`larv-review` §3). Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`, under a release. - **Ask, don't guess.** First check whether the goals already answer the question. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Write every answer once, where it belongs, never only in chat: a goal in `README.md`, a working rule in `AGENTS.md`, a standing choice in `docs/decisions.md`. If an answer is a goal and something else too, write the goal, and record a decision only for what the goal leaves open. - **Ship every chunk with `/larv-review`.** - **Remove a finished item from `todo.md`; keep its release heading until the version is cut.** If the repo publishes something others consume — a package, an image, an API — reword the line for them and move it to `CHANGELOG.md` under `## Unreleased`. A changelog is for the public, never for the next agent. Otherwise delete the line; git history is the record. diff --git a/docs/decisions.md b/docs/decisions.md index 1052c76f..bf2465ca 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -118,4 +118,4 @@ ## chunk: as large as one purpose allows -2026-10-01, lilleman. Serves goal 4.4. Every review has a fixed cost: each reviewer reloads the rules and the files around the change. On 2026-10-01 the prose reviews cost 50,000 to 150,000 tokens each, for changes of 1 to 30 lines. Purpose caps a chunk, never a line count. Valid until the stats or a bench show that larger chunks lower what reviews catch. +2026-10-01, lilleman. Serves goal 4.4. Every review has a fixed cost: each reviewer reloads the rules and the files around the change. Purpose caps a chunk, never a line count. Valid until the stats or a bench show that larger chunks lower what reviews catch. -- 2.52.0 From acfed42cb2a1f227d7152dd7199529e0168a6863 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 21:35:45 +0200 Subject: [PATCH 206/233] Order the plan by the goals, group it into chunks and reword it --- todo.md | 68 ++++++++++++++++++++++++++++++++------------------------- 1 file changed, 38 insertions(+), 30 deletions(-) diff --git a/todo.md b/todo.md index a07e8c5a..a979c786 100644 --- a/todo.md +++ b/todo.md @@ -6,36 +6,44 @@ The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -- **Carry main's #155 into `grounded()`: match the judge's quote with markdown emphasis and whitespace ignored.** The judge drops a bold line's closing `**` when quoting it; `rebuild` still rejects that, so merging it into main would bring back loops stopping on a correct verdict. -- **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. The PR deletes main's `AGENTS.md` paragraph on a rebuild chunk's larv-review, which only main holds. +- **Match the judge's quote in `grounded()` with markdown emphasis and whitespace ignored, as main's #155 does.** The judge drops a bold line's closing `**` when it quotes the line. `rebuild` rejects such a quote, so merging `rebuild` into main would bring back loops that stop on a correct verdict. +- **Score `rebuild` with the four-seat panel, and open its PR into main for the human.** Every dimension and the overall must reach 7.0, and none may fall below the last run. A dimension under the floor gets its places filed above this item. ⚠️ Leave the PR ready and unmerged: only the human merges it, after approving the whole rebuild. The PR deletes main's `AGENTS.md` paragraph on a rebuild chunk's larv-review, which only main holds. ## 0.2.0 -- **Sort `bin/`'s imports on their first binding, and say in `principles/technical-principles.md` → "Deterministic order" how case sorts and which groups Python has.** Today they sort by path, so a module move reorders unchanged lines; "host packages" names no Python group. -- **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. -- **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. -- **Give `docs/decisions.md`'s comprehension-floor and vocabulary entries a premise that has not already expired, with the floor's rule first and its runs' scores as a table, and give the rebuild entry's warning placement its own heading and index line.** A prose pass found both "Valid until the next scoring run" outlived by three runs. -- **Move larv-review's reasons for `/security-review` and for the premises chunk's review into `docs/decisions.md`.** A prose pass found rejected alternatives at the rule. -- **Cut `comprehension-panel`'s run history and the restated description, `systems-architect.md`'s "one home" line, and split its Reasonability Review steps 4 and 5.** A prose pass found them carrying nothing the instructions need. -- **Keep `outcome.Failure`'s docstring to what a failure is, without naming `retried`.** A value type naming its consumer. -- **Give a 🟡 shown factually wrong the 🔴's way out in `review-findings.md`.** Today it can only be fixed, declined on a goal, or filed. -- **Say in `AGENTS.md` that only the rebuild's last chunk opens `rebuild`'s PR into main.** Today it reads as every chunk doing so. -- **Have larv-review's prose pass fix only what the chunk touched, and file the rest per `CLAUDE.md` → "Working loop".** Its fixes land "in this chunk", cited sections and the sweep run when the architecture pass ran included. The 2026-09-30 bench's costliest rebuild runs sprawled outside the chunk: deleted README facts, 13 mypy rounds where main took 6–7 for the same fixes. On 35b, rebuild's one clear win took 6–11 agents to main's 8–16. `~/code/claude-handoffs/claude-config/2026-09-30/bench/comparison.md` -- **Give principles-auditor and prose-reviewer a way to list the project's files.** Their `tools: Read, Grep, Glob` left only Read in the 2026-09-30 audit run, so each read what imports and `.gitignore` named and said which files it could not reach. -- **Judge a cycle on more than the transcript's last 40,000 characters.** `judge.py:80` cuts the session, which spans every cycle of the chunk, so a decision made early in a long run is never judged and the human is not interrupted for it (goal 4). -- **Name `jq` and GNU `date` under README → Install, or drop them from `statusline.sh`.** Without `jq` the status line aborts; under BSD `date` the reset times vanish, so CHANGELOG's "runs on any machine unedited" is false. -- **Inject `loop-claude`'s side effects: `time.sleep`, `subprocess`, `input()`, `isatty` and `os.execv`, and split `project_model` and `interrupt` into decisions and effects.** Functional core, imperative shell; the loop's flow has no tests because nothing reaches it without the effects. -- **Test `run_cycle`, `judge_through_interrupts`, `retried`, `archive`, `trust`, `interrupt`, the models file and the worker's arguments.** Only the pure helpers are tested today. -- **Give a project's loop state named states and one transition function.** Fresh, resuming, awaiting the human and finished come today from whether a transcript exists, two verdict booleans and an open `while True` in `steps.py`. -- **Make a `Verdict` with both `interrupt` and `finished`, or a question without an interrupt, unrepresentable.** `steps.py:49` ignores `finished` when `interrupt` is set. -- **Return a `Stop` when `git` or `os.execv` fails.** `checkout.py:7,15` and `reload.py:52` end in a traceback. -- **Narrow `.gitignore`'s `!bin/*` and `skills/*/**` to the files they mean.** A stray log of `loop-claude` output in `bin/` would be committed with transcript text in it. -- **Archive the transcript as each cycle ends, so a failed exit or Ctrl-C loses nothing.** Today only an interrupt or a finish archives, against goal 2. -- **Key a project on its checkout's full path — its session, archive folder and models entry — and refuse to start while another session on that id is active.** `checkout.py:22` drops the leading `/`, so `~/code/a` and `/a` share a session, an archive folder and a models entry, and one loop can resume or delete the other's session. -- **Move what `loop-claude` writes out of `~/.claude.json`, and bring each case that must stay to the human.** Claude Code owns and writes that file, and `trust`'s read-modify-write loses a write landing in its window. -- **Have `loop-claude` write one stats line per finished chunk, in one file at the root of the transcript archive.** The line names the project, the commit the chunk started from and the archived transcript's hash. It holds the worker's tokens from the transcript, the judge's from its JSON output, and the chunk's cycles and interrupts, which the loop counts. -- **End larv-review with a machine-readable summary, and have `loop-claude` copy it from the transcript onto the chunk's stats 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. -- **Bench about one chunk in ten: redo it under an open PR that changes the workflow, from the commit it started from, and have a claude blind to which run is which rule which outcome better serves this repo's goal 4.** `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/`. +Items are ordered by the goal they serve, highest first. + +- **Name `jq` and GNU `date` under README → Install, or stop `statusline.sh` needing them.** Without `jq` the status line aborts. Under BSD `date` the reset times vanish. Either way CHANGELOG's "runs on any machine unedited" is false. Goal 1. +- **Back up `loop-claude`'s transcript archive to a place other than this repo's remote.** The stats file sits in the archive, so the backup covers it too. Goal 2. +- **Archive the transcript as each cycle ends.** Today only an interrupt or a finished chunk archives it, so a failed exit or Ctrl-C loses the transcript. 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. `checkout.py:22` drops the leading `/`, so `~/code/a` and `/a` share all three, and one loop can resume or delete the other's session. Goal 2. +- **Narrow `.gitignore`'s `!bin/*` and `skills/*/**` to the files they mean.** Today a stray log of `loop-claude` output in `bin/` would be committed, transcript text included. Goal 3. +- **Give principles-auditor and prose-reviewer a way to list the project's files.** In the 2026-09-30 audit run their `tools: Read, Grep, Glob` gave them only Read. Each read the files that imports and `.gitignore` named, and listed the files it could not reach. Goal 4.1. +- **Make `loop-claude`'s loop a tested state machine inside an injected shell.** Goal 4.1. + - Inject the side effects: `time.sleep`, `subprocess`, `input()`, `isatty` and `os.execv`. Split `project_model` and `interrupt` into decisions and effects. + - Give a project's loop state named states and one transition function. Today fresh, resuming, awaiting the human and finished come from whether a transcript exists, two verdict booleans and an open `while True` in `steps.py`. + - Make a `Verdict` with both `interrupt` and `finished`, or with a question and no interrupt, unrepresentable. `steps.py:49` ignores `finished` when `interrupt` is set. + - Test `run_cycle`, `judge_through_interrupts`, `retried`, `archive`, `trust`, `interrupt`, the models file and the worker's arguments. Only the pure helpers are tested today, because nothing reaches the loop's flow without the effects. +- **Move what `loop-claude` writes out of `~/.claude.json`, and bring each case that must stay to the human.** Claude Code owns that file and writes it. `trust` reads it, changes it and writes it back, so a write that lands in between is lost. Goal 4.1. +- **Give `loop-claude`'s two unexplained failures a message.** Goal 4.1. + - Show the judge's reply when its verdict is rejected. Its stdout is discarded today, so a judge that failed three times running leaves nothing to diagnose. + - Return a `Stop` when `git` or `os.execv` fails. `checkout.py:7,15` and `reload.py:52` end in a traceback today. +- **Give larv-review a rule for the two cases reviews found it silent on.** Goal 4.1. + - CLI flags and exit codes: name them among the external contracts that fire the architecture pass, or record that they do not. The product-owner row names the CLI; the architecture row does not. + - A 🟡 shown factually wrong: give it the 🔴's way out in `review-findings.md`. Today it can only be fixed, declined on a goal, or filed. +- **Remove what the rebuild's merge made stale.** The ⚠️ paragraphs in `AGENTS.md` and `todo.md`, and each decision valid "until the rebuild merges". Goal 4.1. +- **Settle the prose findings filed against the workflow's own documents.** Goal 4.1. + - `docs/decisions.md`: give the comprehension-floor and vocabulary entries a premise that has not expired. Both say "Valid until the next scoring run", and three runs have passed. Put the floor's rule first and its runs' scores in a table. + - larv-review: move its reasons for `/security-review` and for the premises chunk's review into `docs/decisions.md`. They are rejected alternatives, which the decision log holds. + - `comprehension-panel`: cut the run history and the restated description. + - `systems-architect.md`: cut the "one home" line, and split Reasonability Review steps 4 and 5. + - `outcome.Failure`'s docstring: say what a failure is, without naming `retried`. A value type does not name its consumer. +- **Make the contributor a standing member of every project's audience.** A project drops them only where its `## Audience` says maintainability does not matter. `CLAUDE.md`'s goals-and-audience rule states it, and larv-review's comprehension floor names the contributor as the reader it serves. The floor then gates every chunk while the contributor stands, and a project that drops them skips it. Goal 4.1. +- **Judge a cycle on more than the transcript's last 40,000 characters.** `judge.py:80` cuts the transcript there. The session spans every cycle of the chunk, so a decision made early in a long run is never judged, and the human is not interrupted for it. Larger chunks make runs longer. Goal 4.2. +- **Sort `bin/`'s imports on their first binding, and say in `principles/technical-principles.md` → "Deterministic order" how case sorts and which groups Python has.** Today they sort by path, so moving a module reorders unchanged lines. "Host packages" names no Python group. Goal 4.3. +- **Have larv-review's prose pass fix only what the chunk touched, and file the rest per `CLAUDE.md` → "Working loop".** Today its fixes land "in this chunk", including cited sections and the sweep that runs with the architecture pass. In the 2026-09-30 bench, rebuild's costliest runs sprawled outside the chunk: one deleted README facts, and one took 13 mypy rounds where main took 6–7 for the same fixes. On 35b, rebuild's one clear win took 6–11 agents to main's 8–16. `~/code/claude-handoffs/claude-config/2026-09-30/bench/comparison.md` Goal 4.4. +- **Record each finished chunk's cost and review numbers on one stats line.** Goal 4.4. + - `loop-claude` writes the line to one file at the root of the transcript archive. The line names the project, the commit the chunk started from and the archived transcript's hash. It holds the worker's tokens from the transcript, the judge's from its JSON output, and the chunk's cycles and interrupts, which the loop counts. + - larv-review ends with a machine-readable summary, and `loop-claude` copies 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: redo it under an open PR that changes the workflow, from the commit it started from, and have a claude blind to which run is which rule which outcome better serves this repo's goal 4.** `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/`. Goal 4.4. -- 2.52.0 From b443035977caabe49fb4beab2b128b20b75f3424 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 21:41:51 +0200 Subject: [PATCH 207/233] Answer the plan review's first round --- todo.md | 36 +++++++++++++++++------------------- 1 file changed, 17 insertions(+), 19 deletions(-) diff --git a/todo.md b/todo.md index a979c786..01cd0f73 100644 --- a/todo.md +++ b/todo.md @@ -7,43 +7,41 @@ The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. - **Match the judge's quote in `grounded()` with markdown emphasis and whitespace ignored, as main's #155 does.** The judge drops a bold line's closing `**` when it quotes the line. `rebuild` rejects such a quote, so merging `rebuild` into main would bring back loops that stop on a correct verdict. -- **Score `rebuild` with the four-seat panel, and open its PR into main for the human.** Every dimension and the overall must reach 7.0, and none may fall below the last run. A dimension under the floor gets its places filed above this item. ⚠️ Leave the PR ready and unmerged: only the human merges it, after approving the whole rebuild. The PR deletes main's `AGENTS.md` paragraph on a rebuild chunk's larv-review, which only main holds. +- **Bring `rebuild` to the comprehension floor on the four-seat panel, and open its PR into main for the human.** Every dimension and the overall must reach 7.0, and none may fall below the last run. A dimension under the floor gets its places filed above this item. ⚠️ Leave the PR ready and unmerged: only the human merges it, after approving the whole rebuild. The PR deletes main's `AGENTS.md` paragraph on a rebuild chunk's larv-review, which only main holds. ## 0.2.0 -Items are ordered by the goal they serve, highest first. - - **Name `jq` and GNU `date` under README → Install, or stop `statusline.sh` needing them.** Without `jq` the status line aborts. Under BSD `date` the reset times vanish. Either way CHANGELOG's "runs on any machine unedited" is false. Goal 1. -- **Back up `loop-claude`'s transcript archive to a place other than this repo's remote.** The stats file sits in the archive, so the backup covers it too. Goal 2. +- **Back up `loop-claude`'s transcript archive to a place other than this repo's remote.** Goal 2. - **Archive the transcript as each cycle ends.** Today only an interrupt or a finished chunk archives it, so a failed exit or Ctrl-C loses the transcript. 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. `checkout.py:22` drops the leading `/`, so `~/code/a` and `/a` share all three, and one loop can resume or delete the other's session. Goal 2. - **Narrow `.gitignore`'s `!bin/*` and `skills/*/**` to the files they mean.** Today a stray log of `loop-claude` output in `bin/` would be committed, transcript text included. Goal 3. +- **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. `checkout.py:22` 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. - **Give principles-auditor and prose-reviewer a way to list the project's files.** In the 2026-09-30 audit run their `tools: Read, Grep, Glob` gave them only Read. Each read the files that imports and `.gitignore` named, and listed the files it could not reach. Goal 4.1. -- **Make `loop-claude`'s loop a tested state machine inside an injected shell.** Goal 4.1. +- **Make `loop-claude`'s loop a tested state machine with its side effects injected.** Functional core, imperative shell. Goal 4.1. - Inject the side effects: `time.sleep`, `subprocess`, `input()`, `isatty` and `os.execv`. Split `project_model` and `interrupt` into decisions and effects. - Give a project's loop state named states and one transition function. Today fresh, resuming, awaiting the human and finished come from whether a transcript exists, two verdict booleans and an open `while True` in `steps.py`. - - Make a `Verdict` with both `interrupt` and `finished`, or with a question and no interrupt, unrepresentable. `steps.py:49` ignores `finished` when `interrupt` is set. + - Make two `Verdict`s unrepresentable: one with both `interrupt` and `finished`, and one with a question and no interrupt. `steps.py:49` ignores `finished` when `interrupt` is set. - Test `run_cycle`, `judge_through_interrupts`, `retried`, `archive`, `trust`, `interrupt`, the models file and the worker's arguments. Only the pure helpers are tested today, because nothing reaches the loop's flow without the effects. -- **Move what `loop-claude` writes out of `~/.claude.json`, and bring each case that must stay to the human.** Claude Code owns that file and writes it. `trust` reads it, changes it and writes it back, so a write that lands in between is lost. Goal 4.1. -- **Give `loop-claude`'s two unexplained failures a message.** Goal 4.1. +- **Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.** Claude Code owns that file and writes it. `trust` reads it, changes it and writes it back, so a write that lands in between is lost. Goal 4.1. +- **Give the `loop-claude` failures that explain nothing a message.** Goal 4.1. - Show the judge's reply when its verdict is rejected. Its stdout is discarded today, so a judge that failed three times running leaves nothing to diagnose. - Return a `Stop` when `git` or `os.execv` fails. `checkout.py:7,15` and `reload.py:52` end in a traceback today. -- **Give larv-review a rule for the two cases reviews found it silent on.** Goal 4.1. +- **Give larv-review a rule for the two cases it is silent on.** Goal 4.1. - CLI flags and exit codes: name them among the external contracts that fire the architecture pass, or record that they do not. The product-owner row names the CLI; the architecture row does not. - A 🟡 shown factually wrong: give it the 🔴's way out in `review-findings.md`. Today it can only be fixed, declined on a goal, or filed. - **Remove what the rebuild's merge made stale.** The ⚠️ paragraphs in `AGENTS.md` and `todo.md`, and each decision valid "until the rebuild merges". Goal 4.1. -- **Settle the prose findings filed against the workflow's own documents.** Goal 4.1. +- **Settle the prose findings earlier reviews filed.** Goal 4.1. - `docs/decisions.md`: give the comprehension-floor and vocabulary entries a premise that has not expired. Both say "Valid until the next scoring run", and three runs have passed. Put the floor's rule first and its runs' scores in a table. - larv-review: move its reasons for `/security-review` and for the premises chunk's review into `docs/decisions.md`. They are rejected alternatives, which the decision log holds. - - `comprehension-panel`: cut the run history and the restated description. - - `systems-architect.md`: cut the "one home" line, and split Reasonability Review steps 4 and 5. + - `comprehension-panel`: cut the run history and the restated description. They carry nothing the instructions need. + - `systems-architect.md`: cut the "one home" line, and break Reasonability Review's steps 4 and 5 into shorter points each. - `outcome.Failure`'s docstring: say what a failure is, without naming `retried`. A value type does not name its consumer. -- **Make the contributor a standing member of every project's audience.** A project drops them only where its `## Audience` says maintainability does not matter. `CLAUDE.md`'s goals-and-audience rule states it, and larv-review's comprehension floor names the contributor as the reader it serves. The floor then gates every chunk while the contributor stands, and a project that drops them skips it. Goal 4.1. +- **Make the contributor a standing member of every project's audience.** A project drops them only where its `## Audience` says maintainability does not matter. State that in `CLAUDE.md`'s goals-and-audience rule, and have larv-review's comprehension floor name the contributor as the reader it serves. The floor then gates every chunk while the contributor stands, and a project that drops them skips it. Goal 4.1. +- **Sort `bin/`'s imports on their first binding, and say in `principles/technical-principles.md` → "Deterministic order" how case sorts and which groups Python has.** Today they sort by path, so moving a module reorders unchanged lines. The principle's "host packages" names no Python group. Goal 4.1. - **Judge a cycle on more than the transcript's last 40,000 characters.** `judge.py:80` cuts the transcript there. The session spans every cycle of the chunk, so a decision made early in a long run is never judged, and the human is not interrupted for it. Larger chunks make runs longer. Goal 4.2. -- **Sort `bin/`'s imports on their first binding, and say in `principles/technical-principles.md` → "Deterministic order" how case sorts and which groups Python has.** Today they sort by path, so moving a module reorders unchanged lines. "Host packages" names no Python group. Goal 4.3. -- **Have larv-review's prose pass fix only what the chunk touched, and file the rest per `CLAUDE.md` → "Working loop".** Today its fixes land "in this chunk", including cited sections and the sweep that runs with the architecture pass. In the 2026-09-30 bench, rebuild's costliest runs sprawled outside the chunk: one deleted README facts, and one took 13 mypy rounds where main took 6–7 for the same fixes. On 35b, rebuild's one clear win took 6–11 agents to main's 8–16. `~/code/claude-handoffs/claude-config/2026-09-30/bench/comparison.md` Goal 4.4. +- **Have larv-review's prose pass fix only what the chunk touched, and file the rest per `CLAUDE.md` → "Working loop".** Today its fixes land "in this chunk", including cited sections and the sweep that runs with the architecture pass. In the 2026-09-30 bench, rebuild's costliest runs sprawled outside the chunk: one deleted README facts, and one took 13 rounds on the mypy case where main took 6–7 for the same fixes. Source: `~/code/claude-handoffs/claude-config/2026-09-30/bench/comparison.md`. Goal 4.4. - **Record each finished chunk's cost and review numbers on one stats line.** Goal 4.4. - - `loop-claude` writes the line to one file at the root of the transcript archive. The line names the project, the commit the chunk started from and the archived transcript's hash. It holds the worker's tokens from the transcript, the judge's from its JSON output, and the chunk's cycles and interrupts, which the loop counts. - - larv-review ends with a machine-readable summary, and `loop-claude` copies 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. + - Have `loop-claude` write the line to one file at the root of the transcript archive. The line names the project, the commit the chunk started from and the archived transcript's hash. It holds the worker's tokens from the transcript, the judge's from its JSON output, and the chunk's cycles and interrupts, which the loop counts. + - End larv-review with a machine-readable summary, and have `loop-claude` copy it from the transcript onto the line: agents launched and rounds per pass; findings per pass by severity, inside the chunk's diff and outside it; and the comprehension scores when the panel ran. - **Write a `workflow-review` skill that reads the stats and files each change it proposes to the workflow as a plan item, and have `AGENTS.md` run it on the chunk shipping a release's last item.** The workflow is `CLAUDE.md`, `principles/`, the skills, the agents and `loop-claude`. The skill's signals: findings outside the chunk's diff and comprehension scores per release, both from the stats; fixes after merge, from git; and the human's corrections, from the archived transcripts. Goal 4.4. -- **Bench about one chunk in ten: redo it under an open PR that changes the workflow, from the commit it started from, and have a claude blind to which run is which rule which outcome better serves this repo's goal 4.** `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/`. 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. -- 2.52.0 From 1dac14801e3482ce31368f5bcb5d5ea00822ab09 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 21:44:41 +0200 Subject: [PATCH 208/233] Bundle the tiny items, and drop the backup item --- CLAUDE.md | 2 +- docs/decisions.md | 2 +- todo.md | 22 ++++++++++------------ 3 files changed, 12 insertions(+), 14 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index c4e5729a..63aaed30 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,7 +11,7 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The - **When the next release has no items and no work has landed towards it, plan it as this chunk.** Weigh the unscheduled items against the goals, put them in order, and get the human's approval before writing any code. - **When the next release has no items left and work has landed towards it, it is finished: stop.** Report what it holds and that it is ready to cut. Under `/loop`, this ends the loop. Until the human cuts it, only a security fix lands, into that release; never start a later release's items or plan a new one. - **Open every chunk with one line:** the last version cut, what is unreleased (`CHANGELOG.md` → `## Unreleased`, or else the log since the last tag), and the release this chunk ships into. A repo that publishes nothing says so once. -- **Work one chunk at a time, and make it as large as one purpose allows.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which three things hold: one PR title states what they achieve together, without listing them; they sit under one release; and they fire the same review passes (`larv-review` §3). Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`, under a release. +- **Work one chunk at a time, and make it as large as one purpose allows.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which three things hold: one PR title states what they achieve together, without listing them; they sit under one release; and they fire the same review passes (`larv-review` §3). Tiny items, a few lines of change each, need no shared purpose: bundle five to ten from one release into one chunk. Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`, under a release. - **Ask, don't guess.** First check whether the goals already answer the question. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Write every answer once, where it belongs, never only in chat: a goal in `README.md`, a working rule in `AGENTS.md`, a standing choice in `docs/decisions.md`. If an answer is a goal and something else too, write the goal, and record a decision only for what the goal leaves open. - **Ship every chunk with `/larv-review`.** - **Remove a finished item from `todo.md`; keep its release heading until the version is cut.** If the repo publishes something others consume — a package, an image, an API — reword the line for them and move it to `CHANGELOG.md` under `## Unreleased`. A changelog is for the public, never for the next agent. Otherwise delete the line; git history is the record. diff --git a/docs/decisions.md b/docs/decisions.md index bf2465ca..1db05974 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -118,4 +118,4 @@ ## chunk: as large as one purpose allows -2026-10-01, lilleman. Serves goal 4.4. Every review has a fixed cost: each reviewer reloads the rules and the files around the change. Purpose caps a chunk, never a line count. Valid until the stats or a bench show that larger chunks lower what reviews catch. +2026-10-01, lilleman. Serves goal 4.4. Every review has a fixed cost: each reviewer reloads the rules and the files around the change. Purpose caps a chunk, never a line count. Tiny items are the exception: five to ten, a few lines each, share one chunk whatever their purposes, since the review's fixed cost dwarfs them. Valid until the stats or a bench show that larger chunks lower what reviews catch. diff --git a/todo.md b/todo.md index 01cd0f73..9f2a39a3 100644 --- a/todo.md +++ b/todo.md @@ -11,10 +11,14 @@ The sketches, the judges' verdicts and what to take from each: `~/code/claude-ha ## 0.2.0 -- **Name `jq` and GNU `date` under README → Install, or stop `statusline.sh` needing them.** Without `jq` the status line aborts. Under BSD `date` the reset times vanish. Either way CHANGELOG's "runs on any machine unedited" is false. Goal 1. -- **Back up `loop-claude`'s transcript archive to a place other than this repo's remote.** Goal 2. +- **Make the small fixes filed against `bin/`, the README and `.gitignore`.** Each is a few lines, so they share one chunk. Goals 1, 3 and 4.1. + - Name `jq` and GNU `date` under README → Install, or stop `statusline.sh` needing them. Without `jq` the status line aborts. Under BSD `date` the reset times vanish. Either way CHANGELOG's "runs on any machine unedited" is false. + - Narrow `.gitignore`'s `!bin/*` and `skills/*/**` to the files they mean. Today a stray log of `loop-claude` output in `bin/` would be committed, transcript text included. + - Sort `bin/`'s imports on their first binding, and say in `principles/technical-principles.md` → "Deterministic order" how case sorts and which groups Python has. Today they sort by path, so moving a module reorders unchanged lines. The principle's "host packages" names no Python group. + - Show the judge's reply when its verdict is rejected. Its stdout is discarded today, so a judge that failed three times running leaves nothing to diagnose. + - Return a `Stop` when `git` or `os.execv` fails. `checkout.py:7,15` and `reload.py:52` end in a traceback today. + - `outcome.Failure`'s docstring: say what a failure is, without naming `retried`. A value type does not name its consumer. - **Archive the transcript as each cycle ends.** Today only an interrupt or a finished chunk archives it, so a failed exit or Ctrl-C loses the transcript. Goal 2. -- **Narrow `.gitignore`'s `!bin/*` and `skills/*/**` to the files they mean.** Today a stray log of `loop-claude` output in `bin/` would be committed, transcript text included. Goal 3. - **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. `checkout.py:22` 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. - **Give principles-auditor and prose-reviewer a way to list the project's files.** In the 2026-09-30 audit run their `tools: Read, Grep, Glob` gave them only Read. Each read the files that imports and `.gitignore` named, and listed the files it could not reach. Goal 4.1. - **Make `loop-claude`'s loop a tested state machine with its side effects injected.** Functional core, imperative shell. Goal 4.1. @@ -23,21 +27,15 @@ The sketches, the judges' verdicts and what to take from each: `~/code/claude-ha - Make two `Verdict`s unrepresentable: one with both `interrupt` and `finished`, and one with a question and no interrupt. `steps.py:49` ignores `finished` when `interrupt` is set. - Test `run_cycle`, `judge_through_interrupts`, `retried`, `archive`, `trust`, `interrupt`, the models file and the worker's arguments. Only the pure helpers are tested today, because nothing reaches the loop's flow without the effects. - **Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.** Claude Code owns that file and writes it. `trust` reads it, changes it and writes it back, so a write that lands in between is lost. Goal 4.1. -- **Give the `loop-claude` failures that explain nothing a message.** Goal 4.1. - - Show the judge's reply when its verdict is rejected. Its stdout is discarded today, so a judge that failed three times running leaves nothing to diagnose. - - Return a `Stop` when `git` or `os.execv` fails. `checkout.py:7,15` and `reload.py:52` end in a traceback today. -- **Give larv-review a rule for the two cases it is silent on.** Goal 4.1. +- **Make the small fixes filed against the workflow's documents.** Each is a few lines, so they share one chunk. Goal 4.1. - CLI flags and exit codes: name them among the external contracts that fire the architecture pass, or record that they do not. The product-owner row names the CLI; the architecture row does not. - A 🟡 shown factually wrong: give it the 🔴's way out in `review-findings.md`. Today it can only be fixed, declined on a goal, or filed. -- **Remove what the rebuild's merge made stale.** The ⚠️ paragraphs in `AGENTS.md` and `todo.md`, and each decision valid "until the rebuild merges". Goal 4.1. -- **Settle the prose findings earlier reviews filed.** Goal 4.1. + - Remove what the rebuild's merge made stale. The ⚠️ paragraphs in `AGENTS.md` and `todo.md`, and each decision valid "until the rebuild merges". - `docs/decisions.md`: give the comprehension-floor and vocabulary entries a premise that has not expired. Both say "Valid until the next scoring run", and three runs have passed. Put the floor's rule first and its runs' scores in a table. - larv-review: move its reasons for `/security-review` and for the premises chunk's review into `docs/decisions.md`. They are rejected alternatives, which the decision log holds. - `comprehension-panel`: cut the run history and the restated description. They carry nothing the instructions need. - `systems-architect.md`: cut the "one home" line, and break Reasonability Review's steps 4 and 5 into shorter points each. - - `outcome.Failure`'s docstring: say what a failure is, without naming `retried`. A value type does not name its consumer. -- **Make the contributor a standing member of every project's audience.** A project drops them only where its `## Audience` says maintainability does not matter. State that in `CLAUDE.md`'s goals-and-audience rule, and have larv-review's comprehension floor name the contributor as the reader it serves. The floor then gates every chunk while the contributor stands, and a project that drops them skips it. Goal 4.1. -- **Sort `bin/`'s imports on their first binding, and say in `principles/technical-principles.md` → "Deterministic order" how case sorts and which groups Python has.** Today they sort by path, so moving a module reorders unchanged lines. The principle's "host packages" names no Python group. Goal 4.1. + - Make the contributor a standing member of every project's audience. A project drops them only where its `## Audience` says maintainability does not matter. State that in `CLAUDE.md`'s goals-and-audience rule, and have larv-review's comprehension floor name the contributor as the reader it serves. The floor then gates every chunk while the contributor stands, and a project that drops them skips it. - **Judge a cycle on more than the transcript's last 40,000 characters.** `judge.py:80` cuts the transcript there. The session spans every cycle of the chunk, so a decision made early in a long run is never judged, and the human is not interrupted for it. Larger chunks make runs longer. Goal 4.2. - **Have larv-review's prose pass fix only what the chunk touched, and file the rest per `CLAUDE.md` → "Working loop".** Today its fixes land "in this chunk", including cited sections and the sweep that runs with the architecture pass. In the 2026-09-30 bench, rebuild's costliest runs sprawled outside the chunk: one deleted README facts, and one took 13 rounds on the mypy case where main took 6–7 for the same fixes. Source: `~/code/claude-handoffs/claude-config/2026-09-30/bench/comparison.md`. Goal 4.4. - **Record each finished chunk's cost and review numbers on one stats line.** Goal 4.4. -- 2.52.0 From 10bbd4458d726fc0f60769f884af7b5bc3019199 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 21:47:39 +0200 Subject: [PATCH 209/233] Answer the plan review's second round --- CLAUDE.md | 4 ++-- bin/loop_claude/loop/main.py | 2 +- docs/decisions.md | 2 +- todo.md | 15 ++++++++------- 4 files changed, 12 insertions(+), 11 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 63aaed30..3b46773e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,7 +11,7 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The - **When the next release has no items and no work has landed towards it, plan it as this chunk.** Weigh the unscheduled items against the goals, put them in order, and get the human's approval before writing any code. - **When the next release has no items left and work has landed towards it, it is finished: stop.** Report what it holds and that it is ready to cut. Under `/loop`, this ends the loop. Until the human cuts it, only a security fix lands, into that release; never start a later release's items or plan a new one. - **Open every chunk with one line:** the last version cut, what is unreleased (`CHANGELOG.md` → `## Unreleased`, or else the log since the last tag), and the release this chunk ships into. A repo that publishes nothing says so once. -- **Work one chunk at a time, and make it as large as one purpose allows.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which three things hold: one PR title states what they achieve together, without listing them; they sit under one release; and they fire the same review passes (`larv-review` §3). Tiny items, a few lines of change each, need no shared purpose: bundle five to ten from one release into one chunk. Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`, under a release. +- **Work one chunk at a time, and make it as large as one purpose allows.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which three things hold: one PR title states what they achieve together, without listing them; they sit under one release; and they fire the same review passes (`larv-review` §3). Tiny items, a few lines of change each, need neither a shared purpose nor the same passes: bundle up to ten from one release into one chunk. Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`, under a release. - **Ask, don't guess.** First check whether the goals already answer the question. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Write every answer once, where it belongs, never only in chat: a goal in `README.md`, a working rule in `AGENTS.md`, a standing choice in `docs/decisions.md`. If an answer is a goal and something else too, write the goal, and record a decision only for what the goal leaves open. - **Ship every chunk with `/larv-review`.** - **Remove a finished item from `todo.md`; keep its release heading until the version is cut.** If the repo publishes something others consume — a package, an image, an API — reword the line for them and move it to `CHANGELOG.md` under `## Unreleased`. A changelog is for the public, never for the next agent. Otherwise delete the line; git history is the record. @@ -142,7 +142,7 @@ The rules every project follows, compose-not-entangle first: `~/.claude/principl ## Vocabulary -- **chunk** — the unit of work: the largest change with one purpose; "Working loop" says how large that is. +- **chunk** — the unit of work, shipped as one PR; "Working loop" says what it holds. - **cycle** — one worker run and the judge's verdict on it, in `loop-claude`. - **gate** — the merge gate: the checks a PR passes before it merges. - **interrupt** — `loop-claude` handing the terminal to the human, `claude --resume`, for a decision that is theirs. diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index c9b6c868..273d9f56 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -4,7 +4,7 @@ usage: loop-claude Run it anywhere inside a project checkout whose README.md has ## Goals and ## Audience, the premises; the task runs at the checkout root. Each cycle a worker runs the task; a judge then reads -the transcript against them and rules whether the chunk, a change with one purpose, is finished. +the transcript against them and rules whether the chunk, the work of one PR, is finished. A question only the human can answer, or a release ready to cut, is an interrupt: `claude --resume` on the terminal, every worktree first marked trusted in ~/.claude.json. An unfinished chunk resumes its session next cycle; the next chunk starts a fresh session. diff --git a/docs/decisions.md b/docs/decisions.md index 1db05974..6bb83844 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -118,4 +118,4 @@ ## chunk: as large as one purpose allows -2026-10-01, lilleman. Serves goal 4.4. Every review has a fixed cost: each reviewer reloads the rules and the files around the change. Purpose caps a chunk, never a line count. Tiny items are the exception: five to ten, a few lines each, share one chunk whatever their purposes, since the review's fixed cost dwarfs them. Valid until the stats or a bench show that larger chunks lower what reviews catch. +2026-10-01, lilleman. Serves goal 4.4. Every review has a fixed cost: each reviewer reloads the rules and the files around the change. Purpose caps a chunk, never a line count. Tiny items are the exception: up to ten, a few lines each, share one chunk whatever their purposes and passes, since the review's fixed cost dwarfs them. Valid until the stats or a bench show that larger chunks lower what reviews catch. diff --git a/todo.md b/todo.md index 9f2a39a3..de47a987 100644 --- a/todo.md +++ b/todo.md @@ -11,10 +11,9 @@ The sketches, the judges' verdicts and what to take from each: `~/code/claude-ha ## 0.2.0 -- **Make the small fixes filed against `bin/`, the README and `.gitignore`.** Each is a few lines, so they share one chunk. Goals 1, 3 and 4.1. +- **Make the small fixes filed against `bin/`, the README and `.gitignore`.** Goals 1, 3 and 4.1. - Name `jq` and GNU `date` under README → Install, or stop `statusline.sh` needing them. Without `jq` the status line aborts. Under BSD `date` the reset times vanish. Either way CHANGELOG's "runs on any machine unedited" is false. - Narrow `.gitignore`'s `!bin/*` and `skills/*/**` to the files they mean. Today a stray log of `loop-claude` output in `bin/` would be committed, transcript text included. - - Sort `bin/`'s imports on their first binding, and say in `principles/technical-principles.md` → "Deterministic order" how case sorts and which groups Python has. Today they sort by path, so moving a module reorders unchanged lines. The principle's "host packages" names no Python group. - Show the judge's reply when its verdict is rejected. Its stdout is discarded today, so a judge that failed three times running leaves nothing to diagnose. - Return a `Stop` when `git` or `os.execv` fails. `checkout.py:7,15` and `reload.py:52` end in a traceback today. - `outcome.Failure`'s docstring: say what a failure is, without naming `retried`. A value type does not name its consumer. @@ -27,17 +26,19 @@ The sketches, the judges' verdicts and what to take from each: `~/code/claude-ha - Make two `Verdict`s unrepresentable: one with both `interrupt` and `finished`, and one with a question and no interrupt. `steps.py:49` ignores `finished` when `interrupt` is set. - Test `run_cycle`, `judge_through_interrupts`, `retried`, `archive`, `trust`, `interrupt`, the models file and the worker's arguments. Only the pure helpers are tested today, because nothing reaches the loop's flow without the effects. - **Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.** Claude Code owns that file and writes it. `trust` reads it, changes it and writes it back, so a write that lands in between is lost. Goal 4.1. -- **Make the small fixes filed against the workflow's documents.** Each is a few lines, so they share one chunk. Goal 4.1. - - CLI flags and exit codes: name them among the external contracts that fire the architecture pass, or record that they do not. The product-owner row names the CLI; the architecture row does not. - - A 🟡 shown factually wrong: give it the 🔴's way out in `review-findings.md`. Today it can only be fixed, declined on a goal, or filed. +- **Make the small changes filed against the review's rules.** Goals 4.1 and 4.4. + - larv-review §3: name CLI flags and exit codes among the external contracts that fire the architecture pass, or record that they do not. The product-owner row names the CLI; the architecture row does not. + - `review-findings.md`: give a 🟡 shown factually wrong the 🔴's way out. Today it can only be fixed, declined on a goal, or filed. + - Make the contributor a standing member of every project's audience. A project drops them only where its `## Audience` says maintainability does not matter. State that in `CLAUDE.md`'s goals-and-audience rule, and have larv-review's comprehension floor name the contributor as the reader it serves. The floor then gates every chunk while the contributor stands, and a project that drops them skips it. + - Have larv-review's prose pass fix only what the chunk touched, and file the rest per `CLAUDE.md` → "Working loop". Today its fixes land "in this chunk", including cited sections and the sweep that runs with the architecture pass. In the 2026-09-30 bench, rebuild's costliest runs sprawled outside the chunk: one deleted README facts, and one took 13 rounds on the mypy case where main took 6–7 for the same fixes. Source: `~/code/claude-handoffs/claude-config/2026-09-30/bench/comparison.md`. +- **Clean up the rules, skills, agents and decision log.** Goal 4.1. - Remove what the rebuild's merge made stale. The ⚠️ paragraphs in `AGENTS.md` and `todo.md`, and each decision valid "until the rebuild merges". - `docs/decisions.md`: give the comprehension-floor and vocabulary entries a premise that has not expired. Both say "Valid until the next scoring run", and three runs have passed. Put the floor's rule first and its runs' scores in a table. - larv-review: move its reasons for `/security-review` and for the premises chunk's review into `docs/decisions.md`. They are rejected alternatives, which the decision log holds. - `comprehension-panel`: cut the run history and the restated description. They carry nothing the instructions need. - `systems-architect.md`: cut the "one home" line, and break Reasonability Review's steps 4 and 5 into shorter points each. - - Make the contributor a standing member of every project's audience. A project drops them only where its `## Audience` says maintainability does not matter. State that in `CLAUDE.md`'s goals-and-audience rule, and have larv-review's comprehension floor name the contributor as the reader it serves. The floor then gates every chunk while the contributor stands, and a project that drops them skips it. +- **Sort `bin/`'s imports on their first binding, and say in `principles/technical-principles.md` → "Deterministic order" how case sorts and which groups Python has.** Today they sort by path, so moving a module reorders unchanged lines. The principle's "host packages" names no Python group. Goal 4.1. - **Judge a cycle on more than the transcript's last 40,000 characters.** `judge.py:80` cuts the transcript there. The session spans every cycle of the chunk, so a decision made early in a long run is never judged, and the human is not interrupted for it. Larger chunks make runs longer. Goal 4.2. -- **Have larv-review's prose pass fix only what the chunk touched, and file the rest per `CLAUDE.md` → "Working loop".** Today its fixes land "in this chunk", including cited sections and the sweep that runs with the architecture pass. In the 2026-09-30 bench, rebuild's costliest runs sprawled outside the chunk: one deleted README facts, and one took 13 rounds on the mypy case where main took 6–7 for the same fixes. Source: `~/code/claude-handoffs/claude-config/2026-09-30/bench/comparison.md`. Goal 4.4. - **Record each finished chunk's cost and review numbers on one stats line.** Goal 4.4. - Have `loop-claude` write the line to one file at the root of the transcript archive. The line names the project, the commit the chunk started from and the archived transcript's hash. It holds the worker's tokens from the transcript, the judge's from its JSON output, and the chunk's cycles and interrupts, which the loop counts. - End larv-review with a machine-readable summary, and have `loop-claude` copy it from the transcript onto the line: agents launched and rounds per pass; findings per pass by severity, inside the chunk's diff and outside it; and the comprehension scores when the panel ran. -- 2.52.0 From e5ae729116036c3e7b9d1f5d58dd0ce92e7d6831 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 21:48:56 +0200 Subject: [PATCH 210/233] Name the plan in the clean-up item --- todo.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/todo.md b/todo.md index de47a987..55298fc2 100644 --- a/todo.md +++ b/todo.md @@ -31,7 +31,7 @@ The sketches, the judges' verdicts and what to take from each: `~/code/claude-ha - `review-findings.md`: give a 🟡 shown factually wrong the 🔴's way out. Today it can only be fixed, declined on a goal, or filed. - Make the contributor a standing member of every project's audience. A project drops them only where its `## Audience` says maintainability does not matter. State that in `CLAUDE.md`'s goals-and-audience rule, and have larv-review's comprehension floor name the contributor as the reader it serves. The floor then gates every chunk while the contributor stands, and a project that drops them skips it. - Have larv-review's prose pass fix only what the chunk touched, and file the rest per `CLAUDE.md` → "Working loop". Today its fixes land "in this chunk", including cited sections and the sweep that runs with the architecture pass. In the 2026-09-30 bench, rebuild's costliest runs sprawled outside the chunk: one deleted README facts, and one took 13 rounds on the mypy case where main took 6–7 for the same fixes. Source: `~/code/claude-handoffs/claude-config/2026-09-30/bench/comparison.md`. -- **Clean up the rules, skills, agents and decision log.** Goal 4.1. +- **Clean up the rules, skills, agents, plan and decision log.** Goal 4.1. - Remove what the rebuild's merge made stale. The ⚠️ paragraphs in `AGENTS.md` and `todo.md`, and each decision valid "until the rebuild merges". - `docs/decisions.md`: give the comprehension-floor and vocabulary entries a premise that has not expired. Both say "Valid until the next scoring run", and three runs have passed. Put the floor's rule first and its runs' scores in a table. - larv-review: move its reasons for `/security-review` and for the premises chunk's review into `docs/decisions.md`. They are rejected alternatives, which the decision log holds. -- 2.52.0 From 3f5f6de1975a2d0446552951bd577ae7295df67c Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 21:54:58 +0200 Subject: [PATCH 211/233] Ground the judge's quote with markdown emphasis and whitespace ignored --- bin/loop_claude/cycle/judge.py | 8 +++++++- bin/test_loop_claude.py | 4 ++++ todo.md | 1 - 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/bin/loop_claude/cycle/judge.py b/bin/loop_claude/cycle/judge.py index 8e62889b..d20f6457 100644 --- a/bin/loop_claude/cycle/judge.py +++ b/bin/loop_claude/cycle/judge.py @@ -94,4 +94,10 @@ def verdict_from(output) -> Verdict | Failure: def grounded(verdict, transcript) -> bool: - return verdict.evidence.strip() != "" and verdict.evidence in transcript + evidence = plain(verdict.evidence) + return evidence != "" and evidence in plain(transcript) + + +def plain(text) -> str: + # The judge drops markdown emphasis and reflows whitespace when it quotes. + return " ".join(text.replace("*", "").replace("_", "").split()) diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 0e24e76a..c15b17d0 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -104,6 +104,10 @@ class Grounded(unittest.TestCase): self.assertFalse(judge.grounded(verdict("invented"), "the transcript")) self.assertFalse(judge.grounded(verdict(""), "the transcript")) self.assertFalse(judge.grounded(verdict(" "), "the transcript")) + transcript = "done.\n\n**Your step:**\n```\n./run.sh\n```\nRun it." + self.assertTrue(judge.grounded(verdict("Your step:\n```\n./run.sh\n```\nRun it."), transcript)) + self.assertTrue(judge.grounded(verdict("Your step: ``` ./run.sh ``` Run it."), transcript)) + self.assertFalse(judge.grounded(verdict("**"), transcript)) class Verdict(unittest.TestCase): diff --git a/todo.md b/todo.md index 55298fc2..f0e52a15 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,6 @@ The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -- **Match the judge's quote in `grounded()` with markdown emphasis and whitespace ignored, as main's #155 does.** The judge drops a bold line's closing `**` when it quotes the line. `rebuild` rejects such a quote, so merging `rebuild` into main would bring back loops that stop on a correct verdict. - **Bring `rebuild` to the comprehension floor on the four-seat panel, and open its PR into main for the human.** Every dimension and the overall must reach 7.0, and none may fall below the last run. A dimension under the floor gets its places filed above this item. ⚠️ Leave the PR ready and unmerged: only the human merges it, after approving the whole rebuild. The PR deletes main's `AGENTS.md` paragraph on a rebuild chunk's larv-review, which only main holds. ## 0.2.0 -- 2.52.0 From e1852ef39006dbe9b4220a32279b2810edf21864 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 22:02:35 +0200 Subject: [PATCH 212/233] File the places the panel on rebuild at 8585257 named under the floor --- docs/decisions.md | 2 +- todo.md | 7 ++++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index 6bb83844..06e90c90 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -30,7 +30,7 @@ ## comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it -2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files; the places the last run named are filed in `todo.md` under 0.1.0, and a later scoring run may not lower any dimension. Valid until the next scoring run, which uses the same four seats. +2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files, and 7.38, 6.75, 7.25, 6.5, 6.88 at 8585257 on 2026-10-01, Self-sufficiency lowest and every seat naming larv-review §3's round rules; the places the last run named are filed in `todo.md` under 0.1.0, and a later scoring run may not lower any dimension. Valid until the next scoring run, which uses the same four seats. ## vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link diff --git a/todo.md b/todo.md index f0e52a15..d5596264 100644 --- a/todo.md +++ b/todo.md @@ -6,6 +6,12 @@ The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. +The places the panel on `rebuild` at 8585257 named (`docs/decisions.md`), capping dimension first: + +- **Write larv-review §3's "Record, then ask", "Round cap" and "Re-entry" as numbered rules, each stated once.** Every seat reread them three times. "Round cap" alone holds nine rules, and changing what a round is touches `SKILL.md`'s "Round cap", "Re-entry" and §4.5, `review-findings.md` → "Rounds" and `CLAUDE.md` → "Vocabulary". +- **Title each `AGENTS.md` index line by what holds at the commit it ships in.** Three seats searched `bin/` for the full-path id and the refused second loop, which wait on 0.2.0. Two found larv-review §3 running the scoring run on every chunk, which the rebuild exemption contradicts. "cut-over", "stats" and "bench" name nothing a reader can find. +- **Name a project's loop states and give them one transition function.** Moved up from 0.2.0's state machine item. Every seat held whether a run resumes, decided by whether its transcript exists (`steps.py:27`), and the reload's state carried through argv (`reload.py:45`) across three files. +- **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`. - **Bring `rebuild` to the comprehension floor on the four-seat panel, and open its PR into main for the human.** Every dimension and the overall must reach 7.0, and none may fall below the last run. A dimension under the floor gets its places filed above this item. ⚠️ Leave the PR ready and unmerged: only the human merges it, after approving the whole rebuild. The PR deletes main's `AGENTS.md` paragraph on a rebuild chunk's larv-review, which only main holds. ## 0.2.0 @@ -21,7 +27,6 @@ The sketches, the judges' verdicts and what to take from each: `~/code/claude-ha - **Give principles-auditor and prose-reviewer a way to list the project's files.** In the 2026-09-30 audit run their `tools: Read, Grep, Glob` gave them only Read. Each read the files that imports and `.gitignore` named, and listed the files it could not reach. Goal 4.1. - **Make `loop-claude`'s loop a tested state machine with its side effects injected.** Functional core, imperative shell. Goal 4.1. - Inject the side effects: `time.sleep`, `subprocess`, `input()`, `isatty` and `os.execv`. Split `project_model` and `interrupt` into decisions and effects. - - Give a project's loop state named states and one transition function. Today fresh, resuming, awaiting the human and finished come from whether a transcript exists, two verdict booleans and an open `while True` in `steps.py`. - Make two `Verdict`s unrepresentable: one with both `interrupt` and `finished`, and one with a question and no interrupt. `steps.py:49` ignores `finished` when `interrupt` is set. - Test `run_cycle`, `judge_through_interrupts`, `retried`, `archive`, `trust`, `interrupt`, the models file and the worker's arguments. Only the pure helpers are tested today, because nothing reaches the loop's flow without the effects. - **Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.** Claude Code owns that file and writes it. `trust` reads it, changes it and writes it back, so a write that lands in between is lost. Goal 4.1. -- 2.52.0 From 2bd29db69cb64914af8153ca7612f2731ebe4455 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 22:04:34 +0200 Subject: [PATCH 213/233] Answer the prose review's first round --- docs/decisions.md | 2 +- todo.md | 11 +++++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index 06e90c90..9f9bed6c 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -30,7 +30,7 @@ ## comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it -2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files, and 7.38, 6.75, 7.25, 6.5, 6.88 at 8585257 on 2026-10-01, Self-sufficiency lowest and every seat naming larv-review §3's round rules; the places the last run named are filed in `todo.md` under 0.1.0, and a later scoring run may not lower any dimension. Valid until the next scoring run, which uses the same four seats. +2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files, and 7.38, 6.75, 7.25, 6.5, 6.88 at 8585257 on 2026-10-01, lowering Locality, Self-sufficiency and the overall, Self-sufficiency lowest and every seat naming larv-review §3's round rules; the places it named under Self-sufficiency and Locality are filed in `todo.md` under 0.1.0, and a later scoring run may not lower any dimension. Valid until the next scoring run, which uses the same four seats. ## vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link diff --git a/todo.md b/todo.md index d5596264..f857ada0 100644 --- a/todo.md +++ b/todo.md @@ -6,11 +6,14 @@ The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -The places the panel on `rebuild` at 8585257 named (`docs/decisions.md`), capping dimension first: +The places the panel on `rebuild` at 8585257 named under Self-sufficiency and Locality, the dimensions under the floor (scores: `docs/decisions.md` → "comprehension floor"): - **Write larv-review §3's "Record, then ask", "Round cap" and "Re-entry" as numbered rules, each stated once.** Every seat reread them three times. "Round cap" alone holds nine rules, and changing what a round is touches `SKILL.md`'s "Round cap", "Re-entry" and §4.5, `review-findings.md` → "Rounds" and `CLAUDE.md` → "Vocabulary". -- **Title each `AGENTS.md` index line by what holds at the commit it ships in.** Three seats searched `bin/` for the full-path id and the refused second loop, which wait on 0.2.0. Two found larv-review §3 running the scoring run on every chunk, which the rebuild exemption contradicts. "cut-over", "stats" and "bench" name nothing a reader can find. -- **Name a project's loop states and give them one transition function.** Moved up from 0.2.0's state machine item. Every seat held whether a run resumes, decided by whether its transcript exists (`steps.py:27`), and the reload's state carried through argv (`reload.py:45`) across three files. +- **Title each `AGENTS.md` index line by what holds at the commit it ships in.** Three seats searched `bin/` for the full-path id and the refused second loop, which wait on 0.2.0. "cut-over", "stats" and "bench" name nothing a reader can find. +- **State in larv-review §3 that a chunk into `rebuild` takes no scoring run.** Two seats found the skill running it whenever the architecture pass fires, and the exemption only in a decision. +- **Name a project's loop states and give them one transition function.** Every seat had to keep two facts in mind across three files: a run resumes only if its transcript exists (`steps.py:27`), and a reload carries its state through argv (`reload.py:45`). +- **Split `written_by_human`'s boolean into one named check per entry shape.** `formats.py:42` packs three tests into one line, and two seats learnt the cases only from `HumanTurns` in the tests. Every seat named it the unit they least wanted to modify. +- **Have stability-reviewer's step 4 run tests where the project's decisions say.** It says never host runtimes, and two seats found README's tests run on the host by decision. - **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`. - **Bring `rebuild` to the comprehension floor on the four-seat panel, and open its PR into main for the human.** Every dimension and the overall must reach 7.0, and none may fall below the last run. A dimension under the floor gets its places filed above this item. ⚠️ Leave the PR ready and unmerged: only the human merges it, after approving the whole rebuild. The PR deletes main's `AGENTS.md` paragraph on a rebuild chunk's larv-review, which only main holds. @@ -37,7 +40,7 @@ The places the panel on `rebuild` at 8585257 named (`docs/decisions.md`), cappin - Have larv-review's prose pass fix only what the chunk touched, and file the rest per `CLAUDE.md` → "Working loop". Today its fixes land "in this chunk", including cited sections and the sweep that runs with the architecture pass. In the 2026-09-30 bench, rebuild's costliest runs sprawled outside the chunk: one deleted README facts, and one took 13 rounds on the mypy case where main took 6–7 for the same fixes. Source: `~/code/claude-handoffs/claude-config/2026-09-30/bench/comparison.md`. - **Clean up the rules, skills, agents, plan and decision log.** Goal 4.1. - Remove what the rebuild's merge made stale. The ⚠️ paragraphs in `AGENTS.md` and `todo.md`, and each decision valid "until the rebuild merges". - - `docs/decisions.md`: give the comprehension-floor and vocabulary entries a premise that has not expired. Both say "Valid until the next scoring run", and three runs have passed. Put the floor's rule first and its runs' scores in a table. + - `docs/decisions.md`: give the comprehension-floor and vocabulary entries a premise that has not expired. Both say "Valid until the next scoring run", and every run since has passed it. Put the floor's rule first and its runs' scores in a table. - larv-review: move its reasons for `/security-review` and for the premises chunk's review into `docs/decisions.md`. They are rejected alternatives, which the decision log holds. - `comprehension-panel`: cut the run history and the restated description. They carry nothing the instructions need. - `systems-architect.md`: cut the "one home" line, and break Reasonability Review's steps 4 and 5 into shorter points each. -- 2.52.0 From e93359a63542454bdf6e5452b12cc33c2d1acccb Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 22:04:40 +0200 Subject: [PATCH 214/233] Count the seats each place cites as the reports do --- todo.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/todo.md b/todo.md index f857ada0..323f4371 100644 --- a/todo.md +++ b/todo.md @@ -8,11 +8,11 @@ The sketches, the judges' verdicts and what to take from each: `~/code/claude-ha The places the panel on `rebuild` at 8585257 named under Self-sufficiency and Locality, the dimensions under the floor (scores: `docs/decisions.md` → "comprehension floor"): -- **Write larv-review §3's "Record, then ask", "Round cap" and "Re-entry" as numbered rules, each stated once.** Every seat reread them three times. "Round cap" alone holds nine rules, and changing what a round is touches `SKILL.md`'s "Round cap", "Re-entry" and §4.5, `review-findings.md` → "Rounds" and `CLAUDE.md` → "Vocabulary". +- **Write larv-review §3's "Record, then ask", "Round cap" and "Re-entry" as numbered rules, each stated once.** Three seats reread them three times. "Round cap" alone holds nine rules, and changing what a round is touches `SKILL.md`'s "Round cap", "Re-entry" and §4.5, `review-findings.md` → "Rounds" and `CLAUDE.md` → "Vocabulary". - **Title each `AGENTS.md` index line by what holds at the commit it ships in.** Three seats searched `bin/` for the full-path id and the refused second loop, which wait on 0.2.0. "cut-over", "stats" and "bench" name nothing a reader can find. - **State in larv-review §3 that a chunk into `rebuild` takes no scoring run.** Two seats found the skill running it whenever the architecture pass fires, and the exemption only in a decision. - **Name a project's loop states and give them one transition function.** Every seat had to keep two facts in mind across three files: a run resumes only if its transcript exists (`steps.py:27`), and a reload carries its state through argv (`reload.py:45`). -- **Split `written_by_human`'s boolean into one named check per entry shape.** `formats.py:42` packs three tests into one line, and two seats learnt the cases only from `HumanTurns` in the tests. Every seat named it the unit they least wanted to modify. +- **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 it. Every seat named it the unit they least wanted to modify. - **Have stability-reviewer's step 4 run tests where the project's decisions say.** It says never host runtimes, and two seats found README's tests run on the host by decision. - **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`. - **Bring `rebuild` to the comprehension floor on the four-seat panel, and open its PR into main for the human.** Every dimension and the overall must reach 7.0, and none may fall below the last run. A dimension under the floor gets its places filed above this item. ⚠️ Leave the PR ready and unmerged: only the human merges it, after approving the whole rebuild. The PR deletes main's `AGENTS.md` paragraph on a rebuild chunk's larv-review, which only main holds. -- 2.52.0 From c5ebc54f60e15d1d716beca6f23b3ee73f25a331 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 22:06:22 +0200 Subject: [PATCH 215/233] Answer the prose review's second round, and ratchet each score on its best run --- docs/decisions.md | 2 +- todo.md | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index 9f9bed6c..2358b363 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -30,7 +30,7 @@ ## comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it -2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files, and 7.38, 6.75, 7.25, 6.5, 6.88 at 8585257 on 2026-10-01, lowering Locality, Self-sufficiency and the overall, Self-sufficiency lowest and every seat naming larv-review §3's round rules; the places it named under Self-sufficiency and Locality are filed in `todo.md` under 0.1.0, and a later scoring run may not lower any dimension. Valid until the next scoring run, which uses the same four seats. +2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files, and 7.38, 6.75, 7.25, 6.5, 6.88 at 8585257 on 2026-10-01, lowering every dimension but Shape, and the overall, Self-sufficiency lowest and every seat naming larv-review §3's round rules; the places it named under Self-sufficiency and Locality are filed in `todo.md` under 0.1.0, and a later scoring run may not score any dimension or the overall below its best run so far, 2026-10-01, lilleman. Valid until the next scoring run, which uses the same four seats. ## vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link diff --git a/todo.md b/todo.md index 323f4371..c96629db 100644 --- a/todo.md +++ b/todo.md @@ -8,14 +8,14 @@ The sketches, the judges' verdicts and what to take from each: `~/code/claude-ha The places the panel on `rebuild` at 8585257 named under Self-sufficiency and Locality, the dimensions under the floor (scores: `docs/decisions.md` → "comprehension floor"): -- **Write larv-review §3's "Record, then ask", "Round cap" and "Re-entry" as numbered rules, each stated once.** Three seats reread them three times. "Round cap" alone holds nine rules, and changing what a round is touches `SKILL.md`'s "Round cap", "Re-entry" and §4.5, `review-findings.md` → "Rounds" and `CLAUDE.md` → "Vocabulary". +- **Write larv-review §3's "Record, then ask", "Round cap" and "Re-entry" as numbered rules, each stated once.** Three seats each reread them three times. "Round cap" alone holds nine rules, and changing what a round is touches `SKILL.md`'s "Round cap", "Re-entry" and §4.5, `review-findings.md` → "Rounds" and `CLAUDE.md` → "Vocabulary". - **Title each `AGENTS.md` index line by what holds at the commit it ships in.** Three seats searched `bin/` for the full-path id and the refused second loop, which wait on 0.2.0. "cut-over", "stats" and "bench" name nothing a reader can find. - **State in larv-review §3 that a chunk into `rebuild` takes no scoring run.** Two seats found the skill running it whenever the architecture pass fires, and the exemption only in a decision. -- **Name a project's loop states and give them one transition function.** Every seat had to keep two facts in mind across three files: a run resumes only if its transcript exists (`steps.py:27`), and a reload carries its state through argv (`reload.py:45`). -- **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 it. Every seat named it the unit they least wanted to modify. +- **Name a project's loop states and give them one transition function.** Every seat had to keep two facts in mind: a run resumes only if its transcript exists (`steps.py:27`), and a reload carries its state through argv (`reload.py:45`). +- **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`. Every seat named it the unit they least wanted to modify. - **Have stability-reviewer's step 4 run tests where the project's decisions say.** It says never host runtimes, and two seats found README's tests run on the host by decision. - **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`. -- **Bring `rebuild` to the comprehension floor on the four-seat panel, and open its PR into main for the human.** Every dimension and the overall must reach 7.0, and none may fall below the last run. A dimension under the floor gets its places filed above this item. ⚠️ Leave the PR ready and unmerged: only the human merges it, after approving the whole rebuild. The PR deletes main's `AGENTS.md` paragraph on a rebuild chunk's larv-review, which only main holds. +- **Bring `rebuild` to the comprehension floor on the four-seat panel, and open its PR into main for the human.** Every dimension and the overall must reach 7.0, and none may fall below its best run so far. A dimension under the floor gets its places filed above this item. ⚠️ Leave the PR ready and unmerged: only the human merges it, after approving the whole rebuild. The PR deletes main's `AGENTS.md` paragraph on a rebuild chunk's larv-review, which only main holds. ## 0.2.0 -- 2.52.0 From 4a8236e7519a871d068b12445ae98aa5009215ab Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 22:06:28 +0200 Subject: [PATCH 216/233] Credit written_by_human's least-want count to the three seats asked --- todo.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/todo.md b/todo.md index c96629db..8c2f3edb 100644 --- a/todo.md +++ b/todo.md @@ -12,7 +12,7 @@ The places the panel on `rebuild` at 8585257 named under Self-sufficiency and Lo - **Title each `AGENTS.md` index line by what holds at the commit it ships in.** Three seats searched `bin/` for the full-path id and the refused second loop, which wait on 0.2.0. "cut-over", "stats" and "bench" name nothing a reader can find. - **State in larv-review §3 that a chunk into `rebuild` takes no scoring run.** Two seats found the skill running it whenever the architecture pass fires, and the exemption only in a decision. - **Name a project's loop states and give them one transition function.** Every seat had to keep two facts in mind: a run resumes only if its transcript exists (`steps.py:27`), and a reload carries its state through argv (`reload.py:45`). -- **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`. Every seat named it the unit they least wanted to modify. +- **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. - **Have stability-reviewer's step 4 run tests where the project's decisions say.** It says never host runtimes, and two seats found README's tests run on the host by decision. - **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`. - **Bring `rebuild` to the comprehension floor on the four-seat panel, and open its PR into main for the human.** Every dimension and the overall must reach 7.0, and none may fall below its best run so far. A dimension under the floor gets its places filed above this item. ⚠️ Leave the PR ready and unmerged: only the human merges it, after approving the whole rebuild. The PR deletes main's `AGENTS.md` paragraph on a rebuild chunk's larv-review, which only main holds. -- 2.52.0 From 6ddcbaf9616636b00537a202611839cf41986822 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 22:08:44 +0200 Subject: [PATCH 217/233] Ratchet each score on its best run on rebuild --- docs/decisions.md | 2 +- todo.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index 2358b363..0c97b487 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -30,7 +30,7 @@ ## comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it -2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files, and 7.38, 6.75, 7.25, 6.5, 6.88 at 8585257 on 2026-10-01, lowering every dimension but Shape, and the overall, Self-sufficiency lowest and every seat naming larv-review §3's round rules; the places it named under Self-sufficiency and Locality are filed in `todo.md` under 0.1.0, and a later scoring run may not score any dimension or the overall below its best run so far, 2026-10-01, lilleman. Valid until the next scoring run, which uses the same four seats. +2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files, and 7.38, 6.75, 7.25, 6.5, 6.88 at 8585257 on 2026-10-01, lowering every dimension but Shape, and the overall, Self-sufficiency lowest and every seat naming larv-review §3's round rules; the places it named under Self-sufficiency and Locality are filed in `todo.md` under 0.1.0, and a later scoring run may not score any dimension or the overall below its best run on `rebuild`, 2026-10-01, lilleman. Valid until the next scoring run, which uses the same four seats. ## vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link diff --git a/todo.md b/todo.md index 8c2f3edb..6079cd88 100644 --- a/todo.md +++ b/todo.md @@ -15,7 +15,7 @@ The places the panel on `rebuild` at 8585257 named under Self-sufficiency and Lo - **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. - **Have stability-reviewer's step 4 run tests where the project's decisions say.** It says never host runtimes, and two seats found README's tests run on the host by decision. - **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`. -- **Bring `rebuild` to the comprehension floor on the four-seat panel, and open its PR into main for the human.** Every dimension and the overall must reach 7.0, and none may fall below its best run so far. A dimension under the floor gets its places filed above this item. ⚠️ Leave the PR ready and unmerged: only the human merges it, after approving the whole rebuild. The PR deletes main's `AGENTS.md` paragraph on a rebuild chunk's larv-review, which only main holds. +- **Bring `rebuild` to the comprehension floor on the four-seat panel, and open its PR into main for the human.** 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. ⚠️ Leave the PR ready and unmerged: only the human merges it, after approving the whole rebuild. The PR deletes main's `AGENTS.md` paragraph on a rebuild chunk's larv-review, which only main holds. ## 0.2.0 -- 2.52.0 From 02216fc6e954f3811a8827197e6680a0a3925a41 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 22:14:58 +0200 Subject: [PATCH 218/233] =?UTF-8?q?Write=20larv-review=20=C2=A73's=20recor?= =?UTF-8?q?d,=20round=20and=20re-entry=20rules=20as=20numbered=20rules,=20?= =?UTF-8?q?and=20exempt=20a=20chunk=20into=20rebuild=20from=20the=20scorin?= =?UTF-8?q?g=20run=20there?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- skills/larv-review/SKILL.md | 26 +++++++++++++++++++++----- todo.md | 4 +--- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 472a51eb..329b96b2 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -35,13 +35,29 @@ Follow `~/.claude/CLAUDE.md` → "Git, commits, and PRs". Never commit to the de | Product-owner | product-owner-reviewer | changes an external surface: API, CLI, UI, error or deprecation text a consumer reads, README and docs an outside reader lands on | | Prose | prose-reviewer | every chunk; a fix, where it touches prose | -A comment is prose, not code. Passes run in this order: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. A 🔀 escalation runs the named pass once the current pass is done; its fixes re-enter like any other. +A comment is prose, not code. Passes run in this order: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. A 🔀 escalation runs the named pass once the current pass is done. -**Record, then ask**, for the architecture pass and the full scan: where, before the chunk began, the repo held the decision this change executes — a decision-log entry, or a planning item crediting the pass — the pass is done: cite the record and skip it. The architecture pass's principles audit and scoring run are excepted: they run whenever the pass fires, unasked, since no record older than the chunk checked the code it writes. A change that *departs* from the record is unreviewed however thorough the record is. Fired and not skipped → ask the user with the evidence and your recommendation; no user reachable → run it. +**Record, then ask** — for the architecture pass and the full scan: -**Round cap.** A round is one launch of a pass's reviewer, whatever launched it, a rerun after the architect's Stage 0 questions — the goals, audience, scale or domain language it found unrecorded — included. The architecture pass's round is the architect (unless skipped), the principles audit and the scoring run, so a fix to any of their findings reruns the whole round; the external auto-reviewer (§4) is a pass of its own, each review it posts a round. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. A pass is done on no 🔴 and no 🟡, until a re-entry reruns it; the 🟢 and ❓ left are addressed in the round that finished it — fixed, answered, declined or filed in `todo.md`; a ❓ only the user can answer is asked; no user reachable → filed. A pass takes at most three rounds per chunk; instead of a fourth, list what is open and ask the user — for the auto-reviewer, before any push that would summon a fourth, fixes waiting unpushed. A yes grants that pass one more round, after which the ask repeats; a no leaves the PR unmerged. +1. A record is a decision-log entry, or a planning item crediting the pass, that the repo held before the chunk began. Where one holds the decision this change executes, the pass is done: cite the record. +2. A change that departs from the record is unreviewed, however thorough the record is. +3. Fired and not skipped → ask the user, with the evidence and your recommendation; no user reachable → run it. +4. The principles audit and the scoring run run whenever the architecture pass fires, unasked: no record older than the chunk checked the code it writes. A chunk whose PR goes into `rebuild` takes no scoring run. -**Re-entry.** A fix is a change no pass has seen, a 🟢's or ❓'s included. A round's fixes re-enter together: run, in table order, each pass whose trigger they fire and the pass whose 🔴 or 🟡 they answer, a pass at its cap getting the cap's ask; then §4. +**Round cap.** + +1. A round is one launch of a pass's reviewer, whatever launched it: a re-entry, or a rerun after the architect's Stage 0 questions. +2. The architecture pass's round is the architect (unless skipped), the principles audit and the scoring run, so a fix to any one's finding reruns all three. +3. The external auto-reviewer (§4) is a pass of its own, each review it posts a round. +4. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. +5. A pass is done on no 🔴 and no 🟡. The round that finishes it addresses each 🟢 and ❓ left: fixed, answered, declined or filed in `todo.md`. A ❓ only the user can answer is asked; no user reachable → filed. +6. A pass takes at most three rounds per chunk. Instead of a fourth, list what is open and ask the user; for the auto-reviewer, before the push that would summon its fourth, the fixes held unpushed. +7. A yes grants that pass one more round, after which the ask repeats; a no leaves the PR unmerged. + +**Re-entry.** + +1. A fix is a change no pass has seen, a 🟢's or ❓'s included. +2. A round's fixes re-enter together: run, in table order, each pass whose trigger they fire and each pass whose 🔴 or 🟡 they answer, a done pass included; a pass at its cap gets "Round cap" rule 6's ask instead. Then §4. ### Architecture @@ -75,7 +91,7 @@ Launch prose-reviewer with what the diff touched and every section this review c ## 4. Gate 1. Run the project's test suite locally unless the last stability round already left it verified green. -2. Watch the forge's checks until every one passes. A red check is a finding; its fix re-enters per §3. +2. Watch the forge's checks until every one passes. A red check is a finding. 3. No CI configured → the gate is local tests only; note it in the summary. 4. Everything green → mark the PR ready, dropping any `WIP:`/`Draft:` title prefix. 5. **External auto-reviewer**, when the repo has one — its config file (`.coderabbit.yaml` and the like), or its comments on earlier PRs; none → skip it, say so. Marking the PR ready is what summons it. Wait up to **10 minutes** for its first review, checking about once a minute; nothing by then → note it in the summary and carry on, never waiting twice. Its rounds, §3 → "Round cap". Once it has reviewed, each later return here, after a fix re-entered per §3, waits up to **5 minutes** for its re-review of the new commit. diff --git a/todo.md b/todo.md index 6079cd88..f26624af 100644 --- a/todo.md +++ b/todo.md @@ -8,9 +8,7 @@ The sketches, the judges' verdicts and what to take from each: `~/code/claude-ha The places the panel on `rebuild` at 8585257 named under Self-sufficiency and Locality, the dimensions under the floor (scores: `docs/decisions.md` → "comprehension floor"): -- **Write larv-review §3's "Record, then ask", "Round cap" and "Re-entry" as numbered rules, each stated once.** Three seats each reread them three times. "Round cap" alone holds nine rules, and changing what a round is touches `SKILL.md`'s "Round cap", "Re-entry" and §4.5, `review-findings.md` → "Rounds" and `CLAUDE.md` → "Vocabulary". - **Title each `AGENTS.md` index line by what holds at the commit it ships in.** Three seats searched `bin/` for the full-path id and the refused second loop, which wait on 0.2.0. "cut-over", "stats" and "bench" name nothing a reader can find. -- **State in larv-review §3 that a chunk into `rebuild` takes no scoring run.** Two seats found the skill running it whenever the architecture pass fires, and the exemption only in a decision. - **Name a project's loop states and give them one transition function.** Every seat had to keep two facts in mind: a run resumes only if its transcript exists (`steps.py:27`), and a reload carries its state through argv (`reload.py:45`). - **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. - **Have stability-reviewer's step 4 run tests where the project's decisions say.** It says never host runtimes, and two seats found README's tests run on the host by decision. @@ -39,7 +37,7 @@ The places the panel on `rebuild` at 8585257 named under Self-sufficiency and Lo - Make the contributor a standing member of every project's audience. A project drops them only where its `## Audience` says maintainability does not matter. State that in `CLAUDE.md`'s goals-and-audience rule, and have larv-review's comprehension floor name the contributor as the reader it serves. The floor then gates every chunk while the contributor stands, and a project that drops them skips it. - Have larv-review's prose pass fix only what the chunk touched, and file the rest per `CLAUDE.md` → "Working loop". Today its fixes land "in this chunk", including cited sections and the sweep that runs with the architecture pass. In the 2026-09-30 bench, rebuild's costliest runs sprawled outside the chunk: one deleted README facts, and one took 13 rounds on the mypy case where main took 6–7 for the same fixes. Source: `~/code/claude-handoffs/claude-config/2026-09-30/bench/comparison.md`. - **Clean up the rules, skills, agents, plan and decision log.** Goal 4.1. - - Remove what the rebuild's merge made stale. The ⚠️ paragraphs in `AGENTS.md` and `todo.md`, and each decision valid "until the rebuild merges". + - Remove what the rebuild's merge made stale. The ⚠️ paragraphs in `AGENTS.md` and `todo.md`, each decision valid "until the rebuild merges", and larv-review §3's exemption of a chunk into `rebuild` from the scoring run. - `docs/decisions.md`: give the comprehension-floor and vocabulary entries a premise that has not expired. Both say "Valid until the next scoring run", and every run since has passed it. Put the floor's rule first and its runs' scores in a table. - larv-review: move its reasons for `/security-review` and for the premises chunk's review into `docs/decisions.md`. They are rejected alternatives, which the decision log holds. - `comprehension-panel`: cut the run history and the restated description. They carry nothing the instructions need. -- 2.52.0 From 9dc4d807400f8a4028829bbe30ad36da43883d82 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 22:16:32 +0200 Subject: [PATCH 219/233] Answer the prose review's first round --- skills/larv-review/SKILL.md | 16 ++++++++-------- todo.md | 2 +- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 329b96b2..ca8bf485 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -39,25 +39,25 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod **Record, then ask** — for the architecture pass and the full scan: -1. A record is a decision-log entry, or a planning item crediting the pass, that the repo held before the chunk began. Where one holds the decision this change executes, the pass is done: cite the record. +1. A record is a decision-log entry, or a planning item crediting the pass, that the repo held before the chunk began. Where one holds the decision this change executes, skip the pass and cite the record. 2. A change that departs from the record is unreviewed, however thorough the record is. -3. Fired and not skipped → ask the user, with the evidence and your recommendation; no user reachable → run it. -4. The principles audit and the scoring run run whenever the architecture pass fires, unasked: no record older than the chunk checked the code it writes. A chunk whose PR goes into `rebuild` takes no scoring run. +3. Fired and not skipped → ask the user whether to run it, with the evidence and your recommendation; no user reachable → run it. +4. The architecture pass runs the principles audit and the scoring run whenever it fires, unasked: no record older than the chunk checked the code it writes. **Round cap.** -1. A round is one launch of a pass's reviewer, whatever launched it: a re-entry, or a rerun after the architect's Stage 0 questions. -2. The architecture pass's round is the architect (unless skipped), the principles audit and the scoring run, so a fix to any one's finding reruns all three. +1. A round is one launch of a pass's reviewer: the first, each re-entry, and the rerun after the architect's Stage 0 questions. +2. The architecture pass's round is the architect (unless skipped), the principles audit and the scoring run, so a fix to any of their findings reruns the whole round. 3. The external auto-reviewer (§4) is a pass of its own, each review it posts a round. 4. From round 2, prompt an agent under `~/.claude/agents/` with the previous round's findings verbatim and what changed since. 5. A pass is done on no 🔴 and no 🟡. The round that finishes it addresses each 🟢 and ❓ left: fixed, answered, declined or filed in `todo.md`. A ❓ only the user can answer is asked; no user reachable → filed. -6. A pass takes at most three rounds per chunk. Instead of a fourth, list what is open and ask the user; for the auto-reviewer, before the push that would summon its fourth, the fixes held unpushed. +6. A pass takes at most three rounds per chunk. Instead of a fourth, list what is open and ask the user. For the auto-reviewer, ask before the push that would summon its fourth, and hold the fixes unpushed until the answer. 7. A yes grants that pass one more round, after which the ask repeats; a no leaves the PR unmerged. **Re-entry.** 1. A fix is a change no pass has seen, a 🟢's or ❓'s included. -2. A round's fixes re-enter together: run, in table order, each pass whose trigger they fire and each pass whose 🔴 or 🟡 they answer, a done pass included; a pass at its cap gets "Round cap" rule 6's ask instead. Then §4. +2. A round's fixes re-enter together: run, in table order, each pass whose trigger they fire, a done pass included, and each pass whose 🔴 or 🟡 they answer; a pass at its cap gets "Round cap" rule 6's ask instead. Then §4. ### Architecture @@ -68,7 +68,7 @@ Launch systems-architect: review the system as a whole entered through this chan Then the principles audit: one principles-auditor per file in `~/.claude/principles/` and one for the README's goals, each over the whole project in every round. A finding outside the chunk is filed in `todo.md`; a 🔴 on a decision is asked, since the decision is the user's. -Then the comprehension floor: the `comprehension-panel` skill's scoring run (`~/.claude/skills/comprehension-panel/SKILL.md` → "The scoring run") over the whole project, not the diff. With any dimension or the overall below 7.0 the chunk does not merge: fix the places the seats name under the capping dimension, or take the user's explicit decision to ship under the floor, record it in `docs/decisions.md` with the scores, and file the places in `todo.md`. No user reachable → fix. At the floor or above, the scores are still a ratchet — a later chunk may not lower any — and the four dimension scores and the overall go in the summary so the next run can see the direction of travel. +Then the comprehension floor: the `comprehension-panel` skill's scoring run (`~/.claude/skills/comprehension-panel/SKILL.md` → "The scoring run") over the whole project, not the diff; a chunk whose PR goes into `rebuild` takes none. With any dimension or the overall below 7.0 the chunk does not merge: fix the places the seats name under the capping dimension, or take the user's explicit decision to ship under the floor, record it in `docs/decisions.md` with the scores, and file the places in `todo.md`. No user reachable → fix. At the floor or above, the scores are still a ratchet — a later chunk may not lower any — and the four dimension scores and the overall go in the summary so the next run can see the direction of travel. ### Security diff --git a/todo.md b/todo.md index f26624af..61306c2f 100644 --- a/todo.md +++ b/todo.md @@ -37,7 +37,7 @@ The places the panel on `rebuild` at 8585257 named under Self-sufficiency and Lo - Make the contributor a standing member of every project's audience. A project drops them only where its `## Audience` says maintainability does not matter. State that in `CLAUDE.md`'s goals-and-audience rule, and have larv-review's comprehension floor name the contributor as the reader it serves. The floor then gates every chunk while the contributor stands, and a project that drops them skips it. - Have larv-review's prose pass fix only what the chunk touched, and file the rest per `CLAUDE.md` → "Working loop". Today its fixes land "in this chunk", including cited sections and the sweep that runs with the architecture pass. In the 2026-09-30 bench, rebuild's costliest runs sprawled outside the chunk: one deleted README facts, and one took 13 rounds on the mypy case where main took 6–7 for the same fixes. Source: `~/code/claude-handoffs/claude-config/2026-09-30/bench/comparison.md`. - **Clean up the rules, skills, agents, plan and decision log.** Goal 4.1. - - Remove what the rebuild's merge made stale. The ⚠️ paragraphs in `AGENTS.md` and `todo.md`, each decision valid "until the rebuild merges", and larv-review §3's exemption of a chunk into `rebuild` from the scoring run. + - Remove what the rebuild's merge made stale. The ⚠️ paragraphs in `AGENTS.md` and `todo.md`, each decision valid "until the rebuild merges", and larv-review §3 → "Architecture"'s exemption of a chunk into `rebuild` from the scoring run. - `docs/decisions.md`: give the comprehension-floor and vocabulary entries a premise that has not expired. Both say "Valid until the next scoring run", and every run since has passed it. Put the floor's rule first and its runs' scores in a table. - larv-review: move its reasons for `/security-review` and for the premises chunk's review into `docs/decisions.md`. They are rejected alternatives, which the decision log holds. - `comprehension-panel`: cut the run history and the restated description. They carry nothing the instructions need. -- 2.52.0 From 4c0f593a6ae276282bbb0e614d1beb42980d715a Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 22:16:58 +0200 Subject: [PATCH 220/233] Answer the prose review's second round --- skills/larv-review/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index ca8bf485..f30359e6 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -42,7 +42,7 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod 1. A record is a decision-log entry, or a planning item crediting the pass, that the repo held before the chunk began. Where one holds the decision this change executes, skip the pass and cite the record. 2. A change that departs from the record is unreviewed, however thorough the record is. 3. Fired and not skipped → ask the user whether to run it, with the evidence and your recommendation; no user reachable → run it. -4. The architecture pass runs the principles audit and the scoring run whenever it fires, unasked: no record older than the chunk checked the code it writes. +4. No record skips the principles audit or the scoring run: no record older than the chunk checked the code it writes. **Round cap.** -- 2.52.0 From 000c76d8b6e0677a69cfd288bd50c832b3ca87a6 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 22:17:21 +0200 Subject: [PATCH 221/233] Answer the prose review's third round --- skills/larv-review/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index f30359e6..762f3394 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -42,7 +42,7 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod 1. A record is a decision-log entry, or a planning item crediting the pass, that the repo held before the chunk began. Where one holds the decision this change executes, skip the pass and cite the record. 2. A change that departs from the record is unreviewed, however thorough the record is. 3. Fired and not skipped → ask the user whether to run it, with the evidence and your recommendation; no user reachable → run it. -4. No record skips the principles audit or the scoring run: no record older than the chunk checked the code it writes. +4. A record or the user's no skips only the architect, never the principles audit or the scoring run: no record older than the chunk checked the code it writes. **Round cap.** -- 2.52.0 From 8cc2ad05d0dd25ea8274b1986d9b3496f2f9dfc8 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 22:22:15 +0200 Subject: [PATCH 222/233] Plan every remaining item into 0.1.0 --- todo.md | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/todo.md b/todo.md index 61306c2f..cab4872f 100644 --- a/todo.md +++ b/todo.md @@ -8,15 +8,11 @@ The sketches, the judges' verdicts and what to take from each: `~/code/claude-ha The places the panel on `rebuild` at 8585257 named under Self-sufficiency and Locality, the dimensions under the floor (scores: `docs/decisions.md` → "comprehension floor"): -- **Title each `AGENTS.md` index line by what holds at the commit it ships in.** Three seats searched `bin/` for the full-path id and the refused second loop, which wait on 0.2.0. "cut-over", "stats" and "bench" name nothing a reader can find. +- **Title each `AGENTS.md` index line by what holds at the commit it ships in.** Three seats searched `bin/` for the full-path id and the refused second loop, which wait on items below. "cut-over", "stats" and "bench" name nothing a reader can find. - **Name a project's loop states and give them one transition function.** Every seat had to keep two facts in mind: a run resumes only if its transcript exists (`steps.py:27`), and a reload carries its state through argv (`reload.py:45`). - **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. - **Have stability-reviewer's step 4 run tests where the project's decisions say.** It says never host runtimes, and two seats found README's tests run on the host by decision. - **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`. -- **Bring `rebuild` to the comprehension floor on the four-seat panel, and open its PR into main for the human.** 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. ⚠️ Leave the PR ready and unmerged: only the human merges it, after approving the whole rebuild. The PR deletes main's `AGENTS.md` paragraph on a rebuild chunk's larv-review, which only main holds. - -## 0.2.0 - - **Make the small fixes filed against `bin/`, the README and `.gitignore`.** Goals 1, 3 and 4.1. - Name `jq` and GNU `date` under README → Install, or stop `statusline.sh` needing them. Without `jq` the status line aborts. Under BSD `date` the reset times vanish. Either way CHANGELOG's "runs on any machine unedited" is false. - Narrow `.gitignore`'s `!bin/*` and `skills/*/**` to the files they mean. Today a stray log of `loop-claude` output in `bin/` would be committed, transcript text included. @@ -49,3 +45,4 @@ The places the panel on `rebuild` at 8585257 named under Self-sufficiency and Lo - 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 `rebuild` to the comprehension floor on the four-seat panel, and open its PR into main for the human.** 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. ⚠️ Leave the PR ready and unmerged: only the human merges it, after approving the whole rebuild. The PR deletes main's `AGENTS.md` paragraph on a rebuild chunk's larv-review, which only main holds. -- 2.52.0 From c260a24ff7319926118803270deb33d66fdd49f2 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 22:25:02 +0200 Subject: [PATCH 223/233] Scope todo.md's panel line to the items it introduces --- todo.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/todo.md b/todo.md index cab4872f..65a0a745 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,7 @@ The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -The places the panel on `rebuild` at 8585257 named under Self-sufficiency and Locality, the dimensions under the floor (scores: `docs/decisions.md` → "comprehension floor"): +The first five items are the places the panel on `rebuild` at 8585257 named under Self-sufficiency and Locality, the dimensions under the floor (scores: `docs/decisions.md` → "comprehension floor"). - **Title each `AGENTS.md` index line by what holds at the commit it ships in.** Three seats searched `bin/` for the full-path id and the refused second loop, which wait on items below. "cut-over", "stats" and "bench" name nothing a reader can find. - **Name a project's loop states and give them one transition function.** Every seat had to keep two facts in mind: a run resumes only if its transcript exists (`steps.py:27`), and a reload carries its state through argv (`reload.py:45`). -- 2.52.0 From 471b86db5ef24f517d5ad9bb119fe75132bdb89e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 22:32:44 +0200 Subject: [PATCH 224/233] Title each decision by what holds now, and make the small fixes filed against bin/, the README, .gitignore and stability-reviewer --- .gitignore | 7 ++++--- AGENTS.md | 8 ++++---- CHANGELOG.md | 3 ++- CLAUDE.md | 2 +- README.md | 2 +- agents/stability-reviewer.md | 2 +- bin/loop_claude/cycle/judge.py | 4 +++- bin/loop_claude/loop/main.py | 16 +++++++++------- bin/loop_claude/loop/reload.py | 20 +++++++++++++------- bin/loop_claude/outcome.py | 2 +- bin/loop_claude/project/checkout.py | 10 ++++++++-- bin/test_loop_claude.py | 15 ++++++++++++++- bin/test_loop_claude_black_box.py | 8 ++++++-- docs/decisions.md | 10 +++++----- todo.md | 10 +--------- 15 files changed, 73 insertions(+), 46 deletions(-) diff --git a/.gitignore b/.gitignore index ba2981f2..ae8d17f1 100644 --- a/.gitignore +++ b/.gitignore @@ -18,15 +18,16 @@ !agents/ !agents/*.md !bin/ -!bin/* +!bin/loop-claude !bin/loop_claude/**/ !bin/loop_claude/**/*.py +!bin/test_*.py !docs/ !docs/*.md !principles/ !principles/*.md !skills/ !skills/comprehension-panel/ -!skills/comprehension-panel/** +!skills/comprehension-panel/*.md !skills/larv-review/ -!skills/larv-review/** +!skills/larv-review/*.md diff --git a/AGENTS.md b/AGENTS.md index 4103ee82..30b6c9ab 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,7 +6,7 @@ Decisions live in `docs/decisions.md`: - larv-review: a project under the comprehension floor is fixed at the capping dimension - loop-claude: a judge decides interrupts, not the worker's self-report -- loop-claude: one session per project, at a fixed id from its full path, and a second loop refuses to start +- loop-claude: one session per project, at a fixed id from its path - loop-claude: the trust file is rewritten before an interrupt - loop-claude: every worktree of the checkout is trusted before an interrupt - bin/: the Python floor is README's Install prerequisite @@ -23,7 +23,7 @@ Decisions live in `docs/decisions.md`: - loop-claude: the judge is retried alone, on its own counter - loop-claude: the judge loads `CLAUDE.md` - loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop -- loop-claude: a loop running main's script stops once at the cut-over +- loop-claude: a loop started on main's script stops at its first reload into the rebuild's - 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 @@ -31,6 +31,6 @@ Decisions live in `docs/decisions.md`: - review: an ask no user answers leaves the PR unmerged - review: the architecture pass audits every principle and goal over the whole project, and a release's last chunk fires it - loop-claude: every claude it starts bypasses permissions inside its sandbox -- stats: a chunk's cost and review numbers are kept in the transcript archive -- bench: a workflow change merges only once three benches rule it better +- loop-claude: the stats line `todo.md` plans goes in the transcript archive +- workflow changes: under the bench `todo.md` plans, one merges only once three benches rule it better - chunk: as large as one purpose allows diff --git a/CHANGELOG.md b/CHANGELOG.md index 155beca6..b794d77c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,12 +4,13 @@ - Run `loop-claude` only in a sandbox with no direct access to production: every claude it starts skips every permission prompt. - First release: `README.md` states what the checkout holds and needs, `loop-claude --help` what `loop-claude` does. -- `settings.json`, the agents and the status line run on any machine unedited; the status line shows reset times in the machine's own time zone. +- `settings.json`, the agents and the status line run unedited on any machine with README → Install's prerequisites; the status line shows reset times in the machine's own time zone. - `loop-claude`'s no-premises exit names what is wrong: `README.md` unopenable or not UTF-8, a `## Goals` or `## Audience` heading missing or repeated, or nothing under one. - `loop-claude` says why when it cannot read or write `~/.claude.json` before an interrupt, naming a `projects` entry that is not an object, and the interrupt then lands in Claude Code's trust dialog. - `loop-claude` skips a transcript line it cannot parse, exits 1 naming a transcript it cannot read, and counts a `claude` it cannot start as a failed worker run. - `loop-claude`'s judge quotes the transcript for every verdict, and a verdict quoting nothing or interrupting without a question, or a `claude` the judge cannot start, is a failed judge run; a `claude` that cannot start for an interrupt exits 1. - `loop-claude`'s exit-2 message says what the human is needed for. +- `loop-claude` exits 1 saying why when it cannot start `git` or reload itself, and shows the judge's reply when it rejects a verdict. - `loop-claude` retries a failed worker within its cycle. - `loop-claude` counts an interrupt reply starting with `<` as typed. - `loop-claude`'s judge sees a reply the human types while claude works, and an interrupt counts one as typed. diff --git a/CLAUDE.md b/CLAUDE.md index 3b46773e..b7cb63b2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -79,7 +79,7 @@ Prose describing the code as it stands — a comment, a README, an `AGENTS.md`, ### Decisions: one home, each linked to a goal or a technical principle -**A decision record owns what a call site may not say.** A rejected alternative, or what something deliberately does not cover, is banned beside the code precisely because the decision record holds it — a standing choice a future reader would otherwise relitigate, where a `CHANGELOG` holds what changed in a release. **The decision log has one home: `docs/decisions.md`**, or `docs/decisions/` split by area once it outgrows one file. `AGENTS.md` carries a one-line index of the titles, so a session or a reviewer sees that a decision exists without loading its reasoning. An entry states the decision, its date, who made it, and the premise it rests on ("valid while X") so it can expire honestly when that premise dies. A decision found anywhere else — an `AGENTS.md` body, a comment, or a README section that is neither a goal nor how one is met — moves there and leaves its index line behind. A goal stays a goal in the README; the log records only what the goal leaves open. +**A decision record owns what a call site may not say.** A rejected alternative, or what something deliberately does not cover, is banned beside the code precisely because the decision record holds it — a standing choice a future reader would otherwise relitigate, where a `CHANGELOG` holds what changed in a release. **The decision log has one home: `docs/decisions.md`**, or `docs/decisions/` split by area once it outgrows one file. `AGENTS.md` carries a one-line index of the titles, so a session or a reviewer sees that a decision exists without loading its reasoning. A title states what holds at the commit it ships in, in words a reader finds in the code or the plan. An entry states the decision, its date, who made it, and the premise it rests on ("valid while X") so it can expire honestly when that premise dies. A decision found anywhere else — an `AGENTS.md` body, a comment, or a README section that is neither a goal nor how one is met — moves there and leaves its index line behind. A goal stays a goal in the README; the log records only what the goal leaves open. **Every decision links to a goal or a technical principle.** An entry names the goal it serves or the technical principle under `~/.claude/principles/` it applies; one that can do neither is a missing goal, and an entry already in the repo with neither behind it is a finding. Propose the goal, never a reason of your own — "Ask, don't guess" under "Working loop" says how. An entry working against a goal or a technical principle stands only while it names the `todo.md` item that ends it. diff --git a/README.md b/README.md index 1750f014..dbecd577 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ Me, on my own machines, which take tagged releases. Nobody else depends on it. ## Install -Check out the latest tag in `~/.claude`, with Python 3.11 or newer as `python3` on `PATH`. Link the tool onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Run it only in a sandbox with no direct access to a production environment, such as a dedicated VM: every claude it starts, the interrupt included, skips every permission prompt. +Check out the latest tag in `~/.claude`, with Python 3.11 or newer as `python3` on `PATH`, and `jq` and GNU `date` for `statusline.sh`. Link the tool onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Run it only in a sandbox with no direct access to a production environment, such as a dedicated VM: every claude it starts, the interrupt included, skips every permission prompt. ## Release diff --git a/agents/stability-reviewer.md b/agents/stability-reviewer.md index 7db07782..c3a4ade0 100644 --- a/agents/stability-reviewer.md +++ b/agents/stability-reviewer.md @@ -11,7 +11,7 @@ You are an elite stability-focused code reviewer with deep expertise in defensiv 1. **Scope the change.** You review every PR; a fresh invocation has no prior context, so determine the diff yourself. Diff the PR branch against its base (`gh pr diff`, or `git merge-base HEAD` then `git diff`), and review the changed lines **plus enough surrounding code and callers** to judge correctness — read the whole changed file when practical; a diff alone hides whether a caller breaks. Read the PR description and, when the project uses an issue tracker (project-specific — check its docs) and the change references a ticket, that ticket: the diff is judged against its stated intent, and a scope mismatch in either direction is a finding — claimed-but-unimplemented, and implemented-but-unasked (#2). 2. **Read every file in the shared principles** at `~/.claude/principles/` — not just `technical-principles.md`, also `frontend.md`, `logging.md`, and `rest-apis.md`. These are mandatory org guidelines; all code MUST comply. Map the relevant file(s) to the change (frontend PR → `frontend.md`; API PR → `rest-apis.md`; etc.). Re-read each time — they change. Flag violations prominently. 3. **Read README.md, AGENTS.md and `docs/decisions.md`** in the current project for project-specific conventions, build instructions, tooling, and the accepted trade-offs a reviewer should honor rather than re-flag. Note the documented test, lint, and static-analysis commands — you will run them. -4. **Verify, don't just read.** Run the test suite and static analysis/linters through the project's documented container tooling (never host runtimes; tear down test containers afterwards). A full-suite run catches broken callers that diff-reading misses. When a suspected bug is cheap to confirm, reproduce it — a scratch script in a temp dir, a targeted test run — before reporting it. Leave the working tree exactly as you found it. Anything you could not run goes in Coverage & Verification, never silently skipped. +4. **Verify, don't just read.** Run the test suite and static analysis/linters as the project's README and decisions say, through its container tooling unless a decision puts them on the host; tear down test containers afterwards. A full-suite run catches broken callers that diff-reading misses. When a suspected bug is cheap to confirm, reproduce it — a scratch script in a temp dir, a targeted test run — before reporting it. Leave the working tree exactly as you found it. Anything you could not run goes in Coverage & Verification, never silently skipped. 5. **Two passes minimum, then hunt absences.** - *Breadth:* every hunk in every changed file, no skimming. Track which files you have covered; batch large diffs, never truncate the review. - *Depth:* trace the riskiest data paths end-to-end (input → logic → persistence/response), the interactions between changed pieces, and between the change and config (timeout hierarchies, retries × idempotency, queue worker counts, env parity). diff --git a/bin/loop_claude/cycle/judge.py b/bin/loop_claude/cycle/judge.py index d20f6457..83705188 100644 --- a/bin/loop_claude/cycle/judge.py +++ b/bin/loop_claude/cycle/judge.py @@ -67,7 +67,9 @@ def run_judge(root, args, prompt, transcript) -> Verdict | Failure: if proc.returncode != 0: return Failure(proc.stderr.strip() or f"the judge exited {proc.returncode}") verdict = verdict_from(structured_output(proc.stdout)) - if isinstance(verdict, Verdict) and not grounded(verdict, transcript): + if isinstance(verdict, Failure): + return Failure(f"{verdict.reason}; it replied: {proc.stdout.strip()}") + if not grounded(verdict, transcript): return Failure(f"the judge quoted {verdict.evidence!r}, nothing in the transcript" + (f", for the question: {verdict.question}" if verdict.interrupt else "")) return verdict diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 273d9f56..8ef4241f 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -10,12 +10,13 @@ on the terminal, every worktree first marked trusted in ~/.claude.json. An unfin its session next cycle; the next chunk starts a fresh session. Cycles continue until an exit below or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary". -Exit 1: no task, not inside a checkout, no premises, a models file it cannot read or write, claude -leaves no transcript or one it cannot read or archive, claude cannot start for an interrupt, a -reload with unreadable state, or the worker or the judge fails three times running, retried a minute -apart within the cycle. A worker fails when claude cannot start, exits non-zero, is killed, or ends -without a result event; a judge when claude cannot start or exits non-zero, or its verdict misses or -mistypes a field, interrupts without a question, or quotes nothing in the transcript. +Exit 1: no task, git cannot start or finds no checkout, no premises, a models file it cannot read or +write, claude leaves no transcript or one it cannot read or archive, claude cannot start for an +interrupt, a reload that cannot start or reads unreadable state, or the worker or the judge fails +three times running, retried a minute apart within the cycle. A worker fails when claude cannot +start, exits non-zero, is killed, or ends without a result event; a judge when claude cannot start +or exits non-zero, or its verdict misses or mistypes a field, interrupts without a question, or +quotes nothing in the transcript. Exit 2: the human is needed, to pick the model or answer an interrupt, and stdin or stdout is not a terminal, the input ends, or the interrupt ended with nothing typed. Rerunning resumes any open session. @@ -63,7 +64,8 @@ def run_loop(argv, env, paths, launcher, cwd) -> Stop: project = project_name(state.root, paths.code) session = session_for(project, paths) while True: - exec_if_edited(launcher, baseline, state) + if stop := exec_if_edited(launcher, baseline, state): + return stop state = dataclasses.replace(state, cycle_number=state.cycle_number + 1) premises = read_premises(state.root) if isinstance(premises, Stop): diff --git a/bin/loop_claude/loop/reload.py b/bin/loop_claude/loop/reload.py index 2f5949a8..7aa7c48a 100644 --- a/bin/loop_claude/loop/reload.py +++ b/bin/loop_claude/loop/reload.py @@ -6,6 +6,8 @@ import subprocess import sys import typing +from loop_claude.outcome import Stop + RELOAD_FLAG = "--reloaded" T = typing.TypeVar("T") @@ -42,11 +44,15 @@ def fingerprint(launcher) -> str: return digest.hexdigest() -def exec_if_edited(launcher, baseline, state) -> None: +def exec_if_edited(launcher, baseline, state) -> Stop | None: if fingerprint(launcher) == baseline: - return - trial = subprocess.run([sys.executable, launcher, "--help"], capture_output=True, text=True) - if trial.returncode != 0: - print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr) - return - os.execv(sys.executable, [sys.executable, str(launcher), RELOAD_FLAG, json.dumps(dataclasses.asdict(state))]) + return None + try: + trial = subprocess.run([sys.executable, launcher, "--help"], capture_output=True, text=True) + if trial.returncode != 0: + print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr) + return None + os.execv(sys.executable, [sys.executable, str(launcher), RELOAD_FLAG, json.dumps(dataclasses.asdict(state))]) + except OSError as failure: + return Stop(1, f"could not reload loop-claude: {failure.strerror}; rerun loop-claude ") + return None diff --git a/bin/loop_claude/outcome.py b/bin/loop_claude/outcome.py index e6a90142..95fa3451 100644 --- a/bin/loop_claude/outcome.py +++ b/bin/loop_claude/outcome.py @@ -3,7 +3,7 @@ import dataclasses @dataclasses.dataclass(frozen=True) class Failure: - """A step failed and its caller decides: `retried` reruns a worker or judge run until it fails three times running; anything else becomes a Stop or a warning.""" + """A step failed, for reason; its caller decides what follows.""" reason: str diff --git a/bin/loop_claude/project/checkout.py b/bin/loop_claude/project/checkout.py index 3400e389..7c700b89 100644 --- a/bin/loop_claude/project/checkout.py +++ b/bin/loop_claude/project/checkout.py @@ -4,7 +4,10 @@ from loop_claude.outcome import Stop def checkout_root(cwd) -> str | Stop: - found = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, cwd=cwd, text=True) + try: + found = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, cwd=cwd, text=True) + except OSError as failure: + return Stop(1, f"could not start git: {failure.strerror}") if found.returncode != 0: return Stop(1, found.stderr.strip()) return found.stdout.strip() @@ -12,7 +15,10 @@ def checkout_root(cwd) -> str | Stop: def checkouts(root) -> list[str]: found = [root] - listing = subprocess.run(["git", "worktree", "list", "--porcelain"], capture_output=True, cwd=root, text=True) + try: + listing = subprocess.run(["git", "worktree", "list", "--porcelain"], capture_output=True, cwd=root, text=True) + except OSError: + return found if listing.returncode == 0: found += [line.split(" ", 1)[1] for line in listing.stdout.splitlines() if line.startswith("worktree ")] return sorted(set(found)) diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index c15b17d0..004a4ab1 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -5,6 +5,7 @@ import pathlib import sys import tempfile import unittest +from unittest import mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) @@ -13,7 +14,7 @@ from loop_claude.claude_code import formats, transcript from loop_claude.cycle import judge from loop_claude.loop import main, reload from loop_claude.outcome import Failure, Stop -from loop_claude.project import premises +from loop_claude.project import checkout, premises CWD = pathlib.Path("/c") @@ -133,6 +134,18 @@ class LoopState(unittest.TestCase): self.assertEqual(reload.decode_state('{"count": 1, "name": "n"}', Stringly), Stringly(1, "n")) self.assertIsNone(reload.decode_state('{"count": "1", "name": "n"}', Stringly)) + def test_stops_when_the_reload_cannot_start_python(self): + with tempfile.TemporaryDirectory() as root, mock.patch("os.execv", side_effect=OSError(2, "No such file or directory")): + launcher = pathlib.Path(root, "loop-claude") + launcher.write_text("") + self.assertEqual(reload.exec_if_edited(launcher, "stale", main.LoopState(1, "/r", "do it")), Stop(1, "could not reload loop-claude: No such file or directory; rerun loop-claude ")) + + +class Checkouts(unittest.TestCase): + def test_lists_the_root_alone_when_git_cannot_start(self): + with tempfile.TemporaryDirectory() as empty, mock.patch.dict(os.environ, {"PATH": empty}): + self.assertEqual(checkout.checkouts(empty), [empty]) + class ReplaceFile(unittest.TestCase): diff --git a/bin/test_loop_claude_black_box.py b/bin/test_loop_claude_black_box.py index 318d6138..689434e7 100644 --- a/bin/test_loop_claude_black_box.py +++ b/bin/test_loop_claude_black_box.py @@ -300,6 +300,10 @@ class Premises(unittest.TestCase): run = checkout.run([worker()]) self.assertEqual((run.code, run.calls), (1, [])) self.assertEqual(run.stderr.strip(), f"README.md in {checkout.root}: Is a directory - no premises.") + (checkout.temp / "fake-bin" / "git").unlink() + run = checkout.run([worker()]) + self.assertEqual((run.code, run.calls), (1, [])) + self.assertEqual(run.stderr.strip(), "could not start git: No such file or directory") def test_names_the_session_by_the_checkout_relative_to_code_or_else_to_the_root(self): checkout = Checkout(self) @@ -378,8 +382,8 @@ class Cycles(unittest.TestCase): self.assertEqual(run.roles(), ["worker", "judge", "judge", "judge"]) self.assertEqual(run.sleeps, [60, 60]) self.assertIn("retrying the judge in a minute: judge down", run.stderr) - self.assertIn("retrying the judge in a minute: the judge returned no verdict", run.stderr) - self.assertEqual(run.stderr.strip().splitlines()[-1], "the judge failed three times running: the judge's verdict has no evidence of type string") + self.assertIn("retrying the judge in a minute: the judge returned no verdict; it replied: {}\n", run.stderr) + self.assertEqual(run.stderr.strip().splitlines()[-1], 'the judge failed three times running: the judge\'s verdict has no evidence of type string; it replied: {"structured_output": {"interrupt": false}}') def test_retries_the_judge_alone_when_its_verdict_quotes_nothing_in_the_transcript(self): checkout = Checkout(self) diff --git a/docs/decisions.md b/docs/decisions.md index 0c97b487..abfce045 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -8,7 +8,7 @@ 2026-09-21, lilleman. Serves goal 4. Asked to name the goal behind each choice, the worker cites a real goal for a choice that goal does not settle, and under-reports its own decisions; the judge's bar is whether the README discriminates between the alternatives. Valid while the worker's self-report stays unreliable. -## loop-claude: one session per project, at a fixed id from its full path, and a second loop refuses to start +## loop-claude: one session per project, at a fixed id from its path 2026-09-21, lilleman; revised 2026-09-30 by lilleman. Serves goal 4. One fixed id per project keeps the session picker at one entry per project and makes any transcript under that id loop-claude's own to delete. The id derives from the checkout's full path, so no two checkouts share one, and `loop-claude` refuses to start while another session on that id is active. Moving the checkout orphans its open sessions, archive folder and models entry: sessions stay in the picker until the human deletes them, migration code not being worth a one-human audience. Until `todo.md`'s "Key a project on its checkout's full path" lands, the id is the checkout's path relative to `~/code`, or to `/` outside it, and a second loop is not refused, so a checkout outside `~/code` mirroring a path inside it shares its id. Valid while claude takes `--session-id` and resumes by it. @@ -76,9 +76,9 @@ 2026-09-28, lilleman, for the rebuild. Serves goals 2 and 4: saving each transcript locally is the first step of backing it up, and it shows afterwards what an unattended run did. A copy of the `.jsonl`, deduplicated by content hash, with the verdict beside it; a rendering drops tool results, and a second-resolution stamp names two states within one second as one file. A failed archive exits 1, since a loop that loses its record silently fails the backup goal. Valid while transcripts stay small enough to copy whole. -## loop-claude: a loop running main's script stops once at the cut-over +## loop-claude: a loop started on main's script stops at its first reload into the rebuild's -2026-09-29, lilleman. Serves goal 4. The rebuild's `LoopState` lacks main's failure count, so a loop running main's script exits 1 at its first reload into the rebuild, telling the human to rerun `loop-claude `. No code exists only for the cut-over: one rerun costs a one-human audience less. Valid until the rebuild merges. +2026-09-29, lilleman. Serves goal 4. The rebuild's `LoopState` lacks main's failure count, so a loop running main's script exits 1 at its first reload into the rebuild, telling the human to rerun `loop-claude `. No code exists only for that reload: one rerun costs a one-human audience less. Valid until the rebuild merges. ## rebuild: a chunk into `rebuild` takes no comprehension scoring run @@ -108,11 +108,11 @@ 2026-09-30, lilleman. Applies "Always grant explicit access to data": the sandbox `loop-claude` runs in is where access is granted, so the worker and the interrupt run with `bypassPermissions`. The worker may read `~/.claude/.credentials.json`: it holds Claude Code's own credentials, which claude reads to run anyway. Its one seam to production is the forge: what it pushes or merges can publish through CI. Valid while `loop-claude` runs only in the sandbox README → Install names. -## stats: a chunk's cost and review numbers are kept in the transcript archive +## loop-claude: the stats line `todo.md` plans goes in the transcript archive 2026-10-01, lilleman. Serves goals 3 and 4.4. The numbers show whether a change to the workflow raised quality or only cost. Each line names another project and its chunk, so the file stays off this repo's remote. `loop-claude` writes the line: the tokens, cycles and interrupts it counts, and the review's numbers from the summary larv-review ends with. Valid while the transcript archive stays off the remote. -## bench: a workflow change merges only once three benches rule it better +## workflow changes: under the bench `todo.md` plans, one merges only once three benches rule it better 2026-10-01, lilleman. Serves goals 4.1 and 4.4. The 2026-09-30 bench showed one run cannot tell a workflow's effect from the variance between runs. One bench ruling it worse closes the PR, since quality comes first (goal 4.1), and `docs/workflow-learnings.md` keeps what the PR changed and why it lost. Three is a starting number, to be evaluated against the stats. Valid until that evaluation changes the number. diff --git a/todo.md b/todo.md index 65a0a745..e8277fb1 100644 --- a/todo.md +++ b/todo.md @@ -6,19 +6,11 @@ The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -The first five items are the places the panel on `rebuild` at 8585257 named under Self-sufficiency and Locality, the dimensions under the floor (scores: `docs/decisions.md` → "comprehension floor"). +The first three items are the places the panel on `rebuild` at 8585257 named under Self-sufficiency and Locality, the dimensions under the floor (scores: `docs/decisions.md` → "comprehension floor"). -- **Title each `AGENTS.md` index line by what holds at the commit it ships in.** Three seats searched `bin/` for the full-path id and the refused second loop, which wait on items below. "cut-over", "stats" and "bench" name nothing a reader can find. - **Name a project's loop states and give them one transition function.** Every seat had to keep two facts in mind: a run resumes only if its transcript exists (`steps.py:27`), and a reload carries its state through argv (`reload.py:45`). - **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. -- **Have stability-reviewer's step 4 run tests where the project's decisions say.** It says never host runtimes, and two seats found README's tests run on the host by decision. - **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 the small fixes filed against `bin/`, the README and `.gitignore`.** Goals 1, 3 and 4.1. - - Name `jq` and GNU `date` under README → Install, or stop `statusline.sh` needing them. Without `jq` the status line aborts. Under BSD `date` the reset times vanish. Either way CHANGELOG's "runs on any machine unedited" is false. - - Narrow `.gitignore`'s `!bin/*` and `skills/*/**` to the files they mean. Today a stray log of `loop-claude` output in `bin/` would be committed, transcript text included. - - Show the judge's reply when its verdict is rejected. Its stdout is discarded today, so a judge that failed three times running leaves nothing to diagnose. - - Return a `Stop` when `git` or `os.execv` fails. `checkout.py:7,15` and `reload.py:52` end in a traceback today. - - `outcome.Failure`'s docstring: say what a failure is, without naming `retried`. A value type does not name its consumer. - **Archive the transcript as each cycle ends.** Today only an interrupt or a finished chunk archives it, so a failed exit or Ctrl-C loses the transcript. 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. `checkout.py:22` 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. - **Give principles-auditor and prose-reviewer a way to list the project's files.** In the 2026-09-30 audit run their `tools: Read, Grep, Glob` gave them only Read. Each read the files that imports and `.gitignore` named, and listed the files it could not reach. Goal 4.1. -- 2.52.0 From 2f3b2f0f6c9d8ea63661f4d23c1a42dc502132fc Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 22:35:22 +0200 Subject: [PATCH 225/233] Un-ignore bin/loop_claude/ itself, and test that no tracked file is ignored --- .gitignore | 1 + bin/test_gitignore.py | 10 ++++++++++ 2 files changed, 11 insertions(+) create mode 100644 bin/test_gitignore.py diff --git a/.gitignore b/.gitignore index ae8d17f1..9cdc73f7 100644 --- a/.gitignore +++ b/.gitignore @@ -19,6 +19,7 @@ !agents/*.md !bin/ !bin/loop-claude +!bin/loop_claude/ !bin/loop_claude/**/ !bin/loop_claude/**/*.py !bin/test_*.py diff --git a/bin/test_gitignore.py b/bin/test_gitignore.py new file mode 100644 index 00000000..42f730e3 --- /dev/null +++ b/bin/test_gitignore.py @@ -0,0 +1,10 @@ +import subprocess +import unittest + +from test_python_floor import ROOT + + +class Gitignore(unittest.TestCase): + def test_ignores_no_tracked_file(self): + ignored = subprocess.run(["git", "ls-files", "-ci", "--exclude-standard"], capture_output=True, check=True, cwd=ROOT, text=True).stdout + self.assertEqual(ignored, "") -- 2.52.0 From be2d96a808a7da7a3a89af3bb3f9ae8b0a6263b3 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 22:39:51 +0200 Subject: [PATCH 226/233] Answer the product-owner review's first round --- AGENTS.md | 2 +- CHANGELOG.md | 2 +- bin/loop_claude/cycle/judge.py | 2 +- bin/loop_claude/loop/main.py | 10 +++++----- bin/test_loop_claude_black_box.py | 4 ++-- docs/decisions.md | 2 +- 6 files changed, 11 insertions(+), 11 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 30b6c9ab..e6d36179 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -32,5 +32,5 @@ Decisions live in `docs/decisions.md`: - review: the architecture pass audits every principle and goal over the whole project, and a release's last chunk fires it - loop-claude: every claude it starts bypasses permissions inside its sandbox - loop-claude: the stats line `todo.md` plans goes in the transcript archive -- workflow changes: under the bench `todo.md` plans, one merges only once three benches rule it better +- workflow changes: one merges only once three runs of the bench `todo.md` plans rule it better - chunk: as large as one purpose allows diff --git a/CHANGELOG.md b/CHANGELOG.md index b794d77c..7a8b4e9f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ - `loop-claude` skips a transcript line it cannot parse, exits 1 naming a transcript it cannot read, and counts a `claude` it cannot start as a failed worker run. - `loop-claude`'s judge quotes the transcript for every verdict, and a verdict quoting nothing or interrupting without a question, or a `claude` the judge cannot start, is a failed judge run; a `claude` that cannot start for an interrupt exits 1. - `loop-claude`'s exit-2 message says what the human is needed for. -- `loop-claude` exits 1 saying why when it cannot start `git` or reload itself, and shows the judge's reply when it rejects a verdict. +- `loop-claude` exits 1 saying why when `git`, or python for a reload, cannot start, and shows the judge's reply when it rejects a verdict. - `loop-claude` retries a failed worker within its cycle. - `loop-claude` counts an interrupt reply starting with `<` as typed. - `loop-claude`'s judge sees a reply the human types while claude works, and an interrupt counts one as typed. diff --git a/bin/loop_claude/cycle/judge.py b/bin/loop_claude/cycle/judge.py index 83705188..92258226 100644 --- a/bin/loop_claude/cycle/judge.py +++ b/bin/loop_claude/cycle/judge.py @@ -68,7 +68,7 @@ def run_judge(root, args, prompt, transcript) -> Verdict | Failure: return Failure(proc.stderr.strip() or f"the judge exited {proc.returncode}") verdict = verdict_from(structured_output(proc.stdout)) if isinstance(verdict, Failure): - return Failure(f"{verdict.reason}; it replied: {proc.stdout.strip()}") + return Failure(f"{verdict.reason}; it replied: {proc.stdout.strip() or 'nothing'}") if not grounded(verdict, transcript): return Failure(f"the judge quoted {verdict.evidence!r}, nothing in the transcript" + (f", for the question: {verdict.question}" if verdict.interrupt else "")) return verdict diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 8ef4241f..858374cc 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -12,11 +12,11 @@ Cycles continue until an exit below or Ctrl-C. Words: ~/.claude/CLAUDE.md → "V Exit 1: no task, git cannot start or finds no checkout, no premises, a models file it cannot read or write, claude leaves no transcript or one it cannot read or archive, claude cannot start for an -interrupt, a reload that cannot start or reads unreadable state, or the worker or the judge fails -three times running, retried a minute apart within the cycle. A worker fails when claude cannot -start, exits non-zero, is killed, or ends without a result event; a judge when claude cannot start -or exits non-zero, or its verdict misses or mistypes a field, interrupts without a question, or -quotes nothing in the transcript. +interrupt, python cannot start for a reload, a reload with unreadable state, or the worker or the +judge fails three times running, retried a minute apart within the cycle. A worker fails when claude +cannot start, exits non-zero, is killed, or ends without a result event; a judge when claude cannot +start or exits non-zero, or its verdict misses or mistypes a field, interrupts without a question, +or quotes nothing in the transcript. Exit 2: the human is needed, to pick the model or answer an interrupt, and stdin or stdout is not a terminal, the input ends, or the interrupt ended with nothing typed. Rerunning resumes any open session. diff --git a/bin/test_loop_claude_black_box.py b/bin/test_loop_claude_black_box.py index 689434e7..17b438f6 100644 --- a/bin/test_loop_claude_black_box.py +++ b/bin/test_loop_claude_black_box.py @@ -377,12 +377,12 @@ class Cycles(unittest.TestCase): self.assertEqual(run.code, 130) self.assertEqual(run.sleeps, [60, 60, 60, 60]) - run = checkout.run([worker(), judge(exit=1, stderr="judge down"), judge(stdout="{}"), judge(verdict={"interrupt": False})]) + run = checkout.run([worker(), judge(exit=1, stderr="judge down"), judge(stdout=""), judge(verdict={"interrupt": False})]) self.assertEqual(run.code, 1) self.assertEqual(run.roles(), ["worker", "judge", "judge", "judge"]) self.assertEqual(run.sleeps, [60, 60]) self.assertIn("retrying the judge in a minute: judge down", run.stderr) - self.assertIn("retrying the judge in a minute: the judge returned no verdict; it replied: {}\n", run.stderr) + self.assertIn("retrying the judge in a minute: the judge returned no verdict; it replied: nothing\n", run.stderr) self.assertEqual(run.stderr.strip().splitlines()[-1], 'the judge failed three times running: the judge\'s verdict has no evidence of type string; it replied: {"structured_output": {"interrupt": false}}') def test_retries_the_judge_alone_when_its_verdict_quotes_nothing_in_the_transcript(self): diff --git a/docs/decisions.md b/docs/decisions.md index abfce045..c2c91732 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -112,7 +112,7 @@ 2026-10-01, lilleman. Serves goals 3 and 4.4. The numbers show whether a change to the workflow raised quality or only cost. Each line names another project and its chunk, so the file stays off this repo's remote. `loop-claude` writes the line: the tokens, cycles and interrupts it counts, and the review's numbers from the summary larv-review ends with. Valid while the transcript archive stays off the remote. -## workflow changes: under the bench `todo.md` plans, one merges only once three benches rule it better +## workflow changes: one merges only once three runs of the bench `todo.md` plans rule it better 2026-10-01, lilleman. Serves goals 4.1 and 4.4. The 2026-09-30 bench showed one run cannot tell a workflow's effect from the variance between runs. One bench ruling it worse closes the PR, since quality comes first (goal 4.1), and `docs/workflow-learnings.md` keeps what the PR changed and why it lost. Three is a starting number, to be evaluated against the stats. Valid until that evaluation changes the number. -- 2.52.0 From f118809d858dbc08f8f306c2db1e975c3d715b20 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 22:44:09 +0200 Subject: [PATCH 227/233] Answer the prose review's first round --- AGENTS.md | 6 +++--- CHANGELOG.md | 3 ++- CLAUDE.md | 2 +- agents/stability-reviewer.md | 2 +- docs/decisions.md | 8 ++++---- 5 files changed, 11 insertions(+), 10 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e6d36179..bd1fb206 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,7 +6,7 @@ Decisions live in `docs/decisions.md`: - larv-review: a project under the comprehension floor is fixed at the capping dimension - loop-claude: a judge decides interrupts, not the worker's self-report -- loop-claude: one session per project, at a fixed id from its path +- loop-claude: one session per project, at a fixed id from its checkout's path - loop-claude: the trust file is rewritten before an interrupt - loop-claude: every worktree of the checkout is trusted before an interrupt - bin/: the Python floor is README's Install prerequisite @@ -31,6 +31,6 @@ Decisions live in `docs/decisions.md`: - review: an ask no user answers leaves the PR unmerged - review: the architecture pass audits every principle and goal over the whole project, and a release's last chunk fires it - loop-claude: every claude it starts bypasses permissions inside its sandbox -- loop-claude: the stats line `todo.md` plans goes in the transcript archive -- workflow changes: one merges only once three runs of the bench `todo.md` plans rule it better +- loop-claude: the planned stats line goes in the transcript archive +- workflow changes: a change merges only once three planned benches rule it better - chunk: as large as one purpose allows diff --git a/CHANGELOG.md b/CHANGELOG.md index 7a8b4e9f..33bc8696 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,8 @@ - `loop-claude` skips a transcript line it cannot parse, exits 1 naming a transcript it cannot read, and counts a `claude` it cannot start as a failed worker run. - `loop-claude`'s judge quotes the transcript for every verdict, and a verdict quoting nothing or interrupting without a question, or a `claude` the judge cannot start, is a failed judge run; a `claude` that cannot start for an interrupt exits 1. - `loop-claude`'s exit-2 message says what the human is needed for. -- `loop-claude` exits 1 saying why when `git`, or python for a reload, cannot start, and shows the judge's reply when it rejects a verdict. +- `loop-claude` exits 1 saying why when `git`, or python for a reload, cannot start. +- `loop-claude` shows the judge's reply when it rejects the judge's verdict. - `loop-claude` retries a failed worker within its cycle. - `loop-claude` counts an interrupt reply starting with `<` as typed. - `loop-claude`'s judge sees a reply the human types while claude works, and an interrupt counts one as typed. diff --git a/CLAUDE.md b/CLAUDE.md index b7cb63b2..f4554bf6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -104,7 +104,7 @@ Prose describing the code as it stands — a comment, a README, an `AGENTS.md`, ## Working with the codebase - Always start a new git worktree when doing something in a codebase, and clean it up when done. Unless told otherwise, branch it off a freshly-updated default branch (`git fetch origin`, then base on `origin/main`), not whatever happens to be checked out. - Keep the project's main checkout (e.g. `~/code/log`, never a worktree) current: when it is behind `origin` — a merge landed, or a fetch shows it — run `git pull --ff-only` there instead of reporting the lag, never with `--autostash`: a dirty checkout is a finding to report, not to carry along. -- Run a project's language runtime, package manager, and task runner through its container/tooling setup, never directly on the host. Example: `docker compose run --rm app …`. +- Run a project's language runtime, package manager, and task runner through its container/tooling setup, never directly on the host unless a decision puts them there. Example: `docker compose run --rm app …`. - Tear down test containers after a run. - Check `README.md` first for build, test, install, and codegen commands; one that misbehaves is fixed per "A false claim is a bug". Refresh `README.md` whenever you change what it describes ("Refresh `README.md` to match"). - Sort wherever order carries no meaning (`~/.claude/principles/technical-principles.md`) — attributes, array and object keys, enum members, imports, table rows, and line-based file lists such as `.gitignore`/`.dockerignore`. Exception: `id` goes first. diff --git a/agents/stability-reviewer.md b/agents/stability-reviewer.md index c3a4ade0..e0f82235 100644 --- a/agents/stability-reviewer.md +++ b/agents/stability-reviewer.md @@ -11,7 +11,7 @@ You are an elite stability-focused code reviewer with deep expertise in defensiv 1. **Scope the change.** You review every PR; a fresh invocation has no prior context, so determine the diff yourself. Diff the PR branch against its base (`gh pr diff`, or `git merge-base HEAD` then `git diff`), and review the changed lines **plus enough surrounding code and callers** to judge correctness — read the whole changed file when practical; a diff alone hides whether a caller breaks. Read the PR description and, when the project uses an issue tracker (project-specific — check its docs) and the change references a ticket, that ticket: the diff is judged against its stated intent, and a scope mismatch in either direction is a finding — claimed-but-unimplemented, and implemented-but-unasked (#2). 2. **Read every file in the shared principles** at `~/.claude/principles/` — not just `technical-principles.md`, also `frontend.md`, `logging.md`, and `rest-apis.md`. These are mandatory org guidelines; all code MUST comply. Map the relevant file(s) to the change (frontend PR → `frontend.md`; API PR → `rest-apis.md`; etc.). Re-read each time — they change. Flag violations prominently. 3. **Read README.md, AGENTS.md and `docs/decisions.md`** in the current project for project-specific conventions, build instructions, tooling, and the accepted trade-offs a reviewer should honor rather than re-flag. Note the documented test, lint, and static-analysis commands — you will run them. -4. **Verify, don't just read.** Run the test suite and static analysis/linters as the project's README and decisions say, through its container tooling unless a decision puts them on the host; tear down test containers afterwards. A full-suite run catches broken callers that diff-reading misses. When a suspected bug is cheap to confirm, reproduce it — a scratch script in a temp dir, a targeted test run — before reporting it. Leave the working tree exactly as you found it. Anything you could not run goes in Coverage & Verification, never silently skipped. +4. **Verify, don't just read.** Run the test suite and static analysis/linters through the project's container tooling, unless a decision puts them on the host; tear down test containers afterwards. A full-suite run catches broken callers that diff-reading misses. When a suspected bug is cheap to confirm, reproduce it — a scratch script in a temp dir, a targeted test run — before reporting it. Leave the working tree exactly as you found it. Anything you could not run goes in Coverage & Verification, never silently skipped. 5. **Two passes minimum, then hunt absences.** - *Breadth:* every hunk in every changed file, no skimming. Track which files you have covered; batch large diffs, never truncate the review. - *Depth:* trace the riskiest data paths end-to-end (input → logic → persistence/response), the interactions between changed pieces, and between the change and config (timeout hierarchies, retries × idempotency, queue worker counts, env parity). diff --git a/docs/decisions.md b/docs/decisions.md index c2c91732..c5959e4d 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -8,9 +8,9 @@ 2026-09-21, lilleman. Serves goal 4. Asked to name the goal behind each choice, the worker cites a real goal for a choice that goal does not settle, and under-reports its own decisions; the judge's bar is whether the README discriminates between the alternatives. Valid while the worker's self-report stays unreliable. -## loop-claude: one session per project, at a fixed id from its path +## loop-claude: one session per project, at a fixed id from its checkout's path -2026-09-21, lilleman; revised 2026-09-30 by lilleman. Serves goal 4. One fixed id per project keeps the session picker at one entry per project and makes any transcript under that id loop-claude's own to delete. The id derives from the checkout's full path, so no two checkouts share one, and `loop-claude` refuses to start while another session on that id is active. Moving the checkout orphans its open sessions, archive folder and models entry: sessions stay in the picker until the human deletes them, migration code not being worth a one-human audience. Until `todo.md`'s "Key a project on its checkout's full path" lands, the id is the checkout's path relative to `~/code`, or to `/` outside it, and a second loop is not refused, so a checkout outside `~/code` mirroring a path inside it shares its id. Valid while claude takes `--session-id` and resumes by it. +2026-09-21, lilleman; revised 2026-09-30 by lilleman. Serves goal 4. One fixed id per project keeps the session picker at one entry per project and makes any transcript under that id loop-claude's own to delete. The id is the checkout's path relative to `~/code`, or to `/` outside it, and a second loop is not refused, so a checkout outside `~/code` mirroring a path inside it shares its id. `todo.md`'s "Key a project on its checkout's full path" derives the id from the full path, so no two checkouts share one, and has `loop-claude` refuse to start while another session on that id is active. Moving the checkout orphans its open sessions, archive folder and models entry: sessions stay in the picker until the human deletes them, migration code not being worth a one-human audience. Valid while claude takes `--session-id` and resumes by it. ## loop-claude: the trust file is rewritten before an interrupt @@ -108,11 +108,11 @@ 2026-09-30, lilleman. Applies "Always grant explicit access to data": the sandbox `loop-claude` runs in is where access is granted, so the worker and the interrupt run with `bypassPermissions`. The worker may read `~/.claude/.credentials.json`: it holds Claude Code's own credentials, which claude reads to run anyway. Its one seam to production is the forge: what it pushes or merges can publish through CI. Valid while `loop-claude` runs only in the sandbox README → Install names. -## loop-claude: the stats line `todo.md` plans goes in the transcript archive +## loop-claude: the planned stats line goes in the transcript archive 2026-10-01, lilleman. Serves goals 3 and 4.4. The numbers show whether a change to the workflow raised quality or only cost. Each line names another project and its chunk, so the file stays off this repo's remote. `loop-claude` writes the line: the tokens, cycles and interrupts it counts, and the review's numbers from the summary larv-review ends with. Valid while the transcript archive stays off the remote. -## workflow changes: one merges only once three runs of the bench `todo.md` plans rule it better +## workflow changes: a change merges only once three planned benches rule it better 2026-10-01, lilleman. Serves goals 4.1 and 4.4. The 2026-09-30 bench showed one run cannot tell a workflow's effect from the variance between runs. One bench ruling it worse closes the PR, since quality comes first (goal 4.1), and `docs/workflow-learnings.md` keeps what the PR changed and why it lost. Three is a starting number, to be evaluated against the stats. Valid until that evaluation changes the number. -- 2.52.0 From e39f7c3eeb10827226c66c2da76a283f66086b09 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 22:44:56 +0200 Subject: [PATCH 228/233] Point todo.md's line references at the lines this chunk moved --- todo.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/todo.md b/todo.md index e8277fb1..e975986a 100644 --- a/todo.md +++ b/todo.md @@ -8,11 +8,11 @@ The sketches, the judges' verdicts and what to take from each: `~/code/claude-ha The first three items are the places the panel on `rebuild` at 8585257 named under Self-sufficiency and Locality, the dimensions under the floor (scores: `docs/decisions.md` → "comprehension floor"). -- **Name a project's loop states and give them one transition function.** Every seat had to keep two facts in mind: a run resumes only if its transcript exists (`steps.py:27`), and a reload carries its state through argv (`reload.py:45`). +- **Name a project's loop states and give them one transition function.** Every seat had to keep two facts in mind: a run resumes only if its transcript exists (`steps.py:27`), and a reload carries its state through argv (`reload.py:47`). - **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`. - **Archive the transcript as each cycle ends.** Today only an interrupt or a finished chunk archives it, so a failed exit or Ctrl-C loses the transcript. 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. `checkout.py:22` 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. +- **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. `checkout.py:28` 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. - **Give principles-auditor and prose-reviewer a way to list the project's files.** In the 2026-09-30 audit run their `tools: Read, Grep, Glob` gave them only Read. Each read the files that imports and `.gitignore` named, and listed the files it could not reach. Goal 4.1. - **Make `loop-claude`'s loop a tested state machine with its side effects injected.** Functional core, imperative shell. Goal 4.1. - Inject the side effects: `time.sleep`, `subprocess`, `input()`, `isatty` and `os.execv`. Split `project_model` and `interrupt` into decisions and effects. @@ -31,7 +31,7 @@ The first three items are the places the panel on `rebuild` at 8585257 named und - `comprehension-panel`: cut the run history and the restated description. They carry nothing the instructions need. - `systems-architect.md`: cut the "one home" line, and break Reasonability Review's steps 4 and 5 into shorter points each. - **Sort `bin/`'s imports on their first binding, and say in `principles/technical-principles.md` → "Deterministic order" how case sorts and which groups Python has.** Today they sort by path, so moving a module reorders unchanged lines. The principle's "host packages" names no Python group. Goal 4.1. -- **Judge a cycle on more than the transcript's last 40,000 characters.** `judge.py:80` cuts the transcript there. The session spans every cycle of the chunk, so a decision made early in a long run is never judged, and the human is not interrupted for it. Larger chunks make runs longer. Goal 4.2. +- **Judge a cycle on more than the transcript's last 40,000 characters.** `judge.py:82` cuts the transcript there. The session spans every cycle of the chunk, so a decision made early in a long run is never judged, and the human is not interrupted for it. Larger chunks make runs longer. Goal 4.2. - **Record each finished chunk's cost and review numbers on one stats line.** Goal 4.4. - Have `loop-claude` write the line to one file at the root of the transcript archive. The line names the project, the commit the chunk started from and the archived transcript's hash. It holds the worker's tokens from the transcript, the judge's from its JSON output, and the chunk's cycles and interrupts, which the loop counts. - End larv-review with a machine-readable summary, and have `loop-claude` copy it from the transcript onto the line: agents launched and rounds per pass; findings per pass by severity, inside the chunk's diff and outside it; and the comprehension scores when the panel ran. -- 2.52.0 From 4e71611e59d43caf13d7a1f2198c78bbdf91486e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 22:46:10 +0200 Subject: [PATCH 229/233] Answer the prose review's second round --- docs/decisions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/decisions.md b/docs/decisions.md index c5959e4d..063fe69e 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -10,7 +10,7 @@ ## loop-claude: one session per project, at a fixed id from its checkout's path -2026-09-21, lilleman; revised 2026-09-30 by lilleman. Serves goal 4. One fixed id per project keeps the session picker at one entry per project and makes any transcript under that id loop-claude's own to delete. The id is the checkout's path relative to `~/code`, or to `/` outside it, and a second loop is not refused, so a checkout outside `~/code` mirroring a path inside it shares its id. `todo.md`'s "Key a project on its checkout's full path" derives the id from the full path, so no two checkouts share one, and has `loop-claude` refuse to start while another session on that id is active. Moving the checkout orphans its open sessions, archive folder and models entry: sessions stay in the picker until the human deletes them, migration code not being worth a one-human audience. Valid while claude takes `--session-id` and resumes by it. +2026-09-21, lilleman; revised 2026-09-30 by lilleman. Serves goal 4. One fixed id per project keeps the session picker at one entry per project and makes any transcript under that id loop-claude's own to delete. The id is the checkout's path relative to `~/code`, or to `/` outside it, and a second loop is not refused, so a checkout outside `~/code` mirroring a path inside it shares its id. Once `todo.md`'s "Key a project on its checkout's full path" lands, the id comes from the full path, so no two checkouts share one, and `loop-claude` refuses to start while another session on that id is active. Moving the checkout orphans its open sessions, archive folder and models entry: sessions stay in the picker until the human deletes them, migration code not being worth a one-human audience. Valid while claude takes `--session-id` and resumes by it. ## loop-claude: the trust file is rewritten before an interrupt -- 2.52.0 From 4ff316884e8aa7a2b5cc972b5841c18020d12635 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 22:52:55 +0200 Subject: [PATCH 230/233] Port main's subagent rule and Opus 5.5 model into rebuild --- .claude/settings.json | 2 +- CLAUDE.md | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.claude/settings.json b/.claude/settings.json index c0b377ed..0f085e46 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -1,3 +1,3 @@ { - "model": "claude-fable-5-1" + "model": "claude-opus-5-5" } diff --git a/CLAUDE.md b/CLAUDE.md index f4554bf6..bf970f3a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -103,6 +103,7 @@ Prose describing the code as it stands — a comment, a README, an `AGENTS.md`, ## Working with the codebase - Always start a new git worktree when doing something in a codebase, and clean it up when done. Unless told otherwise, branch it off a freshly-updated default branch (`git fetch origin`, then base on `origin/main`), not whatever happens to be checked out. +- Give a subagent the least its job needs, stated in its prompt: one that only reads — a prose or doc review — uses the Read tool alone, no shell; one that probes builds under a throwaway image tag it removes, writes only to the session scratchpad, and never removes an image or file it did not create. - Keep the project's main checkout (e.g. `~/code/log`, never a worktree) current: when it is behind `origin` — a merge landed, or a fetch shows it — run `git pull --ff-only` there instead of reporting the lag, never with `--autostash`: a dirty checkout is a finding to report, not to carry along. - Run a project's language runtime, package manager, and task runner through its container/tooling setup, never directly on the host unless a decision puts them there. Example: `docker compose run --rm app …`. - Tear down test containers after a run. -- 2.52.0 From 9f9bb7752421de6bbbfc77e0e9097952cbe8ee64 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 22:53:49 +0200 Subject: [PATCH 231/233] Answer the prose review's first round --- CLAUDE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CLAUDE.md b/CLAUDE.md index bf970f3a..d6c66900 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -103,10 +103,10 @@ Prose describing the code as it stands — a comment, a README, an `AGENTS.md`, ## Working with the codebase - Always start a new git worktree when doing something in a codebase, and clean it up when done. Unless told otherwise, branch it off a freshly-updated default branch (`git fetch origin`, then base on `origin/main`), not whatever happens to be checked out. -- Give a subagent the least its job needs, stated in its prompt: one that only reads — a prose or doc review — uses the Read tool alone, no shell; one that probes builds under a throwaway image tag it removes, writes only to the session scratchpad, and never removes an image or file it did not create. - Keep the project's main checkout (e.g. `~/code/log`, never a worktree) current: when it is behind `origin` — a merge landed, or a fetch shows it — run `git pull --ff-only` there instead of reporting the lag, never with `--autostash`: a dirty checkout is a finding to report, not to carry along. - Run a project's language runtime, package manager, and task runner through its container/tooling setup, never directly on the host unless a decision puts them there. Example: `docker compose run --rm app …`. - Tear down test containers after a run. +- Give a subagent only the access its job needs, and state the limits in its prompt. One that only reads, such as a prose review, gets no shell and no edits. One that probes a build tags the image as throwaway and removes it afterwards, writes only to the session scratchpad, and removes no image or file it did not create. - Check `README.md` first for build, test, install, and codegen commands; one that misbehaves is fixed per "A false claim is a bug". Refresh `README.md` whenever you change what it describes ("Refresh `README.md` to match"). - Sort wherever order carries no meaning (`~/.claude/principles/technical-principles.md`) — attributes, array and object keys, enum members, imports, table rows, and line-based file lists such as `.gitignore`/`.dockerignore`. Exception: `id` goes first. - Pin GitHub Actions to semver tags (`@v3`, `@v3.1.2`), not commit SHAs — including third-party actions. SHA-pin only in special pipelines that test our own specific builds. -- 2.52.0 From 2c0e5055746453bd224ad0c51be34df848e0db5d Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 22:58:32 +0200 Subject: [PATCH 232/233] Remove the rebuild's wait-to-merge warnings and the decisions its merge ends --- AGENTS.md | 6 ------ docs/decisions.md | 18 +----------------- skills/larv-review/SKILL.md | 2 +- todo.md | 5 +---- 4 files changed, 3 insertions(+), 28 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index bd1fb206..a8330c2e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,7 +1,5 @@ # Working here -**⚠️ THE REBUILD NEVER MERGES INTO MAIN WITHOUT THE HUMAN'S EXPLICIT APPROVAL.** Every rebuild chunk is a worktree based on `origin/rebuild` with its PR into `rebuild`, never into main. Other sessions run on `~/.claude` main throughout; only the human merges `rebuild` into main, once they have approved the finished whole. larv-review leaves a PR from `rebuild` into main ready and unmerged. - Decisions live in `docs/decisions.md`: - larv-review: a project under the comprehension floor is fixed at the capping dimension @@ -16,18 +14,14 @@ Decisions live in `docs/decisions.md`: - loop-claude: a reload into an older file is unsupported - loop-claude: a CR-only README.md is reported at line 1 - loop-claude: each project's model lives in loop-claude's own file -- rebuild: loop-claude and the review process are rebuilt on `rebuild` and merge to main whole - review: the round cap counts a pass's rounds per chunk - review: a 🟢's or ❓'s fix re-enters like any fix - review: only a record older than the chunk lets a pass skip - loop-claude: the judge is retried alone, on its own counter - loop-claude: the judge loads `CLAUDE.md` - loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop -- loop-claude: a loop started on main's script stops at its first reload into the rebuild's -- 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 -- rebuild: rebuild's larv-review reviews a chunk into `rebuild` - review: an ask no user answers leaves the PR unmerged - review: the architecture pass audits every principle and goal over the whole project, and a release's last chunk fires it - loop-claude: every claude it starts bypasses permissions inside its sandbox diff --git a/docs/decisions.md b/docs/decisions.md index 063fe69e..939de49e 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -30,7 +30,7 @@ ## comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it -2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files, and 7.38, 6.75, 7.25, 6.5, 6.88 at 8585257 on 2026-10-01, lowering every dimension but Shape, and the overall, Self-sufficiency lowest and every seat naming larv-review §3's round rules; the places it named under Self-sufficiency and Locality are filed in `todo.md` under 0.1.0, and a later scoring run may not score any dimension or the overall below its best run on `rebuild`, 2026-10-01, lilleman. Valid until the next scoring run, which uses the same four seats. +2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files, and 7.38, 6.75, 7.25, 6.5, 6.88 at 8585257 on 2026-10-01, lowering every dimension but Shape, and the overall, Self-sufficiency lowest and every seat naming larv-review §3's round rules; the places it named under Self-sufficiency and Locality are filed in `todo.md` under 0.1.0, and a later scoring run may not score any dimension or the overall below its best run on `rebuild`, 2026-10-01, lilleman. `rebuild` merged into main under the floor at those scores, 2026-10-01, lilleman. Valid until the next scoring run, which uses the same four seats. ## vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link @@ -48,10 +48,6 @@ 2026-09-26, lilleman. Serves goal 4. Claude Code rewrites the user settings' `model` whenever one is picked inside a session, so a loop reading settings runs whatever was picked last; `~/.claude/loop-claude-models.json` has loop-claude as its one writer, and every claude it starts gets that model as `--model`. The file is per machine, outside the synced allowlist, since a tracked file the loop writes would dirty the checkout. Valid while Claude Code keeps rewriting the settings' model from inside a session. -## rebuild: loop-claude and the review process are rebuilt on `rebuild` and merge to main whole - -2026-09-28, lilleman. Serves goal 4. Three scoring runs held Locality at 6 while about thirty chunks fixed the places the seats named, and two blind judges scored main's loop-claude 5 and its review process 4 against 7 for sketches designed from the target result. Other sessions run on `~/.claude` main throughout, so every rebuild chunk merges into `rebuild`, never main, and `rebuild` reaches main only when it passes the comprehension floor and **the human has explicitly approved the whole and merges it themselves**. The ⚠️ warning stands in `AGENTS.md`, atop `todo.md` and on its last item on purpose, 2026-09-28, lilleman: a premature merge lands under every session running on main, so a reader of any one of them must meet it. Valid until the rebuild merges. - ## review: the round cap counts a pass's rounds per chunk 2026-09-28, lilleman, for the rebuild. Serves goal 4. Every round of a pass counts against one cap per chunk, and a fourth asks the human; one counter, and no fix bounces between two passes without end. Valid while one human answers the ask, in the session or from the unmerged PR. @@ -76,14 +72,6 @@ 2026-09-28, lilleman, for the rebuild. Serves goals 2 and 4: saving each transcript locally is the first step of backing it up, and it shows afterwards what an unattended run did. A copy of the `.jsonl`, deduplicated by content hash, with the verdict beside it; a rendering drops tool results, and a second-resolution stamp names two states within one second as one file. A failed archive exits 1, since a loop that loses its record silently fails the backup goal. Valid while transcripts stay small enough to copy whole. -## loop-claude: a loop started on main's script stops at its first reload into the rebuild's - -2026-09-29, lilleman. Serves goal 4. The rebuild's `LoopState` lacks main's failure count, so a loop running main's script exits 1 at its first reload into the rebuild, telling the human to rerun `loop-claude `. No code exists only for that reload: one rerun costs a one-human audience less. Valid until the rebuild merges. - -## rebuild: a chunk into `rebuild` takes no comprehension scoring run - -2026-09-28, lilleman, confirming larv-review's reading of the rebuild decision above. Serves goal 4. The floor and its ratchet gate `rebuild` into main, scored by the plan's last item; the chunks before it pass through half-moved states a per-chunk run would block. Valid until the rebuild merges. - ## 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. @@ -92,10 +80,6 @@ 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. -## rebuild: rebuild's larv-review reviews a chunk into `rebuild` - -2026-09-30, lilleman. Serves goal 4. A blind judge ruled it at least as good as main's on all four cases of the 2026-09-30 bench. Valid until the rebuild merges. - ## review: an ask no user answers leaves the PR unmerged 2026-09-30, claude, for the rebuild. Serves goal 4: the round cap, a BLOCK's restructure, Stage 0's questions and a goal conflict are the human's call, and an unmerged PR is what brings it to them; merging would make the call for them. Where an option reviews more — run the pass, fix under the floor, fix a finding no goal lets the run decline — the run takes it; a ❓ or a prose fix changing a goal or a decision is filed in `todo.md`, which reaches the human without holding the chunk. Valid while a human reads every unmerged PR an unattended run leaves. diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 762f3394..6740e154 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -68,7 +68,7 @@ Launch systems-architect: review the system as a whole entered through this chan Then the principles audit: one principles-auditor per file in `~/.claude/principles/` and one for the README's goals, each over the whole project in every round. A finding outside the chunk is filed in `todo.md`; a 🔴 on a decision is asked, since the decision is the user's. -Then the comprehension floor: the `comprehension-panel` skill's scoring run (`~/.claude/skills/comprehension-panel/SKILL.md` → "The scoring run") over the whole project, not the diff; a chunk whose PR goes into `rebuild` takes none. With any dimension or the overall below 7.0 the chunk does not merge: fix the places the seats name under the capping dimension, or take the user's explicit decision to ship under the floor, record it in `docs/decisions.md` with the scores, and file the places in `todo.md`. No user reachable → fix. At the floor or above, the scores are still a ratchet — a later chunk may not lower any — and the four dimension scores and the overall go in the summary so the next run can see the direction of travel. +Then the comprehension floor: the `comprehension-panel` skill's scoring run (`~/.claude/skills/comprehension-panel/SKILL.md` → "The scoring run") over the whole project, not the diff. With any dimension or the overall below 7.0 the chunk does not merge: fix the places the seats name under the capping dimension, or take the user's explicit decision to ship under the floor, record it in `docs/decisions.md` with the scores, and file the places in `todo.md`. No user reachable → fix. At the floor or above, the scores are still a ratchet — a later chunk may not lower any — and the four dimension scores and the overall go in the summary so the next run can see the direction of travel. ### Security diff --git a/todo.md b/todo.md index e975986a..1c1f8c05 100644 --- a/todo.md +++ b/todo.md @@ -2,8 +2,6 @@ ## 0.1.0 -**⚠️ THE REBUILD NEVER MERGES INTO MAIN WITHOUT THE HUMAN'S EXPLICIT APPROVAL.** Every rebuild chunk is a worktree based on `origin/rebuild` with its PR into `rebuild`, never into main. Other sessions run on `~/.claude` main throughout; only the human merges `rebuild` into main, once they have approved the finished whole. - The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. The first three items are the places the panel on `rebuild` at 8585257 named under Self-sufficiency and Locality, the dimensions under the floor (scores: `docs/decisions.md` → "comprehension floor"). @@ -25,7 +23,6 @@ The first three items are the places the panel on `rebuild` at 8585257 named und - Make the contributor a standing member of every project's audience. A project drops them only where its `## Audience` says maintainability does not matter. State that in `CLAUDE.md`'s goals-and-audience rule, and have larv-review's comprehension floor name the contributor as the reader it serves. The floor then gates every chunk while the contributor stands, and a project that drops them skips it. - Have larv-review's prose pass fix only what the chunk touched, and file the rest per `CLAUDE.md` → "Working loop". Today its fixes land "in this chunk", including cited sections and the sweep that runs with the architecture pass. In the 2026-09-30 bench, rebuild's costliest runs sprawled outside the chunk: one deleted README facts, and one took 13 rounds on the mypy case where main took 6–7 for the same fixes. Source: `~/code/claude-handoffs/claude-config/2026-09-30/bench/comparison.md`. - **Clean up the rules, skills, agents, plan and decision log.** Goal 4.1. - - Remove what the rebuild's merge made stale. The ⚠️ paragraphs in `AGENTS.md` and `todo.md`, each decision valid "until the rebuild merges", and larv-review §3 → "Architecture"'s exemption of a chunk into `rebuild` from the scoring run. - `docs/decisions.md`: give the comprehension-floor and vocabulary entries a premise that has not expired. Both say "Valid until the next scoring run", and every run since has passed it. Put the floor's rule first and its runs' scores in a table. - larv-review: move its reasons for `/security-review` and for the premises chunk's review into `docs/decisions.md`. They are rejected alternatives, which the decision log holds. - `comprehension-panel`: cut the run history and the restated description. They carry nothing the instructions need. @@ -37,4 +34,4 @@ The first three items are the places the panel on `rebuild` at 8585257 named und - 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 `rebuild` to the comprehension floor on the four-seat panel, and open its PR into main for the human.** 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. ⚠️ Leave the PR ready and unmerged: only the human merges it, after approving the whole rebuild. The PR deletes main's `AGENTS.md` paragraph on a rebuild chunk's larv-review, which only main holds. +- **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. -- 2.52.0 From 86b9a85b92505082c8aaa5e49a5a9d6c3be08b97 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 1 Oct 2026 23:00:53 +0200 Subject: [PATCH 233/233] Answer the prose review's first round --- docs/decisions.md | 12 ++++++------ todo.md | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index 939de49e..75a94fb3 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -30,7 +30,7 @@ ## comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it -2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files, and 7.38, 6.75, 7.25, 6.5, 6.88 at 8585257 on 2026-10-01, lowering every dimension but Shape, and the overall, Self-sufficiency lowest and every seat naming larv-review §3's round rules; the places it named under Self-sufficiency and Locality are filed in `todo.md` under 0.1.0, and a later scoring run may not score any dimension or the overall below its best run on `rebuild`, 2026-10-01, lilleman. `rebuild` merged into main under the floor at those scores, 2026-10-01, lilleman. Valid until the next scoring run, which uses the same four seats. +2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files, and 7.38, 6.75, 7.25, 6.5, 6.88 at 8585257 on 2026-10-01, lowering every dimension but Shape, and the overall, Self-sufficiency lowest and every seat naming larv-review §3's round rules; the places it named under Self-sufficiency and Locality are filed in `todo.md` under 0.1.0, and a later scoring run may not score any dimension or the overall below its best run on `rebuild`, 2026-10-01, lilleman. `rebuild` merged into main under the floor at 8585257's scores, 2026-10-01, lilleman. Valid until the next scoring run, which uses the same four seats. ## vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link @@ -50,7 +50,7 @@ ## review: the round cap counts a pass's rounds per chunk -2026-09-28, lilleman, for the rebuild. Serves goal 4. Every round of a pass counts against one cap per chunk, and a fourth asks the human; one counter, and no fix bounces between two passes without end. Valid while one human answers the ask, in the session or from the unmerged PR. +2026-09-28, lilleman. Serves goal 4. Every round of a pass counts against one cap per chunk, and a fourth asks the human; one counter, and no fix bounces between two passes without end. Valid while one human answers the ask, in the session or from the unmerged PR. ## review: a 🟢's or ❓'s fix re-enters like any fix @@ -62,15 +62,15 @@ ## loop-claude: the judge is retried alone, on its own counter -2026-09-28, lilleman, for the rebuild. Serves goal 4. A failed verdict reruns the judge on the same transcript; rerunning the worker would spend a worker run on a judge's fault. Valid while a judge run costs far less than a worker run. +2026-09-28, lilleman. Serves goal 4. A failed verdict reruns the judge on the same transcript; rerunning the worker would spend a worker run on a judge's fault. Valid while a judge run costs far less than a worker run. ## loop-claude: the judge loads `CLAUDE.md` -2026-09-28, lilleman, for the rebuild. Serves goal 4. The judge rules on chunks, releases and premises, which `CLAUDE.md` → "Vocabulary" and "Working loop" define; `--bare` would leave it the prompt's words alone. Valid while those definitions live in `CLAUDE.md`. +2026-09-28, lilleman. Serves goal 4. The judge rules on chunks, releases and premises, which `CLAUDE.md` → "Vocabulary" and "Working loop" define; `--bare` would leave it the prompt's words alone. Valid while those definitions live in `CLAUDE.md`. ## loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop -2026-09-28, lilleman, for the rebuild. Serves goals 2 and 4: saving each transcript locally is the first step of backing it up, and it shows afterwards what an unattended run did. A copy of the `.jsonl`, deduplicated by content hash, with the verdict beside it; a rendering drops tool results, and a second-resolution stamp names two states within one second as one file. A failed archive exits 1, since a loop that loses its record silently fails the backup goal. Valid while transcripts stay small enough to copy whole. +2026-09-28, lilleman. Serves goals 2 and 4: saving each transcript locally is the first step of backing it up, and it shows afterwards what an unattended run did. A copy of the `.jsonl`, deduplicated by content hash, with the verdict beside it; a rendering drops tool results, and a second-resolution stamp names two states within one second as one file. A failed archive exits 1, since a loop that loses its record silently fails the backup goal. Valid while transcripts stay small enough to copy whole. ## loop-claude: a `claude` that cannot start is a failed worker run, retried @@ -82,7 +82,7 @@ ## review: an ask no user answers leaves the PR unmerged -2026-09-30, claude, for the rebuild. Serves goal 4: the round cap, a BLOCK's restructure, Stage 0's questions and a goal conflict are the human's call, and an unmerged PR is what brings it to them; merging would make the call for them. Where an option reviews more — run the pass, fix under the floor, fix a finding no goal lets the run decline — the run takes it; a ❓ or a prose fix changing a goal or a decision is filed in `todo.md`, which reaches the human without holding the chunk. Valid while a human reads every unmerged PR an unattended run leaves. +2026-09-30, claude. Serves goal 4: the round cap, a BLOCK's restructure, Stage 0's questions and a goal conflict are the human's call, and an unmerged PR is what brings it to them; merging would make the call for them. Where an option reviews more — run the pass, fix under the floor, fix a finding no goal lets the run decline — the run takes it; a ❓ or a prose fix changing a goal or a decision is filed in `todo.md`, which reaches the human without holding the chunk. Valid while a human reads every unmerged PR an unattended run leaves. ## review: the architecture pass audits every principle and goal over the whole project, and a release's last chunk fires it diff --git a/todo.md b/todo.md index 1c1f8c05..75aec0f9 100644 --- a/todo.md +++ b/todo.md @@ -2,7 +2,7 @@ ## 0.1.0 -The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. +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 three items are the places the panel on `rebuild` at 8585257 named under Self-sufficiency and Locality, the dimensions under the floor (scores: `docs/decisions.md` → "comprehension floor"). -- 2.52.0