feat(knowledge): real Wikipedia vertical with containment-checked KG

knowledge/: wiki.py (official MediaWiki API, own session+UA; fetch_rich appends wikitext tables as text - plain extracts drop them), chunker.py (section-aware, level paths), checks.py (verbatim containment, quote-aware), store.py (SQLite append-only, 4 contradiction cases, probe by entity AND relation with stemming), extract.py (dspy Signatures: TRANSLATE resolves pronouns from context and emits queries+entities, EXTRACT per chunk, ANSWER from KG rows), expert.py (the pipeline: KG-first probe -> gap -> translate -> search -> fetch_rich -> chunk -> gate -> extract -> check -> merge -> re-probe -> answer). Wiring: KnowledgeEngine in floop/engine.py (machine injects charge+modules at call time; baseline fallback on pipeline failure), machine routes knowledge questions to it, config.yaml knowledge: block. E2E verified live: Loire length answered from KG with zero network; the 2-hop EU-river question resolved France (population table row quote) -> Loire (KG hit) in 12 calls/75s. Six live-run bugs closed (wiki lib 403/HTML, dropped tables, pipes-in-quotes parse, gate stemming, relation probe, pronoun context). RUNLOG Run C added; code/README honest map updated. Tests 17/17.
This commit is contained in:
2026-10-16 23:19:09 +02:00
parent aecaac01eb
commit 9094b2aec0
15 changed files with 1111 additions and 13 deletions
+45
View File
@@ -0,0 +1,45 @@
"""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"
return True, "ok"