diff --git a/bin/loop-claude b/bin/loop-claude index 1dac205b..fa26e552 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)) @@ -261,8 +261,8 @@ def worker_args(task, name, session_id, resuming): ] -def run_worker(args): - proc = subprocess.Popen(["claude", *args], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, text=True) +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 {} @@ -297,7 +297,7 @@ def grounded(verdict, transcript): return not verdict["ask"] or bool(verdict["evidence"]) and verdict["evidence"] in transcript -def judge(task, premises, transcript): +def judge(root, task, premises, transcript): args = [ "-p", "--json-schema", json.dumps(JUDGE_SCHEMA), @@ -309,7 +309,7 @@ def judge(task, premises, transcript): ] prompt = judge_prompt(task, premises, transcript) for attempt in range(3): - proc = subprocess.run(["claude", *args], capture_output=True, input=prompt, text=True) + proc = subprocess.run(["claude", *args], capture_output=True, cwd=root, input=prompt, text=True) verdict = (parse(proc.stdout) or {}).get("structured_output") if proc.returncode == 0 else None if not complete(verdict): failure = proc.stderr.strip() or "the judge returned no verdict" @@ -323,36 +323,36 @@ 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)]) + subprocess.run(["claude", "--permission-mode", "bypassPermissions", "--resume", str(session_id)], cwd=root) return "" if human_turns(entries(path)) > before else "the interrupt ended without the human typing anything" -def run_cycle(task, premises, name, session_id): - if failure := run_worker(worker_args(task, name, session_id, resuming=session_open(session_id))): +def run_cycle(root, task, premises, name, session_id): + if failure := run_worker(root, worker_args(task, name, session_id, resuming=session_open(session_id))): return failure path = session_file(session_id) if not path: sys.exit(f"claude left no transcript for session {session_id}") - verdict = judge(task, premises, render(entries(path))) + verdict = judge(root, 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))) + verdict = judge(root, 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 "" -def reload_if_edited(task, cycle_number, failures): +def reload_if_edited(root, task, cycle_number, failures): try: source = open(__file__, encoding="utf-8").read() except OSError as failure: @@ -364,26 +364,26 @@ def reload_if_edited(task, cycle_number, failures): 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, str(cycle_number), str(failures), task]) + os.execv(sys.executable, [sys.executable, __file__, RELOAD_FLAG, str(cycle_number), str(failures), root, task]) def main(): argv = sys.argv[1:] - cycle_number, failures = 0, 0 + cycle_number, failures, root = 0, 0, "" if argv[:1] == [RELOAD_FLAG]: - cycle_number, failures, argv = int(argv[1]), int(argv[2]), argv[3:] + cycle_number, failures, root, argv = int(argv[1]), int(argv[2]), argv[3], argv[4:] task = " ".join(argv) if task in ("", "-h", "--help"): print(__doc__.strip()) sys.exit(0 if task else 1) - os.chdir(checkout_root()) + root = root or checkout_root() while True: - reload_if_edited(task, cycle_number, failures) + reload_if_edited(root, 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..cb691598 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,19 @@ class CheckoutRoot(unittest.TestCase): os.makedirs("a/b") with contextlib.chdir("a/b"): self.assertEqual(loop.checkout_root(), root) + subprocess.run(["git", "init", "-q", "other"], check=True) + with contextlib.chdir("other"): + 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 +147,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 +191,18 @@ 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.multiple(loop, checkouts=unittest.mock.DEFAULT, trust=unittest.mock.DEFAULT) as mocks, 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") + mocks["checkouts"].assert_called_with(root) + self.assertEqual(run.call_args.kwargs["cwd"], root) 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): @@ -258,7 +261,7 @@ class Verdict(unittest.TestCase): STUB_CLAUDE = """#!/usr/bin/env python3 import json, os, sys args = sys.argv[1:] -open(os.environ["STUB_CALLS"], "a").write(json.dumps(args) + "\\n") +open(os.environ["STUB_CALLS"], "a").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:])) @@ -289,7 +292,7 @@ class RunWorker(unittest.TestCase): for failure, script in scripts.items(): open(stub, "w").write(f"#!/usr/bin/env python3\nimport json\nimport os\nimport sys\n{script}\n") os.chmod(stub, 0o700) - self.assertEqual(loop.run_worker([]), failure) + self.assertEqual(loop.run_worker(bin, []), failure) class RunCycle(unittest.TestCase): @@ -304,10 +307,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,11 +318,12 @@ 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) 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([start[1] for start in starts], ["--name", "--resume", "--name", "--resume", "--resume", "--resume"]) self.assertEqual(starts[1][2], SESSION_ID) @@ -327,36 +331,44 @@ class RunCycle(unittest.TestCase): class Reload(unittest.TestCase): - def test_runs_the_edited_file_before_trusting_it_and_hands_it_the_counters_on_argv(self): + def test_runs_the_edited_file_before_trusting_it_and_hands_it_the_root_and_counters_on_argv(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")) with unittest.mock.patch.object(loop, "__file__", script), unittest.mock.patch("os.execv") as execv: - loop.reload_if_edited("do it", cycle_number=1, failures=0) + loop.reload_if_edited("/r", "do it", cycle_number=1, failures=0) execv.assert_not_called() open(script, "w").write(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("do it", cycle_number=1, failures=2) - execv.assert_called_once_with(sys.executable, [sys.executable, script, loop.RELOAD_FLAG, "1", "2", "do it"]) + loop.reload_if_edited("/r", "do it", cycle_number=1, failures=2) + execv.assert_called_once_with(sys.executable, [sys.executable, script, loop.RELOAD_FLAG, "1", "2", "/r", "do it"]) self.assertEqual(dict(os.environ), environment) class Main(unittest.TestCase): - def test_resumes_the_counters_a_reload_handed_over(self): + def test_resumes_the_root_and_counters_a_reload_handed_over(self): patches = [unittest.mock.patch.object(loop, name) for name in ("checkout_root", "read_premises", "reload_if_edited", "run_cycle")] with contextlib.ExitStack() as stack: mocks = [stack.enter_context(patch) for patch in patches] - stack.enter_context(unittest.mock.patch.object(sys, "argv", ["loop-claude", loop.RELOAD_FLAG, "3", "2", "do it"])) + stack.enter_context(unittest.mock.patch.object(sys, "argv", ["loop-claude", loop.RELOAD_FLAG, "3", "2", "/r", "do it"])) stack.enter_context(unittest.mock.patch.object(sys, "stdout", io.StringIO())) - mocks[0].return_value = os.getcwd() mocks[3].side_effect = SystemExit(0) with self.assertRaises(SystemExit): loop.main() - mocks[2].assert_called_once_with("do it", 3, 2) + mocks[0].assert_not_called() + mocks[1].assert_called_once_with("/r") + mocks[2].assert_called_once_with("/r", "do it", 3, 2) + self.assertEqual(mocks[3].call_args.args[0], "/r") + stack.enter_context(unittest.mock.patch.object(sys, "argv", ["loop-claude", "do it"])) + mocks[0].return_value = "/s" + with self.assertRaises(SystemExit): + loop.main() + mocks[0].assert_called_once_with() + mocks[1].assert_called_with("/s") 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"])) + stack.enter_context(unittest.mock.patch.object(sys, "argv", ["loop-claude", loop.RELOAD_FLAG, "3", "0", "/r", "do it"])) stack.enter_context(unittest.mock.patch.object(sys, "stderr", io.StringIO())) sleep = stack.enter_context(unittest.mock.patch("time.sleep")) with self.assertRaises(SystemExit) as stopped: diff --git a/docs/decisions.md b/docs/decisions.md index 0d107485..a952808e 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -10,7 +10,7 @@ ## loop-claude: one session per project, at a fixed id -2026-09-21, lilleman; the rename and mirrored-path costs accepted 2026-09-25 by larv-review. Serves goal 4. One fixed id per project keeps the session picker at one entry per project and makes any transcript under that id the script's own to delete. The id is uuid5 of the session name, "A loop-claude", so moving the checkout or changing that name orphans open sessions: they stay in the picker until the human deletes them, migration code not being worth a one-human audience. A checkout outside `~/code` mirroring a path inside it would share its id. Valid while claude takes `--session-id` and resumes by it, and no checkout outside `~/code` mirrors a path inside it. +2026-09-21, lilleman; the rename and mirrored-path costs accepted 2026-09-25 by larv-review. Serves goal 4. One fixed id per project keeps the session picker at one entry per project and makes any transcript under that id the script's own to delete. The id derives from the session name, so moving the checkout or changing that name orphans open sessions: they stay in the picker until the human deletes them, migration code not being worth a one-human audience. A checkout outside `~/code` mirroring a path inside it would share its id. Valid while claude takes `--session-id` and resumes by it, and no checkout outside `~/code` mirrors a path inside it. ## loop-claude: the trust file is rewritten before an interrupt 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.