From 43e7e96b4191663e52632cbf4cd6b83b44c285d4 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 28 Oct 2026 18:30:24 +0100 Subject: [PATCH 01/11] Open every line loop-claude prints with the machine's local time --- CHANGELOG.md | 1 + bin/loop_claude/cycle/interrupt.py | 3 +- bin/loop_claude/cycle/retry.py | 6 +- bin/loop_claude/cycle/run.py | 3 +- bin/loop_claude/cycle/worker.py | 7 +-- bin/loop_claude/loop/main.py | 20 +++---- bin/loop_claude/loop/reload.py | 3 +- bin/loop_claude/loop/routing_check.py | 12 ++-- bin/loop_claude/project/model_choice.py | 12 ++-- bin/loop_claude/terminal.py | 13 +++++ bin/loop_claude/test_black_box.py | 20 ++++++- bin/loop_claude/test_loop_claude.py | 73 +++++++++++++++++-------- docs/reading-cost.md | 8 +++ 13 files changed, 123 insertions(+), 58 deletions(-) create mode 100644 bin/loop_claude/terminal.py 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 From 08855e8055ce5780199ffbf1dbbb55b9f155bc71 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 28 Oct 2026 18:33:31 +0100 Subject: [PATCH 02/11] =?UTF-8?q?Answer=20architecture=20round=201:=201=20?= =?UTF-8?q?=F0=9F=94=B4,=202=20=F0=9F=9F=A1=20(0=20misread);=20render=20th?= =?UTF-8?q?e=20stamp=20through=20Effects.local=5Ftime?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 2 +- bin/loop_claude/effects.py | 3 ++- bin/loop_claude/loop/main.py | 1 + bin/loop_claude/terminal.py | 8 +++----- bin/loop_claude/test_loop_claude.py | 26 ++++++++++++++------------ 5 files changed, 21 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6bc2bde0..868506b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +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. +- `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. The time a usage-limit wait ends at now also shows seconds, and no zone name. - 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/effects.py b/bin/loop_claude/effects.py index 831cbd3a..27d37637 100644 --- a/bin/loop_claude/effects.py +++ b/bin/loop_claude/effects.py @@ -37,6 +37,7 @@ class Effects: execv: typing.Callable[[str, list[str]], None] git: Git input: typing.Callable[[str], str] + # A time of day in the machine's zone, as `2026-10-28 11:46:01`. local_time: typing.Callable[[float], str] # The machine's memory; None where it cannot be read. memory: typing.Callable[[], Memory | None] @@ -68,7 +69,7 @@ def system_effects() -> Effects: execv=os.execv, git=git_repo.git, input=input, - local_time=lambda seconds: time.strftime("%Y-%m-%d %H:%M %Z", time.localtime(seconds)), + local_time=lambda seconds: time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(seconds)), memory=read_memory, now=time.time, on_terminal=lambda: sys.stdin.isatty() and sys.stdout.isatty(), diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 02352798..33ca0d7f 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -287,6 +287,7 @@ def fetched_plan(root: str) -> DefaultPlan | Failure: 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.""" + # It says why through effects, as every loop-claude function that prints does; todo.md item 51 moves all of them to one injected effect, and splitting this one off first would only be undone. if isinstance(plan, Failure): item: Item | Failure | None = plan elif isinstance(plan.todo, Failure): diff --git a/bin/loop_claude/terminal.py b/bin/loop_claude/terminal.py index 05b9ec91..9ebaa0b2 100644 --- a/bin/loop_claude/terminal.py +++ b/bin/loop_claude/terminal.py @@ -1,13 +1,11 @@ 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. +# The spelling `YYYY-MM-DD HH:MM:SS` in local time, never UTC, is lilleman's call of 2026-10-28; Effects.local_time renders it. 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.""" + """Prints text on stderr, or on stdout where stdout, opening its first line with the machine's local time, 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) + print(f"{blanks}{effects.local_time(effects.now())} {body}", file=sys.stdout if stdout else sys.stderr, flush=True) diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index 10a35b6e..76fa9808 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -20,7 +20,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from routing_figures import archive, measure 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 loop_claude.effects import Effects, PYTHON_TIMEOUT, run_python, system_effects from claude_code import entries, reply, session from loop_claude import escalation_mark, paths, routing, terminal from failure import Failure @@ -47,17 +47,8 @@ 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() +# How a line said at NOW opens, with FakeEffects' local_time. +STAMP = f"<{NOW}>" def assistant(*parts): @@ -1118,6 +1109,17 @@ class ChunkFacts(unittest.TestCase): self.assertEqual((resumed.made("python"), facts), ([], "")) +class LocalTime(unittest.TestCase): + def test_renders_seconds_in_the_machines_zone(self): + # A POSIX zone two hours ahead of UTC, so a time in UTC would read 14:13:20. Cleanups run last in, first out: the zone is restored before the clock rereads it. + self.addCleanup(time.tzset) + zone = unittest.mock.patch.dict(os.environ, {"TZ": "XXX-2"}) + zone.start() + self.addCleanup(zone.stop) + time.tzset() + self.assertEqual(system_effects().local_time(NOW), "2026-09-21 16:13:20") + + class PythonEffect(unittest.TestCase): def test_runs_a_script_in_the_given_directory(self): with tempfile.TemporaryDirectory() as cwd: From 4d40cc81bc814469c6dfd58fb6cd5bfea7161dfd Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 28 Oct 2026 18:35:09 +0100 Subject: [PATCH 03/11] =?UTF-8?q?Answer=20architecture=20round=202:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=201=20=F0=9F=9F=A1=20(0=20misread);=20expect=20th?= =?UTF-8?q?e=20usage-limit=20time=20with=20seconds=20in=20the=20black-box?= =?UTF-8?q?=20test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/loop_claude/test_black_box.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/loop_claude/test_black_box.py b/bin/loop_claude/test_black_box.py index 58874703..fe2263eb 100644 --- a/bin/loop_claude/test_black_box.py +++ b/bin/loop_claude/test_black_box.py @@ -598,7 +598,7 @@ class Cycles(unittest.TestCase): self.assertEqual(run.code, 130) self.assertEqual(run.roles(), ["worker"] * 5 + ["judge"] * 2 + ["worker"]) self.assertEqual([round(seconds, -1) for seconds in run.sleeps], [60, 60, 3720, 60, 600]) - self.assertIn(f"the worker hit a usage limit (You've hit your session limit); retrying at {datetime.datetime.fromtimestamp(resets_at + 120, datetime.timezone.utc):%Y-%m-%d %H:%M} UTC\n", run.stderr) + self.assertIn(f"the worker hit a usage limit (You've hit your session limit); retrying at {datetime.datetime.fromtimestamp(resets_at + 120, datetime.timezone.utc):%Y-%m-%d %H:%M:%S}\n", run.stderr) self.assertIn("the judge hit a usage limit (You've hit your session limit); retrying at ", run.stderr) def test_retries_the_judge_alone_when_its_verdict_quotes_nothing_in_the_transcript(self): From 6e171fe2c0135d7c55644851d56209554bd1c199 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 28 Oct 2026 18:40:24 +0100 Subject: [PATCH 04/11] =?UTF-8?q?Answer=20principles=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=202=20=F0=9F=9F=A1=20(0=20misread);=20move=20say?= =?UTF-8?q?=20beside=20Effects=20and=20drop=20a=20clock=20comparison=20fro?= =?UTF-8?q?m=20the=20black-box=20test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/loop_claude/cycle/interrupt.py | 5 ++--- bin/loop_claude/cycle/retry.py | 3 +-- bin/loop_claude/cycle/run.py | 3 +-- bin/loop_claude/cycle/worker.py | 3 +-- bin/loop_claude/effects.py | 9 ++++++++- bin/loop_claude/loop/main.py | 3 +-- bin/loop_claude/loop/reload.py | 3 +-- bin/loop_claude/loop/routing_check.py | 3 +-- bin/loop_claude/project/model_choice.py | 5 ++--- bin/loop_claude/terminal.py | 11 ----------- bin/loop_claude/test_black_box.py | 3 +-- bin/loop_claude/test_loop_claude.py | 10 +++++----- 12 files changed, 24 insertions(+), 37 deletions(-) delete mode 100644 bin/loop_claude/terminal.py diff --git a/bin/loop_claude/cycle/interrupt.py b/bin/loop_claude/cycle/interrupt.py index 04458689..45156c62 100644 --- a/bin/loop_claude/cycle/interrupt.py +++ b/bin/loop_claude/cycle/interrupt.py @@ -2,13 +2,12 @@ import dataclasses import sys import uuid -from loop_claude.effects import Effects +from loop_claude.effects import Effects, say from failure import Failure 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 @@ -35,7 +34,7 @@ def put_question(question: str, answer_here: bool, effects: Effects) -> str | Ta try: answer = effects.input(ASK_ANSWER).strip() except EOFError: - print(file=sys.stderr) + print(file=sys.stderr) # Ends the prompt's line; it says nothing, so it gets no time. return needs_human(ANSWER_QUESTION, "the input ended") if not answer: return needs_human(ANSWER_QUESTION, "nothing was typed") diff --git a/bin/loop_claude/cycle/retry.py b/bin/loop_claude/cycle/retry.py index 3fe6ec5d..7860b4a0 100644 --- a/bin/loop_claude/cycle/retry.py +++ b/bin/loop_claude/cycle/retry.py @@ -1,9 +1,8 @@ import typing -from loop_claude.effects import Effects +from loop_claude.effects import Effects, say 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") diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/run.py index 4c33f546..5ee3507f 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -7,7 +7,7 @@ from loop_claude.routing import after_ruling, judge_rung from transcript_archive.write import archive from loop_claude.cycle.worker import AUTO_COMPACT_WINDOW, COMPACT_WINDOW, run_worker, worker_args from claude_code.session import delete_session, Session, session_open, transcript_file -from loop_claude.effects import Effects +from loop_claude.effects import Effects, say from failure import Failure from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict from loop_claude.cycle.judge import judge, Rejected @@ -19,7 +19,6 @@ 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 diff --git a/bin/loop_claude/cycle/worker.py b/bin/loop_claude/cycle/worker.py index 2cad28bf..9f61a158 100644 --- a/bin/loop_claude/cycle/worker.py +++ b/bin/loop_claude/cycle/worker.py @@ -1,11 +1,10 @@ from claude_code.entries import assistant_parts, ends_stream, hit_limit, limit_said, parse_entry, rejected_until -from loop_claude.effects import Effects +from loop_claude.effects import Effects, say from failure import Failure 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 diff --git a/bin/loop_claude/effects.py b/bin/loop_claude/effects.py index 27d37637..b4a2d3e0 100644 --- a/bin/loop_claude/effects.py +++ b/bin/loop_claude/effects.py @@ -37,7 +37,7 @@ class Effects: execv: typing.Callable[[str, list[str]], None] git: Git input: typing.Callable[[str], str] - # A time of day in the machine's zone, as `2026-10-28 11:46:01`. + # A time of day in the machine's zone, as `2026-10-28 11:46:01`. The spelling, and local time over UTC, is lilleman's call of 2026-10-28. local_time: typing.Callable[[float], str] # The machine's memory; None where it cannot be read. memory: typing.Callable[[], Memory | None] @@ -88,3 +88,10 @@ def run_python(args: list[str], cwd: str, timeout: float) -> subprocess.Complete return subprocess.CompletedProcess(command, 1, "", f"could not start: {failure}") except subprocess.TimeoutExpired: return subprocess.CompletedProcess(command, 1, "", f"stopped after {timeout} s") + + +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, 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)] + print(f"{blanks}{effects.local_time(effects.now())} {body}", file=sys.stdout if stdout else sys.stderr, flush=True) diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 33ca0d7f..f4e92809 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -128,7 +128,7 @@ from loop_claude.project.checkout import checkout_root from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint, LoopRun, RELOAD_FLAG from chunk_pick import default_plan, DefaultPlan from git_repo import default_ref -from loop_claude.effects import Effects +from loop_claude.effects import Effects, say from failure import Failure from loop_claude.verdicts import Finished, Unfinished from loop_claude.project.model_choice import get_or_ask_models @@ -143,7 +143,6 @@ 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. diff --git a/bin/loop_claude/loop/reload.py b/bin/loop_claude/loop/reload.py index 5a3d024b..783a1581 100644 --- a/bin/loop_claude/loop/reload.py +++ b/bin/loop_claude/loop/reload.py @@ -6,9 +6,8 @@ import sys import types import typing -from loop_claude.effects import Effects +from loop_claude.effects import Effects, say from model_routing.route import Route -from loop_claude.terminal import say from loop_claude.stop import Stop RELOAD_FLAG = "--reloaded" diff --git a/bin/loop_claude/loop/routing_check.py b/bin/loop_claude/loop/routing_check.py index 8d0cd9a8..72955096 100644 --- a/bin/loop_claude/loop/routing_check.py +++ b/bin/loop_claude/loop/routing_check.py @@ -3,12 +3,11 @@ import pathlib from routing_figures import archive from routing_figures.measure import calls, due, render, totals -from loop_claude.effects import Effects +from loop_claude.effects import Effects, say 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 diff --git a/bin/loop_claude/project/model_choice.py b/bin/loop_claude/project/model_choice.py index f4f38244..79980c8e 100644 --- a/bin/loop_claude/project/model_choice.py +++ b/bin/loop_claude/project/model_choice.py @@ -5,12 +5,11 @@ import sys import typing from claude_code.model_catalog import catalog_models -from loop_claude.effects import Effects +from loop_claude.effects import Effects, say 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) @@ -72,7 +71,7 @@ def ask_for_model(project_key: str, saved: pathlib.Path, folder: pathlib.Path, e try: answer = effects.input(f"{'A number, or any' if offered else 'A'} name claude --model takes: ") except EOFError: - print(file=sys.stderr) + print(file=sys.stderr) # Ends the prompt's line; it says nothing, so it gets no time. return needs_human(f"pick {project_key}'s model", "the input ended") picked = model_picked(answer, offered) if isinstance(picked, Failure): diff --git a/bin/loop_claude/terminal.py b/bin/loop_claude/terminal.py deleted file mode 100644 index 9ebaa0b2..00000000 --- a/bin/loop_claude/terminal.py +++ /dev/null @@ -1,11 +0,0 @@ -import sys - -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; Effects.local_time renders it. -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, 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)] - print(f"{blanks}{effects.local_time(effects.now())} {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 fe2263eb..de16ade3 100644 --- a/bin/loop_claude/test_black_box.py +++ b/bin/loop_claude/test_black_box.py @@ -408,8 +408,7 @@ 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) + self.assertEqual(len(re.findall(rf"(?m)^{STAMP} === cycle 3, worker on worker-model ===$", run.raw_stdout)), 1) 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 76fa9808..5564eec6 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -20,9 +20,9 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from routing_figures import archive, measure 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, system_effects +from loop_claude.effects import Effects, PYTHON_TIMEOUT, run_python, say, system_effects from claude_code import entries, reply, session -from loop_claude import escalation_mark, paths, routing, terminal +from loop_claude import escalation_mark, paths, routing 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 @@ -563,17 +563,17 @@ class Retried(unittest.TestCase): 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()) + 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()) + 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) + say("\n=== cycle 2 ===", FakeEffects().effects(), stdout=True) self.assertEqual((stderr.getvalue(), stdout.getvalue()), ("", f"\n{STAMP} === cycle 2 ===\n")) From c5839001995ad4598919411e6ec5ef10b6797578 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 28 Oct 2026 18:47:39 +0100 Subject: [PATCH 05/11] =?UTF-8?q?Answer=20product-owner=20round=201:=200?= =?UTF-8?q?=20=F0=9F=94=B4,=201=20=F0=9F=9F=A1=20(0=20misread);=20stamp=20?= =?UTF-8?q?the=20transcript=20and=20trust=20lines=20through=20say?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/claude_code/trust.py | 12 ++++++------ bin/loop_claude/cycle/interrupt.py | 4 ++-- bin/loop_claude/cycle/run.py | 8 ++++---- bin/loop_claude/loop/main.py | 4 ++-- bin/transcript_archive/write.py | 8 ++++---- 5 files changed, 18 insertions(+), 18 deletions(-) diff --git a/bin/claude_code/trust.py b/bin/claude_code/trust.py index ae382904..12e12d61 100644 --- a/bin/claude_code/trust.py +++ b/bin/claude_code/trust.py @@ -1,30 +1,30 @@ import json import pathlib -import sys +import typing from failure import Failure from file_writes import replace_json # A failure only warns: claude still opens, and the human answers Claude Code's trust dialog. -def trust(config: pathlib.Path, roots: list[str]) -> None: +def trust(config: pathlib.Path, roots: list[str], note: typing.Callable[[str], None]) -> None: try: with open(config, encoding="utf-8") as handle: data = json.load(handle) except (OSError, ValueError) as failure: - print(f"could not read {config}: {getattr(failure, 'strerror', failure)}", file=sys.stderr) + note(f"could not read {config}: {getattr(failure, 'strerror', failure)}") return marked = mark_trusted(data, roots) if isinstance(marked, Failure): - print(f"could not read {config}: {marked.reason}", file=sys.stderr) + note(f"could not read {config}: {marked.reason}") return updated, untrusted = marked if not untrusted: return if unwritten := replace_json(config, updated, indent=2): - print(f"could not write {config}: {unwritten.reason}", file=sys.stderr) + note(f"could not write {config}: {unwritten.reason}") return - print("trusted for the interrupt: " + ", ".join(untrusted), file=sys.stderr) + note("trusted for the interrupt: " + ", ".join(untrusted)) # Claude Code's config: {"projects": {"/home/me/code/log": {"hasTrustDialogAccepted": true, ...}}, ...} diff --git a/bin/loop_claude/cycle/interrupt.py b/bin/loop_claude/cycle/interrupt.py index 45156c62..1978ab2d 100644 --- a/bin/loop_claude/cycle/interrupt.py +++ b/bin/loop_claude/cycle/interrupt.py @@ -34,7 +34,7 @@ def put_question(question: str, answer_here: bool, effects: Effects) -> str | Ta try: answer = effects.input(ASK_ANSWER).strip() except EOFError: - print(file=sys.stderr) # Ends the prompt's line; it says nothing, so it gets no time. + print(file=sys.stderr) # Ends the prompt's line. It isn't a message, so it gets no time. return needs_human(ANSWER_QUESTION, "the input ended") if not answer: return needs_human(ANSWER_QUESTION, "nothing was typed") @@ -57,7 +57,7 @@ def talk(root: str, session_id: uuid.UUID, worker: Rung, path: str, paths: Paths def hand_over(rung: Rung, args: list[str], root: str, paths: Paths, env: dict[str, str], effects: Effects) -> Failure | None: """Marks the checkout and each of its worktrees trusted, then runs claude on the terminal in root, on rung, with env added to its environment; the failure is why claude could not start.""" - trust(paths.claude_json, worktrees(root, effects)) + trust(paths.claude_json, worktrees(root, effects), lambda text: say(text, effects)) try: effects.claude_on_terminal([*rung.flags(), "--permission-mode", "bypassPermissions", *args], root, env) except OSError as failure: diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/run.py index 5ee3507f..449b0f3b 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -82,7 +82,7 @@ def stopped(cycle: Cycle, stop: Stop, why: str) -> Stop: def archived_stop(project_archive: pathlib.Path, session: Session, task: str, route: Route, stop: Stop, why: str, effects: Effects) -> Stop: """stop, once archived with the route the worker holds. A failed archive exits 1 whatever the stop; when the stop was this archive failing, its reason is said once.""" path = transcript_file(session) - failure = archive(project_archive, path, task, outcomes.stopped(route.worker_line(), why), effects.now()) if path else None + failure = archive(project_archive, path, task, outcomes.stopped(route.worker_line(), why), effects.now(), lambda text: say(text, effects)) if path else None return Stop(1, f"{failure.reason}\n{stop.reason}".rstrip()) if failure and failure.reason != stop.reason else stop @@ -155,7 +155,7 @@ def rule(cycle: Cycle, transcript_path: str) -> Ruled | Stop: def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> Stop | None: """Archives a judge reply loop-claude rejected, so the archive shows what the judge returned before a retry or an exit 1.""" - if unkept := archive(cycle.project_archive, transcript_path, cycle.task, outcomes.rejected(rejected.reason, rejected.reply, str(judge_of(cycle))), cycle.effects.now()): + if unkept := archive(cycle.project_archive, transcript_path, cycle.task, outcomes.rejected(rejected.reason, rejected.reply, str(judge_of(cycle))), cycle.effects.now(), lambda text: say(text, cycle.effects)): return Stop(1, unkept.reason) return None @@ -183,7 +183,7 @@ def ran_on(cycle: Cycle, step_up: StepUp | None) -> Route: def archive_stepped(cycle: Cycle, transcript_path: str, outcome: str, step_up: StepUp | None) -> Failure | None: """Archives the outcome of a ruling, then the step-up it made, if it made one. The first failure is returned.""" for kept in (outcome, outcomes.stepped_up(step_up.after.worker_line())) if step_up else (outcome,): - if failure := archive(cycle.project_archive, transcript_path, cycle.task, kept, cycle.effects.now()): + if failure := archive(cycle.project_archive, transcript_path, cycle.task, kept, cycle.effects.now(), lambda text: say(text, cycle.effects)): return failure return None @@ -196,7 +196,7 @@ def question_for(ruling: Interrupt | QuotedAnswer) -> str: def close(cycle: Cycle, transcript_path: str, verdict: Finished | Unfinished) -> Archived | Stop: outcome = outcomes.finished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle))) if isinstance(verdict, Finished) else outcomes.unfinished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle)), verdict.escalation) - if failure := archive(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects.now()): + if failure := archive(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects.now(), lambda text: say(text, cycle.effects)): return Stop(1, failure.reason) if isinstance(verdict, Finished) and (failure := delete_session(cycle.session)): return Stop(1, failure.reason) diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index f4e92809..def511a9 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -247,7 +247,7 @@ def archive_step(archive_folder: pathlib.Path, session: Session, task: str, befo if after is None or after.worker_line() == before.worker_line(): return None path = transcript_file(session) - failure = archive(archive_folder, path, task, outcomes.stepped_up(after.worker_line()), effects.now()) if path else None + failure = archive(archive_folder, path, task, outcomes.stepped_up(after.worker_line()), effects.now(), lambda text: say(text, effects)) if path else None return Stop(1, failure.reason) if failure else None @@ -286,7 +286,7 @@ def fetched_plan(root: str) -> DefaultPlan | Failure: 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.""" - # It says why through effects, as every loop-claude function that prints does; todo.md item 51 moves all of them to one injected effect, and splitting this one off first would only be undone. + # It prints the reason itself, through effects, like the other loop-claude functions that print. todo.md item 51 moves them all to one injected effect, so changing this one alone would be undone. if isinstance(plan, Failure): item: Item | Failure | None = plan elif isinstance(plan.todo, Failure): diff --git a/bin/transcript_archive/write.py b/bin/transcript_archive/write.py index f147dbe5..8d382294 100644 --- a/bin/transcript_archive/write.py +++ b/bin/transcript_archive/write.py @@ -1,7 +1,7 @@ import hashlib import os import pathlib -import sys +import typing from transcript_archive.location import chunk_folder, outcomes_of from failure import Failure @@ -11,8 +11,8 @@ from transcript_archive.outcomes import TASK from utc_stamp import utc -def archive(project_archive: pathlib.Path, path: str, task: str, outcome: str, at: float) -> Failure | None: - """Keeps the transcript at path, its outcomes file and its session's files in project_archive, in the layout this package's docstring gives; the failure that stopped it, or None. The outcome is stamped and appended to the outcomes file, which opens with the task only when the copy is new.""" +def archive(project_archive: pathlib.Path, path: str, task: str, outcome: str, at: float, note: typing.Callable[[str], None] = lambda text: None) -> Failure | None: + """Keeps the transcript at path, its outcomes file and its session's files in project_archive, in the layout this package's docstring gives; the failure that stopped it, or None. The outcome is stamped and appended to the outcomes file, which opens with the task only when the copy is new. Where a new copy lands, note is told where.""" try: with open(path, "rb") as handle: raw = handle.read() @@ -32,7 +32,7 @@ def archive(project_archive: pathlib.Path, path: str, task: str, outcome: str, a for dest, data in ((outcomes, f"{TASK}{task}\n\n{stamped}\n".encode()), (copy, raw)): if unwritten := replace_file(dest, data): return unarchived(dest, unwritten.reason) - print(f"transcript: {copy}", file=sys.stderr) + note(f"transcript: {copy}") return None From 9fc1392bc80f1aa710a6fc757635ba8f047d78ea Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 28 Oct 2026 18:47:39 +0100 Subject: [PATCH 06/11] =?UTF-8?q?Answer=20stability=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=203=20=F0=9F=9F=A1=20(0=20misread);=20test=20the?= =?UTF-8?q?=20flush=20and=20a=20leading=20indent,=20and=20the=20stamped=20?= =?UTF-8?q?transcript=20line?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/loop_claude/test_black_box.py | 3 ++- bin/loop_claude/test_loop_claude.py | 18 +++++++++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/bin/loop_claude/test_black_box.py b/bin/loop_claude/test_black_box.py index de16ade3..d08131fe 100644 --- a/bin/loop_claude/test_black_box.py +++ b/bin/loop_claude/test_black_box.py @@ -157,7 +157,7 @@ class Run: code: int sleeps: list starts: list - # Without the local time that opens each message loop-claude prints. + # stderr and stdout are without the local time that opens each message loop-claude prints; raw_stderr and raw_stdout keep it. stderr: str stdout: str raw_stderr: str @@ -704,6 +704,7 @@ class Interrupt(unittest.TestCase): self.assertEqual(verdict, f"Task: {TASK}\n\n Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n Stopped: the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal\n\nWorker: {OFF_LADDER}\n") self.assertEqual(stat.S_IMODE((checkout.temp / "deep").stat().st_mode), 0o700) self.assertIn(f"transcript: {checkout.archive() / 'proj'}/", run.stderr) + self.assertRegex(run.raw_stderr, rf"(?m)^{STAMP} transcript: ") session = argument(run.calls[0], "--session-id") run = checkout.run(steps, terminal_input="", stdout_on_terminal=False) self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"])) diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index 5564eec6..8952bcf1 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -576,6 +576,22 @@ class Said(unittest.TestCase): say("\n=== cycle 2 ===", FakeEffects().effects(), stdout=True) self.assertEqual((stderr.getvalue(), stdout.getvalue()), ("", f"\n{STAMP} === cycle 2 ===\n")) + def test_keeps_the_indent_of_the_first_line_after_the_time(self): + with contextlib.redirect_stderr(io.StringIO()) as stderr: + say("\n indented", FakeEffects().effects()) + self.assertEqual(stderr.getvalue(), f"\n{STAMP} indented\n") + + def test_flushes_so_piped_lines_arrive_when_said(self): + flushes = [] + + class Counting(io.StringIO): + def flush(self): + flushes.append(self.getvalue()) + + with contextlib.redirect_stderr(Counting()): + say("hello", FakeEffects().effects()) + self.assertEqual(flushes, [f"{STAMP} hello\n"]) + class Limits(unittest.TestCase): def test_the_worker_reports_the_latest_reset_its_stream_names(self): @@ -1111,7 +1127,7 @@ class ChunkFacts(unittest.TestCase): class LocalTime(unittest.TestCase): def test_renders_seconds_in_the_machines_zone(self): - # A POSIX zone two hours ahead of UTC, so a time in UTC would read 14:13:20. Cleanups run last in, first out: the zone is restored before the clock rereads it. + # A POSIX zone two hours ahead of UTC, so a time in UTC would read 14:13:20. Cleanups run last in, first out: the zone is restored before time.tzset makes the clock read it again. self.addCleanup(time.tzset) zone = unittest.mock.patch.dict(os.environ, {"TZ": "XXX-2"}) zone.start() From 29e055584c09cacec52ef0c6a9cee1101ecd9504 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 28 Oct 2026 18:47:39 +0100 Subject: [PATCH 07/11] =?UTF-8?q?Answer=20prose=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=204=20=F0=9F=9F=A1=20(0=20misread);=20reword=20th?= =?UTF-8?q?e=20time=20comments,=20the=20docstring=20and=20the=20changelog?= =?UTF-8?q?=20sentence?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 2 +- bin/loop_claude/effects.py | 4 ++-- bin/loop_claude/project/model_choice.py | 2 +- todo.md | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 868506b4..4ef09e68 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +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. The time a usage-limit wait ends at now also shows seconds, and no zone name. +- `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. The `retrying at …` time of a usage-limit wait now also shows seconds, and no longer names the zone. - 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/effects.py b/bin/loop_claude/effects.py index b4a2d3e0..72dacf83 100644 --- a/bin/loop_claude/effects.py +++ b/bin/loop_claude/effects.py @@ -37,7 +37,7 @@ class Effects: execv: typing.Callable[[str, list[str]], None] git: Git input: typing.Callable[[str], str] - # A time of day in the machine's zone, as `2026-10-28 11:46:01`. The spelling, and local time over UTC, is lilleman's call of 2026-10-28. + # A date and time in the machine's zone, as `2026-10-28 11:46:01`. lilleman chose this spelling and local time over UTC on 2026-10-28, since the human reads these on their own clock. local_time: typing.Callable[[float], str] # The machine's memory; None where it cannot be read. memory: typing.Callable[[], Memory | None] @@ -91,7 +91,7 @@ def run_python(args: list[str], cwd: str, timeout: float) -> subprocess.Complete 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, so the human sees when it happened. Blank lines before the text stay blank, and only its first line gets the time.""" + """Prints text on stderr, or on stdout where stdout, opening the first line of words with the machine's local time. Blank lines before those words stay blank, and later lines get no time.""" body = text.lstrip("\n") blanks = text[: len(text) - len(body)] print(f"{blanks}{effects.local_time(effects.now())} {body}", file=sys.stdout if stdout else sys.stderr, flush=True) diff --git a/bin/loop_claude/project/model_choice.py b/bin/loop_claude/project/model_choice.py index 79980c8e..d9f0dcc7 100644 --- a/bin/loop_claude/project/model_choice.py +++ b/bin/loop_claude/project/model_choice.py @@ -71,7 +71,7 @@ def ask_for_model(project_key: str, saved: pathlib.Path, folder: pathlib.Path, e try: answer = effects.input(f"{'A number, or any' if offered else 'A'} name claude --model takes: ") except EOFError: - print(file=sys.stderr) # Ends the prompt's line; it says nothing, so it gets no time. + print(file=sys.stderr) # Ends the prompt's line. It isn't a message, so it gets no time. return needs_human(f"pick {project_key}'s model", "the input ended") picked = model_picked(answer, offered) if isinstance(picked, Failure): diff --git a/todo.md b/todo.md index 55d7b7cc..9568b5ec 100644 --- a/todo.md +++ b/todo.md @@ -379,7 +379,7 @@ The key names the project's session, archive folder and models entry. `project_k ### 51. Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints. -"Functional core, imperative shell", in `principles/technical-principles.md`: `archive`, `trust`, `retried`, the worker, `put_question` and `model_choice` print to stderr themselves, and the tests swap the global stream. +"Functional core, imperative shell", in `principles/technical-principles.md`: `retried`, the worker, `put_question`, `model_choice` and `say` print to stderr themselves, and the tests swap the global stream. ### 169. Have rule-hook's `todo-rank-check` catch a `todo.md` that the same Bash call edits and then commits. From 382ebde51ee76635ee51fea14b591a9d614dff93 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 28 Oct 2026 18:47:46 +0100 Subject: [PATCH 08/11] =?UTF-8?q?Answer=20principles=20round=202:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20the=20round?= =?UTF-8?q?=201=20answers=20stand?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From b1f89a995271cc958c9a9f5aae945c160436e848 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 28 Oct 2026 18:49:39 +0100 Subject: [PATCH 09/11] =?UTF-8?q?Answer=20stability=20round=202:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20the=20round?= =?UTF-8?q?=201=20answers=20stand?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From f1d749e0f54efa55a367f71c4411eefc8b28b523 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 28 Oct 2026 18:49:39 +0100 Subject: [PATCH 10/11] =?UTF-8?q?Answer=20product-owner=20round=202:=200?= =?UTF-8?q?=20=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20the=20ro?= =?UTF-8?q?und=201=20answers=20stand?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From c2d72c97c67071f01e262ecb0605e468ec3b1546 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 28 Oct 2026 18:54:30 +0100 Subject: [PATCH 11/11] Record the comprehension check: paired ruling better --- docs/comprehension-history.md | 26 ++++++++++++++++++++++++++ todo.md | 5 ----- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/docs/comprehension-history.md b/docs/comprehension-history.md index 44ae8937..6d84d173 100644 --- a/docs/comprehension-history.md +++ b/docs/comprehension-history.md @@ -2872,3 +2872,29 @@ Inherited architect, decided by: - Self-sufficiency: `skills/larv-review/SKILL.md:78` "Cap": the ask, yes, one-more-round loop is gone, though the bullet now packs four ideas - Locality: `bin/git_repo.py:63` `default_ref`: `guarded=True` means both safe git options and never asking origin, kept at each call site; where it rots first - Locality: `bin/rule_hook/main.py:113` `bash_breaches`: round-cap sits apart from its sibling round-title-counts in `command_breaches`, a split no comment states + +## 2026-10-28T17:54:03Z, PR #391 at f1d749e, against 9014fd0 + +Ruling: better + +| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall | +|---|---|---|---|---|---| +| Mid A | same | better | same | same | better | +| Inherited architect | better | better | same | same | better | + +Mid A, decided by: + +- Locality, Overall: `bin/loop_claude/effects.py:93` `say`: every message goes through one function that adds the time, picks stderr or stdout and always flushes; before, each call site chose its own stream and flush, so the order of stdout and stderr lines depended on hidden buffering +- Locality: `bin/claude_code/trust.py:10` `trust`: reports through a `note` callable the caller passes, so the call shows where its output goes +- Locality: `bin/transcript_archive/write.py:14` `archive`: same, but its default `note` silently drops the `transcript: …` line for a caller that leaves it out +- Self-sufficiency: `bin/loop_claude/effects.py:40` `Effects.local_time`: the new comment gives the format and why it is local time +- Self-sufficiency: `bin/loop_claude/loop/main.py:289` `plan_item`: the new comment sends a cold reader to the plan, and "one injected effect" is unclear beside `say` +- Shape: `bin/loop_claude/cycle/run.py:85` `archived_stop`: the same `lambda text: say(text, effects)` is written out five times and `archive` grows to six parameters + +Inherited architect, decided by: + +- Navigation, Locality, Overall: `bin/loop_claude/effects.py:93` `say`: about 30 `print` calls over nine files, disagreeing on flushing and streams, now go through one function whose docstring states the contract +- Locality: `bin/claude_code/trust.py:10` `trust`: wrote to `sys.stderr` itself before; now takes a `note` callback, so the caller decides where its words go +- Locality: `bin/transcript_archive/write.py:14` `archive`: the same change, but its silent default `note` drops the `transcript: ` line for a new caller without a word +- Shape: `bin/loop_claude/cycle/run.py:85` `archived_stop`: the same lambda is copied seven times across `run.py`, `loop/main.py` and `cycle/interrupt.py`, which roughly cancels the cleaner output path +- Self-sufficiency: `bin/loop_claude/loop/main.py:289` `plan_item`: its comment sends the reader to the plan and reads oddly now that every message goes through `say` diff --git a/todo.md b/todo.md index 9568b5ec..d0132f66 100644 --- a/todo.md +++ b/todo.md @@ -12,7 +12,6 @@ | ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | |---|---|---|---|---|---|---|---|---|---|---|---| -| 244 | 0.4.0 | | owner | **Open every line loop-claude prints to its terminal with the machine's local time, as in `2026-10-28 11:46:01`.** | 2 | 2 | 1 | 3 | 3 | 1.5 by 2 | 1.9 | | 247 | 0.4.0 | | owner | **Count each finished chunk's escaped defects, the later commits that fix code it shipped, in `score-outcomes` and the routing figures.** | 3 | 2 | 1 | 4 | 5 | 1.1 by 4 | 1.7 | | 243 | 0.4.0 | | owner | **Show every loop-claude on the machine that waits for the human in one terminal app, and let the human answer each one there, `/talk` included.** | 4 | 2 | 3 | 7 | 6 | 1.5 by 4 | 0.9 | | 226 | 0.5.0 | | question | **Answer whether rule-hook's `run-heavy` rule should also catch a mutation run or docker build behind `uv run`, `poetry run`, `python3 -m`, `sudo`, `docker image build` and `docker compose up --build`, or narrow the `machine load:` decision's wording.** | 2 | 2 | 3 | 5 | 3 | 1.2 by 2, 1.5 by 2 | 4.0 | @@ -80,10 +79,6 @@ ## Details -### 244. Open every line loop-claude prints to its terminal with the machine's local time, as in `2026-10-28 11:46:01`. - -lilleman's call, 2026-10-28, who also chose the spelling: `YYYY-MM-DD HH:MM:SS` in the machine's local time, never UTC, so the human sees when each line happened, such as how long a question has waited. Today about 27 `print` calls across `bin/loop_claude/` write bare lines to stderr. Route them through one function that adds the stamp, taking the time from `Effects.now` so tests can fix it. A line of a multi-line message, such as a question, gets the stamp only on its first line. - ### 247. Count each finished chunk's escaped defects, the later commits that fix code it shipped, in `score-outcomes` and the routing figures. lilleman's call, 2026-10-28. Escaped defects are the counter-signal of goals 1 and 1.1, and nothing counts them, so nobody can tell whether review spending prevents defects or only polishes. A review costs about 56% of a chunk's dollars. Count, for each finished chunk, the later commits on the default branch that fix lines it added: a fix item's chunk, a `defect` item, or a 🔴 marked `[misread]` whose lines `git blame` traces to the earlier chunk. Show the count per chunk and its median per rung in `score-outcomes` and `routing-figures.md`, so a cheaper review pipeline can be judged against it. Measure on every project in loop-claude's archive.