Files
floop/code/floop/machine.py
T
onibot 004c7974c6 floop: execution branches over ambiguity — fork per reading, conditional answer
His branching design (22-23/10, consolidated; now coded): when an
expert returns SEVERAL defensible readings of one question (the
knowledge ablation audit's ambiguous + alternatives payload), a
question that DEPENDS on that row must not inherit the coin-flip.
The old behaviour: alternatives were passed in the router context
(rejected — it only moves the guess into answer_kg) or collapsed
inside the ANSWER prompt (run L: 'Papandreou was the predecessor' —
the exact rejected behaviour).

The mechanism (floop/branches.py + machine._run_branch):
- LAZY: a branch is born only when the ambiguous row has an OPEN
  dependent subtree (open_subtree, frozen at fork time so every
  branch of the fork copies the same questions); an ambiguity nobody
  needs stays a note.
- A branch is a WORLD, not a fork of the run: the dependent subtree
  is re-created inside the branch with branch-scoped qids (B1.Q2),
  and the shared evidence table is read through a BranchView that
  BINDS the ambiguous row to the branch's reading (a VIEW — the table
  is never mutated, the original row keeps all readings) and hides
  other branches' rows.
- SHARED: acquired knowledge lands in the ONE table, tagged
  provenance['branch']; the KG/seen-index live in the expert, shared
  by construction. A later branch reuses an earlier one's gathering.
- DEATH: by contradiction, dead end (all branch questions failed) or
  NATURAL MERGE (same normalized answer as another branch — one
  conclusion, recorded merged). Never an absurdity judge.
- NESTING: an ambiguous row answered inside a branch (with its own
  dependent) opens sub-branches under it (origin=<branch id>); the
  parent carries its children's conditional as its answer. Branch
  cap (6) drops and NAMES extra readings — never silent.
- CONDITIONAL ANSWER: _finish composes the final answer by FIXED
  CODE over surviving branches — 'if you meant X -> A | if you meant
  Y -> B'; single survivor renders plain. Never a synthesis prompt
  choosing a reading inside itself.
- WARNINGS: FORK/BRANCH lines on screen AND log ([W]) — the fork is
  a machine judgement worth a human's eye, and META's lessons bank
  counts them.

Docs: ALGORITHM.md §6-bis (the mechanism as a law); README honest map
row. Tests: tests/branches.py — 5 E2E (fork+conditional, lazy no-fork,
dead-branch honesty, natural merge, nested sub-branches). Suite 18/18.

Live smoke (ollama-cloud, warm agent KG): the Pedro question runs
clean through the new paths (8 calls, 52s, honest answer; the fork
did not fire — the audit found no second reading in that KG; the
mechanism is proven by the E2E tests, the real-detector proof is his
local run over his accumulated KG).
2026-10-23 16:29:26 +02:00

766 lines
39 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 .branches import (BranchManager, BranchResult, BranchSpec, BranchView,
DEAD_END, open_subtree)
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
# BRANCHING (his design, 22-23/10): the fork bookkeeping. Specs are
# created lazily (only when a dependent of an ambiguous row exists);
# the shared table/stack stay THE run's own — a branch reads the
# table through a BranchView that binds the ambiguous row to its
# reading and hides other branches' rows.
self.branches = BranchManager()
self._current_branch = "" # "" = the root run; else the branch id
# 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:
# BRANCHING: a fork pending means an ambiguous row gained a
# dependent — its readings each own a world now. Run the
# branches to their end BEFORE the main loop continues
# (their conclusions/notes land in the shared table/notes;
# the conditional render happens at _finish).
while self.branches.pending:
spec = self.branches.pending[0]
self._run_branch(spec)
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. WARN on
# screen AND log (his 23/10 ask): the machine auto-answered a
# question without any expert — legible, and a self-improvement
# signal (which phrasings the seed eats -> META's lessons bank).
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")
self.streams.warn(
f"SEED auto-answered {q.qid} '{q.text[:60]}' -> "
f"'{s['known_answer']}' (mask map; zero expert calls)")
# ---- 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 _run_branch(self, spec: BranchSpec) -> None:
"""Execute ONE branch to its end, inside this run.
The branch is a NESTED LOOP SESSION, not a child FloopRun: it
swaps the machine's table view (BranchView binds the ambiguous
row to this branch's reading, hides other branches' rows) and
question stack (the dependent questions re-asked inside this
world), runs the same fixed loop, and restores state after.
Acquired knowledge (rows) lands in the SHARED table tagged with
the branch id; notes and engine_calls accumulate on the run; the
budget is the run's own (shared pool — his design: llm_calls
pool shared, depth+1 burns the existing depth counter).
Death: contradiction (a checked arrival refuses the branch's
values — the row lands with value UNKNOWN and its questions
fail), dead end (the branch's terminal questions all failed),
or natural merge (its answer equals an earlier branch's —
recorded at survivors()). Never an absurdity judge.
"""
view = BranchView(self.table, spec)
self.streams.warn(
f"BRANCH {spec.id} starts: reading '{spec.value[:60]}' "
f"(bound from {spec.ambiguous_eid})")
main_table, main_stack = self.table, self.stack
main_branch = self._current_branch
self.table = view # type: ignore[assignment]
self._current_branch = spec.id
# the branch's stack: the dependent subtree FROZEN at fork time —
# the same question set for every branch of the fork (B1 consuming
# the originals changed nothing about what B2 copies). Copied
# inside this world with BRANCH-SCOPED qids (a collision would make
# a copy look already-answered) and deps rewired to the copies.
branch_stack = QuestionStack(spec.value)
by_orig = {q.qid: q for q in main_stack.items}
copies_by_orig: dict[str, str] = {}
for orig_qid in spec.subtree_qids:
orig = by_orig.get(orig_qid)
if orig is None:
continue
nq = branch_stack.add(OpenQuestion(
text=orig.text, answer_type=orig.answer_type,
deps=[], reason=f"branch {spec.id} of {orig_qid}"))
nq.qid = f"{spec.id}.{orig_qid}"
# deps: the ambiguous row is BOUND (present in the view with its
# reading fixed — not a dependency anymore); deps on copied
# siblings point at the COPIES; deps on other already-answered
# questions keep the reference (their rows live in the shared table)
nq.deps = [copies_by_orig.get(d, d) for d in orig.deps
if d != spec.ambiguous_qid]
copies_by_orig[orig_qid] = nq.qid
for q in main_stack.items:
if q.qid in copies_by_orig:
q.status = "answered"
q.reason = f"answered by branches over {spec.ambiguous_qid}"
self.stack = branch_stack # type: ignore[assignment]
try:
while True:
try:
# NESTED FORK: an ambiguous row inside this branch with
# its own dependent opens sub-branches (origin=this
# branch); run them to their end before continuing —
# the same lazy law, one level deeper.
while any(s.origin == spec.id
for s in self.branches.pending):
sub = next(s for s in self.branches.pending
if s.origin == spec.id)
self._run_branch(sub)
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 inside a branch")
break
self._missing_round()
continue
self._route_and_execute(q)
except BudgetExhausted:
self.notes.append(
f"budget exhausted inside branch {spec.id} "
f"at llm_calls={self.budget.llm_calls}")
break
except Exception as e: # noqa: BLE001
if _lm_dead(e):
self.notes.append(
f"LM unreachable inside branch {spec.id}; "
f"branch aborted honestly")
break
raise
# the branch's conclusion. A branch whose OWN children
# answered carries the CHILDREN's conditional as its answer
# (nesting composes); otherwise synthesize from its rows.
answer = ""
kids = [s for s in self.branches.specs if s.origin == spec.id]
if kids and branch_stack.open_count() == 0:
answer = self.branches.conditional_answer(self.query, origin=spec.id)
if answer and not answer.startswith("No reading"):
self.branches.record_answer(spec.id, answer)
self.streams.state(
f"branch {spec.id} concluded (nested, "
f"{len(kids)} sub-branches): {answer[:80]}", think=True)
else:
self.branches.record_dead(spec.id)
self.notes.append(
f"branch {spec.id}: dead — no sub-reading survived")
elif (branch_stack.open_count() == 0 and branch_stack.items[1:]
and any(i.status == "answered"
for i in branch_stack.items[1:])):
try:
self._charge()
answer = self.modules.synthesize(
self.query, view.dump(), unverified=True)
self.branches.record_answer(spec.id, answer)
self.streams.state(
f"branch {spec.id} concluded: {answer[:80]}", think=True)
except (BudgetExhausted, Exception) as e: # noqa: BLE001
self.branches.record_dead(spec.id)
self.notes.append(f"branch {spec.id}: synthesis failed ({e})")
else:
self.branches.record_dead(spec.id)
self.notes.append(
f"branch {spec.id}: dead — no reading survived "
f"(all dependents failed)")
finally:
self.table = main_table
self.stack = main_stack
self._current_branch = main_branch
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)
# BRANCHING TRIGGER (his design): an ambiguous row with an OPEN
# dependent subtree forks the run into one branch per reading —
# LAZY (empty subtree: no fork, the ambiguity stays a note, the
# pick rides), the subtree FROZEN here so every branch of the
# fork copies the same questions (the first branch consuming the
# originals must not change what the second copies).
if row.payload.get("ambiguous"):
subtree = open_subtree(self.stack, q.qid)
if subtree:
specs = self.branches.fork_specs(
row, origin=self._current_branch, subtree_qids=subtree)
if specs:
self.notes.append(
f"{q.qid}: forking {len(specs)} branches over the "
f"readings of {row.eid}: "
+ "; ".join(f"{s.id}={s.value[:40]}" for s in specs))
self.streams.warn(
f"FORK {q.qid} over {row.eid}: {len(specs)} readings "
f"-> branches {', '.join(s.id for s in specs)}")
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 = ""
if self.branches.specs:
# CONDITIONAL ANSWER (run L law): several readings survived —
# the answer is composed by FIXED CODE from the branch results,
# never by one synthesis prompt choosing a reading inside itself.
answer = self.branches.conditional_answer(self.query)
self.streams.final(answer)
self.notes.append(
f"conditional answer over {len(self.branches.specs)} branches: "
+ "; ".join(f"{s.id}={self.branches.results[s.id].status}"
for s in self.branches.specs))
else:
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__}); "
f"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))