Answer principles round 1: 1 🔴, 7 🟡 (0 misread); every effect is handed in as an argument, no test patches a global, and the traces principle scopes tools that run on their user's machine
CI / tests (pull_request) Successful in 3m43s

This commit is contained in:
2026-11-19 12:42:03 +01:00
parent 8ca612b7a4
commit cb3135bc8c
124 changed files with 1437 additions and 793 deletions
+21 -8
View File
@@ -5,11 +5,11 @@ import sys
import typing
from claude_code.model_catalog import catalog_models
from chunk_driver.claims import CLAIMS, locked
from loop_effects.effects import Effects, say
from failure import Failure
from agent_cycle.stop import needs_human, needs_terminal, Stop
from loop_state.paths import Paths
from text_files.file_writes import replace_json
@dataclasses.dataclass(frozen=True)
@@ -21,6 +21,8 @@ class Models:
# The environment variables that name the judge's and the worker's model for one run, over the model saved or configured.
JUDGE_MODEL = "LOOP_CLAUDE_JUDGE_MODEL"
WORKER_MODEL = "LOOP_CLAUDE_WORKER_MODEL"
# The file, in CLAIMS under the home folder, that save_model keeps locked with flock while it rereads and replaces the models file. The models file's own folder is a checkout of this setup, which takes no lock file.
MODELS_LOCK = "models.lock"
def overridden(env: typing.Mapping[str, str], default: str) -> Models:
@@ -48,18 +50,29 @@ def get_or_ask_model(project_key: str, paths: Paths, driver: str, effects: Effec
chosen = ask_for_model(project_key, saved, paths.model_catalog, driver, effects)
if isinstance(chosen, Stop):
return chosen
# Reread: another loop may have saved its project while this one waited on the human.
models = read_models_file(saved)
if isinstance(models, Failure):
return Stop(1, models.reason)
if failure := replace_json(saved, {**models, project_key: chosen}, indent="\t", sort_keys=True):
return Stop(1, f"could not save the model in {saved}: {failure.reason}")
if failure := save_model(project_key, chosen, paths, effects.replace_file):
return Stop(1, failure.reason)
say(f"{project_key} runs on {chosen}", effects)
return chosen
def save_model(project_key: str, chosen: str, paths: Paths, replace: typing.Callable[[pathlib.Path, bytes], Failure | None]) -> Failure | None:
"""Adds the project's model to the models file, whose only writer this is, through replace, which writes a file as replace_file does. It holds MODELS_LOCK from its read to its write, so two drivers that save at once both keep their pick."""
saved = paths.models_file
with locked(paths.home / CLAIMS / MODELS_LOCK) as unlocked:
if unlocked:
return Failure(f"could not save the model in {saved}: {unlocked.reason}")
# Read under the lock: another driver may have saved its project while this one waited on the human.
models = read_models_file(saved)
if isinstance(models, Failure):
return models
if failure := replace(saved, json.dumps({**models, project_key: chosen}, indent="\t", sort_keys=True).encode()):
return Failure(f"could not save the model in {saved}: {failure.reason}")
return None
def read_models_file(saved: pathlib.Path) -> dict[str, str] | Failure:
"""Each project's model, as the models file at saved maps them; none where there is no such file. loop-claude and the replay tools read it."""
"""Each project's model, as the models file at saved maps them; none where there is no such file. The chunk drivers and the replay tools read it, and only save_model writes it."""
try:
with open(saved, encoding="utf-8") as handle:
models = json.load(handle)
+67 -1
View File
@@ -1,8 +1,10 @@
import dataclasses
import fcntl
import json
import pathlib
import sys
import tempfile
import unittest
import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
@@ -10,6 +12,8 @@ from failure import Failure
from loop_effects.doubles import FakeEffects
from chunk_driver.drivers import LOOP_CLAUDE
from chunk_driver.project import model_choice
from loop_state.paths import paths_from
from text_files.file_writes import replace_file
from agent_cycle.stop import Stop
@@ -20,6 +24,68 @@ class Overridden(unittest.TestCase):
self.assertEqual(model_choice.overridden({"LOOP_CLAUDE_JUDGE_MODEL": "j", "LOOP_CLAUDE_WORKER_MODEL": "w"}, "saved"), model_choice.Models("j", "w"))
class SavingAModel(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.paths = paths_from(pathlib.Path(temp.name))
self.lock = self.paths.home / ".local/state/loop-claude/models.lock"
def test_adds_the_projects_model_to_those_the_file_holds(self):
self.paths.models_file.parent.mkdir()
self.paths.models_file.write_text(json.dumps({"other": "model-x"}))
self.assertIsNone(model_choice.save_model("proj", "model-b", self.paths, replace_file))
self.assertEqual(json.loads(self.paths.models_file.read_text()), {"other": "model-x", "proj": "model-b"})
def lock_is_held(self) -> bool:
with open(self.lock, "a") as other:
try:
fcntl.flock(other, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
return True
return False
def test_holds_the_models_lock_from_its_read_to_its_write(self):
self.paths.models_file.parent.mkdir()
held = []
class Watched(pathlib.PosixPath):
"""The models file, which notes whether the lock is held each time it is opened."""
def __fspath__(watched) -> str:
held.append(self.lock_is_held())
return super().__fspath__()
def replace(path: pathlib.Path, data: bytes) -> None:
held.append(self.lock_is_held())
paths = dataclasses.replace(self.paths, models_file=Watched(self.paths.models_file))
self.assertIsNone(model_choice.save_model("proj", "model-b", paths, replace))
self.assertEqual(held, [True, True])
self.assertFalse(self.lock_is_held())
def test_doesnt_save_anything_where_it_cannot_take_the_lock(self):
self.paths.models_file.parent.mkdir()
self.lock.parent.parent.mkdir(parents=True)
self.lock.parent.write_text("")
saved = model_choice.save_model("proj", "model-b", self.paths, replace_file)
assert isinstance(saved, Failure)
self.assertRegex(saved.reason, f"^could not save the model in {self.paths.models_file}: cannot lock {self.lock.parent}: \\w")
self.assertFalse(self.paths.models_file.exists())
def test_a_pick_is_saved_through_save_model_alone(self):
self.paths.models_file.parent.mkdir()
fake, held = FakeEffects(inputs=["my-model"]), []
def replace(path: pathlib.Path, data: bytes) -> Failure:
held.append(self.lock_is_held())
return Failure("could not save")
fake.replace_file = replace
self.assertEqual(model_choice.get_or_ask_model("proj", self.paths, LOOP_CLAUDE, fake.effects()), Stop(1, f"could not save the model in {self.paths.models_file}: could not save"))
self.assertEqual(held, [True])
class ModelPrompt(unittest.TestCase):
OFFERED = [("claude-opus-5-5", "Opus 5.5"), ("claude-haiku-4-5", "Haiku 4.5")]
-1
View File
@@ -2,7 +2,6 @@ import pathlib
import sys
import tempfile
import unittest
import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))