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
CI / tests (pull_request) Successful in 3m43s
This commit is contained in:
@@ -1,12 +1,13 @@
|
||||
"""How entry points claim a checkout before they start a chunk in it, so that two never start the same chunk and do-epic never starts one where loop-claude runs.
|
||||
|
||||
An entry point holds `starting` on `project_lock` while it lists the windows of the checkout's chunks and starts new ones. It starts each chunk in a tmux window with CHUNK_FLAG, and hands that window the variables named with HANDED.
|
||||
An entry point holds `starting` on `project_lock` while it lists the windows of the checkout's chunks and starts new ones. Where the lock cannot be taken, `starting` yields a Failure, and the entry point doesn't start any chunk. It starts each chunk in a tmux window with CHUNK_FLAG, and hands that window the variables named with HANDED.
|
||||
"""
|
||||
import contextlib
|
||||
import fcntl
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from transcript_archive.project_key import project_key
|
||||
from agent_cycle import tmux
|
||||
|
||||
@@ -21,12 +22,28 @@ HANDED = "LOOP_CLAUDE_"
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def starting(folder: pathlib.Path) -> typing.Iterator[None]:
|
||||
"""Holds the LOCK in folder: project_lock's for a project, or do-epic's for an epic. Raises OSError where the file cannot be opened or locked."""
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
with open(folder / LOCK, "a") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
yield
|
||||
def starting(folder: pathlib.Path) -> typing.Iterator[Failure | None]:
|
||||
"""Holds the LOCK in folder: project_lock's for a project, or do-epic's for an epic. It yields a Failure, and doesn't hold any lock, where the file cannot be opened or locked."""
|
||||
with locked(folder / LOCK) as failure:
|
||||
yield failure
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def locked(file: pathlib.Path) -> typing.Iterator[Failure | None]:
|
||||
"""Holds a flock on file, which it makes with its folder. It yields a Failure, and doesn't hold any lock, where the file cannot be opened or locked."""
|
||||
try:
|
||||
file.parent.mkdir(parents=True, exist_ok=True)
|
||||
lock = open(file, "a")
|
||||
except OSError as failure:
|
||||
yield Failure(f"cannot lock {failure.filename or file}: {failure.strerror}")
|
||||
return
|
||||
with lock:
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
except OSError as failure:
|
||||
yield Failure(f"cannot lock {file}: {failure.strerror}")
|
||||
return
|
||||
yield None
|
||||
|
||||
|
||||
def project_lock(root: str, home: pathlib.Path) -> pathlib.Path:
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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")]
|
||||
|
||||
|
||||
@@ -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]))
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ from agent_cycle.verdicts import Finished, TakenIn, Unfinished
|
||||
from transcript_archive import outcomes, write
|
||||
from model_routing.ladder import ProjectRung, Rung
|
||||
from model_routing.ladder_file import read_ladder, SHIPPED
|
||||
from text_files.file_writes import replace_file
|
||||
from model_routing.route import Route
|
||||
from agent_cycle import run
|
||||
from claude_code import session
|
||||
@@ -59,7 +60,7 @@ class Steps(unittest.TestCase):
|
||||
transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n")
|
||||
before = Route(self.FABLE_LOW, 3, 3, 4)
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW))
|
||||
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW, replace=replace_file))
|
||||
after = chunk_run.closed_cycle(chunk_run.ChunkRun(cycle_number=1, task="Do it.", unfinished_evidence=""), OPUS_PROJECT, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), archive, "a-driver", a_loop(FakeEffects().effects(), session=opened))
|
||||
self.assertEqual(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(self.FABLE_MEDIUM, 3, 3, 4))
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
@@ -79,6 +80,6 @@ class Steps(unittest.TestCase):
|
||||
transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n")
|
||||
before = Route(self.FABLE_LOW, 3, 3, 4)
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW))
|
||||
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW, replace=replace_file))
|
||||
chunk_run.closed_cycle(chunk_run.ChunkRun(cycle_number=1, task="Do it.", unfinished_evidence=""), OPUS_PROJECT, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_escape_and_impact=6)), before), archive, "a-driver", a_loop(FakeEffects().effects(), session=opened))
|
||||
self.assertEqual(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(self.FABLE_LOW, 3, 3, 4, escape_and_impact_taken_in=6))
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import pathlib
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from failure import Failure
|
||||
from chunk_driver.claims import LOCK, starting
|
||||
|
||||
|
||||
class Starting(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.folder = pathlib.Path(temp.name)
|
||||
|
||||
def test_yields_none_while_it_holds_the_lock_in_a_folder_it_makes(self) -> None:
|
||||
with starting(self.folder / "state" / "proj") as failure:
|
||||
self.assertIsNone(failure)
|
||||
self.assertTrue((self.folder / "state" / "proj" / LOCK).is_file())
|
||||
|
||||
def test_yields_a_failure_naming_the_path_it_could_not_make(self) -> None:
|
||||
(self.folder / "state").write_text("", encoding="utf-8")
|
||||
with starting(self.folder / "state") as failure:
|
||||
assert isinstance(failure, Failure)
|
||||
self.assertRegex(failure.reason, f"^cannot lock {self.folder}/state: \\w")
|
||||
|
||||
def test_yields_a_failure_naming_the_lock_it_could_not_open(self) -> None:
|
||||
(self.folder / LOCK).mkdir()
|
||||
with starting(self.folder) as failure:
|
||||
assert isinstance(failure, Failure)
|
||||
self.assertRegex(failure.reason, f"^cannot lock {self.folder}/{LOCK}: \\w")
|
||||
|
||||
def test_an_error_raised_while_the_lock_is_held_is_the_callers(self) -> None:
|
||||
with self.assertRaises(OSError), starting(self.folder):
|
||||
raise OSError("not the lock's")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,4 +1,5 @@
|
||||
import contextlib
|
||||
import functools
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
@@ -7,7 +8,6 @@ import sys
|
||||
import tempfile
|
||||
import types
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
@@ -15,10 +15,11 @@ from chunk_driver.doubles import a_loop
|
||||
from chunk_driver import cycle_start
|
||||
from failure import Failure
|
||||
from loop_effects.doubles import FakeEffects, NOW, STAMP
|
||||
from git_cli.git_repo import git
|
||||
from git_cli import git_repo
|
||||
from transcript_archive import outcomes, write
|
||||
from model_routing.ladder import ProjectRung, Rung
|
||||
from model_routing.ladder_file import read_ladder, SHIPPED
|
||||
from text_files.file_writes import replace_file
|
||||
from model_routing.route import Route, WorkerLine
|
||||
from claude_code import session
|
||||
|
||||
@@ -28,19 +29,18 @@ OPUS_PROJECT = ProjectRung(read_ladder(SHIPPED), Rung("claude-opus-5-5", "medium
|
||||
class SetupVersion(unittest.TestCase):
|
||||
def test_names_the_release_and_the_commit_or_why_git_cannot_tell(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
isolated = {"GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1", "GIT_CEILING_DIRECTORIES": root}
|
||||
with unittest.mock.patch.dict(os.environ, isolated):
|
||||
gone = cycle_start.setup_version(pathlib.Path(root), git)
|
||||
self.assertRegex(gone, r"^unknown: [^\n]*not a git repository")
|
||||
for step in (["init", "-q"], ["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "one"]):
|
||||
self.assertIsInstance(git(*step, cwd=root), str)
|
||||
head = git("rev-parse", "HEAD", cwd=root).strip()
|
||||
self.assertEqual(cycle_start.setup_version(pathlib.Path(root), git), f"{head[:7]} ({head})")
|
||||
git("tag", "v0.1.0", cwd=root)
|
||||
self.assertEqual(cycle_start.setup_version(pathlib.Path(root), git), f"v0.1.0 ({head})")
|
||||
git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "two", cwd=root)
|
||||
head = git("rev-parse", "HEAD", cwd=root).strip()
|
||||
self.assertEqual(cycle_start.setup_version(pathlib.Path(root), git), f"v0.1.0-1-g{head[:7]} ({head})")
|
||||
git = functools.partial(git_repo.git, env={**os.environ, "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1", "GIT_CEILING_DIRECTORIES": root})
|
||||
gone = cycle_start.setup_version(pathlib.Path(root), git)
|
||||
self.assertRegex(gone, r"^unknown: [^\n]*not a git repository")
|
||||
for step in (["init", "-q"], ["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "one"]):
|
||||
self.assertIsInstance(git(*step, cwd=root), str)
|
||||
head = git("rev-parse", "HEAD", cwd=root).strip()
|
||||
self.assertEqual(cycle_start.setup_version(pathlib.Path(root), git), f"{head[:7]} ({head})")
|
||||
git("tag", "v0.1.0", cwd=root)
|
||||
self.assertEqual(cycle_start.setup_version(pathlib.Path(root), git), f"v0.1.0 ({head})")
|
||||
git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "two", cwd=root)
|
||||
head = git("rev-parse", "HEAD", cwd=root).strip()
|
||||
self.assertEqual(cycle_start.setup_version(pathlib.Path(root), git), f"v0.1.0-1-g{head[:7]} ({head})")
|
||||
|
||||
def test_names_why_git_cannot_name_the_commit_on_one_line(self):
|
||||
def fake_git(*args, cwd=None):
|
||||
@@ -79,12 +79,12 @@ class Routes(unittest.TestCase):
|
||||
transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n")
|
||||
self.assertIsNone(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)))
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(route.worker_line(), "working", "j", ""), NOW))
|
||||
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(route.worker_line(), "working", "j", ""), NOW, replace=replace_file))
|
||||
with contextlib.redirect_stderr(stderr):
|
||||
self.assertEqual(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), route)
|
||||
self.assertEqual(stderr.getvalue(), "")
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.stepped_up(WorkerLine('{"model": "claude-opus-5-5", "rung": 3}')), NOW + 1))
|
||||
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.stepped_up(WorkerLine('{"model": "claude-opus-5-5", "rung": 3}')), NOW + 1, replace=replace_file))
|
||||
with contextlib.redirect_stderr(io.StringIO()) as stderr:
|
||||
self.assertIsNone(cycle_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)))
|
||||
self.assertEqual(stderr.getvalue(), f'{STAMP} routing the chunk afresh: the archive\'s latest Worker: line names no route that can be read: {{"model": "claude-opus-5-5", "rung": 3}}\n')
|
||||
|
||||
Reference in New Issue
Block a user