Close every file loop-claude and its tests open
This commit is contained in:
+19
-17
@@ -48,6 +48,7 @@ import glob
|
||||
import itertools
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -55,7 +56,7 @@ import time
|
||||
import uuid
|
||||
|
||||
ARCHIVE = os.path.expanduser(os.environ.get("LOOP_CLAUDE_TRANSCRIPTS", "~/.claude/loop-claude-transcripts"))
|
||||
RELOAD_BASELINE = open(__file__, encoding="utf-8").read()
|
||||
RELOAD_BASELINE = pathlib.Path(__file__).read_text(encoding="utf-8")
|
||||
RELOAD_FLAG = "--reloaded"
|
||||
SESSION_NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec")
|
||||
|
||||
@@ -168,7 +169,7 @@ def checkout_root():
|
||||
|
||||
def read_premises(root):
|
||||
try:
|
||||
found = sections(open(os.path.join(root, "README.md"), encoding="utf-8").read())
|
||||
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:
|
||||
@@ -277,7 +278,7 @@ def loop_state(argv):
|
||||
|
||||
def reload_if_edited(state):
|
||||
try:
|
||||
source = open(__file__, encoding="utf-8").read()
|
||||
source = pathlib.Path(__file__).read_text(encoding="utf-8")
|
||||
except OSError as failure:
|
||||
print(f"keeping the running script: {failure}", file=sys.stderr)
|
||||
return
|
||||
@@ -390,9 +391,10 @@ def delete_transcript_files(path):
|
||||
|
||||
|
||||
def entries(path):
|
||||
for raw in open(path, encoding="utf-8"):
|
||||
if entry := parse(raw):
|
||||
yield entry
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
for raw in handle:
|
||||
if entry := parse(raw):
|
||||
yield entry
|
||||
|
||||
|
||||
def parse(raw):
|
||||
@@ -428,17 +430,17 @@ def typed(entry):
|
||||
|
||||
|
||||
def run_worker(root, args):
|
||||
proc = subprocess.Popen(["claude", *args], cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, text=True)
|
||||
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()
|
||||
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:
|
||||
|
||||
+32
-26
@@ -66,13 +66,13 @@ class ReadPremises(unittest.TestCase):
|
||||
os.mkdir(readme)
|
||||
self.assertIn("Is a directory", self.exit_message(root))
|
||||
os.rmdir(readme)
|
||||
open(readme, "wb").write(b"# T\n## Goals\n1. g\xff\n## Audience\nme\n")
|
||||
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):
|
||||
open(readme, "w").write(text)
|
||||
pathlib.Path(readme).write_text(text)
|
||||
self.assertIn(missing, self.exit_message(root))
|
||||
open(readme, "w").write("# T\n## Goals\n1. g\n## Audience\nme\n")
|
||||
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")
|
||||
|
||||
|
||||
@@ -232,7 +232,7 @@ class Archive(unittest.TestCase):
|
||||
def test_keeps_the_copy_and_every_folder_it_creates_as_private_as_the_transcript(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
transcript = os.path.join(root, "session.jsonl")
|
||||
open(transcript, "w").write(json.dumps(assistant({"type": "text", "text": "said"})) + "\n")
|
||||
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]
|
||||
@@ -241,7 +241,7 @@ class Archive(unittest.TestCase):
|
||||
while folder != root:
|
||||
self.assertEqual(stat.S_IMODE(os.stat(folder).st_mode), 0o700, folder)
|
||||
folder = os.path.dirname(folder)
|
||||
self.assertIn("said", open(copy).read())
|
||||
self.assertIn("said", pathlib.Path(copy).read_text())
|
||||
|
||||
|
||||
class Said(unittest.TestCase):
|
||||
@@ -258,10 +258,10 @@ class DeleteTranscriptFiles(unittest.TestCase):
|
||||
root = os.path.join(home, ".claude", "projects", "p")
|
||||
os.makedirs(root)
|
||||
transcript = os.path.join(root, f"{SESSION_ID}.jsonl")
|
||||
open(transcript, "w").write("{}\n")
|
||||
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"))
|
||||
open(os.path.join(root, f"{SESSION_ID}.orphaned-1-ab.jsonl"), "w").write("{}\n")
|
||||
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.assertEqual(os.listdir(root), [])
|
||||
@@ -272,7 +272,7 @@ 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")
|
||||
open(transcript, "w").write("{}\n")
|
||||
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")
|
||||
with (
|
||||
@@ -285,7 +285,11 @@ class Interrupt(unittest.TestCase):
|
||||
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")
|
||||
run.side_effect = lambda *args, **kwargs: open(transcript, "a").write(json.dumps(human("typed")) + "\n")
|
||||
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.assertEqual(loop.interrupt(root, SESSION_ID, "m", transcript, "q?"), "")
|
||||
|
||||
|
||||
@@ -353,12 +357,13 @@ class Verdict(unittest.TestCase):
|
||||
|
||||
|
||||
STUB_CLAUDE = """#!/usr/bin/env python3
|
||||
import json, os, sys
|
||||
import json, os, pathlib, sys
|
||||
args = sys.argv[1:]
|
||||
open(os.environ["STUB_CALLS"], "a").write(json.dumps([os.getcwd(), *args]) + "\\n")
|
||||
with open(os.environ["STUB_CALLS"], "a") as calls:
|
||||
calls.write(json.dumps([os.getcwd(), *args]) + "\\n")
|
||||
if "--json-schema" in args:
|
||||
plan = open(os.environ["STUB_VERDICTS"]).read().split()
|
||||
open(os.environ["STUB_VERDICTS"], "w").write(" ".join(plan[1:]))
|
||||
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")
|
||||
@@ -367,7 +372,8 @@ else:
|
||||
flag = "--session-id" if "--session-id" in args else "--resume"
|
||||
folder = os.path.expanduser("~/.claude/projects/p")
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
open(os.path.join(folder, args[args.index(flag) + 1] + ".jsonl"), "a").write(json.dumps({"type": "assistant", "message": {"content": [{"type": "text", "text": "worked"}]}}) + "\\n")
|
||||
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"}))
|
||||
"""
|
||||
|
||||
@@ -384,7 +390,7 @@ class RunWorker(unittest.TestCase):
|
||||
}
|
||||
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():
|
||||
open(stub, "w").write(f"#!/usr/bin/env python3\nimport json\nimport os\nimport sys\n{script}\n")
|
||||
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)
|
||||
|
||||
@@ -393,49 +399,49 @@ 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")
|
||||
open(stub, "w").write(STUB_CLAUDE)
|
||||
pathlib.Path(stub).write_text(STUB_CLAUDE)
|
||||
os.chmod(stub, 0o700)
|
||||
calls, verdicts = os.path.join(home, "calls"), os.path.join(home, "verdicts")
|
||||
open(verdicts, "w").write("fail continue finished unquoted continue")
|
||||
pathlib.Path(verdicts).write_text("fail continue finished unquoted continue")
|
||||
loop.ARCHIVE = 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"), "")
|
||||
open(verdicts, "w").write("interrupt")
|
||||
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))
|
||||
open(verdicts, "w").write("interrupt fail fail fail")
|
||||
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}"))
|
||||
for plan in ("fail fail fail", "unquoted unquoted unquoted"):
|
||||
open(verdicts, "w").write(plan)
|
||||
pathlib.Path(verdicts).write_text(plan)
|
||||
stop = loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5")
|
||||
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(open(verdicts).read(), "")
|
||||
self.assertEqual({json.loads(line)[0] for line in open(calls)}, {home})
|
||||
starts = [args[args.index("-p") + 1:][:3] for args in map(json.loads, open(calls)) if "--json-schema" not in args]
|
||||
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], SESSION_ID)
|
||||
self.assertEqual(sleep.call_count, 8)
|
||||
self.assertEqual({args[args.index("--model") + 1] for args in map(json.loads, open(calls))}, {"claude-opus-5-5"})
|
||||
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")
|
||||
open(script, "w").write(loop.RELOAD_BASELINE.replace("import glob\n", "import glob\nimport no_such_module\n"))
|
||||
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()
|
||||
open(script, "w").write(loop.RELOAD_BASELINE.replace("RELOAD_FLAG = ", "RELOAD_FLAG = \"x\" or "))
|
||||
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"))
|
||||
|
||||
@@ -4,6 +4,5 @@
|
||||
|
||||
Ships when a four-seat scoring run puts every dimension and the overall at 7.0 or above (`docs/decisions.md`). Ordered by the dimension each item lifts, lowest first, per the 2026-09-26 panel; each is one chunk.
|
||||
|
||||
- **Close every file `bin/loop-claude` and `bin/test_loop_claude.py` open, so the suite runs without a ResourceWarning.**
|
||||
- **Route an external auto-reviewer's behaviour-changing fix in `larv-review` §9 back through §5.** Today nothing sends it there.
|
||||
- **Rerun the four-seat panel and score every dimension and the overall at 7.0 or above.** A dimension under it gets its places filed above, and this item stays last.
|
||||
|
||||
Reference in New Issue
Block a user