"""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"