diff --git a/CHANGELOG.md b/CHANGELOG.md index a6896f23..6bc2bde0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- `loop-claude` now opens every message it prints with the machine's local time, as in `2026-10-28 11:46:01`, so you can see when each happened, such as how long a question has waited. A message of several lines, such as a question, carries the time on its first line only. - larv-review now gives each review pass at most two rounds per chunk, where it gave three and then asked for more, and no longer asks: the fixes answering a pass's second round merge once the gate passes. rule-hook's new `round-cap` rule refuses a round commit that would take a pass past round 2, such as `Answer stability round 3: …`, and takes no override. It counts the pass's earlier round commits on the branch, so a third commit titled round 2 is refused too. `larv-review round-count` marks a pass at two rounds as at the cap. - rule-hook has a new rule, `repeat-read`, and now runs before each Read call too. It blocks a Read, or a Bash `cat`, `head` or `sed -n ',p'` of one file, when every line it asks for is already in the agent's context, and the block names those lines. The rule takes no override. - A line is in context when an earlier read's result in the agent's own transcript showed it since the last compaction, as the file holds it now. A subagent is judged on its own transcript, not its session's. diff --git a/bin/loop_claude/cycle/interrupt.py b/bin/loop_claude/cycle/interrupt.py index d5d2b455..04458689 100644 --- a/bin/loop_claude/cycle/interrupt.py +++ b/bin/loop_claude/cycle/interrupt.py @@ -8,6 +8,7 @@ from claude_code.transcript import human_turns, read_transcript from loop_claude.stop import needs_human, needs_terminal, Stop from loop_claude.paths import Paths from model_routing.ladder import Rung +from loop_claude.terminal import say from claude_code.trust import trust from loop_claude.project.checkout import worktrees @@ -24,7 +25,7 @@ class Talk: def put_question(question: str, answer_here: bool, effects: Effects) -> str | Talk | Stop: """Prints question for the human. Where answer_here, returns the line they type at loop-claude's terminal, stripped, or Talk where they type TALK; else Talk at once. A Stop where loop-claude is off a terminal, or they type nothing, or the input ends.""" - print(f"\n{question}", file=sys.stderr) + say(f"\n{question}", effects) if stop := needs_terminal(ANSWER_QUESTION, effects.on_terminal()): return stop # Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, input takes the first line; the rest wait, and the next question drops them. A longer answer goes through TALK. diff --git a/bin/loop_claude/cycle/retry.py b/bin/loop_claude/cycle/retry.py index ca4ba056..3fe6ec5d 100644 --- a/bin/loop_claude/cycle/retry.py +++ b/bin/loop_claude/cycle/retry.py @@ -1,9 +1,9 @@ -import sys import typing from loop_claude.effects import Effects from failure import Failure from claude_code.reply import Limited +from loop_claude.terminal import say from loop_claude.stop import Stop T = typing.TypeVar("T") @@ -24,7 +24,7 @@ def retried(who: str, attempt: typing.Callable[[], T | Failure | Limited], effec failures = 0 now = effects.now() wait = limit_wait(result, now) - print(f"the {who} hit a usage limit ({result.said}); retrying at {effects.local_time(now + wait)}", file=sys.stderr, flush=True) + say(f"the {who} hit a usage limit ({result.said}); retrying at {effects.local_time(now + wait)}", effects) effects.sleep(wait) continue if not isinstance(result, Failure): @@ -34,7 +34,7 @@ def retried(who: str, attempt: typing.Callable[[], T | Failure | Limited], effec failures += 1 if failures == FAILURES_RUNNING: return Stop(1, f"the {who} failed three times running: {result.reason}") - print(f"retrying the {who} in a minute: {result.reason}", file=sys.stderr) + say(f"retrying the {who} in a minute: {result.reason}", effects) effects.sleep(RETRY_DELAY) diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/run.py index 3cc0cc39..4c33f546 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -19,6 +19,7 @@ from claude_code.transcript import read_transcript from loop_claude.cycle.retry import retried from model_routing.route import Route from model_routing.ladder import Rung +from loop_claude.terminal import say from loop_claude.escalation_mark import StepUp from loop_claude.stop import Stop from model_routing import worker_rungs @@ -109,7 +110,7 @@ def step(cycle: Cycle, state: Active) -> Event | Stop: def work(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, step_up: StepUp | None) -> WorkerRan | Stop: if isinstance(answered, QuotedAnswer): - print(f"\n=== {prompts.QUOTE_SOURCES} answered: {answered.question} ===\n{answered.answer}", flush=True) + say(f"\n=== {prompts.QUOTE_SOURCES} answered: {answered.question} ===\n{answered.answer}", cycle.effects, stdout=True) if stop := keep_answer(cycle, answered, step_up): return stop # worker_start runs inside the lambda: a failed attempt may have opened the session. diff --git a/bin/loop_claude/cycle/worker.py b/bin/loop_claude/cycle/worker.py index 02f051c4..2cad28bf 100644 --- a/bin/loop_claude/cycle/worker.py +++ b/bin/loop_claude/cycle/worker.py @@ -1,5 +1,3 @@ -import sys - from claude_code.entries import assistant_parts, ends_stream, hit_limit, limit_said, parse_entry, rejected_until from loop_claude.effects import Effects from failure import Failure @@ -7,6 +5,7 @@ from claude_code.reply import Limited from claude_code.transcript import part_line from machine_load.memory import ROOM_SHARE from model_routing.ladder import Rung +from loop_claude.terminal import say from claude_code.session import Session PRINTED_TOOL_INPUT = 160 @@ -33,7 +32,7 @@ def run_worker(root: str, args: list[str], env: dict[str, str], effects: Effects resets.append(resets_at) for part in assistant_parts(event): if line := part_line(part, PRINTED_TOOL_INPUT): - print(line, flush=True) + say(line, effects, stdout=True) return worker_outcome(proc.wait(), result, resets) @@ -42,7 +41,7 @@ def wait_for_memory(effects: Effects) -> None: said = False while (memory := effects.memory()) is not None and not memory.has_room(): if not said: - print(f"waiting to start the worker until at least {ROOM_SHARE:.0%} of the machine's memory is available; {memory.available // 1024} MiB of {memory.total // 1024} MiB is available now", file=sys.stderr, flush=True) + say(f"waiting to start the worker until at least {ROOM_SHARE:.0%} of the machine's memory is available; {memory.available // 1024} MiB of {memory.total // 1024} MiB is available now", effects) said = True effects.sleep(MEMORY_POLL) diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 7596988d..02352798 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -117,7 +117,6 @@ Rerunning resumes any open session. """ import dataclasses import pathlib -import sys import typing from loop_claude.routing import after_unfinished, first_route, kept, routed_item @@ -144,6 +143,7 @@ from loop_claude.cycle import prompts from loop_claude.project.premises import read_premises from loop_claude.project.records import read_records from model_routing.route import Route, route_from +from loop_claude.terminal import say from claude_code.session import Session, session_named, session_open, transcript_file # Seconds routing waits for origin to name its default branch, asked only where the checkout records none; past them, the chunk runs on the project's rung. @@ -158,7 +158,7 @@ def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: except KeyboardInterrupt: stop = Stop(130, "") if stop.reason: - print(stop.reason, file=sys.stderr if stop.code else sys.stdout) + say(stop.reason, effects, stdout=not stop.code) return stop.code @@ -187,8 +187,8 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc # After the reads above, so a loop that stops on one makes no worktree. facts, item = chunk_start(session, launcher.with_name("chunk-preflight"), loop_run.root, effects) project = project_rung(models.worker) - route = routed(loop_run.route, project, models.worker, lambda: archived_route(archive_folder, session), item) - print(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", flush=True) + route = routed(loop_run.route, project, models.worker, lambda: archived_route(archive_folder, session, effects), item) + say(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", effects, stdout=True) concluded = run_cycle(Cycle(effects=effects, facts=facts, judge_model=models.judge, paths=paths, premises=premises, project=project, project_archive=archive_folder, records=records, root=loop_run.root, route=route, session=session, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence)) if isinstance(concluded, Stop): return concluded @@ -252,23 +252,23 @@ def archive_step(archive_folder: pathlib.Path, session: Session, task: str, befo return Stop(1, failure.reason) if failure else None -def archived_route(archive_folder: pathlib.Path, session: Session) -> Route | None: +def archived_route(archive_folder: pathlib.Path, session: Session, effects: Effects) -> Route | None: """The route the latest verdict archived for the session's open chunk names; None for a chunk not yet judged.""" transcript = transcript_file(session) worker = latest_worker(archive_folder, transcript) if transcript else None if isinstance(worker, Failure): - print(f"routing the chunk afresh: {worker.reason}", file=sys.stderr) + say(f"routing the chunk afresh: {worker.reason}", effects) return None route = route_from(worker) if worker else None if worker and route is None: - print(f"routing the chunk afresh: the archive's latest Worker: line names no route loop-claude can read: {worker}", file=sys.stderr) + say(f"routing the chunk afresh: the archive's latest Worker: line names no route loop-claude can read: {worker}", effects) return route def chunk_start(session: Session, preflight: pathlib.Path, root: str, effects: Effects) -> tuple[str, typing.Callable[[], Item | None]]: """The facts for a fresh worker's prompt, empty where the session is open, and the reader of the item that routes the chunk. The reader reads the default branch as last fetched: for a fresh chunk, by the preflight that runs first; for an open session, which runs none, by whatever fetched last.""" facts = "" if session_open(session) else chunk_facts(preflight, root, effects) - return facts, lambda: plan_item(fetched_plan(root)) + return facts, lambda: plan_item(fetched_plan(root), effects) def chunk_facts(preflight: pathlib.Path, root: str, effects: Effects) -> str: @@ -285,7 +285,7 @@ def fetched_plan(root: str) -> DefaultPlan | Failure: return ref if isinstance(ref, Failure) else default_plan(root, ref) -def plan_item(plan: DefaultPlan | Failure) -> Item | None: +def plan_item(plan: DefaultPlan | Failure, effects: Effects) -> Item | None: """The item that routes a chunk, chunk_pick.chunk_item's pick from the default branch; None without one, so the chunk runs on the project's rung.""" if isinstance(plan, Failure): item: Item | Failure | None = plan @@ -294,7 +294,7 @@ def plan_item(plan: DefaultPlan | Failure) -> Item | None: else: item = routed_item(plan.todo, plan.cut) if isinstance(item, Failure): - print(f"routing on the project's rung: {item.reason}", file=sys.stderr) + say(f"routing on the project's rung: {item.reason}", effects) return None return item diff --git a/bin/loop_claude/loop/reload.py b/bin/loop_claude/loop/reload.py index f6d8dd53..5a3d024b 100644 --- a/bin/loop_claude/loop/reload.py +++ b/bin/loop_claude/loop/reload.py @@ -8,6 +8,7 @@ import typing from loop_claude.effects import Effects from model_routing.route import Route +from loop_claude.terminal import say from loop_claude.stop import Stop RELOAD_FLAG = "--reloaded" @@ -84,7 +85,7 @@ def exec_if_edited(launcher: pathlib.Path, baseline: str, loop_run: LoopRun, eff return None trial = effects.python([str(launcher), "--help"], loop_run.root) if trial.returncode != 0: - print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr) + say(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", effects) return None try: effects.execv(sys.executable, [sys.executable, str(launcher), RELOAD_FLAG, json.dumps(dataclasses.asdict(loop_run))]) diff --git a/bin/loop_claude/loop/routing_check.py b/bin/loop_claude/loop/routing_check.py index 3b6344b5..8d0cd9a8 100644 --- a/bin/loop_claude/loop/routing_check.py +++ b/bin/loop_claude/loop/routing_check.py @@ -1,6 +1,5 @@ """Every CYCLES_PER_CHECK cycles across all projects, measure the archive's routing figures, keep them at its root, and interrupt the human with each call for a routing change not raised before: docs/decisions.md → `routing:`.""" import pathlib -import sys from routing_figures import archive from routing_figures.measure import calls, due, render, totals @@ -9,6 +8,7 @@ from failure import Failure from loop_claude.cycle.interrupt import hand_over from loop_claude.paths import Paths from model_routing.ladder import Rung +from loop_claude.terminal import say from loop_claude.stop import Stop from utc_stamp import utc @@ -18,7 +18,7 @@ def check_routing(root: pathlib.Path, rung: Rung, paths: Paths, effects: Effects with archive.locked(root) as held: new = new_calls(root, paths, effects) if held else [] if isinstance(new, Failure): - print(f"routing figures: {new.reason}", file=sys.stderr) + say(f"routing figures: {new.reason}", effects) return None return raise_calls(root, new, rung, paths, effects) if new else None @@ -32,7 +32,7 @@ def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[str] | kept = archive.raised(root) if isinstance(kept, Failure): return kept - print(f"\n=== cycle {cycle} across loop-claude's archive: measuring the routing figures ===", flush=True) + say(f"\n=== cycle {cycle} across loop-claude's archive: measuring the routing figures ===", effects, stdout=True) measured = archive.measure_archive(root, str(paths.home), kept.since) if isinstance(measured, Failure): return measured @@ -46,14 +46,14 @@ def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[str] | def raise_calls(root: pathlib.Path, new: list[str], rung: Rung, paths: Paths, effects: Effects) -> Stop | None: """Puts the calls to the human through a claude in this setup's checkout, where the routing decision lives. Off a terminal they are only said, and stay in the figures, raised at the next measurement on a terminal.""" listed = "".join(f"- {call}\n" for call in new) - print(f"\nloop-claude's routing figures call for a routing change:\n{listed}The figures: {root / archive.FIGURES}", file=sys.stderr) + say(f"\nloop-claude's routing figures call for a routing change:\n{listed}The figures: {root / archive.FIGURES}", effects) if not effects.on_terminal(): - print("Not on a terminal: the calls are raised again at the next measurement.", file=sys.stderr) + say("Not on a terminal: the calls are raised again at the next measurement.", effects) return None prompt = f"Put these calls for a routing change from loop-claude's figures to the human, and change nothing until they answer:\n{listed}The figures are in {root / archive.FIGURES}. The ladder, its steps and the delegation rule are docs/decisions.md → `routing:`, and a change to them is the human's. Record what they decide as ~/.claude/CLAUDE.md says; the next chunk of this repo files the plan item for these calls." if unstarted := hand_over(rung, [prompt], str(paths.claude_dir), paths, {}, effects): return Stop(1, f"could not start claude for the routing calls: {unstarted.reason}") # Raised once the human has seen them, answered or not: an unanswered call reaches the plan through AGENTS.md, so it is not asked twice. if unmarked := archive.mark_raised(root, new, utc(effects.now())): - print(f"routing figures: {unmarked.reason}", file=sys.stderr) + say(f"routing figures: {unmarked.reason}", effects) return None diff --git a/bin/loop_claude/project/model_choice.py b/bin/loop_claude/project/model_choice.py index c903e2c8..f4f38244 100644 --- a/bin/loop_claude/project/model_choice.py +++ b/bin/loop_claude/project/model_choice.py @@ -10,6 +10,7 @@ from failure import Failure from loop_claude.stop import needs_human, needs_terminal, Stop from loop_claude.paths import Paths from file_writes import replace_json +from loop_claude.terminal import say @dataclasses.dataclass(frozen=True) @@ -44,7 +45,7 @@ def get_or_ask_model(project_key: str, paths: Paths, effects: Effects) -> str | return models if failure := replace_json(saved, {**models, project_key: chosen}, indent="\t", sort_keys=True): return Stop(1, f"could not save the model in {saved}: {failure.reason}") - print(f"{project_key} runs on {chosen}", file=sys.stderr) + say(f"{project_key} runs on {chosen}", effects) return chosen @@ -65,11 +66,8 @@ def ask_for_model(project_key: str, saved: pathlib.Path, folder: pathlib.Path, e if stop := needs_terminal(f"pick {project_key}'s model, or merge {{\"{project_key}\": \"\"}} into {saved}", effects.on_terminal()): return stop offered = catalog_models(folder) - print(f"\nThe model to run {project_key} on, saved in {saved}:", file=sys.stderr) - for number, (model_id, label) in enumerate(offered, 1): - print(f" {number}. {label} ({model_id})", file=sys.stderr) - if not offered: - print(f" no model catalog cached in {folder}", file=sys.stderr) + choices = [f" {number}. {label} ({model_id})" for number, (model_id, label) in enumerate(offered, 1)] or [f" no model catalog cached in {folder}"] + say("\n".join([f"\nThe model to run {project_key} on, saved in {saved}:", *choices]), effects) while True: try: answer = effects.input(f"{'A number, or any' if offered else 'A'} name claude --model takes: ") @@ -78,7 +76,7 @@ def ask_for_model(project_key: str, saved: pathlib.Path, folder: pathlib.Path, e return needs_human(f"pick {project_key}'s model", "the input ended") picked = model_picked(answer, offered) if isinstance(picked, Failure): - print(picked.reason, file=sys.stderr) + say(picked.reason, effects) elif picked: return picked diff --git a/bin/loop_claude/terminal.py b/bin/loop_claude/terminal.py new file mode 100644 index 00000000..05b9ec91 --- /dev/null +++ b/bin/loop_claude/terminal.py @@ -0,0 +1,13 @@ +import sys +import time + +from loop_claude.effects import Effects + + +# The spelling `YYYY-MM-DD HH:MM:SS` in local time, never UTC, is lilleman's call of 2026-10-28. +def say(text: str, effects: Effects, *, stdout: bool = False) -> None: + """Prints text on stderr, or on stdout where stdout, opening its first line with the machine's local time as `2026-10-28 11:46:01`, so the human sees when it happened. Blank lines before the text stay blank, and only its first line gets the time.""" + body = text.lstrip("\n") + blanks = text[: len(text) - len(body)] + stamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(effects.now())) + print(f"{blanks}{stamp} {body}", file=sys.stdout if stdout else sys.stderr, flush=True) diff --git a/bin/loop_claude/test_black_box.py b/bin/loop_claude/test_black_box.py index 8760387f..58874703 100644 --- a/bin/loop_claude/test_black_box.py +++ b/bin/loop_claude/test_black_box.py @@ -157,8 +157,11 @@ class Run: code: int sleeps: list starts: list + # Without the local time that opens each message loop-claude prints. stderr: str stdout: str + raw_stderr: str + raw_stdout: str def roles(self): return [call["role"] for call in self.calls] @@ -228,8 +231,10 @@ class Checkout: code=code, sleeps=[event["sleep"] for event in started if "sleep" in event], starts=[event["argv"] for event in started if "argv" in event], - stderr=stderr, - stdout=stdout, + stderr=unstamped(stderr), + stdout=unstamped(stdout), + raw_stderr=stderr, + raw_stdout=stdout, ) def run_on_terminal(self, command, cwd, typed, stdout_on_terminal, before_typing, typed_early): @@ -295,6 +300,13 @@ class Checkout: return outcomes +STAMP = r"\d{4}-\d\d-\d\d \d\d:\d\d:\d\d" + + +def unstamped(text): + return re.sub(rf"(?m)^{STAMP} ", "", text) + + def argument(call, flag): return call["argv"][call["argv"].index(flag) + 1] if flag in call["argv"] else None @@ -311,7 +323,7 @@ class Premises(unittest.TestCase): outside.mkdir() run = checkout.run([], cwd=outside) self.assertEqual((run.code, run.calls), (1, [])) - self.assertIn("not a git repository", run.stderr) + self.assertRegex(run.raw_stderr, rf"(?m)^{STAMP} .*not a git repository") readmes = { None: "README.md in {root}: No such file or directory - no premises.", b"# P\n## Goals\n1. g\xff\n## Audience\nme\n": "README.md in {root} is not UTF-8 on line 3 - no premises.", @@ -396,6 +408,8 @@ class Cycles(unittest.TestCase): self.assertNotIn("landed-it", run.calls[5]["stdin"]) self.assertEqual([path.name for path in checkout.transcripts()[0].parent.iterdir()], [checkout.transcripts()[0].name]) self.assertIn("=== cycle 3, worker on worker-model ===", run.stdout) + (header,) = re.findall(rf"(?m)^({STAMP}) === cycle 3, worker on worker-model ===$", run.raw_stdout) + self.assertLess(abs(time.time() - time.mktime(time.strptime(header, "%Y-%m-%d %H:%M:%S"))), 120) copies = {verdict.removeprefix(f"Task: {TASK}\n\n"): copy for copy, verdict in checkout.archived().items()} self.assertEqual(sorted(copies), [f" Stopped: Ctrl-C\n\nWorker: {OFF_LADDER}\n", f" Verdict: finished\n\nEvidence:\n> landed-it\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n", f" Verdict: unfinished\n\nEvidence:\n> started\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"]) self.assertIn('"text": "landed-it"', copies[f" Verdict: finished\n\nEvidence:\n> landed-it\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"]) diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index c11a8a00..10a35b6e 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -10,6 +10,7 @@ import stat import subprocess import sys import tempfile +import time import unittest import unittest.mock import uuid @@ -21,7 +22,7 @@ from loop_claude.project import checkout, model_choice, records from chunk_pick import DefaultPlan, LastCut from loop_claude.effects import Effects, PYTHON_TIMEOUT, run_python from claude_code import entries, reply, session -from loop_claude import escalation_mark, paths, routing +from loop_claude import escalation_mark, paths, routing, terminal from failure import Failure from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished from loop_claude.cycle import interrupt, judge, prompts, retry, run, states, worker @@ -46,6 +47,17 @@ OPUS_179_AT_6 = '{"model": "claude-opus-5-5", "effort": "medium", "item": 179, " CWD = pathlib.Path("/c") NOW = 1790000000 +# How a line said at NOW opens in a zone two hours ahead of UTC, which setUpModule sets: a stamp in UTC would read 14:13:20. +STAMP = "2026-09-21 16:13:20" + + +def setUpModule(): + zone = unittest.mock.patch.dict(os.environ, {"TZ": "XXX-2"}) + zone.start() + # Cleanups run last in, first out: the zone is restored before the clock rereads it. + unittest.addModuleCleanup(time.tzset) + unittest.addModuleCleanup(zone.stop) + time.tzset() def assistant(*parts): @@ -437,7 +449,7 @@ class Cycles(unittest.TestCase): fake = FakeEffects(streams=[worker, worker], claude=[judged("interrupt"), judged("unfinished")], inputs=["Use B."]) with contextlib.redirect_stderr(io.StringIO()) as said: self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=6)) - self.assertIn("\nWhich one?\n", said.getvalue()) + self.assertIn(f"\n{STAMP} Which one?\n", said.getvalue()) self.assertEqual(fake.made("claude_on_terminal"), []) resumed = fake.made("stream_claude")[1] self.assertEqual(resumed[resumed.index("--resume") + 1], str(self.session.id)) @@ -504,7 +516,7 @@ class Cycles(unittest.TestCase): with contextlib.redirect_stderr(io.StringIO()) as said: self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse B. Use A.")), Stop(2, "the human is needed to answer the question above, but nothing was typed")) self.assertEqual(len(fake.made("stream_claude")), 1) - self.assertIn("\nWhich one?\n", said.getvalue()) + self.assertIn(f"\n{STAMP} Which one?\n", said.getvalue()) self.assertNotIn("Use ... A.", said.getvalue()) @unittest.skipIf(os.geteuid() == 0, "root writes into a read-only directory") @@ -554,7 +566,24 @@ class Retried(unittest.TestCase): results = [Limited(NOW + 3600, "You've hit your session limit"), "done"] with contextlib.redirect_stderr(io.StringIO()) as said: retry.retried("judge", lambda: results.pop(0), FakeEffects().effects()) - self.assertEqual(said.getvalue(), f"the judge hit a usage limit (You've hit your session limit); retrying at <{NOW + 3720}>\n") + self.assertEqual(said.getvalue(), f"{STAMP} the judge hit a usage limit (You've hit your session limit); retrying at <{NOW + 3720}>\n") + + +class Said(unittest.TestCase): + def test_opens_a_line_with_the_local_time_of_the_effects_clock(self): + with contextlib.redirect_stderr(io.StringIO()) as stderr, contextlib.redirect_stdout(io.StringIO()) as stdout: + terminal.say("hello", FakeEffects().effects()) + self.assertEqual((stderr.getvalue(), stdout.getvalue()), (f"{STAMP} hello\n", "")) + + def test_stamps_only_the_first_line_of_a_question_after_its_blank_line(self): + with contextlib.redirect_stderr(io.StringIO()) as stderr: + terminal.say("\nWhich one?\n\nA or B?", FakeEffects().effects()) + self.assertEqual(stderr.getvalue(), f"\n{STAMP} Which one?\n\nA or B?\n") + + def test_says_on_stdout_where_asked(self): + with contextlib.redirect_stderr(io.StringIO()) as stderr, contextlib.redirect_stdout(io.StringIO()) as stdout: + terminal.say("\n=== cycle 2 ===", FakeEffects().effects(), stdout=True) + self.assertEqual((stderr.getvalue(), stdout.getvalue()), ("", f"\n{STAMP} === cycle 2 ===\n")) class Limits(unittest.TestCase): @@ -607,12 +636,12 @@ class Interrupts(unittest.TestCase): def test_stops_off_a_terminal_before_asking(self): fake = FakeEffects(on_terminal=False) - self.assertEqual(self.put(fake), (Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"), "\nWhich one?\n")) + self.assertEqual(self.put(fake), (Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"), f"\n{STAMP} Which one?\n")) self.assertEqual(fake.calls, []) def test_returns_the_line_typed_after_the_question_stripped_dropping_what_was_typed_before(self): fake = FakeEffects(inputs=[" Use B. "]) - self.assertEqual(self.put(fake), ("Use B.", "\nWhich one?\n")) + self.assertEqual(self.put(fake), ("Use B.", f"\n{STAMP} Which one?\n")) self.assertEqual(fake.calls, [("discard_typed", None), ("input", "Answer (/talk opens claude, Enter stops the loop): ")]) def test_talks_on_talk_or_at_once_where_the_answer_is_not_asked_for_here(self): @@ -626,7 +655,7 @@ class Interrupts(unittest.TestCase): def test_stops_on_an_empty_answer_or_the_inputs_end(self): for typed, why, said in ((" ", "nothing was typed", ""), (EOFError(), "the input ended", "\n")): with self.subTest(why=why): - self.assertEqual(self.put(FakeEffects(inputs=[typed])), (Stop(2, f"the human is needed to answer the question above, but {why}"), f"\nWhich one?\n{said}")) + self.assertEqual(self.put(FakeEffects(inputs=[typed])), (Stop(2, f"the human is needed to answer the question above, but {why}"), f"\n{STAMP} Which one?\n{said}")) def test_stops_when_nothing_was_typed_in_the_session(self): with tempfile.TemporaryDirectory() as home: @@ -956,15 +985,15 @@ class Routing(unittest.TestCase): class RouteSources(unittest.TestCase): def test_routes_on_the_plan_item_and_says_why_it_routes_on_the_projects_rung(self): - self.assertIsNone(main.plan_item(DefaultPlan("", NO_CUT))) - self.assertEqual(main.plan_item(DefaultPlan(TODO, LastCut("v0.1.0", "", 3, [TODO]))).id, 3) - self.assertIsNone(main.plan_item(DefaultPlan(TODO, LastCut("v0.2.0", "", 3, [TODO])))) + self.assertIsNone(main.plan_item(DefaultPlan("", NO_CUT), FakeEffects().effects())) + self.assertEqual(main.plan_item(DefaultPlan(TODO, LastCut("v0.1.0", "", 3, [TODO])), FakeEffects().effects()).id, 3) + self.assertIsNone(main.plan_item(DefaultPlan(TODO, LastCut("v0.2.0", "", 3, [TODO])), FakeEffects().effects())) unreadable = Failure("git show origin/main:todo.md printed text that is not UTF-8") for plan, said in ((DefaultPlan(TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |"), NO_CUT), "routing on the project's rung: item 3's L 'x' is not a whole number from 1 to 4\n"), (DefaultPlan(unreadable, NO_CUT), f"routing on the project's rung: {unreadable.reason}\n"), (Failure("no origin remote"), "routing on the project's rung: no origin remote\n")): with self.subTest(said=said): with contextlib.redirect_stderr(io.StringIO()) as stderr: - self.assertIsNone(main.plan_item(plan)) - self.assertTrue(stderr.getvalue().startswith(said), stderr.getvalue()) + self.assertIsNone(main.plan_item(plan, FakeEffects().effects())) + self.assertTrue(stderr.getvalue().startswith(f"{STAMP} {said}"), stderr.getvalue()) def test_resumes_on_the_archived_route_and_says_why_it_routes_afresh(self): with tempfile.TemporaryDirectory() as home: @@ -973,28 +1002,28 @@ class RouteSources(unittest.TestCase): transcript = pathlib.Path(home, "projects", "-fake", f"{opened.id}.jsonl") route = Route(Rung("claude-opus-5-5", "high"), 3, 4, 5) with contextlib.redirect_stderr(io.StringIO()) as stderr: - self.assertIsNone(main.archived_route(archive, opened)) + self.assertIsNone(main.archived_route(archive, opened, FakeEffects().effects())) transcript.parent.mkdir(parents=True) transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n") - self.assertIsNone(main.archived_route(archive, opened)) + self.assertIsNone(main.archived_route(archive, opened, FakeEffects().effects())) with contextlib.redirect_stderr(io.StringIO()): self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(route.worker_line(), "working", "j", ""), NOW)) with contextlib.redirect_stderr(stderr): - self.assertEqual(main.archived_route(archive, opened), route) + self.assertEqual(main.archived_route(archive, opened, FakeEffects().effects()), route) self.assertEqual(stderr.getvalue(), "") with contextlib.redirect_stderr(io.StringIO()): self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.stepped_up(WorkerLine('{"model": "claude-opus-5-5", "rung": 3}')), NOW + 1)) with contextlib.redirect_stderr(io.StringIO()) as stderr: - self.assertIsNone(main.archived_route(archive, opened)) - self.assertEqual(stderr.getvalue(), 'routing the chunk afresh: the archive\'s latest Worker: line names no route loop-claude can read: {"model": "claude-opus-5-5", "rung": 3}\n') + self.assertIsNone(main.archived_route(archive, opened, FakeEffects().effects())) + self.assertEqual(stderr.getvalue(), f'{STAMP} routing the chunk afresh: the archive\'s latest Worker: line names no route loop-claude can read: {{"model": "claude-opus-5-5", "rung": 3}}\n') (chunk,) = archive.iterdir() chunk.chmod(0) try: with contextlib.redirect_stderr(io.StringIO()) as stderr: - self.assertIsNone(main.archived_route(archive, opened)) + self.assertIsNone(main.archived_route(archive, opened, FakeEffects().effects())) finally: chunk.chmod(0o700) - self.assertTrue(stderr.getvalue().startswith("routing the chunk afresh: could not read the archive"), stderr.getvalue()) + self.assertTrue(stderr.getvalue().startswith(f"{STAMP} routing the chunk afresh: could not read the archive"), stderr.getvalue()) class Steps(unittest.TestCase): @@ -1033,11 +1062,11 @@ class Steps(unittest.TestCase): self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW)) after = main.after_verdict(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), self.OPUS, run.Concluded(Unfinished("working", 4), before)) self.assertIsNone(main.archive_step(archive, opened, "Do it.", before, after.route, FakeEffects().effects())) - self.assertEqual(main.archived_route(archive, opened), Route(Rung("claude-opus-5-5", "high"), 3, 3, 4)) + self.assertEqual(main.archived_route(archive, opened, FakeEffects().effects()), Route(Rung("claude-opus-5-5", "high"), 3, 3, 4)) self.assertIsNone(main.archive_step(archive, opened, "Do it.", after.route, after.route, FakeEffects().effects())) finished = main.after_verdict(after, self.OPUS, run.Concluded(Finished("done"), after.route)) self.assertIsNone(main.archive_step(archive, opened, "Do it.", after.route, finished.route, FakeEffects().effects())) - self.assertEqual(main.archived_route(archive, opened), Route(Rung("claude-opus-5-5", "high"), 3, 3, 4)) + self.assertEqual(main.archived_route(archive, opened, FakeEffects().effects()), Route(Rung("claude-opus-5-5", "high"), 3, 3, 4)) blocked = pathlib.Path(home, "blocked") blocked.write_text("") stop = main.archive_step(blocked, opened, "Do it.", before, after.route, FakeEffects().effects()) @@ -1055,7 +1084,7 @@ class Steps(unittest.TestCase): self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW)) after = main.after_verdict(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), self.OPUS, run.Concluded(Unfinished("working", highest_escape_and_impact_taken_in=6), before)) self.assertIsNone(main.archive_step(archive, opened, "Do it.", before, after.route, FakeEffects().effects())) - self.assertEqual(main.archived_route(archive, opened), Route(self.OPUS, 3, 3, 4, escape_and_impact_taken_in=6)) + self.assertEqual(main.archived_route(archive, opened, FakeEffects().effects()), Route(self.OPUS, 3, 3, 4, escape_and_impact_taken_in=6)) class ChunkFacts(unittest.TestCase): diff --git a/docs/reading-cost.md b/docs/reading-cost.md index df0c81cc..968c8c34 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -899,3 +899,11 @@ Read most (opens and searches): ## Reading cost, chunk c49a63a648d0, finished 2026-10-28T16:32:11Z 118558 new input tokens before the first commit. + +## Reading cost, chunk 96afddd04db4, finished 2026-10-28T17:23:03Z + +105744 new input tokens before the first commit. + +Read most (opens and searches): + +- `rules/todo-items.md` 4