"""The derived-answer engine (phase 3a, RESEARCH-derived-answers Part 3). No LLM in the loop. The query is a small TYPED DSL (conjunctive + temporal, hand-writable — the LLM translator arrives in 3b); the evaluation is goal-directed over the store; THE ANSWER IS THE PROOF TERM: every step names its operator and the edge ids it consumed, and re-execution over the store IS the verification (deterministic, no model). This is the Logic-LM move of the lineage applied to floop's own layer: LLMs translate at the two ends, fixed code decides inside. DSL (the subset pinned by tests/prover.py): {"lookup": {subject, rel_any, bind} | [lookups...] "filter": [{open_now: [var]}, {before: [a, b]}, {neq_value: [var, lit]}] "select": "all" | "latest_end"} lookup binds `var` to every matching edge (subject exact-normalized, rel in rel_any). A second lookup may carry same_value_as: var — a join on the bound value (the SAME office, a different holder). Filters: open_now (the edge's window is open now — end None or >= today's year), before (window a ends before window b starts — the interval succession law), neq_value (a bound subject differs from a literal — exclusion of the queried entity itself). select: all (the binding SET — multi-binding IS the ambiguity) or latest_end (the most recent closed window among the surviving bindings — the predecessor). Evaluation semantics, honestly narrow: - values compare through norm_name (the store's normalization); - `before` requires BOTH windows to have real endpoints on the compared sides — an open end is NOT "before" anything (the world moved on, we cannot prove when); - select=latest_end sorts by t_end descending, requiring a real t_end; - nothing is ever invented: no closed path -> empty bindings (UNKNOWN). """ from __future__ import annotations from dataclasses import dataclass, field from typing import Any from .store import KnowledgeStore, norm_name _THIS_YEAR = "2026" # open_now: an open end or an end >= today coexists _KNOWN_FILTERS = {"open_now", "before", "neq_value"} _KNOWN_SELECTS = {"all", "latest_end"} def validate_query(q: Any) -> tuple[bool, str]: """The shared grammar: a DSL term type-checks BEFORE evaluation. The translator (LLM) proposes; this deterministic gate decides. A mistranslation surfaces as an invalid term — unknown filter, unknown select, empty rel_any, malformed lookup — and NEVER reaches evaluate(): no wrong answer can hide inside an unexecutable query. Returns (ok, reason). """ if not isinstance(q, dict) or not q: return False, "empty or non-dict query" lookups = q.get("lookup") if isinstance(lookups, dict): lookups = [lookups] if not lookups or not isinstance(lookups, list): return False, "no lookup" for lk in lookups: if not isinstance(lk, dict) or not lk.get("subject"): return False, "lookup without subject" if not lk.get("rel_any"): return False, "lookup without rel_any" if not isinstance(lk["rel_any"], list): return False, "rel_any not a list" if not lk.get("bind"): return False, "lookup without bind var" for f in q.get("filter", []): if not isinstance(f, dict) or len(f) != 1: return False, f"malformed filter {f!r}" key = next(iter(f)) if key not in _KNOWN_FILTERS: return False, f"unknown filter {key!r}" if not isinstance(f[key], list): return False, f"filter args not a list: {key}" sel = q.get("select", "all") if sel not in _KNOWN_SELECTS: return False, f"unknown select {sel!r}" return True, "ok" @dataclass class Step: op: str # lookup | filter | select note: str = "" edges: list[int] = field(default_factory=list) @dataclass class Proof: bindings: list[dict] = field(default_factory=list) steps: list[Step] = field(default_factory=list) def _edges_of(store: KnowledgeStore, subject: str, rel_any: list[str]) -> list: """All live edges of one subject under any of the rels (order: id).""" rows = store.db.execute( "SELECT e.id, e.rel, e.dst_value, e.t_start, e.t_end, n.norm_name " "FROM edges e JOIN nodes n ON n.id=e.src_node " "WHERE n.norm_name=? AND e.retracted=0 ORDER BY e.id", (norm_name(subject),)).fetchall() return [r for r in rows if r[1] in rel_any] def _row_to_binding(var: str, r) -> dict: return {var: {"eid": r[0], "rel": r[1], "value": r[2], "start": r[3], "end": r[4], "subject": r[5]}} def _window_open_now(b: dict) -> bool: end = b["end"] return end is None or end >= _THIS_YEAR def _before(a: dict, b: dict) -> bool: """Window a ENDED before window b STARTED. Both sides must be real — an open end is not 'before' anything (honesty: no invented dates).""" if a["end"] is None or b["start"] is None: return False return a["end"] <= b["start"] # year granularity, closed-open def evaluate(store: KnowledgeStore, query: dict) -> Proof: """Goal-directed evaluation. Returns the proof term (bindings + steps).""" proof = Proof() lookups = query.get("lookup") if isinstance(lookups, dict): lookups = [lookups] # ---- first lookup: bind every matching edge ------------------------- first = lookups[0] var = first["bind"] rows = _edges_of(store, first["subject"], first.get("rel_any", [])) proof.steps.append(Step("lookup", f"bind {var}: subject={first['subject']} " f"rels={first.get('rel_any')}", [r[0] for r in rows])) bindings = [_row_to_binding(var, r) for r in rows] # ---- further lookups: JOIN on the bound value ----------------------- for lk in lookups[1:]: jvar = lk["bind"] joined = [] for b in bindings: same = b[lk.get("same_value_as", var)]["value"] # the joining side's subject may be a VARIABLE (?x): iterate # every live edge under the rels and keep value matches rows = store.db.execute( "SELECT e.id, e.rel, e.dst_value, e.t_start, e.t_end, n.norm_name " "FROM edges e JOIN nodes n ON n.id=e.src_node " "WHERE e.rel IN (%s) AND e.retracted=0 ORDER BY e.id" % ",".join("?" * len(lk.get("rel_any", []))), tuple(lk.get("rel_any", []))).fetchall() for r in rows: if norm_name(r[2]) == norm_name(same): nb = dict(b) nb[jvar] = {"eid": r[0], "rel": r[1], "value": r[2], "start": r[3], "end": r[4], "subject": r[5]} nb["?x"] = r[5] # the OTHER holder joined.append(nb) proof.steps.append(Step("lookup", f"join {jvar} on value={same}", [r[0]])) bindings = joined # ---- filters ---------------------------------------------------------- for f in query.get("filter", []): for key, args in f.items(): kept = [] for b in bindings: if key == "open_now": ok = _window_open_now(b[args[0]]) elif key == "before": ok = _before(b[args[0]], b[args[1]]) elif key == "neq_value": # the arg may be a bound edge var (dict) or a plain # string var ('?x') holding the joined subject's name ref = b.get(args[0]) subj = (ref["subject"] if isinstance(ref, dict) else ref) or "" ok = norm_name(subj) != norm_name(args[1]) else: raise ValueError(f"unknown filter {key!r}") if ok: kept.append(b) proof.steps.append(Step("filter", f"{key} {args}", [b[var]["eid"] for b in kept if var in b])) bindings = kept # ---- select ----------------------------------------------------------- sel = query.get("select", "all") if sel == "latest_end": def _end_key(b): e = next((v["end"] for k, v in b.items() if isinstance(v, dict) and v.get("end")), None) return e or "" bindings = sorted(bindings, key=_end_key, reverse=True) bindings = bindings[:1] proof.steps.append(Step("select", "latest_end", [b[var]["eid"] for b in bindings if var in b])) elif sel != "all": raise ValueError(f"unknown select {sel!r}") proof.bindings = bindings return proof def re_execute(store: KnowledgeStore, query: dict, proof: Proof) -> bool: """The check: the same store must reproduce the SAME closed path. Deterministic, no model — evaluation is pure, so this is equality of the re-run proof term against the claimed one. A store that changed under the proof (retractions, new edges winning latest_end) makes the re-run differ and the claimed proof FAILS: the check is real. """ fresh = evaluate(store, query) if len(fresh.bindings) != len(proof.bindings): return False for a, b in zip(fresh.bindings, proof.bindings): ka = {k: (v["eid"] if isinstance(v, dict) else v) for k, v in a.items()} kb = {k: (v["eid"] if isinstance(v, dict) else v) for k, v in b.items()} if ka != kb: return False return True