A run that asked the user ends IN the question (fixed-code clarify) #22

Merged
onibot merged 1 commits from feature/clarify-answer into main 2026-10-23 17:16:52 +02:00
2 changed files with 120 additions and 2 deletions
+52 -1
View File
@@ -731,6 +731,15 @@ class FloopRun:
def _finish(self, t0: float) -> RunReport:
verified = False # STUB prover — v0.2: derivability check (clingo/Z3)
answer = ""
# CLARIFICATION FIRST (his 23/10 run): a run that ASKED THE USER
# something ends IN THE QUESTION — composed by fixed code from the
# pending user rows, never by a synthesis prompt reading
# needs_user_input as plain text and inventing 'the evidence is
# unknown'. The branch answer handles ambiguity (its readings);
# this handles every OTHER honest defer: the machine knows what
# it wants to ask — it says so, and only that.
pending_user = [r for r in self.table.rows()
if r.note == "needs_user_input" and not r.retracted]
if self.branches.specs:
# CONDITIONAL ANSWER (run L law): several readings survived —
# the answer is composed by FIXED CODE from the branch results,
@@ -741,6 +750,10 @@ class FloopRun:
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))
elif pending_user:
answer = self._clarify_answer(pending_user)
self.streams.final(answer)
self.notes.append("answer: clarification requested from the user")
else:
try:
self._charge()
@@ -763,4 +776,42 @@ class FloopRun:
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))
elapsed_s=round(time.time() - t0, 1))
def _clarify_answer(self, pending_user: list[EvidenceRow]) -> str:
"""The run ends in its QUESTION to the user, composed by fixed
code. Each pending user row carries the instantiated question its
ROUTE deferred (the row's qid names the open question); the
answer asks them, names what the machine already holds so the
user answers with context, and states what was left un-answered.
Zero LLM calls — the question text was already composed by the
loop; this renders it."""
parts: list[str] = []
for r in pending_user:
q = next((i for i in self.stack.items if i.qid == r.qid), None)
qtext = q.text if q is not None else "(deferred question)"
# what the machine holds that motivated the ask — the row the
# deferring question depended on, rendered plain (value +
# ambiguity note when present)
context = ""
if q is not None:
for d in q.deps:
for dep in self.table.for_question(d):
val = str(dep.payload.get("value", ""))
if not val or val.upper() == "UNKNOWN":
continue
if dep.payload.get("ambiguous"):
alts = dep.payload.get("alternatives") or []
others = " / ".join(
a.get("value", "") for a in alts[:3])
context = (f" (so far: {val} — but other "
f"defensible readings exist: {others})")
else:
context = f" (so far: {val})"
break
if context:
break
parts.append(f"I need to ask you: {qtext}{context}")
if len(parts) == 1:
return parts[0]
return "I need to ask you a few things: " + " | ".join(parts)
+68 -1
View File
@@ -70,7 +70,11 @@ def test_user_expert_fails_question():
rep = FloopRun("goal?", budget(), modules=fm).run()
assert rep.questions[1][1] == "failed"
assert any("needs_user_input" in e for e in rep.evidence_rows)
assert rep.final_answer == "ANSWER(goal?)" # synthesis still happens, honestly
# the 23/10 law: a run that ASKED ends IN THE QUESTION (fixed code),
# never a synthesis prompt swallowing the ask — 'the evidence does
# not identify...' is the rejected behaviour
assert rep.final_answer.startswith("I need to ask you:"), rep.final_answer
assert any("clarification requested" in n for n in rep.notes)
def test_recursion_depth_cap():
@@ -290,6 +294,69 @@ def test_seed_warning_is_emitted():
print("ok: seed WARNING lands in run.log (auto-answer is loud)")
def test_route_to_user_ends_in_the_question():
"""His 23/10 run: ROUTE deferred a subquestion to the user (the
evidence only flagged ambiguity) — and the final ANSWER prompt
swallowed the ask, inventing 'the evidence does not identify...'.
A run that ASKED ends IN THE QUESTION, composed by fixed code: the
instantiated question, what the machine holds as context, zero
synthesis calls. (The ambiguity+dependent shape now forks branches —
tested in branches.py; this covers every OTHER honest defer.)"""
import tempfile
from floop.stream import RunStreams
from floop.state import AnswerType, EvidenceRow
streams = RunStreams("clarify test", verbose=False,
runs_dir=tempfile.mkdtemp())
class PlainEngine:
def __init__(self, modules, charge, expert_kind):
self.charge = charge
def run(self, qid, question, parent_question, table, answer_type, streams=None):
self.charge()
return EvidenceRow(
qid=qid, answer_type=AnswerType.OPEN,
payload={"value": "Paris", "quote": "q"},
engine="knowledge", trace=[], provenance={},
verified=False, note="")
import floop.machine as M
real = M.LLMExpertEngine
M.LLMExpertEngine = PlainEngine
try:
# FakeModules.route_question returns (route_fn(question), "fake") —
# our route must return the ATTENDANT string alone, not a tuple
def route(q):
if "district" in q:
return "user"
return "knowledge"
fm = FakeModules(
init_subs=[
{"text": "What is the capital of France?", "deps": [],
"answer_type": "OPEN"},
{"text": "Which specific district of that capital does the user mean?",
"deps": [1], "answer_type": "OPEN"},
],
route_fn=route)
# the generic FakeModules.missing_decompose would inject a fallback
# question after the defer, reopening the loop and reaching a plain
# synthesis — this test isolates the defer path (missing adds nothing)
fm.missing_decompose = lambda goal, evidence: []
run = FloopRun("What is the capital of France and which district do you mean?",
budget(), modules=fm, streams=streams)
rep = run.run()
finally:
M.LLMExpertEngine = real
# the run ends IN THE QUESTION to the user, by fixed code
assert rep.final_answer.startswith("I need to ask you:"), rep.final_answer
assert "district" in rep.final_answer, rep.final_answer
assert "(so far: Paris)" in rep.final_answer, rep.final_answer
# the synthesis NEVER ran: the ask is not invented from the table
assert "synthesize" not in fm.calls, fm.calls
assert any("clarification requested" in n for n in rep.notes), rep.notes
print("ok: a run that asks ends in the question (fixed code, no synthesis)")
# keep a handle to restore the real engine after monkeypatching
from floop.engine import LLMExpertEngine as _restore_llm_engine