Merge pull request 'Open every line loop-claude prints with the machine's local time' (#391) from item-244 into main
This commit was merged in pull request #391.
This commit is contained in:
@@ -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. 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 '<A>,<B>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.
|
||||
|
||||
@@ -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, ...}}, ...}
|
||||
|
||||
@@ -2,7 +2,7 @@ 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
|
||||
@@ -24,7 +24,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.
|
||||
@@ -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)
|
||||
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:
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import sys
|
||||
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.stop import Stop
|
||||
@@ -24,7 +23,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 +33,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)
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -109,7 +109,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.
|
||||
@@ -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)
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
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 loop_claude.effects import Effects, say
|
||||
from failure import Failure
|
||||
from claude_code.reply import Limited
|
||||
from claude_code.transcript import part_line
|
||||
@@ -33,7 +31,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 +40,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)
|
||||
|
||||
|
||||
@@ -37,6 +37,7 @@ class Effects:
|
||||
execv: typing.Callable[[str, list[str]], None]
|
||||
git: Git
|
||||
input: typing.Callable[[str], str]
|
||||
# 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]
|
||||
@@ -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(),
|
||||
@@ -87,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 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)
|
||||
|
||||
@@ -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
|
||||
@@ -129,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
|
||||
@@ -158,7 +157,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 +186,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
|
||||
@@ -248,27 +247,27 @@ 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
|
||||
|
||||
|
||||
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,8 +284,9 @@ 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."""
|
||||
# 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):
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ 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.stop import Stop
|
||||
|
||||
@@ -84,7 +84,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))])
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
"""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
|
||||
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
|
||||
@@ -18,7 +17,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 +31,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 +45,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
|
||||
|
||||
@@ -5,7 +5,7 @@ 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
|
||||
@@ -44,7 +44,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,20 +65,17 @@ 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}\": \"<model>\"}} 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: ")
|
||||
except EOFError:
|
||||
print(file=sys.stderr)
|
||||
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):
|
||||
print(picked.reason, file=sys.stderr)
|
||||
say(picked.reason, effects)
|
||||
elif picked:
|
||||
return picked
|
||||
|
||||
|
||||
@@ -157,8 +157,11 @@ class Run:
|
||||
code: int
|
||||
sleeps: list
|
||||
starts: list
|
||||
# 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
|
||||
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,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)
|
||||
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"<UTC> Stopped: Ctrl-C\n\nWorker: {OFF_LADDER}\n", f"<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n", f"<UTC> Verdict: unfinished\n\nEvidence:\n> started\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
|
||||
self.assertIn('"text": "landed-it"', copies[f"<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
|
||||
@@ -584,7 +597,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):
|
||||
@@ -691,6 +704,7 @@ class Interrupt(unittest.TestCase):
|
||||
self.assertEqual(verdict, f"Task: {TASK}\n\n<UTC> Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n<UTC> 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"]))
|
||||
|
||||
@@ -10,6 +10,7 @@ import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
import unittest.mock
|
||||
import uuid
|
||||
@@ -19,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, say, system_effects
|
||||
from claude_code import entries, reply, session
|
||||
from loop_claude import escalation_mark, paths, routing
|
||||
from failure import Failure
|
||||
@@ -46,6 +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, with FakeEffects' local_time.
|
||||
STAMP = f"<{NOW}>"
|
||||
|
||||
|
||||
def assistant(*parts):
|
||||
@@ -437,7 +440,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 +507,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 +557,40 @@ 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:
|
||||
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:
|
||||
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:
|
||||
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):
|
||||
@@ -607,12 +643,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 +662,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 +992,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 +1009,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 +1069,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 +1091,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):
|
||||
@@ -1089,6 +1125,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 time.tzset makes the clock read it again.
|
||||
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:
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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: <path>` 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`
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
@@ -379,7 +374,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.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user