Answer architecture round 1: 1 🔴, 6 🟡; escalate in an unrouted chunk's first cycle, hold the limit and marker in routing.py, count escalations per starting rung, decline counting the limit from the current rung

This commit is contained in:
2026-10-15 16:20:28 +02:00
parent 33d5013039
commit c0be1fdffc
8 changed files with 63 additions and 38 deletions
+10 -13
View File
@@ -1,13 +1,9 @@
from model_routing.ladder import climbed, highest, LADDER, position, Rung
from loop_claude.routing import ESCALATION_MARKER, escalation_rungs
from model_routing.ladder import highest, LADDER, Rung
from loop_claude.project.records import HUMAN_RULE_NAMES, RECORD_FILES
from loop_claude.routing import item_rung
from markdown_text import quoted
from model_routing.route import Route
# How many rungs above the one its item picks the worker may escalate a task without the human's yes: docs/decisions.md → `routing: a worker hands a task one rung up`.
ESCALATION_CAP = 2
def either(names: tuple[str, ...]) -> str:
"""The names as `a, b or c`."""
return f"{', '.join(names[:-1])} or {names[-1]}"
@@ -21,7 +17,8 @@ ANSWERS_RECORDED = f"every answer the human typed in it that a later chunk could
def fresh(task: str, premises: str, route: Route, anchor: Rung | None) -> str:
routed = f"{routed_by(route, anchor)}\n\n" if route.item else ""
# A chunk no item routed gets no route paragraph, but may still escalate.
routed = f"{routed_by(route, anchor)}\n\n" if route.item else "".join(f"{text.lstrip()}\n\n" for text in [escalation(route, anchor)] if text)
return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one.\n\n{routed}The chunk's todo.md items, or else the task above, set its scope. The goals below choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n{premises}"
@@ -41,15 +38,15 @@ def off_the_projects_rung(route: Route, anchor: Rung | None) -> str:
def escalation(route: Route, anchor: Rung | None) -> str:
"""The rungs an escalation trigger lets the worker hand a task to: from one above its own up to ESCALATION_CAP above the rung its item picks; empty off the ladder or on its top rung."""
if anchor is None or route.rung not in LADDER or route.rung == LADDER[-1]:
"""The rungs routing.escalation_rungs opens to the worker, and how to mark an escalated subagent's prompt; empty off the ladder or on its top rung."""
if anchor is None or route.rung not in LADDER[:-1]:
return ""
cap = position(climbed(item_rung(anchor, route), ESCALATION_CAP))
rungs = [f"`{rung.agent_args()}`" for rung in LADDER[position(route.rung) + 1:cap + 1]]
marked = f" Open the subagent's prompt with `{ESCALATION_MARKER} <n>:`, n the trigger's number."
rungs = [f"`{rung.agent_args()}`" for rung in escalation_rungs(anchor, route)]
if not rungs:
return " An escalation trigger in `~/.claude/CLAUDE.md` lets you hand a task to a subagent above your rung only once the human agrees."
return f" An escalation trigger in `~/.claude/CLAUDE.md` lets you hand a task to a subagent above your rung only once the human agrees.{marked}"
further = f", and on each further trigger one rung higher, up to {rungs[-1]}" if len(rungs) > 1 else ""
return f" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the task to a subagent with the Agent tool set to {rungs[0]}, one rung above yours{further}; above that, ask the human first."
return f" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the task to a subagent with the Agent tool set to {rungs[0]}, one rung above yours{further}; above that, ask the human first.{marked}"
def resumed(unfinished_evidence: str, route: Route, anchor: Rung | None) -> str:
+14 -1
View File
@@ -1,12 +1,15 @@
"""Which ladder rung a chunk's worker and judge run on: docs/decisions.md → `routing:`."""
import dataclasses
from model_routing.ladder import climbed, floored, highest, LADDER, picked, position, project_rung, Rung, stepped_up
from failure import Failure
from model_routing.ladder import floored, highest, LADDER, picked, project_rung, Rung, stepped_up
from todo_table import Item, items
from model_routing.route import Route
UNFINISHED_PER_STEP = 2
# How many rungs above item_rung the worker may escalate a task without the human's yes, and how it opens an escalated subagent's prompt: docs/decisions.md → `routing: a worker hands a task one rung up`.
ESCALATION_CAP = 2
ESCALATION_MARKER = "Escalation trigger"
# The models `judge-replay` found returning, on their cheapest rung, every verdict the reference judge reproduced: docs/decisions.md → `routing: on a model judge-replay covered`.
JUDGE_REPLAYED = ("claude-opus-5-5",)
@@ -38,6 +41,16 @@ def item_rung(anchor: Rung, route: Route) -> Rung:
return picked(anchor, route.risk_and_complexity) if route.item else anchor
def escalation_rungs(anchor: Rung, route: Route) -> tuple[Rung, ...]:
"""The rungs an escalation trigger opens to the worker, least competent first: from one above its own up to ESCALATION_CAP above item_rung; none off the ladder.
A step-up between cycles raises the worker but not that limit, as lilleman set it from the rung the chunk started on.
"""
if route.rung not in LADDER:
return ()
return LADDER[position(route.rung) + 1:position(climbed(item_rung(anchor, route), ESCALATION_CAP)) + 1]
def stepped(anchor: Rung, route: Route, bundled: int) -> Route:
"""The route after one more unfinished verdict; bundled is the highest R + C the judge saw the worker take into the chunk, 0 for none."""
# An archived rung since removed from LADDER restarts from the project's rung.
+5 -3
View File
@@ -660,11 +660,13 @@ class WorkerArgs(unittest.TestCase):
def test_names_the_rungs_an_escalation_trigger_lets_the_worker_hand_a_task_to_at_most_two_above_its_items(self):
opus = Rung("claude-opus-5-5", "medium")
fresh = prompts.fresh("Do it.", "## Goals", Route(opus, 3, 9), opus)
self.assertIn("whether or not it is item 3. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the task to a subagent with the Agent tool set to `model opus, effort high`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort xhigh`; above that, ask the human first.\n\n", fresh)
self.assertTrue(prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 9), opus).endswith(" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours; above that, ask the human first."))
self.assertTrue(prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 9), opus).endswith(" An escalation trigger in `~/.claude/CLAUDE.md` lets you hand a task to a subagent above your rung only once the human agrees."))
self.assertIn("whether or not it is item 3. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the task to a subagent with the Agent tool set to `model opus, effort high`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort xhigh`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.\n\n", fresh)
self.assertTrue(prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 9), opus).endswith(" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number."))
self.assertTrue(prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 9), opus).endswith(" An escalation trigger in `~/.claude/CLAUDE.md` lets you hand a task to a subagent above your rung only once the human agrees. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number."))
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-fable-5-1", "max"), 3, 20), opus))
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("m")), None))
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-opus-5-5", "low"), 3, 9), opus))
self.assertIn("before creating a new one.\n\nWhen an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the task to a subagent with the Agent tool set to `model opus, effort high`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort xhigh`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.\n\nThe chunk's", prompts.fresh("Do it.", "## Goals", Route(opus), opus))
def test_opens_a_fresh_session_by_name_and_resumes_an_open_one(self):
opened = session.session_named("A proj loop-claude", pathlib.Path("/h/.claude/projects"))
+26 -12
View File
@@ -7,6 +7,7 @@ import typing
from claude_code.entries import assistant_parts, parts, tool_call, usage_count
from git_command import commits
from loop_claude.routing import ESCALATION_MARKER
from model_routing.ladder import position, Rung
from round_titles import round_counts
from model_routing.route import route_from
@@ -20,8 +21,7 @@ MEASURED_AT_LEAST = 5
DIMENSIONS = ("project", "subagent type", "rung", "tool")
# The tool label of a message that follows no tool call, such as the first message after a prompt.
PROMPT = "prompt"
# How a worker opens the prompt of a subagent it escalates a task to: CLAUDE.md → "Working with the codebase".
ESCALATION = re.compile(r"Escalation trigger ([0-9]+):")
ESCALATION = re.compile(rf"{ESCALATION_MARKER} ([0-9]+):")
@dataclasses.dataclass(frozen=True)
@@ -61,7 +61,7 @@ class ChunkFigures:
unfinished: int
delegated: collections.Counter[str]
reports: dict[str, Reports]
escalated: collections.Counter[str]
escalated: collections.Counter[int]
@dataclasses.dataclass(frozen=True)
@@ -71,7 +71,6 @@ class Figures:
tokens: dict[str, collections.Counter[str]]
routed: dict[Rung, list[ChunkFigures]]
reports: dict[str, Reports]
escalated: collections.Counter[str]
skipped: tuple[str, ...] = ()
@@ -93,8 +92,21 @@ def measured(chunk: Chunk, home: str) -> ChunkFigures:
for _, tools, spent in spend(subagent.entries):
add(tokens, chunk.project, kind, rung, tools, spent)
start = route_from(cycles[0][1]) if cycles else None
escalated = collections.Counter(found[1] for _, arguments in launches.values() if (found := ESCALATION.match(str(arguments.get("prompt") or ""))))
return ChunkFigures(tokens, start.rung if start and start.item else None, rounds_past_first(chunk.worker, home), sum(len(UNFINISHED_AT.findall(kept)) for kept in chunk.outcomes), delegated, reports, escalated)
return ChunkFigures(
tokens=tokens,
start=start.rung if start and start.item else None,
rounds_past_first=rounds_past_first(chunk.worker, home),
unfinished=sum(len(UNFINISHED_AT.findall(kept)) for kept in chunk.outcomes),
delegated=delegated,
reports=reports,
escalated=escalations(launches),
)
def escalations(launches: dict[str, tuple[str, dict]]) -> collections.Counter[int]:
"""How many Agent calls the worker escalated on each trigger, by the trigger number each call's prompt opens with."""
opened = (ESCALATION.match(str(arguments.get("prompt") or "")) for _, arguments in launches.values())
return collections.Counter(int(found[1]) for found in opened if found)
def agent_calls(worker: list[dict]) -> dict[str, tuple[str, dict]]:
@@ -187,13 +199,12 @@ def totals(chunks: list[ChunkFigures], skipped: tuple[str, ...] = ()) -> Figures
tokens = {dimension: sum((chunk.tokens.get(dimension, collections.Counter()) for chunk in chunks), collections.Counter()) for dimension in DIMENSIONS}
routed: dict[Rung, list[ChunkFigures]] = {}
reports: dict[str, Reports] = {}
escalated: collections.Counter[str] = sum((chunk.escalated for chunk in chunks), collections.Counter())
for chunk in chunks:
if chunk.start:
routed.setdefault(chunk.start, []).append(chunk)
for kind, found in chunk.reports.items():
reports[kind] = reports.get(kind, Reports(0, 0, 0)) + found
return Figures(len(chunks), tokens, routed, reports, escalated, skipped)
return Figures(len(chunks), tokens, routed, reports, skipped)
def calls(figures: Figures) -> list[str]:
@@ -222,19 +233,22 @@ def render(figures: Figures, found: list[str], at: str, cycle: int, since: str)
"".join(f"- {call}\n" for call in found).rstrip("\n") or "None.",
*[part for dimension in DIMENSIONS for part in (f"## Tokens by {dimension}", table((dimension.capitalize(), "Tokens"), [(label, str(tokens)) for label, tokens in figures.tokens[dimension].most_common()]))],
"## Routed chunks by the rung they started on",
table(("Rung", "Chunks", "Review rounds past each pass's first, mean", "Unfinished verdicts, mean", "Subagent rungs"), [
(str(rung), str(len(chunks)), f"{mean(chunks, lambda chunk: chunk.rounds_past_first):.1f}", f"{mean(chunks, lambda chunk: chunk.unfinished):.1f}", ", ".join(f"{label} {times}" for label, times in sum((chunk.delegated for chunk in chunks), collections.Counter()).most_common()))
table(("Rung", "Chunks", "Review rounds past each pass's first, mean", "Unfinished verdicts, mean", "Subagent rungs", "Escalations by trigger"), [
(str(rung), str(len(chunks)), f"{mean(chunks, lambda chunk: chunk.rounds_past_first):.1f}", f"{mean(chunks, lambda chunk: chunk.unfinished):.1f}", ", ".join(f"{label} {times}" for label, times in sum((chunk.delegated for chunk in chunks), collections.Counter()).most_common()), escalated(chunks))
for rung, chunks in sorted(figures.routed.items(), key=lambda item: position(item[0]))
]),
"## Subagent reports against the searches they ran, in characters",
table(("Subagent type", "Subagents", "Reports", "Searches"), [(kind, str(found.subagents), str(found.report), str(found.searches)) for kind, found in sorted(figures.reports.items())]),
"## Escalations by trigger",
table(("Trigger", "Subagents"), [(trigger, str(times)) for trigger, times in sorted(figures.escalated.items(), key=lambda item: int(item[0]))]),
*(["## Chunks skipped, unreadable", "".join(f"- {folder}\n" for folder in figures.skipped).rstrip("\n")] if figures.skipped else []),
]
return "\n\n".join(sections) + "\n"
def escalated(chunks: list[ChunkFigures]) -> str:
"""The chunks' escalations as `trigger 2: 3, trigger 3: 1`."""
return ", ".join(f"trigger {trigger}: {times}" for trigger, times in sorted(sum((chunk.escalated for chunk in chunks), collections.Counter()).items()))
def table(header: tuple[str, ...], rows: list[tuple[str, ...]]) -> str:
if not rows:
return "None."
+4 -5
View File
@@ -77,7 +77,7 @@ class Measured(unittest.TestCase):
message("m1", "2026-10-14T10:00:00Z", call("Agent", "a1", prompt="Escalation trigger 2: the test failed twice"), call("Agent", "a2", prompt="Escalation trigger 2: again"), call("Agent", "a3", prompt="Escalation trigger 3: a 🔴 in round 2")),
message("m2", "2026-10-14T10:01:00Z", call("Agent", "a4", prompt="Find the callers. Escalation trigger 1: not at the start"), call("Agent", "a5", prompt="Escalation trigger x: no number")),
]
self.assertEqual(measured(Chunk("log", [], worker, []), "/h").escalated, {"2": 2, "3": 1})
self.assertEqual(measured(Chunk("log", [], worker, []), "/h").escalated, {2: 2, 3: 1})
def test_counts_review_rounds_past_each_passs_first_once_per_title(self):
commit = lambda id_, title: message(id_, "2026-10-14T10:00:00Z", call("Bash", command=f"git commit -m '{title}'"))
@@ -151,12 +151,11 @@ class Calls(unittest.TestCase):
self.assertIn("Measured 2026-10-15T00:00:00Z, at cycle 40 across loop-claude's archive, from 1 finished chunk.", text)
self.assertIn("## Calls for a routing change\n\n- Call.\n", text)
self.assertIn("| b | 20 |\n| a | 2 |", text)
self.assertIn(f"| {LOW} | 1 | 1.0 | 0.0 | {HIGH} 2 |", text)
self.assertIn(f"| {LOW} | 1 | 1.0 | 0.0 | {HIGH} 2 | |", text)
two = ChunkFigures({}, HIGH, 0, 1, collections.Counter({str(HIGH): 2, str(LOW): 1}), {}, collections.Counter())
self.assertIn(f"| {LOW} | 1 | 1.0 | 0.0 | {HIGH} 2 |\n| {HIGH} | 1 | 0.0 | 1.0 | {HIGH} 2, {LOW} 1 |", render(totals([two, chunk]), [], "2026-10-15T00:00:00Z", 40, ""))
self.assertIn(f"| {LOW} | 1 | 1.0 | 0.0 | {HIGH} 2 | |\n| {HIGH} | 1 | 0.0 | 1.0 | {HIGH} 2, {LOW} 1 | |", render(totals([two, chunk]), [], "2026-10-15T00:00:00Z", 40, ""))
self.assertIn("| Explore | 2 | 3 | 4 |", text)
self.assertIn("## Escalations by trigger\n\n| Trigger | Subagents |\n| --- | --- |\n| 2 | 3 |\n| 3 | 1 |\n", render(totals([figures(escalated={"2": 2}), figures(escalated={"2": 1, "3": 1})]), [], "2026-10-15T00:00:00Z", 40, ""))
self.assertIn("## Escalations by trigger\n\nNone.\n", text)
self.assertIn(f"| {LOW} | 2 | 0.0 | 0.0 | | trigger 2: 3, trigger 10: 1 |", render(totals([figures(escalated={2: 2}), figures(escalated={2: 1, 10: 1})]), [], "2026-10-15T00:00:00Z", 40, ""))
self.assertIn("## Calls for a routing change\n\nNone.\n", render(totals([]), [], "2026-10-15T00:00:00Z", 20, ""))
self.assertIn("from 0 finished chunks that finished after the reset of 2026-10-14T00:00:00Z.", render(totals([]), [], "2026-10-15T00:00:00Z", 20, "2026-10-14T00:00:00Z"))