Files
floop/code/floop/machine.py
T
onibot aabacf8c44 floop: DATE answer type + deterministic year check (his 22/10 run)
His local run: the term-start question answered '15' — not a date —
and the dependent predecessor question became unclear downstream.

- AnswerType.DATE joins the enum; the Subquestion desc the model sees
  now says: DATE for a specific date (day, month and year — '15' alone
  is NOT a date)
- _looks_like_date: deterministic admission bar — a plausible year
  (1500-2999). '2 June 2018'/'June 2018'/'2018' pass; '15', a month
  name alone, garbage: refused
- _append_checked: a DATE answer without a year becomes UNKNOWN, the
  question fails honestly, a note lands in the run log — the wrong
  type never flows silently into dependents

VERIFIED: tests/date_type.py 4/4 (enum+desc in the rendered schema,
deterministic admission, '15' rejected end-to-end, real date accepted);
suite 16/16.
2026-10-22 23:58:19 +02:00

584 lines
29 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""The machine — fixed control code. The LLM proposes; the machine disposes.
ALGORITHM.md mapping (v0.1 draft — every STUB is named honestly):
- INIT/MISSING/ROUTE/ANSWER are dspy LLM calls (dspy_modules.py)
- the check layer and the prover are STUBS: no formal verification happens,
so NOTHING is ever marked verified — the honest Unverified fallback
- expert engines are STUBS: the LLM call itself is the draft engine (engine.py)
- the stop condition is the question stack going terminal, not a prover check
- recursion: FLOOP-on-a-question with a budget slice and a depth cap (§4)
"""
from __future__ import annotations
import re
import time
from dataclasses import dataclass, field
from .engine import CATALOG, LLMExpertEngine, UserRequestEngine
from .setops import detect_setop, setop_row
from .dspy_modules import FloopModules
from .state import (AnswerType, Budget, BudgetExhausted, EvidenceRow,
EvidenceTable, OpenQuestion, QuestionStack, instantiate)
from .stream import RunStreams
EXPERT_ENGINES = ("knowledge", "logic", "analytic", "numeric")
_YEAR_RE = re.compile(r"\b(?:1[5-9]\d{2}|20\d{2}|2[1-9]\d{2})\b") # 1500–2999
def _looks_like_date(v: str) -> bool:
"""Deterministic DATE admission: the value must carry a plausible
year (1500-2999). '2 June 2018', 'June 2018', '2018' pass; a bare
'15' — or a month name alone — is NOT a date and must never
satisfy a DATE question (his 22/10 local run)."""
return bool(_YEAR_RE.search(v or ""))
def _fmt_num(x: float) -> str:
"""Deterministic number formatting for computed rows: integers plain,
floats trimmed (no trailing .0)."""
return str(int(x)) if float(x).is_integer() else f"{x:g}"
def _coerce_atype(value) -> "AnswerType":
from .state import AnswerType as AT
if isinstance(value, AT):
return value
try:
return AT(str(value).upper())
except ValueError:
return AT.OPEN
@dataclass
class RunReport:
goal: str
final_answer: str
verified: bool
llm_calls: int
engine_calls: int
depth: int
notes: list[str] = field(default_factory=list)
questions: list[tuple] = field(default_factory=list) # (qid, status, text)
evidence_rows: list[str] = field(default_factory=list) # rendered row summaries
elapsed_s: float = 0.0
def _lm_dead(e: BaseException) -> bool:
"""Is this exception the LM dying (transport/timeout), not a code bug?
Walks the cause chain: dspy wraps transport deaths in LM* classes
(LMTransportError) over raw TimeoutErrors. Code bugs must still crash
loudly in development."""
seen: list[BaseException] = []
cur: BaseException | None = e
while cur is not None and cur not in seen:
seen.append(cur)
if type(cur).__name__.startswith("LM"):
return True
if "timed out" in str(cur).lower():
return True
cur = cur.__cause__ or cur.__context__
return False
class FloopRun:
"""One FLOOP execution over one question (top-level or recursive child)."""
def __init__(self, question: str, budget: Budget, depth: int = 0,
modules: FloopModules | None = None, parent_goal: str = "",
streams: RunStreams | None = None,
knowledge_engine=None) -> None:
self.query = question
self.budget = budget
self.depth = depth
self.parent_goal = parent_goal
self.modules = modules or FloopModules()
self.streams = streams or RunStreams(question)
self.tprefix = ">" * (depth + 1) + " " if depth else "" # depth marker on screen
self.table = EvidenceTable()
self.stack = QuestionStack(question)
self.user_engine = UserRequestEngine(self.modules)
self.knowledge_engine = knowledge_engine # None -> baseline LLM expert
self.notes: list[str] = []
self.engine_calls = 0
# RE-ASK METER (run L): dspy's adapter fallback fires extra LM calls
# the budget never charged. The prompt-log callback sees them; wire
# its meter to our budget so the count is honest. The BEHAVIOUR of
# dspy stays untouched (his call: the fallback is future
# self-improvement signal, not a bug).
from .llm import _PROMPT_LOG
if _PROMPT_LOG is not None:
_PROMPT_LOG.meter = self._meter_reask
# ---- budget -----------------------------------------------------------
def _charge(self) -> None:
self.budget.charge_llm()
self.streams.log(f"budget llm_calls={self.budget.llm_calls}"
f"/{self.budget.max_llm_calls} depth={self.depth}")
def _meter_reask(self, stage: str) -> None:
"""The prompt-log callback detected an adapter re-ask: charge the
budget for the extra wire call (a re-ask may hit the ceiling but
never kills the run mid-step), and note it for the report."""
try:
self.budget.charge_llm()
except BudgetExhausted:
pass # ceiling reached: the call already happened; note only
self.notes.append(f"re-ask charged: stage={stage}")
# ---- the loop (ALGORITHM.md §2) ----------------------------------------
def run(self) -> RunReport:
t0 = time.time()
self._init_decompose()
while True:
try:
q = self.stack.pickable(self.table)
if q is None:
if self.stack.all_terminal():
break
if self.budget.missing_used >= self.budget.missing_extensions:
self.notes.append("missing-extension limit reached; questions may still be open")
break
self._missing_round()
continue
self._route_and_execute(q)
except BudgetExhausted:
self.notes.append(f"budget exhausted at llm_calls={self.budget.llm_calls}")
break
except Exception as e: # noqa: BLE001 — LM deaths abort honestly
if _lm_dead(e):
self.notes.append(
f"LM unreachable at llm_calls={self.budget.llm_calls} "
f"({type(e).__name__}); aborting — no answer beats a made-up one")
break
raise
return self._finish(t0)
# ---- steps -------------------------------------------------------------
def _init_decompose(self) -> None:
self._charge()
self.streams.call("INIT", f"decompose: {self.query[:80]}",
think=self.tprefix + f"decomposing: {self.query[:100]}")
subs, raw = self.modules.init_decompose(self.query)
if not subs and (raw or "").strip():
# DEGRADE (run I): the model WROTE subquestions but none parsed
# (its numbered format beat the parser) — route the ORIGINAL
# question as one OPEN subquestion instead of routing garbage
# like a bare '1'. Deterministic, logged, budget-safe. The
# atomic case (empty raw) keeps the old stop-and-synthesize.
self.streams.output(
"INIT", f"(no parseable subquestions from {len(raw)} chars "
f"— degrading to the original question)", think=True)
subs = [{"text": self.query, "deps": [],
"answer_type": AnswerType.OPEN}]
else:
self.streams.output("INIT", chr(10).join(s["text"] for s in subs) or "(no subquestions)")
self._add_questions(subs, reason="init")
def _missing_round(self) -> None:
self._charge()
self.budget.missing_used += 1
self.streams.call("MISSING", f"goal stuck: {self.query[:80]}",
think=self.tprefix + "goal not derivable; asking what is missing")
subs = self.modules.missing_decompose(self.query, self.table.dump())
self.streams.output("MISSING", chr(10).join(s["text"] for s in subs) or "(no new questions)")
self._add_questions(subs, reason="missing")
def _add_questions(self, subs: list[dict], reason: str) -> None:
created: list[OpenQuestion] = []
for s in subs:
created.append(self.stack.add(OpenQuestion(
text=s["text"], answer_type=_coerce_atype(s["answer_type"]),
reason=reason)))
# resolve deps: sibling line numbers -> sibling qids; #E refs are not
# dependencies (their rows already exist or never will) — the text keeps
# the reference and instantiate() substitutes it at pick time.
for q, s in zip(created, subs):
resolved = []
for tok in s["deps"]:
if isinstance(tok, int) and 1 <= tok <= len(created):
resolved.append(created[tok - 1].qid)
q.deps = resolved
# anonymization seeds (his design): identity questions the mask map
# already answers land as evidence NOW — zero LLM calls
for q, s in zip(created, subs):
if s.get("known_answer"):
self.table.append(EvidenceRow(
qid=q.qid, answer_type=q.answer_type,
payload={"value": s["known_answer"],
"quote": f"{s['known_answer']} — named in the question itself"},
engine="mask:seed", trace=["anonymization: placeholder resolved from the mask map"],
provenance={}, verified=True))
q.status = "answered"
q.reason = "identity seeded from the mask map"
self.notes.append(
f"{q.qid}: seeded from anonymization — no expert call needed")
# ---- fan-out (the planner's expansion; deterministic guard) --------------
FANOUT_MARK = re.compile(r"\b(for each|of each|per)\b", re.I)
_NUMWORDS = {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5,
"six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10,
"eleven": 11, "twelve": 12}
def _fan_items(self, q: OpenQuestion) -> tuple[str, list[str]] | None:
"""The list an entity-fan question iterates over: the LIST row in its
deps, or a scalar comma-list row ('Po, Adige, Tiber'), or the table's
single list row when the text points with 'those/these'. Deterministic
— question shape is the machine's business, never the LLM's."""
for d in q.deps:
for r in self.table.for_question(d):
if isinstance(r.payload.get("list_items"), list) and r.payload["list_items"]:
return r.eid, list(r.payload["list_items"])
val = str(r.payload.get("value", ""))
if val.count(",") >= 1 and len(val) <= 80 and not val.replace(",", "").strip().isdigit():
items = [t.strip() for t in val.split(",") if t.strip()]
if 2 <= len(items) <= 12:
return r.eid, items
if re.search(r"\b(those|these|that)\b", q.text, re.I):
lists = [r for r in self.table.rows()
if isinstance(r.payload.get("list_items"), list)
and r.payload["list_items"] and not r.retracted]
if len(lists) == 1:
return lists[0].eid, list(lists[0].payload["list_items"])
return None
def _fan_count(self, qtext: str) -> int:
"""N when the question bounds the fan: 'those three rivers' -> 3."""
for w, n in self._NUMWORDS.items():
if re.search(rf"\b{w}\b", qtext, re.I):
return n
m = re.search(r"\b(\d{1,2})\b", qtext)
return int(m.group(1)) if m else 0
def _attribute_of(self, qtext: str) -> str:
"""'What is the average annual water flow (discharge) for each of
those rivers?' -> 'average annual water flow (discharge)'."""
m = re.match(r"(?:What is|What are|Which is|Which are)\s+(?:the\s+)?(.+?)"
r"\s+(?:for|of)\s+each", qtext, re.I)
if m:
return m.group(1).strip()
t = re.sub(self.FANOUT_MARK, "", qtext, count=1)
return re.sub(r"\?+$", "", t).strip()[:80]
def _detect_fanout(self, q: OpenQuestion) -> tuple[str, list[str]] | None:
"""A 'for each' subquestion over a known list is N entity questions +
one join — never one knowledge call over all entities at once."""
if not self.FANOUT_MARK.search(q.text):
return None
return self._fan_items(q)
def _expand_fanout(self, q: OpenQuestion, fan: tuple[str, list[str]]) -> None:
list_eid, items = fan
# TOP-N HONESTY: 'those three rivers' over an ordered (ranked) list
# is the top 3 by table order. An UNORDERED list has no top-N —
# slicing it silently answered alphabetical trivia (2026-10-20:
# adda, adige, arno instead of Po, Adige, Tiber). Refuse instead.
n = self._fan_count(q.text)
if n and 0 < n < len(items):
list_row = self.table.row(list_eid)
ranked = (list_row.payload.get("coverage") or {}).get("ranked", False) \
if list_row else False
if ranked:
items = items[:n]
self.notes.append(f"{q.qid}: fan-out sliced to top {n} of "
f"{len(fan[1])} by table order (ranked list)")
else:
self.notes.append(
f"{q.qid}: fan-out REFUSED top-{n} slice — the list has no "
f"proven order (ingested before ordinals or unranked source); "
f"all {len(items)} entities expanded")
self.streams.state(
f"fan-out warning: top-{n} asked but the list is not "
f"ranked — expanding all {len(items)} entities", think=True)
attribute = self._attribute_of(q.text)
self.streams.call("FANOUT", f"expanding {q.qid} into {len(items)} entity questions",
think=self.tprefix + f"fan-out: {q.qid} over {list_eid}'s "
f"{len(items)} items ({', '.join(items)}) — one question per item, then a join")
# 1) one entity question per item (no deps: the list row already exists)
entity_qids: list[str] = []
for item in items:
eq = self.stack.add(OpenQuestion(
text=f"What is the {attribute} of {item}?",
answer_type=AnswerType.CONSTANT,
reason=f"fan-out of {q.qid}", deps=[]))
eq.fan_group = q.qid
entity_qids.append(eq.qid)
# 2) the join: an EXISTING dependent that asks for the sum/total is
# promoted to join (deterministic sum); otherwise create one
join_q: OpenQuestion | None = None
for other in self.stack.items:
if other is q or other.status != "open" or other.parent_goal:
continue
if q.qid in other.deps and re.search(r"\b(sum|total)\b", other.text, re.I):
join_q = other
break
if join_q is None:
join_q = self.stack.add(OpenQuestion(
text=re.sub(r"\?+$", "", re.sub(self.FANOUT_MARK, "", q.text, count=1)).strip()
+ "?",
answer_type=AnswerType.FUNCTION,
reason=f"fan-out join of {q.qid}", deps=list(entity_qids)))
join_q.fan_group = q.qid
join_q.fan_join = True
join_q.fan_source = list_eid
# 3) rewire q's dependents to the entity questions (q answers nothing)
for other in self.stack.items:
if other is not q and q.qid in other.deps:
other.deps = [d for d in other.deps if d != q.qid] + entity_qids
# 4) q is answered BY the expansion
q.status = "answered"
q.reason = f"expanded (fan-out) into {len(entity_qids)} entity questions"
self.notes.append(f"{q.qid}: {q.reason}")
self.streams.output("FANOUT", f"{q.qid} -> {len(entity_qids)} entity questions "
f"+ join {join_q.qid}")
def _join_rows(self, q: OpenQuestion) -> EvidenceRow | None:
"""The join: deterministic sum over the fan group's entity rows.
Computation is its own proof (verified=True); missing values make a
PARTIAL sum, named in the note — never a silent one."""
group = q.fan_group
entity_rows = [r for r in self.table.rows()
if r.provenance.get("fan_group") == group and r.eid != q.fan_source]
nums: list[float] = []
ids: list[str] = []
for r in entity_rows:
m = re.search(r"[-+]?[\d,]*\.?\d+", str(r.payload.get("value", "")))
if m:
nums.append(float(m.group().replace(",", "")))
ids.append(r.eid)
if not nums:
return None
total = sum(nums)
partial = len(nums) < len(entity_rows)
self.streams.state(f"join: sum of {len(nums)} entity rows = {total}", think=True)
if partial:
missing = [r.eid for r in entity_rows
if r.eid not in ids]
self.streams.state(
f"join partial: {len(nums)} of {len(entity_rows)} values summed; "
f"missing {', '.join(missing)}", think=True)
return EvidenceRow(
qid=q.qid, answer_type=AnswerType.FUNCTION,
payload={"value": _fmt_num(total), "sum_of": ids,
"sum_count": len(nums)},
engine="logic:join",
trace=[f"deterministic sum over {len(nums)} entity rows: "
f"{' + '.join(ids)}"],
provenance={"op": "sum", "operands": ids, "fan_group": group},
verified=True, # computation is its own proof
note=(f"partial: {len(nums)} of {len(entity_rows)} values summed"
if partial else ""))
def _route_and_execute(self, q: OpenQuestion) -> None:
# SETOP GUARD: a count over list rows already in evidence is
# computation, not routing — the machine computes it deterministically
# (logic's first real engine) and never spends the ROUTE call.
spec = detect_setop(q.text, self.table)
if spec is not None:
self.streams.call("LOGIC", f"setop on {q.qid}: {spec['op']} "
f"({spec['a'].eid}" + (f", {spec['b'].eid}" if spec['b'] else "") + ")",
think=self.tprefix + f"setop {spec['op']} over list rows; no LLM needed")
row = setop_row(spec, q.qid, q.answer_type)
self.table.append(row)
self.engine_calls += 1
self.streams.output("LOGIC", f"{spec['op']} = {row.payload['value']} "
f"({row.payload['list_count']} items) [computed]")
q.status = "answered"
q.reason = "setop computed"
return
# FAN-OUT GUARD (planner): a subquestion that asks for an attribute
# 'for each' item of a list row in its deps is N entity questions +
# 1 join — never ONE knowledge question over all entities at once.
fan = self._detect_fanout(q)
if fan is not None:
self._expand_fanout(q, fan)
return
# FAN-OUT JOIN: the join question never routes anywhere — its answer
# is a deterministic sum over the fan group's entity rows
if q.fan_join and q.fan_group:
row = self._join_rows(q)
if row is not None:
self.table.append(row)
self.engine_calls += 1
self.streams.output("JOIN",
f"sum = {row.payload['value']} "
f"({row.payload['sum_count']} values) [computed]")
q.status = "answered"
q.reason = "fan-out join computed"
return
# no numeric rows yet: leave open — entity rows are still coming
self.notes.append(f"{q.qid}: join found no numeric rows yet")
return
self._charge()
self.streams.call("ROUTE", f"{q.qid}: {q.text[:80]}",
think=self.tprefix + f"routing {q.qid}: {q.text[:90]}")
attendant, why = self.modules.route_question(q.text, CATALOG, self._context(q))
self.streams.output("ROUTE", f"{attendant} ({why})")
if attendant == "floop":
self._execute_child(q)
elif attendant == "user":
row = self.user_engine.run(q.qid, instantiate(q.text, self.table),
self.query, self.table, q.answer_type)
self.table.append(row)
self.engine_calls += 1
q.status = "failed"
q.reason = "user expert not wired (draft)"
elif attendant in EXPERT_ENGINES:
if attendant == "knowledge" and self.knowledge_engine is not None:
self.knowledge_engine.charge = self._charge
self.knowledge_engine.modules = self.modules
self.streams.call("EXPERT", f"knowledge pipeline on {q.qid}: {q.text[:80]}",
think=self.tprefix + f"asking knowledge (KG pipeline): {q.text[:90]}")
row = self.knowledge_engine.run(q.qid, instantiate(q.text, self.table),
self.query, self.table, q.answer_type,
streams=self.streams)
else:
engine = LLMExpertEngine(self.modules, self._charge, expert_kind=attendant)
self.streams.call("EXPERT", f"{attendant} on {q.qid}: {q.text[:80]}",
think=self.tprefix + f"asking {attendant}: {q.text[:90]}")
row = engine.run(q.qid, instantiate(q.text, self.table),
self.query, self.table, q.answer_type, streams=self.streams)
self.engine_calls += 1
self._append_checked(row, q)
else:
self.notes.append(f"router returned invalid attendant {attendant!r} for {q.qid}")
self.table.append(EvidenceRow(
qid=q.qid, answer_type=q.answer_type, payload={"value": "UNKNOWN"},
engine=f"unrouted:{attendant}", trace=[why], provenance={},
verified=False, note="route_invalid"))
q.status = "failed"
q.reason = "route invalid"
def _execute_child(self, q: OpenQuestion) -> None:
if self.depth + 1 > self.budget.max_depth:
self.notes.append(f"{q.qid}: depth cap reached; refusing to recurse")
q.status = "failed"
q.reason = "depth cap"
return
child_budget = self.budget.slice_for_child()
child = FloopRun(question=instantiate(q.text, self.table),
budget=child_budget, depth=self.depth + 1,
modules=self.modules, parent_goal=self.query,
streams=self.streams,
knowledge_engine=self.knowledge_engine)
report = child.run()
self.budget.llm_calls += child_budget.llm_calls
self.streams.state(
f"child run done: llm_calls={report.llm_calls} rows={len(report.evidence_rows)}",
think=True)
row = EvidenceRow(
qid=q.qid, answer_type=q.answer_type,
payload={"value": report.final_answer},
engine="floop-child",
trace=[f"child run: {report.llm_calls} llm calls, {len(report.evidence_rows)} rows"],
provenance={"depth": self.depth + 1, "llm_calls": report.llm_calls},
verified=False, # child answers carry no proof in the draft
note="child answer unverified")
self.table.append(row)
self.engine_calls += 1
q.status = "answered"
def _append_checked(self, row: EvidenceRow, q: OpenQuestion) -> None:
"""STUB arrival check (design: type check + contradiction check). Only the
trivial refusal fires: an expert that reports UNKNOWN fails its question."""
# fan-out bookkeeping: entity rows carry the group so the join finds them
if q.fan_group:
row.provenance["fan_group"] = q.fan_group
# DATE type check (his 22/10 local run: term-start answered '15'):
# deterministic — a DATE value must carry a year; bare numbers
# are not dates and must never satisfy a DATE question
if q.answer_type == AnswerType.DATE:
v = str(row.payload.get("value", ""))
if not _looks_like_date(v):
self.notes.append(
f"{q.qid}: DATE answer rejected (no year): {v[:60]!r}")
row.payload["value"] = "UNKNOWN"
row.payload["note"] = "rejected: DATE without a year"
# PR-3: skim notices also land in the run notes — legibility law:
# derived answers render CONTENT, not counts alone
for n in (row.payload.get("skim") or [])[:2]:
self.notes.append(f"{q.qid}: skim: {n[:150]}")
# Layer-1 ambiguity audit (run J): the expert flagged several office
# readings — the report must carry them, the machine must not choose
if row.payload.get("ambiguous"):
alts = row.payload.get("alternatives") or []
self.notes.append(
f"{q.qid}: AMBIGUOUS: {row.payload.get('axis')} — "
f"other readings: " + "; ".join(
a.get("value") for a in alts[:3]))
self.table.append(row)
if str(row.payload.get("value", "")).strip().upper() == "UNKNOWN":
q.status = "failed"
q.reason = "expert returned UNKNOWN"
else:
q.status = "answered"
def _context(self, q: OpenQuestion) -> str:
"""What the router sees. A list row renders its ITEMS — 'E1: 50' is
an ambiguous scalar that routes 'those countries' questions to the
user; 'E1: list of 50 items: Albania, ...' answers them. Skim notices
(PR-3) render as 'seen in passing' pointers — the router knows what
exists and where it lives, without treating it as answered evidence."""
def render(r) -> str:
if isinstance(r.payload.get("list_items"), list):
return (f"list of {r.payload['list_count']} items: "
f"{', '.join(r.payload['list_items'][:8])}...")
val = str(r.payload.get("value", r.payload.get("quote", "")))
if r.payload.get("ambiguous"):
alts = r.payload.get("alternatives") or []
other = "; ".join(a.get("value", "") for a in alts[:3])
return (f"{val} — AMBIGUOUS, other defensible readings: "
f"{other}")
return val
lines = []
notices = []
for d in q.deps:
for r in self.table.for_question(d):
lines.append(f"{r.eid} (answers {r.qid}): {render(r)}")
for n in (r.payload.get("skim") or [])[:2]:
notices.append(f"seen in passing ({r.eid}): {n}")
if not lines:
# no declared deps: the router must still SEE what the machine
# holds — an empty context routes referential questions to the
# user, who is a last resort, not a default.
for r in self.table.rows():
if r.retracted:
continue
lines.append(f"{r.eid} (answers {r.qid}): {render(r)}")
for n in (r.payload.get("skim") or [])[:2]:
notices.append(f"seen in passing ({r.eid}): {n}")
return "\n".join(lines[:8] + notices[:4])
# ---- answer ------------------------------------------------------------
def _finish(self, t0: float) -> RunReport:
verified = False # STUB prover — v0.2: derivability check (clingo/Z3)
answer = ""
try:
self._charge()
self.streams.call("ANSWER", f"synthesize answer for: {self.query[:80]}",
think=self.tprefix + "writing the answer from the evidence table")
answer = self.modules.synthesize(
self.query, self.table.dump(), unverified=not verified)
self.streams.final(answer)
except BudgetExhausted:
self.notes.append("budget died before the answer step")
except Exception as e: # noqa: BLE001 — a dead LM answers nothing
if _lm_dead(e):
self.notes.append(f"LM unreachable before synthesis ({type(e).__name__}); "
"evidence is kept, the answer is not written")
else:
raise
return RunReport(
goal=self.query, final_answer=answer, verified=verified,
llm_calls=self.budget.llm_calls, engine_calls=self.engine_calls,
depth=self.depth, notes=self.notes,
questions=[(i.qid, i.status, i.text) for i in self.stack.items],
evidence_rows=self.table.dump().splitlines(),
elapsed_s=round(time.time() - t0, 1))