"""Test doubles for the suites that run cycles: FakeEffects stands in for loop_effects.effects.Effects, Worker and Streamed for a worker's claude, and judged for a judge's reply.""" import json import pathlib import subprocess import uuid from loop_effects.effects import Effects from claude_code import entries from machine_load import memory CWD = pathlib.Path("/c") NOW = 1790000000 def assistant(*parts): return {"type": "assistant", "message": {"content": list(parts)}} def human(content): return {"type": "user", "message": {"content": content}} # The window the loops under test run in. class FakeEffects: """Effects that record each call and answer from a script, one answer per call.""" def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True, free_memory=(), dm_failures=(), tmux_version="tmux 3.2", windows=None, owner="/r"): self.calls = [] # Each tmux command run. They stay out of self.calls, as the DMs do. tmux prints `windows` for list-windows, or without them finds no session. self.tmux_calls = [] self.tmux_version = tmux_version self.windows = windows # The checkout the session's @loop-root option names. self.owner = owner # Each direct message sent. They stay out of self.calls, so a test that lists every call doesn't list them. Without a script, each is sent. self.dms = [] # The directory each DM named, in the order of self.dms; None where it named none. self.dm_directories = [] self.dm_failures = list(dm_failures) self.scripts = {"claude": list(claude), "claude_on_terminal": list(on_terminal_claude), "git": list(git), "input": list(inputs), "python": list(python), "stream_claude": list(streams)} # Without a script, every read finds all memory available. self.free_memory = list(free_memory) self.terminal = on_terminal self.worker_environments = [] self.worker_folders = [] self.terminal_environments = [] self.terminal_folders = [] # Each timer started, as its delay and action, which a test runs where the timer fires. self.timers = [] def effects(self): return Effects( claude=lambda args, cwd, stdin: self.answer("claude", (args, stdin)), claude_on_terminal=self.on_terminal_claude, discard_typed=lambda: self.calls.append(("discard_typed", None)), dm=self.dm, execv=self.execv, git=lambda *args, cwd=None, timeout=None, guarded=False, errors="strict": self.answer("git", list(args)), input=lambda prompt: self.answer("input", prompt), local_time=lambda seconds: f"<{seconds}>", memory=self.memory, now=lambda: NOW, on_terminal=lambda: self.terminal, python=lambda args, cwd: self.answer("python", (args, cwd)), sleep=lambda seconds: self.calls.append(("sleep", seconds)), stream_claude=self.stream, timer=self.timer, tmux=self.tmux, tmux_on_terminal=lambda args: self.tmux(args).returncode, ) def timer(self, delay, action): self.timers.append((delay, action)) return lambda: self.calls.append(("stop_timer", delay)) def tmux(self, args): self.tmux_calls.append(args) if args[0] == "list-windows": return subprocess.CompletedProcess(args, 1 if self.windows is None else 0, self.windows or "", "no server") return subprocess.CompletedProcess(args, 0, {"-V": self.tmux_version + "\n", "show-options": self.owner + "\n"}.get(args[0], "@9\n"), "") def dm(self, text, directory): self.dms.append(text) self.dm_directories.append(directory) return self.dm_failures.pop(0) if self.dm_failures else None def memory(self): self.calls.append(("memory", None)) return self.free_memory.pop(0) if self.free_memory else memory.Memory(available=16, total=16) def on_terminal_claude(self, args, cwd, env): self.terminal_environments.append(env) self.terminal_folders.append(cwd) return self.answer("claude_on_terminal", args) def stream(self, args, cwd, env): self.worker_environments.append(env) self.worker_folders.append(cwd) return self.answer("stream_claude", args) def answer(self, seam, what): self.calls.append((seam, what)) answer = self.scripts[seam].pop(0) if isinstance(answer, BaseException): raise answer return answer(what) if callable(answer) else answer def execv(self, path, args): self.calls.append(("execv", args)) raise OSError(2, "No such file or directory") def made(self, seam): return [what for called, what in self.calls if called == seam] def ran(stdout="", code=0, stderr=""): return subprocess.CompletedProcess([], code, stdout, stderr) def judged(verdict, evidence="working", answer="", escalation="", release_ready=False, cost=None, reversed=""): reply = {"answer": answer, "escalation": escalation, "evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict in ("interrupt", "quoted") else "", "answered_before": "", "left_open": "", "release_ready": release_ready, "reversed": reversed} return ran(json.dumps({"structured_output": reply, **({} if cost is None else {"total_cost_usd": cost})})) class Worker: """A worker claude: writes a line to the session's transcript, then streams a result.""" def __init__(self, home, prompted=False, text="working", usage=None, sent=None): self.home = home # Whether it records its -p prompt in the transcript first, as claude does. self.prompted = prompted self.text = text # The usage its message records, twice as Claude Code writes a message of two blocks; none where None. self.usage = usage # The time its message records, as utc() writes it; none where None. self.sent = sent def __call__(self, args): flag = "--session-id" if "--session-id" in args else "--resume" path = self.home / "projects" / "-fake" / f"{args[args.index(flag) + 1]}.jsonl" path.parent.mkdir(parents=True, exist_ok=True) with open(path, "a") as handle: if flag == "--session-id": handle.write(json.dumps({"type": "custom-title"}) + "\n" + json.dumps({"type": "queue-operation", "timestamp": str(uuid.uuid7())}) + "\n") if self.prompted: handle.write(json.dumps({**human(args[args.index("-p") + 1]), "promptSource": "sdk"}) + "\n") said = assistant({"type": "text", "text": self.text}) if self.usage is not None: said["message"] |= {"id": "msg-1", "model": "claude-opus-5-5", "usage": self.usage} if self.sent is not None: said["timestamp"] = self.sent handle.write((json.dumps(said) + "\n") * (1 if self.usage is None else 2)) return Streamed(0) class Streamed: """A started claude. An event of None is an idle stretch of CHECK_EVERY seconds, which advances `clock` by that; `held` are the shells it has, and `stopped` collects the ones stopped.""" def __init__(self, code, *events, clock=None, held=()): self.code = code self.events = events or ({"type": "result"},) self.clock = clock self.held = list(held) self.stopped = [] def lines(self, idle): for event in self.events: if event is None: self.clock[0] += idle yield None if event is None else json.dumps(event) + "\n" def shells(self): return self.held def stop(self, shell): self.stopped.append(shell) def wait(self): return self.code # How a line said at NOW opens, with FakeEffects' local_time. STAMP = f"<{NOW}>" def kinds(*found): return [entries.entry_from(entry) for entry in found] def said(*texts): return entries.AssistantTurn(parts=tuple(entries.Text(text) for text in texts))