"""A chunk's route: its worker's rung and the plan item that picked it. The archive keeps the route as a record beside each verdict.""" import dataclasses import json import re import typing from todo_table import LEVELS from model_routing.ladder import REVIEW_STEPS, Rung # How a worker opens the prompt of a subagent it escalates a task to, `Escalation trigger 2: …`: docs/decisions.md → `routing: a worker hands a task one rung up`. ESCALATION_MARKER = "Escalation trigger" # What Route.record writes. The outcome writers take only this as the worker, so mypy refuses a str(route) there. Record = typing.NewType("Record", str) # A worker line loop-claude wrote before it archived the route as a record. Nothing writes this format any more, so its wording never changes. route_from reads it for the chunks the routing figures still count, and for a chunk a rerun resumes across the change. LEGACY_WORKER = re.compile(r"(?P.+?)(?:, routed by item (?P[0-9]+)'s L of (?P[0-9]+) and E \+ I of (?P[0-9]+))?(?:, taking in an E \+ I of (?P[0-9]+))?(?:, escalated at transcript entry (?P[0-9]+))?") HIGHEST_ESCAPE_AND_IMPACT = LEVELS["E"] + LEVELS["I"] def on_its_scale(escape_and_impact: int) -> bool: """Whether E + I is a level on the scales todo_table.LEVELS gives; E and I each start at 1.""" return 2 <= escape_and_impact <= HIGHEST_ESCAPE_AND_IMPACT def on_their_scales(likelihood: int, escape_and_impact: int) -> bool: """Whether L and E + I are levels on the scales todo_table.LEVELS gives.""" return 1 <= likelihood <= LEVELS["L"] and on_its_scale(escape_and_impact) def levels_fit(item: int, likelihood: int, escape_and_impact: int, escape_and_impact_taken_in: int) -> bool: """Whether a route may hold these. It has an item with levels on their scales, or no item and no levels. Its E + I taken in is 0, or on its scale and above the item's; Route.taking_in keeps only one that steps the reviewers further.""" routed = on_their_scales(likelihood, escape_and_impact) if item else not (likelihood or escape_and_impact) return routed and (escape_and_impact_taken_in == 0 or (on_its_scale(escape_and_impact_taken_in) and escape_and_impact_taken_in > escape_and_impact)) @dataclasses.dataclass(frozen=True) class Route: """A chunk's worker rung and the plan item that picked it, 0 for none. The item's L picked the worker's rung; reviewed_on, the higher of its E + I and the highest E + I the worker took in, picks the reviewers' and the judge's. A route holds only levels that levels_fit, so no rung is picked from a level off its scale. unfinished counts the unfinished verdicts towards the next one-rung step; a reload hands it over with the rung. """ # Each field below but rung and unfinished is a key of the archive's records, so renaming one makes the records already archived unreadable, and their chunks route afresh. # The fields a loop-claude from before L and E + I replaced R + C hands on reload; the reloaded script drops such a route, and the chunk routes afresh. RETIRED: typing.ClassVar[frozenset[str]] = frozenset({"risk_and_complexity"}) rung: Rung item: int = 0 likelihood: int = 0 escape_and_impact: int = 0 unfinished: int = 0 # The highest E + I the judge saw the worker take in, kept only where it picks a higher review step than the item's; 0 otherwise. escape_and_impact_taken_in: int = 0 # The escalation mark, as loop_claude/escalation_mark.py says: how many transcript entries the session held when an escalation last stepped the worker up, 0 before any. escalated_at: int = 0 def __post_init__(self) -> None: # Raises on a programming error only, so nothing catches it: route_from and the reload decoder check fits before they build a route. if not levels_fit(self.item, self.likelihood, self.escape_and_impact, self.escape_and_impact_taken_in): raise ValueError(f"a route by item {self.item} cannot hold an L of {self.likelihood}, an E + I of {self.escape_and_impact} and an E + I taken in of {self.escape_and_impact_taken_in}") @staticmethod def fits(fields: typing.Mapping[str, typing.Any]) -> bool: """Whether a route may be built from these fields.""" return levels_fit(fields.get("item", 0), fields.get("likelihood", 0), fields.get("escape_and_impact", 0), fields.get("escape_and_impact_taken_in", 0)) def taking_in(self, escape_and_impact: int) -> "Route": """The route after the judge saw the worker take in an item of this E + I, 0 for none: it keeps the E + I only where REVIEW_STEPS steps it further than reviewed_on, so the archive records a step-up only where REVIEW_STEPS steps the review floor further.""" return dataclasses.replace(self, escape_and_impact_taken_in=escape_and_impact) if REVIEW_STEPS.get(escape_and_impact, 0) > REVIEW_STEPS.get(self.reviewed_on(), 0) else self def reviewed_on(self) -> int: """The E + I that picks the reviewers' and the judge's rung: the routed item's or the highest taken in, whichever is higher; 0 for neither.""" return max(self.escape_and_impact, self.escape_and_impact_taken_in) def record(self) -> Record: """What the archive records as each verdict's worker: a JSON object of the rung's model and effort and the RECORD_FIELDS, leaving out each that is 0 or empty; route_from reads it back.""" fields = {"model": self.rung.model, "effort": self.rung.effort, **{name: getattr(self, name) for name in RECORD_FIELDS}} return Record(json.dumps({name: value for name, value in fields.items() if value})) # The Route fields a record holds beside the rung's model and effort. A human reads the record in the archive, so it is flatter than the JSON a reload hands over (loop_claude/loop/reload.py) and leaves out zeros. It leaves out unfinished, so a rerun restarts that count. RECORD_FIELDS = tuple(field.name for field in dataclasses.fields(Route) if field.name not in ("rung", "unfinished")) def route_from(worker: str) -> Route | None: """The route an archived worker line names, whether a record or a line written before records. None where it names no model, holds fields Route.record never writes, or holds levels off their scales; and for an older line, where it names a model without an effort.""" fields = record_fields(worker) if worker.startswith("{") else legacy_fields(worker) if fields is None or not Route.fits(fields): return None return Route(Rung(fields["model"], fields.get("effort", "")), **{name: fields.get(name, 0) for name in RECORD_FIELDS}) def record_fields(record: str) -> dict[str, typing.Any] | None: """The fields of a record Route.record wrote; None for any other text.""" try: fields = json.loads(record) except ValueError: return None if not (isinstance(fields, dict) and isinstance(fields.get("model"), str) and isinstance(fields.get("effort", ""), str) and fields.keys() <= {"model", "effort", *RECORD_FIELDS}): return None # type(), not isinstance(): JSON true is no integer. return fields if all(type(fields.get(name, 0)) is int and fields.get(name, 0) >= 0 for name in RECORD_FIELDS) else None def legacy_fields(line: str) -> dict[str, typing.Any] | None: """The fields of a LEGACY_WORKER line, as record_fields gives them; None for any other text.""" found = LEGACY_WORKER.fullmatch(line) rung = Rung.parse(found["rung"]) if found else None if not (found and rung): return None return {"model": rung.model, "effort": rung.effort, **{name: int(value or 0) for name, value in found.groupdict().items() if name != "rung"}}