Files
floop/code/knowledge/checks.py
onibot 99f8b6e9db knowledge: temporal restrictions layer (phase 2, RESEARCH-derived-answers Part 2)
The extractor's temporal vocabulary is RESTRICTIONS, never Allen labels:
typed Fact gains start/end/point (optional, ISO-ish) + granularity +
orders [{rel: before|after|concurrent, other: <sibling index>}] — the
text's connectives transcribed, not classified. The Allen algebra stays
a COMPUTED VIEW over endpoints.

- checks.py: every stated date must be CONTAINED IN THE QUOTE — an
  invented date rejects the whole candidate (LLM proposes, code
  verifies against the source surface).
- store.py: edges gain t_start/t_end (valid-time window, None end =
  OPEN, honest to 'since 2018'); fact_order table (order assertions
  between addressable facts — reification is free); _classify consumes
  interval arithmetic: overlapping open windows -> alternatives
  (coexistence provable, no statistics), disjoint windows ->
  succession (never a conflict). Boundary law at year granularity:
  [2014,2018) vs [2018,None) = succession — the mandate changed hands
  in 2018. add_fact_order validates rel in {before, after, concurrent}.
- expert.py: _ingest_candidate returns (merged, eid) and passes the
  windows; the prose path collects positional fact_ids and wires the
  orders' sibling references to real edge ids (malformed refs skip
  honestly).

Tests: temporal.py 6/6 (typed fields, containment rejection, open-
window overlap -> alternatives, touch-at-year -> succession, empty
stays empty, fact_order ingest) + 7/7 interval cases incl. the
open-past degenerate. Suite: all green.

LIVE (run 20261025-205018, cold KG, glm-5.3-flash): 29 edges carry
windows (Spain 2018 / PSOE 2017 / SI 2022 all open-ended), 25
fact_order rows (Madrid before Congress of Deputies...), 8 invented
end-dates REJECTED by the containment check (the footballer Pedro
articles — the check catching exactly what it should), 0 conflicts.
The run itself answered UNKNOWN on its Q1 ("what DATE did he take
office") — honest: the blind extractor did not transcribe the exact
date this run and the noisy re-probe view (four Pedros) is the known
branch weakness, not a phase-2 regression. Design note for phase 4:
the three presidencies live under DIFFERENT rels, so the alternatives
substrate must be queried trans-rel by the consumer (alternatives_of
is per-rel by construction).
2026-10-25 21:07:34 +01:00

52 lines
1.9 KiB
Python

"""The load-bearing check: quote containment + trusted source.
Nothing enters the store without a verbatim span string-contained in the fetched
document text (KNOWLEDGE.md §3, DESIGN §3). All checks are deterministic code.
"""
from __future__ import annotations
import re
TRUSTED_DOMAINS = ("en.wikipedia.org",)
def normalize_ws(s: str) -> str:
"""Collapse whitespace and strip surrounding quotes the model may add."""
s = re.sub(r"\s+", " ", s).strip()
while len(s) >= 2 and s[0] in "\"'" and s[-1] in "\"'":
s = s[1:-1].strip()
return s
def quote_containment(quote: str, full_text: str) -> bool:
"""The quote must appear verbatim (whitespace-collapsed) in the fetched text."""
q = normalize_ws(quote)
if not q or len(q) < 10: # too short to be a meaningful span
return False
return q in normalize_ws(full_text)
def trusted_source(url: str) -> bool:
from urllib.parse import urlparse
host = urlparse(url).netloc.lower()
return any(host == d or host.endswith("." + d) for d in TRUSTED_DOMAINS)
def check_candidate(cand: dict, full_text: str) -> tuple[bool, str]:
"""Validate one extraction candidate. Returns (ok, reason)."""
quote = cand.get("quote", "")
if not quote:
return False, "no quote"
if not quote_containment(quote, full_text):
return False, "containment failed"
subj, rel, obj = cand.get("subject", ""), cand.get("relation", ""), cand.get("object", "")
if not (subj and rel and obj):
return False, "incomplete triple"
# phase 2: temporal restrictions are quotable — every stated date must
# be CONTAINED IN THE QUOTE (an invented date rejects the candidate;
# the model proposes, code verifies against the source surface)
for field in ("start", "end", "point"):
val = (cand.get(field) or "").strip()
if val and val not in quote:
return False, f"temporal {field} not in quote"
return True, "ok"