Build and validate the reload state in one unit
This commit is contained in:
+50
-43
@@ -42,6 +42,7 @@ Claude Code internals this rests on, observed on 2.1.282, the model catalog on 2
|
|||||||
- ~/.claude/cache/model-catalog/*.json holds catalog.config.models, each with an id and a name; the newest
|
- ~/.claude/cache/model-catalog/*.json holds catalog.config.models, each with an id and a name; the newest
|
||||||
file has the highest fetchedAt.
|
file has the highest fetchedAt.
|
||||||
"""
|
"""
|
||||||
|
import dataclasses
|
||||||
import glob
|
import glob
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
@@ -90,29 +91,18 @@ JUDGE_SCHEMA = {
|
|||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
argv = sys.argv[1:]
|
state = loop_state(sys.argv[1:])
|
||||||
if argv[:1] == [RELOAD_FLAG]:
|
|
||||||
state = reloaded_state(argv[1:])
|
|
||||||
else:
|
|
||||||
state = {"cycle_number": 0, "failures": 0, "root": "", "task": " ".join(argv)}
|
|
||||||
if state["task"] in ("", "-h", "--help"):
|
|
||||||
print(__doc__.strip())
|
|
||||||
sys.exit(0 if state["task"] else 1)
|
|
||||||
task = state["task"]
|
|
||||||
root = state["root"] or checkout_root()
|
|
||||||
cycle_number, failures = state["cycle_number"], state["failures"]
|
|
||||||
while True:
|
while True:
|
||||||
reload_if_edited(root, task, cycle_number, failures)
|
reload_if_edited(state)
|
||||||
cycle_number += 1
|
state = dataclasses.replace(state, cycle_number=state.cycle_number + 1)
|
||||||
premises = read_premises(root)
|
premises = read_premises(state.root)
|
||||||
name = session_name(root)
|
name = session_name(state.root)
|
||||||
print(f"\n=== cycle {cycle_number} ===", flush=True)
|
print(f"\n=== cycle {state.cycle_number} ===", flush=True)
|
||||||
failure = run_cycle(root, task, premises, name, uuid.uuid5(SESSION_NAMESPACE, name), project_model(root))
|
failure = run_cycle(state.root, state.task, premises, name, uuid.uuid5(SESSION_NAMESPACE, name), project_model(state.root))
|
||||||
|
state = dataclasses.replace(state, failures=state.failures + 1 if failure else 0)
|
||||||
if not failure:
|
if not failure:
|
||||||
failures = 0
|
|
||||||
continue
|
continue
|
||||||
failures += 1
|
if state.failures == 3:
|
||||||
if failures == 3:
|
|
||||||
sys.exit(f"the worker failed three times running: {failure}")
|
sys.exit(f"the worker failed three times running: {failure}")
|
||||||
print(f"retrying the worker in a minute: {failure}", file=sys.stderr)
|
print(f"retrying the worker in a minute: {failure}", file=sys.stderr)
|
||||||
time.sleep(60)
|
time.sleep(60)
|
||||||
@@ -137,29 +127,6 @@ def run_cycle(root, task, premises, name, session_id, chosen):
|
|||||||
return ""
|
return ""
|
||||||
|
|
||||||
|
|
||||||
def reload_if_edited(root, task, cycle_number, failures):
|
|
||||||
try:
|
|
||||||
source = open(__file__, encoding="utf-8").read()
|
|
||||||
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
|
|
||||||
state = {"cycle_number": cycle_number, "failures": failures, "root": root, "task": task}
|
|
||||||
os.execv(sys.executable, [sys.executable, __file__, RELOAD_FLAG, json.dumps(state)])
|
|
||||||
|
|
||||||
|
|
||||||
def reloaded_state(handed):
|
|
||||||
state = parse(handed[0]) if len(handed) == 1 else None
|
|
||||||
if not state or {"cycle_number", "failures", "root"} - state.keys() or not isinstance(state.get("task"), str) or not state["task"]:
|
|
||||||
sys.exit(f"the reload cannot read the loop's state from {handed}; rerun loop-claude <task>")
|
|
||||||
return state
|
|
||||||
|
|
||||||
|
|
||||||
def checkout_root():
|
def checkout_root():
|
||||||
found = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True)
|
found = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True)
|
||||||
if found.returncode != 0:
|
if found.returncode != 0:
|
||||||
@@ -250,6 +217,46 @@ def project(root):
|
|||||||
return root.removeprefix(os.path.expanduser("~/code/")).lstrip("/")
|
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"):
|
||||||
|
print(__doc__.strip())
|
||||||
|
sys.exit(0 if task else 1)
|
||||||
|
return LoopState(0, 0, checkout_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"]):
|
||||||
|
sys.exit(f"the reload cannot read the loop's state from {argv[1:]}; rerun loop-claude <task>")
|
||||||
|
return LoopState(**handed)
|
||||||
|
|
||||||
|
|
||||||
|
def reload_if_edited(state):
|
||||||
|
try:
|
||||||
|
source = open(__file__, encoding="utf-8").read()
|
||||||
|
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
|
# ~/.claude/loop-claude-models.json
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -436,19 +436,19 @@ class Reload(unittest.TestCase):
|
|||||||
script = os.path.join(root, "loop-claude")
|
script = os.path.join(root, "loop-claude")
|
||||||
open(script, "w").write(loop.RELOAD_BASELINE.replace("import glob\n", "import glob\nimport no_such_module\n"))
|
open(script, "w").write(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:
|
with unittest.mock.patch.object(loop, "__file__", script), unittest.mock.patch("os.execv") as execv:
|
||||||
loop.reload_if_edited("/r", "do it", cycle_number=1, failures=0)
|
loop.reload_if_edited(loop.LoopState(1, 0, "/r", "do it"))
|
||||||
execv.assert_not_called()
|
execv.assert_not_called()
|
||||||
open(script, "w").write(loop.RELOAD_BASELINE.replace("RELOAD_FLAG = ", "RELOAD_FLAG = \"x\" or "))
|
open(script, "w").write(loop.RELOAD_BASELINE.replace("RELOAD_FLAG = ", "RELOAD_FLAG = \"x\" or "))
|
||||||
environment = dict(os.environ)
|
environment = dict(os.environ)
|
||||||
with unittest.mock.patch.object(loop, "__file__", script), unittest.mock.patch("os.execv") as execv:
|
with unittest.mock.patch.object(loop, "__file__", script), unittest.mock.patch("os.execv") as execv:
|
||||||
loop.reload_if_edited("/r", "do it", cycle_number=1, failures=2)
|
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"})])
|
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)
|
self.assertEqual(dict(os.environ), environment)
|
||||||
|
|
||||||
|
|
||||||
class Main(unittest.TestCase):
|
class Main(unittest.TestCase):
|
||||||
def test_exits_naming_the_reload_when_it_hands_over_anything_but_the_state_with_a_task(self):
|
def test_exits_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": ""})]):
|
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), unittest.mock.patch.object(sys, "argv", ["loop-claude", loop.RELOAD_FLAG, *handed]), self.assertRaises(SystemExit) as stopped:
|
with self.subTest(handed=handed), unittest.mock.patch.object(sys, "argv", ["loop-claude", loop.RELOAD_FLAG, *handed]), self.assertRaises(SystemExit) as stopped:
|
||||||
loop.main()
|
loop.main()
|
||||||
self.assertEqual(stopped.exception.code, f"the reload cannot read the loop's state from {handed}; rerun loop-claude <task>")
|
self.assertEqual(stopped.exception.code, f"the reload cannot read the loop's state from {handed}; rerun loop-claude <task>")
|
||||||
@@ -464,7 +464,7 @@ class Main(unittest.TestCase):
|
|||||||
loop.main()
|
loop.main()
|
||||||
mocks[0].assert_not_called()
|
mocks[0].assert_not_called()
|
||||||
mocks[1].assert_called_once_with("/r")
|
mocks[1].assert_called_once_with("/r")
|
||||||
mocks[2].assert_called_once_with("/r", "do it", 3, 2)
|
mocks[2].assert_called_once_with(loop.LoopState(3, 2, "/r", "do it"))
|
||||||
self.assertEqual(mocks[3].call_args.args[0], "/r")
|
self.assertEqual(mocks[3].call_args.args[0], "/r")
|
||||||
mocks[4].assert_called_once_with("/r")
|
mocks[4].assert_called_once_with("/r")
|
||||||
self.assertEqual(mocks[3].call_args.args[-1], mocks[4].return_value)
|
self.assertEqual(mocks[3].call_args.args[-1], mocks[4].return_value)
|
||||||
|
|||||||
Reference in New Issue
Block a user