Files
floop/code/floop/state.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

178 lines
6.3 KiB
Python

"""Shared state: evidence table, open questions, budget. The machine's data structures.
Laws enforced here (PIPELINE.md §5):
- the table is append-only; retraction is a flag, never a deletion
- every row carries provenance and a trace
- prose is never stored: payload is a typed dict; verbatim quotes live in payload["quote"]
"""
from __future__ import annotations
import json
import re
import time
from dataclasses import dataclass, field
from enum import Enum
class AnswerType(str, Enum):
OPEN = "OPEN"
FUNCTION = "FUNCTION"
INTERVAL = "INTERVAL"
CONSTANT = "CONSTANT"
LIST = "LIST"
DATE = "DATE"
class BudgetExhausted(Exception):
pass
@dataclass
class OpenQuestion:
text: str
answer_type: AnswerType = AnswerType.OPEN
deps: list[str] = field(default_factory=list) # qids this question waits on
parent_goal: bool = False
reason: str = "" # init | missing | child-goal
qid: str = "" # assigned by QuestionStack
status: str = "open" # open | answered | failed
# fan-out bookkeeping (set by the machine's planner expansion)
fan_group: str = "" # original qid whose expansion produced this question
fan_join: bool = False # this question is the group's join (sum) question
fan_source: str = "" # the list row eid the expansion reads
@dataclass
class EvidenceRow:
answer_type: AnswerType
payload: dict # typed fields; for knowledge: {"quote": ..., "url": ...} verbatim only
engine: str # e.g. "stub:knowledge", "floop-child"
eid: str = "" # assigned by EvidenceTable.append
qid: str = ""
trace: list[str] = field(default_factory=list)
provenance: dict = field(default_factory=dict) # expert, llm_calls, ts, cost
verified: bool = False
note: str = "" # type mismatches, failures — never prose claims
retracted: bool = False
class EvidenceTable:
def __init__(self) -> None:
self._rows: list[EvidenceRow] = []
self._next = 1
def append(self, row: EvidenceRow) -> EvidenceRow:
if row.payload is None or not isinstance(row.payload, dict):
raise ValueError("payload must be a typed dict — no free-form prose (table law 4)")
row.eid = f"E{self._next}"
self._next += 1
self._rows.append(row) # append-only
return row
def row(self, eid: str) -> EvidenceRow | None:
return next((r for r in self._rows if r.eid == eid), None)
def rows(self) -> list[EvidenceRow]:
return list(self._rows)
def for_question(self, qid: str) -> list[EvidenceRow]:
return [r for r in self._rows if r.qid == qid]
def dump(self) -> str:
out = []
for r in self._rows:
mark = "verified" if r.verified else "unverified"
ret = " RETRACTED" if r.retracted else ""
out.append(
f"{r.eid} (answers {r.qid}, {r.answer_type.value}, {mark}{ret}) "
f"engine={r.engine} payload={json.dumps(r.payload, ensure_ascii=False)}"
+ (f" note={r.note}" if r.note else "")
)
return "\n".join(out) if out else "(empty)"
class QuestionStack:
def __init__(self, goal: str) -> None:
self.goal = OpenQuestion(text=goal, parent_goal=True, reason="user question")
self.goal.qid = "Q0"
self.items: list[OpenQuestion] = [self.goal]
self._next = 1
def add(self, q: OpenQuestion) -> OpenQuestion:
q.qid = f"Q{self._next}"
self._next += 1
self.items.append(q)
return q
def pickable(self, table: EvidenceTable) -> OpenQuestion | None:
"""First open question whose deps are answered. Dependency order IS execution order — no search."""
failed_qids = {i.qid for i in self.items if i.status == "failed" and not i.parent_goal}
updated = True
while updated: # cascade: a failed dependency kills its dependents too
updated = False
for q in self.items:
if q.status != "open" or q.parent_goal:
continue
if table.for_question(q.qid):
continue # already has evidence — never re-picked (loop guard)
dead = [d for d in q.deps if d in failed_qids]
if dead:
q.status = "failed"
q.reason = "dependency failed: " + ",".join(dead)
failed_qids.add(q.qid)
updated = True
continue
if all(table.for_question(d) for d in q.deps):
return q
return None
def open_count(self) -> int:
return sum(1 for q in self.items if q.status == "open" and not q.parent_goal)
def all_terminal(self) -> bool:
"""Every subquestion answered or failed — the goal itself is 'answered'
by the synthesis step, not by a row (prover stub lives in the machine)."""
return all(q.status in ("answered", "failed")
for q in self.items if not q.parent_goal)
@dataclass
class Budget:
max_llm_calls: int
max_depth: int
max_retries: int
missing_extensions: int
min_child_budget: int = 6
llm_calls: int = 0
engine_calls: int = 0
missing_used: int = 0
def charge_llm(self) -> None:
if self.llm_calls >= self.max_llm_calls:
raise BudgetExhausted(f"llm_calls={self.llm_calls}/{self.max_llm_calls}")
self.llm_calls += 1
def slice_for_child(self) -> "Budget":
remaining = self.max_llm_calls - self.llm_calls
child = Budget(
max_llm_calls=max(self.min_child_budget, remaining // 2),
max_depth=self.max_depth,
max_retries=self.max_retries,
missing_extensions=self.missing_extensions,
min_child_budget=self.min_child_budget,
)
return child
def instantiate(text: str, table: EvidenceTable) -> str:
"""ReWOO plan-on-slots: replace #E<n> references with the row's value."""
def sub(m: re.Match) -> str:
r = table.row(f"E{m.group(1)}")
if r is None:
return m.group(0)
val = r.payload.get("value", r.payload.get("quote", r.payload.get("user_reply")))
if val is None:
val = json.dumps(r.payload, ensure_ascii=False)
return str(val)
return re.sub(r"#E(\d+)", sub, text)