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"
+78
View File
@@ -0,0 +1,78 @@
"""Section-aware chunker for Wikipedia plain-text extracts.
The MediaWiki extract keeps headings as '== Section ==' / '=== Sub ===' lines.
Each chunk = one (sub)section; a chunk never mixes sections, so its heading
path is always honest. A section longer than the cap is split at sentence
boundaries; all its pieces carry the same path.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
HEADING_RE = re.compile(r"^(={2,6})\s*(.+?)\s*\1\s*$", re.M)
SENTENCE_RE = re.compile(r"(?<=[.!?])\s+(?=[A-Z\"'(])")
@dataclass
class Chunk:
idx: int
heading_path: str # e.g. "Course > Upper Loire"
text: str # the chunk body
char_start: int # offset into the full text
def _split_long(text: str, cap: int) -> list[str]:
"""Split a too-long section at sentence boundaries into <=cap pieces."""
if len(text) <= cap:
return [text]
sentences = SENTENCE_RE.split(text)
out: list[str] = []
cur = ""
for s in sentences:
if cur and len(cur) + len(s) + 1 > cap:
out.append(cur)
cur = s
else:
cur = f"{cur} {s}".strip()
if cur:
out.append(cur)
return out
def chunk_page(text: str, target: int = 32000, cap: int = 48000) -> list[Chunk]:
"""Split a plain-text extract into one chunk per (sub)section.
`target` packs nothing (kept for API compat); `cap` guards the extraction
call size. Sizes in CHARS (draft: ~4 chars/token).
"""
marks = [(m.start(), m.end(), len(m.group(1)), m.group(2))
for m in HEADING_RE.finditer(text)]
chunks: list[Chunk] = []
def add(path: str, body: str, start: int) -> None:
if not body.strip():
return
for j, piece in enumerate(_split_long(body, cap)):
chunks.append(Chunk(idx=len(chunks), heading_path=path,
text=piece, char_start=start))
if not marks:
add("", text, 0)
return chunks
# preamble (before first heading)
if marks[0][0] > 0:
add("", text[: marks[0][0]], 0)
# walk headings maintaining a level stack -> honest paths
stack: list[tuple[int, str]] = [] # (level, title)
for i, (h_start, h_end, level, title) in enumerate(marks):
while stack and stack[-1][0] >= level:
stack.pop()
stack.append((level, title))
next_start = marks[i + 1][0] if i + 1 < len(marks) else len(text)
body = text[h_end:next_start]
add(" > ".join(t for _, t in stack), body, h_start)
return chunks
+195
View File
@@ -0,0 +1,195 @@
"""The knowledge expert pipeline: KG-first, gather on gap, containment-checked.
Per question (one routed knowledge call):
1. TRANSLATE: question -> retrieval focus (keywords/entities) [LLM, cheap]
2. KG PROBE: lexical seed match + BFS depth-1 [engine]
3. gap? -> SEARCH en.wikipedia (official search) [engine]
4. FETCH top articles, CHUNK by sections [engine]
5. EXTRACT per chunk (map) with verbatim spans [LLM]
6. CHECK: containment in FULL text + well-formedness [engine]
7. MERGE into the store: corroboration / conflicts / supersession [engine]
8. ANSWER from KG rows (select + one LLM answer call) [LLM]
Laws: no quote, no edge; no edge, no answer. Every step logged via RunStreams.
"""
from __future__ import annotations
import hashlib
import re
import time
from dataclasses import dataclass
import dspy
from .checks import check_candidate
from .chunker import chunk_page
from .extract import (AnswerFromKG, ExtractSignature, TranslateSignature,
parse_facts)
from .store import KnowledgeStore
from .wiki import WikipediaClient, WikiPage
WORD_RE = re.compile(r"[A-Za-zÀ-ÿ0-9']+")
@dataclass
class KnowledgeConfig:
kb_path: str = "knowledge_store/kg.sqlite"
max_articles: int = 3 # per knowledge call
max_search_results: int = 4 # candidates considered
max_chunks_extracted: int = 6 # per call (lexical gate decides which)
max_extract_retries: int = 2
chunk_chars_target: int = 32000
chunk_chars_cap: int = 48000
class KnowledgeExpert:
"""The machine's knowledge attendant — replaces stub:knowledge when wired."""
def __init__(self, config: KnowledgeConfig | None = None,
store: KnowledgeStore | None = None,
client: WikipediaClient | None = None, streams=None):
self.cfg = config or KnowledgeConfig()
self.store = store or KnowledgeStore(self.cfg.kb_path)
self.client = client or WikipediaClient()
self.streams = streams
self.extract = dspy.Predict(ExtractSignature)
self.answer = dspy.Predict(AnswerFromKG)
self.translate = dspy.Predict(TranslateSignature)
# ---- helpers -----------------------------------------------------------
def _log(self, text: str, think: bool = False) -> None:
if self.streams:
self.streams.state(text, think=think)
@staticmethod
def _keywords(question: str, k: int = 6) -> list[str]:
"""Deterministic lexical focus: content words of the question (draft)."""
stops = {"what", "which", "who", "when", "where", "is", "are", "was", "were",
"the", "of", "in", "on", "at", "a", "an", "and", "or", "to", "for",
"does", "do", "did", "by", "its", "it", "that", "this", "most", "second"}
words = [w.lower() for w in WORD_RE.findall(question)]
seen: list[str] = []
for w in words:
if w not in stops and len(w) > 2 and w not in seen:
seen.append(w)
return seen[:k]
# ---- the pipeline --------------------------------------------------------
def answer_question(self, question: str, parent_question: str = "",
evidence: str = "", charge_llm=None) -> dict:
"""Returns the answer dict {value, quote, url, source, confidence}.
`parent_question` + `evidence` are the machine's context: the original
goal and the rows this question depends on (design §4: instantiated
question + parent + referenced rows in). References like 'that state'
resolve against them."""
t0 = time.time()
context = (f"Original question: {parent_question}" if parent_question else "")
if evidence:
context += (chr(10) * 2 if context else "") + f"Evidence:\n{evidence}"
kws = self._keywords(question)
self._log(f"knowledge: question={question[:80]!r} keywords={kws}", think=True)
# 2. KG probe first: question keywords + entities from the machine's
# context (evidence rows) — 'that state' probes as 'france'
probe_seeds = list(kws)
for line in (evidence or "").splitlines():
if ":" in line:
val = line.split(":", 1)[1].split("(answers")[0].strip()
if val and len(val.split()) <= 4:
probe_seeds.extend(val.split())
rows = self.store.probe(probe_seeds)
self._log(f"kg probe ({probe_seeds}): {len(rows)} rows", think=True)
answer = self._answer_from_rows(question, rows, charge_llm)
if answer["value"] and answer["value"].upper() != "UNKNOWN":
self._log(f"kg hit: {answer['value'][:60]}", think=True)
return {**answer, "source": "knowledge_graph", "kg_rows": len(rows)}
# 3-4. gap -> search + fetch. TRANSLATE (LLM) first: the question becomes
# entity-first Wikipedia queries — deterministic keywords alone surface
# list articles and miss demographics pages.
if charge_llm:
charge_llm()
pred = self.translate(question=question, context=context)
q_raw = (pred.queries or "").strip()
queries = [q.strip() for q in
next((ln.split(":", 1)[1] for ln in q_raw.splitlines()
if ln.strip().upper().startswith("QUERIES")), q_raw).split(",")
if q.strip()][:2]
if not queries:
queries = [" ".join(kws[:3])]
self._log(f"translate -> queries {queries}", think=True)
pages: list[WikiPage] = []
seen: set[str] = set()
for query in queries:
candidates = self.client.search(query, limit=self.cfg.max_search_results)
self._log(f"wiki search ({query!r}): {candidates}", think=True)
for title in candidates:
if len(pages) >= self.cfg.max_articles or title in seen:
continue
seen.add(title)
try:
pages.append(self.client.fetch_rich(title))
except Exception as e: # noqa: BLE001 — network honesty: log and continue
self._log(f"fetch failed: {title}: {e}")
# 5-7. chunk -> extract -> check -> merge (lexical gate on chunks)
checked = 0
merged = 0
for page in pages:
chunks = chunk_page(page.text, target=self.cfg.chunk_chars_target,
cap=self.cfg.chunk_chars_cap)
gated = [c for c in chunks if self._gate(c, kws)][: self.cfg.max_chunks_extracted]
self._log(f"{page.title}: {len(chunks)} chunks, {len(gated)} gated in")
for chunk in gated:
if charge_llm:
charge_llm()
raw = self.extract(question=question, heading=chunk.heading_path, text=chunk.text)
for cand in parse_facts(raw.facts):
checked += 1
ok, reason = check_candidate(cand, page.text)
if not ok:
self._log(f"candidate rejected ({reason}): {cand.get('subject', '')[:40]}")
continue
doc_id = self.store.add_document(
url=page.url, title=page.title, fetched_at=page.fetched_at,
sha256=hashlib.sha256(page.text.encode()).hexdigest())
qid = self.store.add_quote(doc_id, cand["quote"], page.url, page.fetched_at)
self.store.add_edge(cand["subject"], cand["relation"], cand["object"], qid)
merged += 1
# 8. re-probe (same seeds) and answer from the merged KG
rows = self.store.probe(probe_seeds)
self._log(f"merged {merged}/{checked} candidates; re-probe: {len(rows)} rows", think=True)
answer = self._answer_from_rows(question, rows, charge_llm)
src = "knowledge_graph" if answer["value"].upper() != "UNKNOWN" else "wikipedia_miss"
return {**answer, "source": src,
"stats": {"checked": checked, "merged": merged,
"pages": [p.title for p in pages],
"elapsed_s": round(time.time() - t0, 1)}}
def _gate(self, chunk, keywords: list[str]) -> bool:
"""Lexical gate with stemming: chunk must mention a question stem."""
from .store import stem
if not keywords:
return True
low = chunk.text.casefold()
return any(stem(k) in low or k in low for k in keywords)
def _answer_from_rows(self, question: str, rows, charge_llm=None) -> dict:
if not rows:
return {"value": "UNKNOWN", "quote": "", "url": "", "confidence": "low"}
if charge_llm:
charge_llm()
rendered = "\n".join(
f"K{i}: {r.src} | {r.rel} | {r.dst} | quote: {r.quote} | {r.url}"
f"{' | CONFLICT' if r.conflict else ''}"
for i, r in enumerate(rows))
pred = self.answer(question=question, rows=rendered)
return {
"value": pred.value.strip(),
"quote": pred.quote.strip(),
"url": next((r.url for r in rows if r.quote and pred.quote.strip()
and r.quote.strip() in pred.quote.strip()), rows[0].url),
"confidence": pred.confidence.strip().lower(),
}
+68
View File
@@ -0,0 +1,68 @@
"""LLM extraction per chunk (map) — dspy Signatures, minimal per floop convention.
The extractor sees ONE chunk (+ heading path); it proposes typed candidates with
VERBATIM spans. The containment check (checks.py) validates every span against
the FULL document text — so chunking can never fake a quote.
"""
from __future__ import annotations
import dspy
class TranslateSignature(dspy.Signature):
"""You are the TRANSLATE step of a knowledge machine. Turn the question
into Wikipedia search queries AND resolved entity terms. Resolve
references ('that state', 'the same river') using the context: the original
question and the evidence rows already gathered. Output two lines:
QUERIES: 1-2 wikipedia search queries, comma separated.
ENTITIES: the resolved entity names the answer is about, comma separated."""
question: str = dspy.InputField()
context: str = dspy.InputField(desc="the original question + evidence rows with answers already found; resolve pronouns from here; may be empty")
queries: str = dspy.OutputField(desc="line starting with QUERIES: 1-2 comma-separated wikipedia search queries")
entities: str = dspy.OutputField(desc="line starting with ENTITIES: comma-separated resolved entity names, e.g. ENTITIES: France, longest river")
class ExtractSignature(dspy.Signature):
"""You are the EXTRACT step of a knowledge machine. From the given text,
extract facts that help answer the question. Each fact is one line:
subject | relation | object | verbatim quote from the text.
The quote must be the FULL sentence or table ROW that states the fact,
copied exactly (at least 10 characters). Only facts the text states;
no inference."""
question: str = dspy.InputField()
heading: str = dspy.InputField(desc="section path of this chunk; context only")
text: str = dspy.InputField()
facts: str = dspy.OutputField(
desc="one fact per line: subject | relation | object | verbatim quote; empty if none")
class AnswerFromKG(dspy.Signature):
"""You are the ANSWER step of a knowledge machine. Answer the question using
ONLY the given knowledge-graph rows, each with its quote and source. Cite
rows by id. If the rows do not answer it, say UNKNOWN."""
question: str = dspy.InputField()
rows: str = dspy.InputField(desc="kg rows: id, subject, relation, object, quote, url")
value: str = dspy.OutputField(desc="the answer, or UNKNOWN")
quote: str = dspy.OutputField(desc="VERBATIM supporting quote from the rows, or empty")
confidence: str = dspy.OutputField(desc="high medium low")
def parse_facts(raw: str) -> list[dict]:
"""Parse the extractor's piped lines; malformed lines are dropped+counted.
Split into AT MOST 4 fields — the quote is the last field and may itself
contain pipes (table rows like 'France | 68,635,900 | 15.2%')."""
out: list[dict] = []
for line in (raw or "").strip().splitlines():
line = line.strip()
if not line or "|" not in line:
continue
parts = [p.strip() for p in line.split("|", 3)]
if len(parts) < 4:
continue
subject, relation, obj, quote = parts
if not (subject and relation and obj and quote):
continue
out.append({"subject": subject, "relation": relation,
"object": obj, "quote": quote})
return out
+244
View File
@@ -0,0 +1,244 @@
"""KnowledgeStore: SQLite, append-only, per KNOWLEDGE.md §2 and DESIGN §2.
Laws implemented:
- append-only: no UPDATE/DELETE; corrections are retraction flags; conflicts are rows
- every edge points at a quote (the quote carries the truth, the edge is the index)
- contradiction is classified, never guessed: temporal (ref_date) / supersession /
real conflict (exposed) / retraction — the four cases of KNOWLEDGE.md §2
"""
from __future__ import annotations
import json
import re
import sqlite3
import unicodedata
from dataclasses import dataclass
from pathlib import Path
SCHEMA = """
CREATE TABLE IF NOT EXISTS documents (
id INTEGER PRIMARY KEY, url TEXT UNIQUE, source TEXT, fetched_at TEXT,
sha256 TEXT, trusted INTEGER, title TEXT
);
CREATE TABLE IF NOT EXISTS quotes (
id INTEGER PRIMARY KEY, doc_id INTEGER, verbatim TEXT, url TEXT, access_date TEXT
);
CREATE TABLE IF NOT EXISTS nodes (
id INTEGER PRIMARY KEY, norm_name TEXT, sort TEXT,
UNIQUE(norm_name, sort)
);
CREATE TABLE IF NOT EXISTS edges (
id INTEGER PRIMARY KEY, src_node INTEGER, rel TEXT, dst_value TEXT,
dst_node INTEGER, quote_id INTEGER, extraction_confidence REAL,
ref_date TEXT, supersedes INTEGER, preferred INTEGER DEFAULT 0,
retracted INTEGER DEFAULT 0, retraction_reason TEXT, corroboration INTEGER DEFAULT 1
);
CREATE TABLE IF NOT EXISTS conflicts (
id INTEGER PRIMARY KEY, node INTEGER, rel TEXT, value_a TEXT, value_b TEXT,
edge_a INTEGER, edge_b INTEGER, note TEXT
);
CREATE INDEX IF NOT EXISTS idx_edges_src ON edges(src_node, rel);
CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(norm_name);
"""
def norm_name(name: str) -> str:
"""Conservative normalization: casefold + strip punctuation/diacritics, collapse ws."""
s = unicodedata.normalize("NFKD", name)
s = "".join(c for c in s if not unicodedata.combining(c))
s = re.sub(r"[^\w\s]", " ", s)
return re.sub(r"\s+", " ", s).strip().casefold()
def stem(word: str) -> str:
"""Tiny suffix stemmer so question words match text words (draft):
'populated'/'population' -> 'populat', 'states' -> 'state'."""
w = word.lower()
if len(w) > 3 and w.endswith("s"):
w = w[:-1]
if w.endswith("ed"):
w = w[:-2]
elif w.endswith("ing"):
w = w[:-3]
elif w.endswith("ion"):
w = w[:-3]
return w
@dataclass
class EdgeView:
src: str
rel: str
dst: str
quote: str
url: str
ref_date: str | None
corroboration: int
preferred: bool
conflict: bool
class KnowledgeStore:
"""All writes append; queries surface conflicts. File-backed (SQLite)."""
def __init__(self, path: str | Path):
self.path = Path(path)
self.path.parent.mkdir(parents=True, exist_ok=True)
self.db = sqlite3.connect(self.path)
self.db.executescript(SCHEMA)
self.db.commit()
self._mirror: Path | None = None
# ---- documents & quotes ------------------------------------------------
def add_document(self, url: str, title: str, fetched_at: str, sha256: str,
trusted: bool = True, source: str = "wikipedia") -> int:
cur = self.db.execute(
"INSERT OR IGNORE INTO documents(url, source, fetched_at, sha256, trusted, title) "
"VALUES(?,?,?,?,?,?)", (url, source, fetched_at, sha256, int(trusted), title))
self.db.commit()
row = self.db.execute("SELECT id FROM documents WHERE url=?", (url,)).fetchone()
return row[0]
def add_quote(self, doc_id: int, verbatim: str, url: str, access_date: str) -> int:
cur = self.db.execute(
"INSERT INTO quotes(doc_id, verbatim, url, access_date) VALUES(?,?,?,?)",
(doc_id, verbatim, url, access_date))
self.db.commit()
return cur.lastrowid
# ---- nodes & edges -------------------------------------------------------
def get_or_add_node(self, name: str, sort: str) -> int:
nn = norm_name(name)
row = self.db.execute("SELECT id FROM nodes WHERE norm_name=? AND sort=?",
(nn, sort)).fetchone()
if row:
return row[0]
cur = self.db.execute("INSERT INTO nodes(norm_name, sort) VALUES(?,?)", (nn, sort))
self.db.commit()
return cur.lastrowid
def add_edge(self, src_name: str, rel: str, dst_value: str, quote_id: int,
src_sort: str = "CONCEPT", dst_node_name: str | None = None,
dst_sort: str = "CONCEPT", confidence: float = 0.8,
ref_date: str | None = None) -> int | None:
"""Add an edge, applying the four contradiction cases (KNOWLEDGE.md §2).
Returns the edge id, or None when the candidate was a duplicate
(corroboration was counted instead).
"""
src = self.get_or_add_node(src_name, src_sort)
dst_node = self.get_or_add_node(dst_node_name, dst_sort) if dst_node_name else None
# exact duplicate -> corroboration
dup = self.db.execute(
"SELECT id FROM edges WHERE src_node=? AND rel=? AND dst_value=? AND retracted=0",
(src, rel, dst_value)).fetchone()
if dup:
self.db.execute("UPDATE edges SET corroboration = corroboration + 1 WHERE id=?",
(dup[0],))
self.db.commit()
return None
# contradiction classification: same src+rel, different value, not retracted
others = self.db.execute(
"SELECT id, dst_value, ref_date FROM edges WHERE src_node=? AND rel=? "
"AND retracted=0 AND id NOT IN (SELECT supersedes FROM edges WHERE supersedes IS NOT NULL)",
(src, rel)).fetchall()
cur = self.db.execute(
"INSERT INTO edges(src_node, rel, dst_value, dst_node, quote_id, "
"extraction_confidence, ref_date, preferred) VALUES(?,?,?,?,?,?,?,0)",
(src, rel, dst_value, dst_node, quote_id, confidence, ref_date))
edge_id = cur.lastrowid
for other_id, other_val, other_date in others:
case = self._classify(new_val=dst_value, new_date=ref_date,
old_val=other_val, old_date=other_date)
if case == "duplicate":
continue
elif case == "supersedes":
self.db.execute("UPDATE edges SET supersedes=? WHERE id=?", (other_id, edge_id))
self.db.execute("UPDATE edges SET preferred=1 WHERE id=?", (edge_id,))
elif case == "temporal":
pass # both coexist; queries pick by date
else: # contradiction
self.db.execute(
"INSERT INTO conflicts(node, rel, value_a, value_b, edge_a, edge_b) "
"VALUES(?,?,?,?,?,?)", (src, rel, other_val, dst_value, other_id, edge_id))
self.db.commit()
return edge_id
@staticmethod
def _classify(new_val: str, new_date: str | None, old_val: str, old_date: str | None) -> str:
"""Deterministic four-case classification (KNOWLEDGE.md §2)."""
nv, ov = norm_name(new_val), norm_name(old_val)
if nv == ov:
return "duplicate"
# subsumption: the new value equals the old plus extra qualifiers
if ov and ov in nv and (new_date or old_date):
return "supersedes"
# both dated -> time series, not contradiction
if new_date and old_date and new_date != old_date:
return "temporal"
return "contradiction"
# ---- queries --------------------------------------------------------------
def probe(self, seeds: list[str], depth: int = 1, limit: int = 20) -> list[EdgeView]:
"""KG-first probe: stems match node names AND edge relations/values.
Entity questions hit via node names; ranking/property questions
(whose answer entity is unknown) hit via the relation. Corroboration-
weighted, conflicts surfaced, retracted skipped."""
views: list[EdgeView] = []
seen_nodes: set[int] = set()
seen_edges: set[int] = set()
stems = {stem(s) for s in seeds if len(s) > 2}
for st in sorted(stems):
# entity matches: node names containing the stem (or vice versa)
rows = self.db.execute(
"SELECT id, norm_name FROM nodes WHERE norm_name LIKE ? OR ? LIKE '%' || norm_name || '%'",
(f"%{st}%", st)).fetchall()
for nid, _nname in rows:
if nid in seen_nodes:
continue
seen_nodes.add(nid)
self._collect_edges(nid, views, seen_edges, limit)
# property matches: relation or value containing the stem
erows = self.db.execute(
"SELECT id FROM edges WHERE retracted=0 AND (rel LIKE ? OR dst_value LIKE ?) LIMIT ?",
(f"%{st}%", f"%{st}%", limit)).fetchall()
for (eid,) in erows:
if eid not in seen_edges:
self._collect_edge_by_id(eid, views, seen_edges)
views.sort(key=lambda v: -v.corroboration)
return views
def _collect_edges(self, nid: int, views: list, seen: set, limit: int) -> None:
for e in self.db.execute(
"SELECT e.id, e.rel, e.dst_value, e.dst_node, e.ref_date, e.corroboration, "
"e.preferred, e.retracted, q.verbatim, q.url, n.norm_name "
"FROM edges e JOIN quotes q ON q.id=e.quote_id "
"JOIN nodes n ON n.id=e.src_node "
"WHERE e.src_node=? AND e.retracted=0 ORDER BY e.corroboration DESC LIMIT ?",
(nid, limit)):
self._append_view(e, views, seen)
def _collect_edge_by_id(self, eid: int, views: list, seen: set) -> None:
e = self.db.execute(
"SELECT e.id, e.rel, e.dst_value, e.dst_node, e.ref_date, e.corroboration, "
"e.preferred, e.retracted, q.verbatim, q.url, n.norm_name "
"FROM edges e JOIN quotes q ON q.id=e.quote_id "
"JOIN nodes n ON n.id=e.src_node WHERE e.id=?", (eid,)).fetchone()
if e:
self._append_view(e, views, seen)
def _append_view(self, e, views: list, seen: set) -> None:
(eid, rel, dstv, dstn, rd, cor, pref, retr, quote, url, sname) = e
if eid in seen:
return
seen.add(eid)
conflict = self.db.execute(
"SELECT 1 FROM conflicts WHERE edge_a=? OR edge_b=?", (eid, eid)).fetchone()
views.append(EdgeView(
src=sname, rel=rel, dst=dstv, quote=quote, url=url,
ref_date=rd, corroboration=cor, preferred=bool(pref),
conflict=bool(conflict)))
def close(self) -> None:
self.db.close()
+92
View File
@@ -0,0 +1,92 @@
"""Knowledge tests: chunker, containment, store's four contradiction cases.
No network, no LLM. Run: uv run python knowledge/tests/store.py
"""
from __future__ import annotations
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # code/
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) # repo root (for floop if needed)
from knowledge.checks import check_candidate, quote_containment, trusted_source
from knowledge.chunker import chunk_page
from knowledge.store import KnowledgeStore
def test_chunker_sections():
text = ("Intro paragraph about rivers.\n\n== Etymology ==\nThe name comes from Latin Liger.\n\n"
"== Course ==\n\n=== Upper ===\nIt starts in the Massif Central.\n\n"
"=== Lower ===\nIt reaches the Atlantic near Nantes.\n\n"
"== Long section ==\n" + ("Sentence one. " * 4000))
chunks = chunk_page(text, target=800, cap=1000)
assert chunks, "must produce chunks"
paths = [c.heading_path for c in chunks]
assert "Etymology" in paths
assert "Course > Upper" in paths, f"level-aware path: {paths}"
assert "Course > Lower" in paths
assert "" in paths or True # preamble has empty path
assert all(len(c.text) <= 1000 + 50 for c in chunks), "cap respected (sentence slack)"
# containment: chunk text must be findable in the original
assert all(c.text[:40] in text for c in chunks if len(c.text) > 40)
print("ok test_chunker_sections")
def test_containment():
doc = "The Loire is the longest river in France. It drains 117,054 km2 of land."
assert quote_containment("the longest river in France", doc)
assert not quote_containment("the longest river in Spain", doc)
assert not quote_containment("short", doc) # <10 chars -> meaningless
ok, reason = check_candidate(
{"subject": "Loire", "relation": "is_longest_river_of", "object": "France",
"quote": "the longest river in France"}, doc)
assert ok, reason
ok, reason = check_candidate(
{"subject": "Loire", "relation": "is_longest_river_of", "object": "France",
"quote": "longest river in Germany"}, doc)
assert not ok and "containment" in reason
print("ok test_containment")
def test_store_four_cases(tmp="/tmp/floop_kg_test.sqlite"):
p = Path(tmp)
if p.exists():
p.unlink()
ks = KnowledgeStore(p)
doc = ks.add_document(url="https://en.wikipedia.org/wiki/Test", title="Test",
fetched_at="2026-10-17T00:00:00+00:00", sha256="x" * 64)
q1 = ks.add_quote(doc, "The Loire is the longest river in France.", "url", "d")
q2 = ks.add_quote(doc, "The Loire is 1,006 kilometres long.", "url", "d")
# case: plain add
e1 = ks.add_edge("Loire", "longest_river_of", "France", q1)
assert e1 is not None
# exact duplicate -> corroboration, no new edge
e2 = ks.add_edge("loire", "longest_river_of", "France", q1)
assert e2 is None
row = ks.db.execute("SELECT corroboration FROM edges WHERE id=?", (e1,)).fetchone()
assert row[0] == 2
# temporal: same rel, different values, both dated -> coexist, no conflict
a = ks.add_edge("Loire", "length_km", "1006", q2, ref_date="2026")
b = ks.add_edge("Loire", "length_km", "1012", q2, ref_date="2020")
assert a and b
conflicts = ks.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
assert conflicts == 0, "dated different values are a time series, not a conflict"
# contradiction: same rel, undated different values -> exposed conflict
c1 = ks.add_edge("Seine", "length_km", "777", q1)
c2 = ks.add_edge("Seine", "length_km", "776", q1)
conflicts = ks.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
assert conflicts == 1, "undated different values must be exposed as conflict"
# probe: seeds find edges with quotes
rows = ks.probe(["Loire", "loire"])
assert any(r.rel == "longest_river_of" and r.dst == "France" for r in rows)
assert all(r.quote for r in rows), "every edge points at a quote"
ks.close()
print("ok test_store_four_cases")
if __name__ == "__main__":
test_chunker_sections()
test_containment()
test_store_four_cases()
print("\n3 knowledge tests passed")
+171
View File
@@ -0,0 +1,171 @@
"""Wikipedia access via the official MediaWiki API (action API, en.wikipedia only).
Why raw API over the `wikipedia` pip package (tested 2026-10-17): the package
sends params with empty-string values (e.g. redirects: '') which make the API
return an HTML error page instead of JSON, and its default User-Agent is blocked
(403). The official action API called directly with a proper session is reliable
and gives us search + plain-text extracts + revision ids in one place.
Search-first per Emili (2026-10-17): use the Wikipedia search engine to find
articles, then fetch and analyze them chunk by chunk.
"""
from __future__ import annotations
import re
import time
from dataclasses import dataclass, field
import requests
API = "https://en.wikipedia.org/w/api.php"
UA = "floop-bot/0.1 (research; contact: emili@oniricapps.com)"
LANG = "en"
def tables_as_text(wikitext: str, max_tables: int = 3, max_rows: int = 40) -> str:
"""Parse wikitext tables into plain text rows. Used by fetch_rich so
ranking/list articles (whose data lives in tables, not prose) carry
their facts; containment is checked against the ENRICHED text."""
out: list[str] = []
for m in re.finditer(r"\{\|(.*?)\|\}", wikitext, flags=re.S):
if len(out) >= max_tables:
break
rows: list[str] = []
for line in m.group(1).splitlines():
line = line.strip()
if re.fullmatch(r"\|-?", line): # wikitext row separator, not a cell
continue
if line.startswith("!") or line.startswith("|"):
cells = [c.strip().lstrip("!|").strip() for c in line.split("||")]
cells = [re.sub(r"\[\[(?:[^|\]]*\|)?([^\]]+)\]\]", r"\1", c) for c in cells]
cells = [re.sub(r"\{\{[^}]*\|([^}]*)\}\}", r"\1", c) for c in cells]
cells = [re.sub(r"\{\{[^}]*\}\}", "", c) for c in cells]
cells = [re.sub(r"<[^>]+>", "", c).replace("!!", " ").strip() for c in cells if c]
if cells:
rows.append(" | ".join(cells))
if len(rows) >= max_rows:
break
if rows:
out.append(chr(10).join(rows))
return (chr(10) * 2).join(out)
class WikiError(RuntimeError):
pass
@dataclass
class WikiPage:
"""A fetched article: plain text + section structure, verbatim-preserving."""
title: str
pageid: int
url: str
text: str # the full plain-text extract (contains section headings)
fetched_at: str # ISO timestamp
rev_id: int | None = None
@property
def sections(self) -> list[str]:
"""Heading lines as present in the extract (== Section == markers)."""
return re.findall(r"^==+ .+? ==+\s*$", self.text, flags=re.M)
class WikipediaClient:
"""Thin, honest client over the MediaWiki action API. All calls logged by the caller."""
def __init__(self, timeout: int = 15, max_retries: int = 2, backoff: float = 1.5):
self.timeout = timeout
self.max_retries = max_retries
self.backoff = backoff
self.session = requests.Session()
self.session.headers.update({"User-Agent": UA})
self.calls = 0
# ---- low-level ---------------------------------------------------------
def _get(self, **params) -> dict:
params.setdefault("format", "json")
params.setdefault("formatversion", "2")
last_err: Exception | None = None
for attempt in range(self.max_retries + 1):
self.calls += 1
try:
r = self.session.get(API, params=params, timeout=self.timeout)
if r.status_code == 403:
raise WikiError("403 forbidden — check User-Agent policy compliance")
r.raise_for_status()
ct = r.headers.get("content-type", "")
if "json" not in ct:
raise WikiError(f"non-JSON response (content-type={ct}) — API misuse")
return r.json()
except (requests.RequestException, WikiError) as e:
last_err = e
if attempt < self.max_retries:
time.sleep(self.backoff * (attempt + 1))
raise WikiError(f"wikipedia api failed after {self.max_retries + 1} attempts: {last_err}")
# ---- api surface --------------------------------------------------------
def search(self, query: str, limit: int = 5) -> list[str]:
"""Official search: list=search. Returns candidate article titles."""
data = self._get(action="query", list="search", srsearch=query, srlimit=limit)
return [h["title"] for h in data.get("query", {}).get("search", [])]
def summary(self, title: str) -> str:
data = self._get(action="query", titles=title, prop="extracts",
explaintext=True, exintro=True, redirects=True)
pages = data.get("query", {}).get("pages", [])
if not pages:
raise WikiError(f"no page for {title!r}")
pg = pages[0]
if "missing" in pg:
raise WikiError(f"page missing: {title!r}")
return pg.get("extract", "")
def fetch(self, title: str) -> WikiPage:
"""Full plain-text extract with headings preserved (for section chunking)."""
from datetime import datetime, timezone
data = self._get(action="query", titles=title, prop="extracts|info",
explaintext=True, redirects=True, inprop="url")
pages = data.get("query", {}).get("pages", [])
if not pages:
raise WikiError(f"no page for {title!r}")
pg = pages[0]
if "missing" in pg or "extract" not in pg:
raise WikiError(f"page missing or empty: {title!r}")
return WikiPage(
title=pg["title"],
pageid=pg["pageid"],
url=pg.get("fullurl", f"https://{LANG}.wikipedia.org/wiki/{pg['title'].replace(' ', '_')}"),
text=pg["extract"],
fetched_at=datetime.now(timezone.utc).isoformat(timespec="seconds"),
rev_id=pg.get("lastrevid"),
)
def fetch_wikitext(self, title: str) -> str:
"""Raw wikitext (tables live here; the plain extract drops them)."""
data = self._get(action="query", titles=title, prop="revisions",
rvprop="content", rvslots="main", redirects=True)
pages = data.get("query", {}).get("pages", [])
if not pages:
raise WikiError(f"no page for {title!r}")
pg = pages[0]
if "missing" in pg or "revisions" not in pg:
raise WikiError(f"page missing: {title!r}")
return pg["revisions"][0]["slots"]["main"]["content"]
def fetch_rich(self, title: str) -> WikiPage:
"""Extract + table text appended: wikitext tables are parsed into rows
and appended as text so ranking/list questions have their data."""
page = self.fetch(title)
extra = tables_as_text(self.fetch_wikitext(title))
if extra:
page.text = page.text + "\n\n== Tables ==\n" + extra
return page
def disambiguation(self, title: str) -> list[str]:
"""Titles a disambiguation page points to (handles the wiki lib's classic trap)."""
data = self._get(action="query", titles=title, prop="links", pllimit=50,
plnamespace=0, redirects=True)
pages = data.get("query", {}).get("pages", [])
if not pages:
return []
return [l["title"] for l in pages[0].get("links", [])]