Files
2026-11-18 16:21:35 +01:00

105 lines
6.5 KiB
Python

"""A chunk's route: its worker's rung and the plan item that picked it. The archive keeps the route as JSON on the Worker: line that ends each verdict, interrupt, quoted answer, stop and step-up."""
import dataclasses
import json
import typing
from plan.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.worker_line writes. The outcome writers take only this as the worker, so mypy refuses a str(route) there.
WorkerLine = typing.NewType("WorkerLine", str)
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."""
return item_levels_fit(item, likelihood, escape_and_impact) and taken_in_fits(escape_and_impact, escape_and_impact_taken_in)
def item_levels_fit(item: int, likelihood: int, escape_and_impact: int) -> bool:
return on_their_scales(likelihood, escape_and_impact) if item else not (likelihood or escape_and_impact)
def taken_in_fits(escape_and_impact: int, taken_in: int) -> bool:
return taken_in == 0 or (on_its_scale(taken_in) and 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'. 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 worker lines, so renaming one makes the lines already archived unreadable, and their chunks route afresh.
rung: Rung
item: int = 0
likelihood: int = 0
escape_and_impact: int = 0
unfinished: int = 0
# The highest E + I among the items the worker names on its `Chunk items:` line, 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 agent_cycle/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: a caller builds a route from levels it checked with fits, or from an item todo_table.items read, whose levels are all on their scales.
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 worker takes 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' 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 worker_line(self) -> WorkerLine:
"""What the archive records as each verdict's worker: a JSON object of the rung's model and effort and the WORKER_LINE_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 WORKER_LINE_FIELDS}}
return WorkerLine(json.dumps({name: value for name, value in fields.items() if value}))
# The Route fields a worker line holds beside the rung's model and effort. A human reads the line 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.
WORKER_LINE_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; None for a line Route.worker_line could not have written, such as text that isn't JSON."""
try:
fields = json.loads(worker)
except ValueError:
return None
return route_of(fields)
def route_of(fields: object) -> Route | None:
"""The route these fields of a worker line name, with an unfinished count of 0; None for fields Route.worker_line could not have written. A reload decodes its route through it too (loop_claude/loop/reload.py), so Route has one decoder."""
if not isinstance(fields, dict) or not fields.keys() <= {"model", "effort", *WORKER_LINE_FIELDS}:
return None
if not isinstance(fields.get("model"), str) or not isinstance(fields.get("effort", ""), str):
return None
# type(), not isinstance(): JSON true is no integer.
if not all(type(fields.get(name, 0)) is int and fields.get(name, 0) >= 0 for name in WORKER_LINE_FIELDS) or not Route.fits(fields):
return None
return Route(Rung(fields["model"], fields.get("effort", "")), **{name: fields.get(name, 0) for name in WORKER_LINE_FIELDS})