Give the reload and the strike their own modules

This commit is contained in:
2026-09-28 11:11:23 +02:00
parent 5de7e0fc9c
commit 4171a1ecbe
9 changed files with 88 additions and 69 deletions
+1 -1
View File
@@ -8,4 +8,4 @@ sys.path.insert(0, str(LAUNCHER.parent))
from loop_claude import main, paths 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()))
View File
+2 -2
View File
@@ -3,8 +3,8 @@ import subprocess
from loop_claude.outcome import Stop from loop_claude.outcome import Stop
def checkout_root(): def checkout_root(cwd):
found = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True) found = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, cwd=cwd, text=True)
if found.returncode != 0: if found.returncode != 0:
return Stop(1, found.stderr.strip()) return Stop(1, found.stderr.strip())
return found.stdout.strip() return found.stdout.strip()
+1 -7
View File
@@ -10,6 +10,7 @@ import uuid
from loop_claude.checkout import checkouts, project_name from loop_claude.checkout import checkouts, project_name
from loop_claude.outcome import Continue, Retry, Stop from loop_claude.outcome import Continue, Retry, Stop
from loop_claude.strike import strike
SESSION_NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec") 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): def run_cycle(root, task, premises, chosen, paths, env):
name = session_name(root, paths.code) name = session_name(root, paths.code)
session_id = uuid.uuid5(SESSION_NAMESPACE, name) session_id = uuid.uuid5(SESSION_NAMESPACE, name)
+12 -42
View File
@@ -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. file has the highest fetchedAt.
""" """
import dataclasses import dataclasses
import hashlib
import json
import os
import pathlib
import subprocess
import sys import sys
from loop_claude.checkout import checkout_root 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.outcome import Continue, Retry, Stop
from loop_claude.premises import read_premises from loop_claude.premises import read_premises
from loop_claude.reload import RELOAD_FLAG, decode_state, fingerprint, reload_if_edited
RELOAD_FLAG = "--reloaded" from loop_claude.strike import strike
@dataclasses.dataclass(frozen=True) @dataclasses.dataclass(frozen=True)
@@ -66,9 +61,9 @@ class LoopState:
task: str task: str
def main(argv, env, paths, launcher): def main(argv, env, paths, launcher, cwd):
try: try:
stop = run_loop(argv, env, paths, launcher) stop = run_loop(argv, env, paths, launcher, cwd)
except KeyboardInterrupt: except KeyboardInterrupt:
stop = Stop(130, "") stop = Stop(130, "")
if stop.reason: if stop.reason:
@@ -76,8 +71,8 @@ def main(argv, env, paths, launcher):
return stop.code return stop.code
def run_loop(argv, env, paths, launcher): def run_loop(argv, env, paths, launcher, cwd):
state = loop_state(argv) state = loop_state(argv, cwd)
if isinstance(state, Stop): if isinstance(state, Stop):
return state return state
baseline = fingerprint(launcher) baseline = fingerprint(launcher)
@@ -102,40 +97,15 @@ def run_loop(argv, env, paths, launcher):
state = dataclasses.replace(state, failures=0) state = dataclasses.replace(state, failures=0)
# The reload
def loop_state(argv, cwd):
def loop_state(argv):
if argv[:1] != [RELOAD_FLAG]: if argv[:1] != [RELOAD_FLAG]:
task = " ".join(argv) task = " ".join(argv)
if task in ("", "-h", "--help"): if task in ("", "-h", "--help"):
return Stop(0 if task else 1, __doc__.strip()) 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) return root if isinstance(root, Stop) else LoopState(0, 0, root, task)
handed = parse(argv[1]) if len(argv) == 2 else None state = decode_state(argv[1], LoopState) if len(argv) == 2 else None
shape = {field.name: field.type for field in dataclasses.fields(LoopState)} if not (state and state.root and state.task):
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 <task>") return Stop(1, f"the reload cannot read the loop's state from {argv[1:]}; rerun loop-claude <task>")
return LoopState(**handed) return state
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))])
+43
View File
@@ -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))])
+11
View File
@@ -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)
+17 -16
View File
@@ -15,10 +15,11 @@ import uuid
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) 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.outcome import Continue, Retry, Stop
from loop_claude.paths import paths_from from loop_claude.paths import paths_from
CWD = pathlib.Path("/c")
LAUNCHER = pathlib.Path(__file__).resolve().with_name("loop-claude") LAUNCHER = pathlib.Path(__file__).resolve().with_name("loop-claude")
PATHS = paths_from(pathlib.Path("/h"), {}) PATHS = paths_from(pathlib.Path("/h"), {})
SESSION_ID = str(getattr(uuid, "uuid7", uuid.uuid4)()) 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): def test_is_the_checkout_from_any_directory_inside_it_and_exits_outside_one(self):
with tempfile.TemporaryDirectory() as tmp, contextlib.chdir(tmp): with tempfile.TemporaryDirectory() as tmp, contextlib.chdir(tmp):
root = os.getcwd() 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) subprocess.run(["git", "init", "-q"], check=True)
os.makedirs("a/b") os.makedirs("a/b")
with contextlib.chdir("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) subprocess.run(["git", "init", "-q", "other"], check=True)
with contextlib.chdir("other"): with contextlib.chdir("other"):
self.assertEqual(checkout.checkouts(root), [root]) 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_*")) shutil.copytree(LAUNCHER.parent, copy, ignore=shutil.ignore_patterns("__pycache__", "test_*"))
launcher, edited = copy / "loop-claude", copy / "loop_claude" / "cycle.py" launcher, edited = copy / "loop-claude", copy / "loop_claude" / "cycle.py"
state = main.LoopState(1, 2, "/r", "do it") 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: with unittest.mock.patch("os.execv") as execv, contextlib.redirect_stderr(io.StringIO()) as err:
baseline = main.fingerprint(launcher) baseline = reload.fingerprint(launcher)
edited.write_text(edited.read_text() + "\ndef\n") 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() execv.assert_not_called()
self.assertIn("keeping the running script", err.getvalue()) self.assertIn("keeping the running script", err.getvalue())
edited.write_text(edited.read_text().replace("\ndef\n", "\n# edited\n")) 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"})]) 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): 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")): 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: 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(main.main(argv, {}, PATHS, LAUNCHER, CWD), code)
self.assertEqual({"stdout": out, "stderr": err}[stream].getvalue(), main.loop_state(argv).reason + "\n") 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): 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): class RunLoop(unittest.TestCase):
def test_stops_naming_the_reload_when_it_hands_over_anything_but_the_state_with_a_task(self): 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, "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): 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 <task>")) 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 <task>"))
def test_resumes_the_root_and_counters_a_reload_handed_over(self): 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_model")]
@@ -473,7 +474,7 @@ class RunLoop(unittest.TestCase):
mocks = [stack.enter_context(patch) for patch in patches] mocks = [stack.enter_context(patch) for patch in patches]
stack.enter_context(unittest.mock.patch.object(sys, "stdout", io.StringIO())) stack.enter_context(unittest.mock.patch.object(sys, "stdout", io.StringIO()))
mocks[3].return_value = stopped 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[0].assert_not_called()
mocks[1].assert_called_once_with("/r") 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[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, {}) mocks[4].assert_called_once_with("/r", PATHS, {})
self.assertEqual(mocks[3].call_args.args[3], mocks[4].return_value) self.assertEqual(mocks[3].call_args.args[3], mocks[4].return_value)
mocks[0].return_value = "/s" mocks[0].return_value = "/s"
self.assertEqual(main.run_loop(["do", "it"], {}, PATHS, LAUNCHER), stopped) self.assertEqual(main.run_loop(["do", "it"], {}, PATHS, LAUNCHER, CWD), stopped)
mocks[0].assert_called_once_with() mocks[0].assert_called_once_with(CWD)
mocks[1].assert_called_with("/s") mocks[1].assert_called_with("/s")
self.assertIn("=== cycle 4 ===", sys.stdout.getvalue()) self.assertIn("=== cycle 4 ===", sys.stdout.getvalue())
for leaf in (0, 1, 4): for leaf in (0, 1, 4):
with self.subTest(leaf=leaf): with self.subTest(leaf=leaf):
mocks[leaf].return_value = Stop(2, f"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[leaf].return_value = "/s"
mocks[3].side_effect = [Retry("claude exited 3")] * 3 mocks[3].side_effect = [Retry("claude exited 3")] * 3
stack.enter_context(unittest.mock.patch.object(sys, "stderr", io.StringIO())) stack.enter_context(unittest.mock.patch.object(sys, "stderr", io.StringIO()))
sleep = stack.enter_context(unittest.mock.patch("time.sleep")) 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.assertIn("retrying the worker in a minute: claude exited 3", sys.stderr.getvalue())
self.assertEqual(sleep.call_count, 2) self.assertEqual(sleep.call_count, 2)
+1 -1
View File
@@ -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`. 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 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. - **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.** - **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`. - **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`.