From f0ff379251daadbba4fd3782bed26bf7b3927457 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sun, 8 Nov 2026 20:02:58 +0100 Subject: [PATCH] =?UTF-8?q?Answer=20stability=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=206=20=F0=9F=9F=A1=20(0=20misread);=20slim=20chun?= =?UTF-8?q?k=5Ffigures,=20type=20a=20call's=20kind,=20keep=20the=20state?= =?UTF-8?q?=20through=20replace=5Fjson,=20add=20the=20missing=20state=20an?= =?UTF-8?q?d=20raise=20tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 2 +- bin/loop_claude/loop/routing_check.py | 2 +- bin/loop_claude/test_loop_claude.py | 11 +++++++ bin/repo_checks/test_citations.py | 2 +- bin/routing_figures/calls.py | 12 +++++--- bin/routing_figures/chunk.py | 34 ++++++++++++++------- bin/routing_figures/render.py | 4 +-- bin/routing_figures/state.py | 11 ++++--- bin/routing_figures/test_routing_figures.py | 28 ++++++++++++----- 9 files changed, 73 insertions(+), 33 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ee7dfab9..615eedfb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -- `loop-claude` now keeps the cycle it last measured the routing figures at, and each routing call it raised, in `routing-state.json` at the archive's root, and reads them back from there in place of `routing-figures.md` and `routing-calls-raised.md`. Both markdown files read as before, and a `Reset` line in `routing-calls-raised.md` still resets the figures. The first loop to close a cycle after the upgrade measures the figures at once, and puts a call raised since the latest reset to you once more. +- `loop-claude` now keeps the cycle it last measured the routing figures at, and each routing call it raised, in `routing-state.json` at the archive's root, and reads them back from there in place of `routing-figures.md` and `routing-calls-raised.md`. The two markdown files hold what they held before. From them, loop-claude now reads only a `Reset` line in `routing-calls-raised.md`, which still resets the figures. The first loop to close a cycle after the upgrade measures the figures at once. If the figures still make a call raised since the latest reset, it puts that call to you once more. - `loop-claude` and the routing figures no longer read a `Worker:` line written as a sentence, as versions before 0.4.0 archived. A rerun routes a chunk whose archive still ends in one afresh, and the figures leave it out of the routed chunks and charge its dollars to a row named by the sentence. ## 0.6.0 diff --git a/bin/loop_claude/loop/routing_check.py b/bin/loop_claude/loop/routing_check.py index c90fba99..7fa59cfa 100644 --- a/bin/loop_claude/loop/routing_check.py +++ b/bin/loop_claude/loop/routing_check.py @@ -1,4 +1,4 @@ -"""Every state.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:`.""" +"""Every state.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: loop-claude measures review rounds…`.""" import pathlib from routing_figures import archive diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index 6e5466f9..7cc9642b 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -21,6 +21,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from routing_figures import archive, state from loop_claude.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal +from routing_figures.calls import Call from loop_claude.project import checkout, model_choice, records from loop_claude.loop import chunk_start, close from loop_claude.waiting.answers import ClaudeEnded, ClaudeOpening, send, Typed @@ -970,6 +971,16 @@ class RoutingCheck(unittest.TestCase): self.assertIsNone(stop) self.assertIn("routing figures: could not write", said) + def test_puts_every_new_call_to_the_human_and_says_one_it_cannot_keep(self): + new = [Call("reports", ("Explore",)), Call("rounds", ("x", "y"))] + fake = FakeEffects(on_terminal_claude=[0]) + with contextlib.redirect_stderr(io.StringIO()) as said, unittest.mock.patch.object(state, "mark_raised", return_value=Failure("full")): + self.assertIsNone(routing_check.raise_calls(self.root, "/code/log", "s1", new, Rung("m", "high"), self.paths, self.paths.waiting, fake.effects())) + ((args),) = fake.made("claude_on_terminal") + self.assertIn(f"change nothing until they answer:\n- {new[0].sentence()}\n- {new[1].sentence()}\nThe figures", args[6]) + self.assertIn(f"call for a routing change:\n- {new[0].sentence()}\n- {new[1].sentence()}\n", said.getvalue()) + self.assertIn("routing figures: full", said.getvalue()) + class ModelPrompt(unittest.TestCase): OFFERED = [("claude-opus-5-5", "Opus 5.5"), ("claude-haiku-4-5", "Haiku 4.5")] diff --git a/bin/repo_checks/test_citations.py b/bin/repo_checks/test_citations.py index 06cb373f..f4cd4548 100644 --- a/bin/repo_checks/test_citations.py +++ b/bin/repo_checks/test_citations.py @@ -52,7 +52,7 @@ class Citations(unittest.TestCase): def test_agents_md_lists_exactly_the_decision_titles(self): listed = (ROOT / "AGENTS.md").read_text().split("Decisions live in `docs/decisions.md`:\n\n")[1].split("\n\n")[0] - # AGENTS.md sorts the titles, which docs/decisions.md keeps in no order. + # The two files order the titles differently, so they are compared sorted. self.assertEqual(sorted(LISTED_TITLE.findall(listed)), sorted(DECISION_TITLE.findall((ROOT / "docs/decisions.md").read_text()))) def test_every_todo_citation_of_a_decision_names_a_title(self): diff --git a/bin/routing_figures/calls.py b/bin/routing_figures/calls.py index 2a50c526..939d505f 100644 --- a/bin/routing_figures/calls.py +++ b/bin/routing_figures/calls.py @@ -1,4 +1,4 @@ -"""The routing figures summed over every chunk, and the routing changes they call for: docs/decisions.md → `routing:`.""" +"""The routing figures summed over every chunk, and the routing changes they call for: docs/decisions.md → `routing: loop-claude measures review rounds…`.""" import collections import dataclasses import statistics @@ -54,8 +54,9 @@ def totals(chunks: list[ChunkFigures], skipped: tuple[str, ...] = (), unread: tu ) +Kind = typing.Literal["rounds", "unfinished", "reports"] # Each kind of call to the sentence it is put to the human in, filled with its subjects in order. -SENTENCES = { +SENTENCES: dict[Kind, str] = { "rounds": "Chunks routed onto {} took more review rounds past each pass's first than chunks routed onto {}.", "unfinished": "Chunks routed onto {} took more unfinished verdicts than chunks routed onto {}.", "reports": "{} subagents' reports took more of the worker's context than their searches would have.", @@ -64,8 +65,8 @@ SENTENCES = { @dataclasses.dataclass(frozen=True) class Call: - """A routing change the figures call for, known again by its fields when raised twice. kind is a key of SENTENCES; subjects are the two rungs compared, lower first, or the subagent type.""" - kind: str + """A routing change the figures call for. Its fields, not its sentence, tell whether it was raised before. kind names its sentence in SENTENCES; subjects are the two rungs compared, lower first, or the subagent type.""" + kind: Kind subjects: tuple[str, ...] def sentence(self) -> str: @@ -77,7 +78,8 @@ def calls(figures: Figures) -> list[Call]: compared = sorted((rung for rung, chunks in figures.routed.items() if len(chunks) >= MEASURED_AT_LEAST and position(rung) >= 0), key=position) found = [] for lower, upper in zip(compared, compared[1:]): - for kind, of in (("rounds", lambda chunk: chunk.rounds_past_first), ("unfinished", lambda chunk: chunk.unfinished)): + measures: tuple[tuple[Kind, typing.Callable[[ChunkFigures], int]], ...] = (("rounds", lambda chunk: chunk.rounds_past_first), ("unfinished", lambda chunk: chunk.unfinished)) + for kind, of in measures: if mean(figures.routed[lower], of) > mean(figures.routed[upper], of): found.append(Call(kind, (str(lower), str(upper)))) # Characters stand in for tokens: reports and the tool results their subagents read are both text the worker would read, so their sums compare their shares of its context. diff --git a/bin/routing_figures/chunk.py b/bin/routing_figures/chunk.py index 3e4d053d..274fcad0 100644 --- a/bin/routing_figures/chunk.py +++ b/bin/routing_figures/chunk.py @@ -65,21 +65,15 @@ def chunk_figures(chunk: Chunk, home: str, history: list[BranchChunk] | None = N launches = agent_calls(chunk.worker) reported = results(chunk.worker) delegated = [delegation(subagent, launches, reported, cycles) for subagent in chunk.subagents] - spent = [Spent("worker", str(rung_at(cycles, message.at)), message) for message in messages(chunk.worker)] - spent += [Spent(one.kind, one.rung, message) for one in delegated for message in one.messages] - judged = [judged for kept in chunk.outcomes for judged in judge_costs(kept)] - dollars, unattributed = costed(spent, judged, chunk.project, recorded_costs(chunk.worker)) + dollars, unattributed = chunk_dollars(chunk, cycles, delegated) start = route_from(cycles[0][1]) if cycles else None - reports: dict[str, Reports] = {} - for one in delegated: - reports[one.kind] = reports.get(one.kind, Reports(0, 0, 0)) + Reports(1, one.report_chars, one.read_chars) return ChunkFigures( dollars=dollars, start=start.rung if start and start.item else None, rounds_past_first=rounds_past_first(commit_titles(chunk.worker, home)), unfinished=sum(len(UNFINISHED_AT.findall(kept)) for kept in chunk.outcomes), delegated=collections.Counter(one.rung for one in delegated), - reports=reports, + reports=reports_by_type(delegated), escalated=escalations(launches), unattributed=unattributed, lacking=transcripts_lacking(launches, chunk.subagents), @@ -87,6 +81,21 @@ def chunk_figures(chunk: Chunk, home: str, history: list[BranchChunk] | None = N ) +def chunk_dollars(chunk: Chunk, cycles: list[tuple[str, str]], delegated: list[Delegation]) -> tuple[Dollars, float]: + """What costed makes of the messages of the worker, each on the rung of the cycle it ran in, and of its subagents, and of the chunk's judge runs.""" + spent = [Spent("worker", str(rung_at(cycles, message.at)), message) for message in messages(chunk.worker)] + spent += [Spent(one.kind, one.rung, message) for one in delegated for message in one.messages] + judged = [judged for kept in chunk.outcomes for judged in judge_costs(kept)] + return costed(spent, judged, chunk.project, recorded_costs(chunk.worker)) + + +def reports_by_type(delegated: list[Delegation]) -> dict[str, Reports]: + reports: dict[str, Reports] = {} + for one in delegated: + reports[one.kind] = reports.get(one.kind, Reports(0, 0, 0)) + Reports(1, one.report_chars, one.read_chars) + return reports + + @dataclasses.dataclass(frozen=True) class Delegation: """One subagent as the figures count it: its type, the rung it ran on, the characters of its report and of the tool results it read, and its messages.""" @@ -141,13 +150,16 @@ def agent_calls(worker: list[dict]) -> dict[str, tuple[str, dict]]: def rung_at(cycles: list[tuple[str, str]], timestamp: str) -> Rung | str: """The rung of the cycle running at timestamp: the worker named by the first outcome stamped at or after it, or else by the last outcome. A worker line route_from cannot read is returned as its text, and "unrouted" where no outcome names a worker.""" - # An outcome is stamped to the second, as 2026-10-15T00:00:00Z, and a message to the millisecond, so the message's stamp is cut to the second to compare them as text. - second = timestamp[:19] + "Z" - found = next((rung for stamp, rung in cycles if stamp >= second), cycles[-1][1] if cycles else "unrouted") + found = next((rung for stamp, rung in cycles if stamp >= to_the_second(timestamp)), cycles[-1][1] if cycles else "unrouted") route = route_from(found) return route.rung if route else found +def to_the_second(timestamp: str) -> str: + """A message's stamp, such as 2026-10-15T00:00:00.123Z, cut to the second, as an outcome is stamped: 2026-10-15T00:00:00Z. Stamps in that one form sort as text in time order.""" + return timestamp[:19] + "Z" + + def subagent_rung(entries: list[dict], arguments: dict, worker: Rung | str) -> Rung: """The model the subagent ran, at the effort its Agent call set, or else at the worker's.""" model = next((message["model"] for entry in entries if entry.get("type") == "assistant" and isinstance(message := entry.get("message"), dict) and isinstance(message.get("model"), str)), str(arguments.get("model") or "unknown")) diff --git a/bin/routing_figures/render.py b/bin/routing_figures/render.py index b0ab9c57..d088a62a 100644 --- a/bin/routing_figures/render.py +++ b/bin/routing_figures/render.py @@ -22,8 +22,8 @@ def render(figures: Figures, found: list[Call], at: str, cycle: int, since: str) routed_table(figures), "## Escalations by trigger across every chunk, routed or not", f"{triggers(figures.escalated) or 'None'}.", - "## Subagent reports against the searches they ran, in characters", - table(("Subagent type", "Subagents", "Reports", "Searches"), [(kind, str(reports.subagents), str(reports.report_chars), str(reports.read_chars)) for kind, reports in sorted(figures.reports.items())]), + "## Subagent reports against the tool results they read, in characters", + table(("Subagent type", "Subagents", "Reports", "Tool results read"), [(kind, str(reports.subagents), str(reports.report_chars), str(reports.read_chars)) for kind, reports in sorted(figures.reports.items())]), *(["## Chunks skipped, unreadable", bullets(figures.skipped)] if figures.skipped else []), *(["## Default branches unread", bullets(figures.unread)] if figures.unread else []), ] diff --git a/bin/routing_figures/state.py b/bin/routing_figures/state.py index f6d11a9e..9f88146a 100644 --- a/bin/routing_figures/state.py +++ b/bin/routing_figures/state.py @@ -1,4 +1,6 @@ -"""What loop-claude keeps at the archive's root between measurements: the cycle it last measured at and each call it raised, as fields in STATE, and the calls raised as lines the human reads in RAISED, where a reset is written: docs/decisions.md → `routing:`.""" +"""What loop-claude keeps at the archive's root between measurements: docs/decisions.md → `routing: loop-claude measures review rounds…`. + +STATE holds, as fields loop-claude reads back, the cycle it last measured at and each call it raised. RAISED lists the raised calls for the human to read. A chunk appends a reset to RAISED by hand, as AGENTS.md says, and loop-claude reads the resets from there.""" import dataclasses import json import pathlib @@ -6,7 +8,7 @@ import re from routing_figures.calls import Call, SENTENCES from failure import Failure -from file_writes import replace_file +from file_writes import replace_file, replace_json from utc_stamp import STAMPED CYCLES_PER_CHECK = 20 @@ -53,7 +55,7 @@ def read_state(root: pathlib.Path) -> State | Failure: return State(0, ()) except (OSError, UnicodeDecodeError) as failure: return Failure(f"could not read {root / STATE}: {failure}") - return decoded(text) or Failure(f"could not read {root / STATE}: not the shape its comment in routing_figures/state.py shows") + return decoded(text) or Failure(f"could not read {root / STATE}: not the shape the comment on STATE in bin/routing_figures/state.py shows") def decoded(text: str) -> State | None: @@ -77,8 +79,7 @@ def stamped(entry: object) -> Stamped | None: def write_state(root: pathlib.Path, state: State) -> Failure | None: - text = json.dumps({"measured_at": state.measured_at, "raised": [{"at": entry.at, "kind": entry.call.kind, "subjects": list(entry.call.subjects)} for entry in state.raised]}, indent="\t") - unwritten = replace_file(root / STATE, (text + "\n").encode()) + unwritten = replace_json(root / STATE, {"measured_at": state.measured_at, "raised": [{"at": entry.at, "kind": entry.call.kind, "subjects": list(entry.call.subjects)} for entry in state.raised]}, indent="\t") return Failure(f"could not write {root / STATE}: {unwritten.reason}") if unwritten else None diff --git a/bin/routing_figures/test_routing_figures.py b/bin/routing_figures/test_routing_figures.py index d945ac8e..60b80713 100644 --- a/bin/routing_figures/test_routing_figures.py +++ b/bin/routing_figures/test_routing_figures.py @@ -420,13 +420,27 @@ class Archive(unittest.TestCase): a, b, c = Call("reports", ("Explore",)), Call("rounds", ("x", "y")), Call("unfinished", ("x", "y")) self.assertEqual(state.raised(self.root), state.Raised("", frozenset())) self.assertIsNone(state.mark_raised(self.root, [a], "2026-10-15T00:00:00Z")) - self.assertIsNone(state.mark_raised(self.root, [b], "2026-10-15T01:00:00Z")) - self.assertEqual((self.root / state.RAISED).read_text(), f"# Routing calls raised\n\n- 2026-10-15T00:00:00Z {a.sentence()}\n- 2026-10-15T01:00:00Z {b.sentence()}\n") - self.assertEqual(state.raised(self.root), state.Raised("", frozenset({a, b}))) + self.assertIsNone(state.mark_raised(self.root, [b, c], "2026-10-15T01:00:00Z")) + self.assertEqual((self.root / state.RAISED).read_text(), f"# Routing calls raised\n\n- 2026-10-15T00:00:00Z {a.sentence()}\n- 2026-10-15T01:00:00Z {b.sentence()}\n- 2026-10-15T01:00:00Z {c.sentence()}\n") + self.assertEqual(state.raised(self.root), state.Raised("", frozenset({a, b, c}))) with open(self.root / state.RAISED, "a") as handle: - handle.write("- 2026-10-15T00:30:00Z Reset\n") - self.assertIsNone(state.mark_raised(self.root, [c], "2026-10-15T00:20:00Z")) - self.assertEqual(state.raised(self.root), state.Raised("2026-10-15T00:30:00Z", frozenset({b}))) + handle.write("- 2026-10-15T01:00:00Z Reset\n") + self.assertEqual(state.raised(self.root), state.Raised("2026-10-15T01:00:00Z", frozenset()), "a call stamped at the reset's second was raised before it") + self.assertIsNone(state.mark_raised(self.root, [a], "2026-10-15T02:00:00Z")) + self.assertEqual(state.raised(self.root), state.Raised("2026-10-15T01:00:00Z", frozenset({a}))) + + @unittest.skipIf(os.geteuid() == 0, "root writes into a read-only directory") + def test_fails_when_it_cannot_keep_the_state(self): + self.root.chmod(0o555) + self.addCleanup(self.root.chmod, 0o755) + self.assertIsInstance(state.mark_measured(self.root, 40), Failure) + self.assertIsInstance(state.mark_raised(self.root, [Call("reports", ("Explore",))], "2026-10-15T00:00:00Z"), Failure) + + def test_fails_when_it_cannot_list_a_raised_call_for_the_human(self): + self.assertIsNone(state.mark_measured(self.root, 40)) + written = state.replace_file + with unittest.mock.patch.object(state, "replace_file", lambda path, data: Failure("full") if path.name == state.RAISED else written(path, data)): + self.assertEqual(state.mark_raised(self.root, [Call("reports", ("Explore",))], "2026-10-15T00:00:00Z"), Failure(f"could not write {self.root / state.RAISED}: full")) def test_knows_a_raised_call_by_its_fields_whatever_its_line_reads(self): call = Call("reports", ("Explore",)) @@ -435,7 +449,7 @@ class Archive(unittest.TestCase): self.assertEqual(state.raised(self.root).calls, frozenset({call})) def test_fails_on_a_state_it_cannot_read(self): - for text in ("not json", "[]", '{"measured_at": "40", "raised": []}', '{"measured_at": 40, "raised": [{"at": "x", "kind": "nope", "subjects": []}]}', '{"measured_at": 40, "raised": [{"at": "x", "kind": "reports", "subjects": ["a", "b"]}]}', '{"measured_at": true, "raised": []}'): + for text in ("not json", "[]", '{"measured_at": "40", "raised": []}', '{"measured_at": 40, "raised": [{"at": "x", "kind": "nope", "subjects": []}]}', '{"measured_at": 40, "raised": [{"at": "x", "kind": "reports", "subjects": ["a", "b"]}]}', '{"measured_at": true, "raised": []}', '{"measured_at": 40, "raised": [{"at": "x", "kind": "reports", "subjects": "a"}]}'): with self.subTest(text): (self.root / state.STATE).write_text(text) self.assertIsInstance(state.read_state(self.root), Failure)