"""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 docs/decisions.md → "Working rules" says, and loop-claude reads the resets from there.""" import dataclasses import json import pathlib import re from routing_figures.calls import Call, SENTENCES from failure import Failure from records.file_writes import replace_file, replace_json from records.utc_stamp import STAMPED CYCLES_PER_CHECK = 20 RAISED = "routing-calls-raised.md" RAISED_HEADING = "# Routing calls raised\n" # Each line is a call and when it was raised, or a reset: `- ` or `- Reset`. After a reset the figures count only chunks that finished after it, and a call raised before it may be raised again. RAISED_LINE = re.compile(rf"^- ({STAMPED}) (.+)$", re.MULTILINE) RESET = "Reset" # {"measured_at": 40, "raised": [{"at": "2026-10-15T00:00:00Z", "kind": "reports", "subjects": ["Explore"]}]} STATE = "routing-state.json" @dataclasses.dataclass(frozen=True) class Stamped: """A call and when it was raised.""" at: str call: Call @dataclasses.dataclass(frozen=True) class State: """measured_at is the cycle the kept figures were measured at, 0 before any; raised holds every call raised, oldest first.""" measured_at: int raised: tuple[Stamped, ...] @dataclasses.dataclass(frozen=True) class Raised: """since is the latest reset's stamp, empty for none; calls are those raised after it.""" since: str calls: frozenset[Call] def due(cycle: int, measured_at: int) -> bool: """Whether CYCLES_PER_CHECK cycles have closed since the figures were last measured. Counting from the last measurement still measures when another loop's cycles carried the count past a multiple of CYCLES_PER_CHECK.""" return cycle >= measured_at + CYCLES_PER_CHECK def read_state(root: pathlib.Path) -> State | Failure: """The kept state; before any is kept, no measurement and no call.""" try: text = (root / STATE).read_text(encoding="utf-8") except FileNotFoundError: 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 the comment on STATE in bin/routing_figures/state.py shows") def decoded(text: str) -> State | None: try: data = json.loads(text) except ValueError: return None if not isinstance(data, dict) or type(data.get("measured_at")) is not int or not isinstance(data.get("raised"), list): return None raised = [stamped(entry) for entry in data["raised"]] return State(data["measured_at"], tuple(entry for entry in raised if entry)) if all(raised) else None def stamped(entry: object) -> Stamped | None: if not isinstance(entry, dict) or not isinstance(at := entry.get("at"), str) or (kind := entry.get("kind")) not in SENTENCES: return None subjects = entry.get("subjects") if not isinstance(subjects, list) or not all(isinstance(subject, str) for subject in subjects) or len(subjects) != SENTENCES[kind].count("{}"): return None return Stamped(at, Call(kind, tuple(subjects))) def write_state(root: pathlib.Path, state: State) -> Failure | None: 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 def mark_measured(root: pathlib.Path, cycle: int) -> Failure | None: kept = read_state(root) return kept if isinstance(kept, Failure) else write_state(root, dataclasses.replace(kept, measured_at=cycle)) def raised(root: pathlib.Path) -> Raised | Failure: """The calls raised after the latest reset that RAISED names.""" text = read_raised(root) if isinstance(text, Failure): return text kept = read_state(root) if isinstance(kept, Failure): return kept since = max((stamp for stamp, what in RAISED_LINE.findall(text) if what == RESET), default="") return Raised(since, frozenset(entry.call for entry in kept.raised if entry.at > since)) def mark_raised(root: pathlib.Path, calls: list[Call], at: str) -> Failure | None: """Keeps the calls in STATE, and adds a line for each to RAISED.""" kept = read_state(root) if isinstance(kept, Failure): return kept text = read_raised(root) if isinstance(text, Failure): return text if unwritten := write_state(root, dataclasses.replace(kept, raised=kept.raised + tuple(Stamped(at, call) for call in calls))): return unwritten # The first line opens a list below the heading; each later one joins it. gap = "\n" if RAISED_LINE.search(text) else "\n\n" unwritten = replace_file(root / RAISED, (text.rstrip("\n") + gap + "".join(f"- {at} {call.sentence()}\n" for call in calls)).encode()) return Failure(f"could not write {root / RAISED}: {unwritten.reason}") if unwritten else None def read_raised(root: pathlib.Path) -> str | Failure: try: return (root / RAISED).read_text(encoding="utf-8") except FileNotFoundError: return RAISED_HEADING except (OSError, UnicodeDecodeError) as failure: return Failure(f"could not read {root / RAISED}: {failure}")