"""Every CYCLES_PER_CHECK-th cycle 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, render, totals from loop_claude.effects import Effects from failure import Failure from loop_claude.stop import needs_terminal, Stop from loop_claude.paths import Paths from claude_code.trust import trust from utc_stamp import utc from loop_claude.project.checkout import worktrees CYCLES_PER_CHECK = 20 ANSWER_CALLS = "answer the routing calls above" def check_routing(root: pathlib.Path, paths: Paths, effects: Effects) -> Stop | None: """Stops only for an interrupt it cannot hold; a figure it cannot measure or keep is said on stderr, and the loop goes on.""" new = new_calls(root, paths, effects) if isinstance(new, Failure): print(f"routing figures: {new.reason}", file=sys.stderr) return None return raise_calls(root, new, paths, effects) if new else None def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[str] | Failure: """The calls not raised before, measured and kept at every CYCLES_PER_CHECK-th cycle; none at any other.""" cycle = archive.cycles(root) if isinstance(cycle, Failure) or not cycle or cycle % CYCLES_PER_CHECK: return cycle if isinstance(cycle, Failure) else [] print(f"\n=== cycle {cycle} across loop-claude's archive: measuring the routing figures ===", flush=True) measured = archive.measure_archive(root, str(paths.home)) if isinstance(measured, Failure): return measured figures = totals(measured) found = calls(figures) return archive.write_figures(root, render(figures, found, utc(effects.now()), cycle)) or archive.unraised(root, found) def raise_calls(root: pathlib.Path, new: list[str], paths: Paths, effects: Effects) -> Stop | None: """Hands the terminal to a claude in this setup's checkout, where the routing decision lives; a call counts as raised once that claude ends.""" question = "loop-claude's routing figures call for a routing change, which is yours to decide:\n" + "".join(f"- {call}\n" for call in new) + f"The figures are in {root / archive.FIGURES}. The ladder's bands and the delegation rule are docs/decisions.md → `routing:`." print(f"\n{question}", file=sys.stderr) if stop := needs_terminal(ANSWER_CALLS, effects.on_terminal()): return stop trust(paths.claude_json, worktrees(str(paths.claude_dir), effects)) try: effects.claude_on_terminal(["--permission-mode", "bypassPermissions", question], str(paths.claude_dir)) except OSError as failure: return Stop(1, f"could not start claude for the routing calls: {failure.strerror}") if unmarked := archive.mark_raised(root, new, utc(effects.now())): print(f"routing figures: {unmarked.reason}", file=sys.stderr) return None