diff --git a/bin/loop-claude b/bin/loop-claude index 1dac205b..e3112eff 100755 --- a/bin/loop-claude +++ b/bin/loop-claude @@ -94,11 +94,11 @@ def sections(text): return {name: ["\n".join(body) for body in bodies] for name, bodies in found.items()} -def read_premises(): +def read_premises(root): try: - found = sections(open("README.md", encoding="utf-8").read()) + found = sections(open(os.path.join(root, "README.md"), encoding="utf-8").read()) except OSError as failure: - sys.exit(f"README.md in {os.getcwd()}: {failure.strerror} - no premises.") + sys.exit(f"README.md in {root}: {failure.strerror} - no premises.") for name in ("Goals", "Audience"): bodies = found.get(name, []) if not bodies: @@ -117,12 +117,12 @@ def checkout_root(): return found.stdout.strip() -def project(): - return os.getcwd().removeprefix(os.path.expanduser("~/code/")).lstrip("/") +def project(root): + return root.removeprefix(os.path.expanduser("~/code/")).lstrip("/") -def session_name(): - return f"A {project()} loop-claude" +def session_name(root): + return f"A {project(root)} loop-claude" def session_file(session_id): @@ -196,23 +196,23 @@ def make_private(folder): os.umask(mask) -def archive(path, note): - folder = os.path.join(ARCHIVE, project()) +def archive(root, path, note): + folder = os.path.join(ARCHIVE, project(root)) try: stamp = time.strftime("%Y-%m-%dT%H-%M-%SZ", time.gmtime(os.path.getmtime(path))) make_private(folder) dest = os.path.join(folder, f"{stamp}.md") if not os.path.exists(dest): with open(os.open(dest, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as copy: - copy.write(f"# {stamp} {project()}\n\n{note}\n\n{render(entries(path))}\n") + copy.write(f"# {stamp} {project(root)}\n\n{note}\n\n{render(entries(path))}\n") print(f"transcript: {dest}", file=sys.stderr) except OSError as failure: print(f"could not archive the transcript: {failure}", file=sys.stderr) -def checkouts(): - found = [os.getcwd()] - listing = subprocess.run(["git", "worktree", "list", "--porcelain"], capture_output=True, text=True) +def checkouts(root): + found = [root] + listing = subprocess.run(["git", "worktree", "list", "--porcelain"], capture_output=True, cwd=root, text=True) if listing.returncode == 0: found += [line.split(" ", 1)[1] for line in listing.stdout.splitlines() if line.startswith("worktree ")] return sorted(set(found)) @@ -323,17 +323,17 @@ def judge(task, premises, transcript): time.sleep(60) -def interrupt(session_id, path, question): +def interrupt(root, session_id, path, question): print(f"\n{question}", file=sys.stderr) if not (sys.stdin.isatty() and sys.stdout.isatty()): return "stdin or stdout is not a terminal" - trust(checkouts()) + trust(checkouts(root)) before = human_turns(entries(path)) subprocess.run(["claude", "--permission-mode", "bypassPermissions", "--resume", str(session_id)]) return "" if human_turns(entries(path)) > before else "the interrupt ended without the human typing anything" -def run_cycle(task, premises, name, session_id): +def run_cycle(root, task, premises, name, session_id): if failure := run_worker(worker_args(task, name, session_id, resuming=session_open(session_id))): return failure path = session_file(session_id) @@ -341,13 +341,13 @@ def run_cycle(task, premises, name, session_id): sys.exit(f"claude left no transcript for session {session_id}") verdict = judge(task, premises, render(entries(path))) while verdict["ask"]: - archive(path, f"Task: {task}\n\nVerdict: needs input\n\n{verdict['question']}") - if failure := interrupt(session_id, path, verdict["question"]): + archive(root, path, f"Task: {task}\n\nVerdict: needs input\n\n{verdict['question']}") + if failure := interrupt(root, session_id, path, verdict["question"]): print(failure, file=sys.stderr) sys.exit(2) verdict = judge(task, premises, render(entries(path))) if verdict["finished"]: - archive(path, f"Task: {task}\n\nVerdict: finished") + archive(root, path, f"Task: {task}\n\nVerdict: finished") end_session(path) return "" @@ -376,14 +376,15 @@ def main(): if task in ("", "-h", "--help"): print(__doc__.strip()) sys.exit(0 if task else 1) - os.chdir(checkout_root()) + root = checkout_root() + os.chdir(root) while True: reload_if_edited(task, cycle_number, failures) cycle_number += 1 - premises = read_premises() - name = session_name() + premises = read_premises(root) + name = session_name(root) print(f"\n=== cycle {cycle_number} ===", flush=True) - failure = run_cycle(task, premises, name, uuid.uuid5(SESSION_NAMESPACE, name)) + failure = run_cycle(root, task, premises, name, uuid.uuid5(SESSION_NAMESPACE, name)) if not failure: failures = 0 continue diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index a0017d47..cfc62731 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -37,9 +37,9 @@ class Sections(unittest.TestCase): class ReadPremises(unittest.TestCase): - def exit_message(self): + def exit_message(self, root): with self.assertRaises(SystemExit) as stopped: - loop.read_premises() + loop.read_premises(root) self.assertTrue(stopped.exception.code.endswith("no premises.")) return stopped.exception.code @@ -51,17 +51,18 @@ class ReadPremises(unittest.TestCase): "# T\n## Goals\n1. g\n## Audience\n": "nothing under ## Audience", "# T\n## Goals\n1. g\n## Audience\nme\n## Goals\n": "## Goals more than once", } - with tempfile.TemporaryDirectory() as root, contextlib.chdir(root): - self.assertIn(f"README.md in {os.getcwd()}: No such file or directory", self.exit_message()) - os.mkdir("README.md") - self.assertIn("Is a directory", self.exit_message()) - os.rmdir("README.md") + with tempfile.TemporaryDirectory() as root: + readme = os.path.join(root, "README.md") + self.assertIn(f"README.md in {root}: No such file or directory", self.exit_message(root)) + os.mkdir(readme) + self.assertIn("Is a directory", self.exit_message(root)) + os.rmdir(readme) for text, missing in texts.items(): with self.subTest(missing=missing): - open("README.md", "w").write(text) - self.assertIn(missing, self.exit_message()) - open("README.md", "w").write("# T\n## Goals\n1. g\n## Audience\nme\n") - self.assertEqual(loop.read_premises(), "## Goals\n1. g\n\n## Audience\nme") + open(readme, "w").write(text) + self.assertIn(missing, self.exit_message(root)) + open(readme, "w").write("# T\n## Goals\n1. g\n## Audience\nme\n") + self.assertEqual(loop.read_premises(root), "## Goals\n1. g\n\n## Audience\nme") class Render(unittest.TestCase): @@ -99,19 +100,17 @@ class CheckoutRoot(unittest.TestCase): os.makedirs("a/b") with contextlib.chdir("a/b"): self.assertEqual(loop.checkout_root(), root) + self.assertEqual(loop.checkouts(root), [root]) class Project(unittest.TestCase): def test_names_a_checkout_relative_to_code_and_any_other_relative_to_root(self): with unittest.mock.patch.dict(os.environ, {"HOME": "/h"}): - with unittest.mock.patch("os.getcwd", return_value="/h/code/a/b"): - self.assertEqual(loop.project(), "a/b") - self.assertEqual(loop.session_name(), "A a/b loop-claude") - with unittest.mock.patch("os.getcwd", return_value="/h/code"): - self.assertEqual(loop.project(), "h/code") - with unittest.mock.patch("os.getcwd", return_value="/srv/x"): - self.assertEqual(loop.project(), "srv/x") - self.assertEqual(loop.session_name(), "A srv/x loop-claude") + self.assertEqual(loop.project("/h/code/a/b"), "a/b") + self.assertEqual(loop.session_name("/h/code/a/b"), "A a/b loop-claude") + self.assertEqual(loop.project("/h/code"), "h/code") + self.assertEqual(loop.project("/srv/x"), "srv/x") + self.assertEqual(loop.session_name("/srv/x"), "A srv/x loop-claude") class WorkerArgs(unittest.TestCase): @@ -146,11 +145,11 @@ class JudgePrompt(unittest.TestCase): 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, unittest.mock.patch("os.getcwd", return_value="/srv/a/b"): + with tempfile.TemporaryDirectory() as root: transcript = os.path.join(root, "session.jsonl") open(transcript, "w").write(json.dumps(assistant({"type": "text", "text": "said"})) + "\n") loop.ARCHIVE = os.path.join(root, "deep", "archive") - loop.archive(transcript, "note") + 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] self.assertEqual(stat.S_IMODE(os.stat(copy).st_mode), 0o600) folder = os.path.dirname(copy) @@ -190,16 +189,16 @@ class Interrupt(unittest.TestCase): transcript = os.path.join(root, "session.jsonl") open(transcript, "w").write("{}\n") with unittest.mock.patch("sys.stdin.isatty", return_value=False): - self.assertEqual(loop.interrupt(SESSION_ID, transcript, "q?"), "stdin or stdout is not a terminal") + self.assertEqual(loop.interrupt(root, SESSION_ID, transcript, "q?"), "stdin or stdout is not a terminal") with ( unittest.mock.patch("sys.stdin.isatty", return_value=True), unittest.mock.patch("sys.stdout.isatty", return_value=True), unittest.mock.patch.multiple(loop, checkouts=unittest.mock.DEFAULT, trust=unittest.mock.DEFAULT), unittest.mock.patch("subprocess.run") as run, ): - self.assertEqual(loop.interrupt(SESSION_ID, transcript, "q?"), "the interrupt ended without the human typing anything") + self.assertEqual(loop.interrupt(root, SESSION_ID, transcript, "q?"), "the interrupt ended without the human typing anything") run.side_effect = lambda *args, **kwargs: open(transcript, "a").write(json.dumps(human("typed")) + "\n") - self.assertEqual(loop.interrupt(SESSION_ID, transcript, "q?"), "") + self.assertEqual(loop.interrupt(root, SESSION_ID, transcript, "q?"), "") class Trust(unittest.TestCase): @@ -304,10 +303,10 @@ class RunCycle(unittest.TestCase): 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("task", "premises", "A name", SESSION_ID), "") + self.assertEqual(loop.run_cycle(home, "task", "premises", "A name", SESSION_ID), "") open(verdicts, "w").write("ask") with self.assertRaises(SystemExit) as stopped, unittest.mock.patch("sys.stderr") as stderr: - loop.run_cycle("task", "premises", "A name", SESSION_ID) + loop.run_cycle(home, "task", "premises", "A name", SESSION_ID) self.assertEqual(stopped.exception.code, 2) said = "".join(str(call.args[0]) for call in stderr.write.call_args_list) self.assertIn(f"transcript: {loop.ARCHIVE}", said) @@ -315,7 +314,7 @@ class RunCycle(unittest.TestCase): for plan in ("fail fail fail", "unquoted unquoted unquoted"): open(verdicts, "w").write(plan) with self.assertRaises(SystemExit) as stopped: - loop.run_cycle("task", "premises", "A name", SESSION_ID) + loop.run_cycle(home, "task", "premises", "A name", SESSION_ID) self.assertTrue(stopped.exception.code.startswith("the judge ")) if plan.startswith("unquoted"): self.assertIn("asking: q?", stopped.exception.code) @@ -353,7 +352,9 @@ class Main(unittest.TestCase): mocks[3].side_effect = SystemExit(0) with self.assertRaises(SystemExit): loop.main() + mocks[1].assert_called_once_with(os.getcwd()) mocks[2].assert_called_once_with("do it", 3, 2) + self.assertEqual(mocks[3].call_args.args[0], os.getcwd()) self.assertIn("=== cycle 4 ===", sys.stdout.getvalue()) mocks[3].side_effect = ["claude exited 3"] * 3 stack.enter_context(unittest.mock.patch.object(sys, "argv", ["loop-claude", loop.RELOAD_FLAG, "3", "0", "do it"])) diff --git a/todo.md b/todo.md index ee50a303..016a9484 100644 --- a/todo.md +++ b/todo.md @@ -4,7 +4,6 @@ Ordered by how many seats of the 2026-09-25 scoring panel (`docs/decisions.md`) named the place; each is one chunk. -- Pass the checkout root to `project`, `read_premises` and `checkouts`, today each reads the cwd `main` set once. - Reject empty evidence in `grounded` by name, today `bool(evidence) and evidence in transcript`, where a tidy-up drops the guard and `"" in transcript` is always true. - Split `CLAUDE.md`'s release bullet under "Working loop" so the plan-it and stop predicates each stand alone, today six rules in one paragraph differing by one clause. - Delete the prose three seats found restating the code: `statusline.sh`'s colour-threshold comment, the second process-global-state rule in `agents/stability-reviewer.md`, the file list in `principles/README.md`, and `JUDGE_SCHEMA`'s `finished` description.