"""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, origin_question TEXT, 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 TABLE IF NOT EXISTS edge_vectors ( edge_id INTEGER PRIMARY KEY, model TEXT, text_hash TEXT, vec BLOB ); 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() # a value is FUNCTIONAL (only one can be true) when it is date-like or a # bare number/quantity: '29 February 1972', '2018', '15', '1,006 km', # '17 november 2023'. Two entity-ish values ('prime minister of Spain' vs # 'Secretary-General of the PSOE') are co-true readings of a multi-valued # relation instead. The signal: no entity WORDS survive after dropping # numbers, month names, and units. _MONTHS = {"january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december", "gener", "febrer", "marc", "abril", "maig", "juny", "juliol", "agost", "setembre", "octubre", "novembre", "desembre", "de", "d", "of", "the", "in", "on", "at", "since", "until"} _UNITS = {"km", "km2", "mi", "m", "kg", "s", "cu", "ft", "ms", "mm", "cm", "people", "inhabitants", "days", "years", "months", "hours", "percent", "m3", "m3/s", "bps", "kb", "mb", "gb", "%", "eur", "usd", "millions", "billions"} def _looks_functional(value: str) -> bool: """True when the value is date-like or a bare quantity (phase 1 signal: functional relations keep the contradiction case; entity-ish pairs go to alternatives). A value with two or more entity words is NOT functional ('prime minister of Spain'); a date or quantity is. A lone entity word ('Spain') is an entity reading, not a datum — functional needs NUMBERS with at most one unit/month word.""" words = re.findall(r"[A-Za-zÀ-ÿ]{1,}", value or "") entity_words = [w for w in words if w.lower() not in _MONTHS and w.lower() not in _UNITS] has_number = bool(re.search(r"\d", value or "")) if not has_number: return False # pure words: an entity reading (Spain / PSOE) return len(entity_words) < 2 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: eid: int 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._migrate() self.db.commit() self._mirror: Path | None = None def _migrate(self) -> None: """Idempotent, additive migrations. CREATE TABLE IF NOT EXISTS never upgrades an existing file, so stores predating a column change must be migrated here or every query touching the column crashes (2026-10-19: edges.origin_question, added with the set gate; 2026-10-20: edges.list_ord, the member's position in the source table — a ranked table's order IS information and was being lost).""" cols = {r[1] for r in self.db.execute("PRAGMA table_info(edges)")} if "origin_question" not in cols: self.db.execute("ALTER TABLE edges ADD COLUMN origin_question TEXT") self.db.commit() if "list_ord" not in cols: self.db.execute("ALTER TABLE edges ADD COLUMN list_ord INTEGER") self.db.commit() # ---- phase 1: the conflict taxonomy (RESEARCH-derived-answers.md) ---- # alternatives: co-true readings of one (src, rel) — the polisèmia # (the three presidencies). Same shape as conflicts (pairwise), but # the world holds BOTH: it is the ambiguity substrate, never an # error state. self.db.execute( "CREATE TABLE IF NOT EXISTS alternatives (" " id INTEGER PRIMARY KEY, node INTEGER, rel TEXT, " " value_a TEXT, value_b TEXT, edge_a INTEGER, edge_b INTEGER, " " UNIQUE(node, rel, edge_a, edge_b))") self.db.commit() # same_as: paraphrase merges. Append-only law — the merge never # deletes; the alias pair is recorded and the canonical edge's # corroboration goes up. self.db.execute( "CREATE TABLE IF NOT EXISTS same_as (" " id INTEGER PRIMARY KEY, edge_a INTEGER, edge_b INTEGER, " " UNIQUE(edge_a, edge_b))") self.db.commit() # ---- 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, origin_question: str | None = None, list_ord: int | 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, dst_node, quote_id 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, origin_question, ref_date, preferred, list_ord) " "VALUES(?,?,?,?,?,?,?,?,0,?)", (src, rel, dst_value, dst_node, quote_id, confidence, origin_question, ref_date, list_ord)) edge_id = cur.lastrowid for other_id, other_val, other_date, other_dn, other_q in others: case = self._classify(new_val=dst_value, new_date=ref_date, old_val=other_val, old_date=other_date, new_node=dst_node, old_node=other_dn, new_quote=quote_id, old_quote=other_q) if case in ("duplicate", "paraphrase"): if case == "paraphrase": self.db.execute( "INSERT OR IGNORE INTO same_as(edge_a, edge_b) VALUES(?,?)", (other_id, edge_id)) self.db.execute( "UPDATE edges SET corroboration = corroboration + 1 WHERE id=?", (other_id,)) 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 elif case == "coasserted": pass # one trusted sentence asserts both: conjunction, never a conflict elif case == "alternatives": self.db.execute( "INSERT OR IGNORE INTO alternatives(node, rel, value_a, value_b, edge_a, edge_b) " "VALUES(?,?,?,?,?,?)", (src, rel, other_val, dst_value, other_id, edge_id)) 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, new_node: int | None = None, old_node: int | None = None, new_quote: int | None = None, old_quote: int | None = None) -> str: """Deterministic taxonomy (KNOWLEDGE.md §2 + RESEARCH-derived-answers Part 1). Cost-ordered: the cheapest signal decides. duplicate same normalized value coasserted same quote — one trusted sentence asserts both (conjunction: the platform sentence split into facts) supersedes subsumption with dates temporal both dated, different dates — time series paraphrase tails resolve to the SAME node (same institution / office behind two surfaces) — the same fact alternatives different tails or discriminant entity, multi-valued reading — co-true (the polisèmia) contradiction the residue: functional relation, incompatible values Phase 2 (temporal windows) will feed real start/end into this; for now ref_date is the only date carrier, as before. """ nv, ov = norm_name(new_val), norm_name(old_val) if nv == ov: return "duplicate" # CO-ASSERTED: same quote — a trusted source asserting A and B in one # sentence means the world holds both. Provenance is the cheapest # possible signal and it is already on the row. if new_quote is not None and new_quote == old_quote: return "coasserted" # 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" # PARAPHRASE: both tails carry a resolved node and it is the SAME # node — two surfaces of the same institution/office. The merge is # an alias (same_as), never a conflict. if new_node and old_node and new_node == old_node: return "paraphrase" # ALTERNATIVES vs CONTRADICTION: value type decides functionality. # A date-like or bare-numeric value on a date-like relation is # functional (only one can be true); two entity-ish values are # co-true readings of a multi-valued relation (a person holds many # offices). Temporal windows (phase 2) will tighten this with # interval overlap; today tails-differ + entity-ish is the signal. if _looks_functional(new_val) or _looks_functional(old_val): return "contradiction" return "alternatives" # ---- phase 1: alternatives query (the ambiguity substrate) ------------- def alternatives_of(self, src_name: str, rel: str) -> list[tuple[str, str]]: """The co-true readings of one (src, rel): the alternatives bucket. Returns [(value, tail_node_name), ...] — the set the audit and the render consume (the ambiguity was detected at INGEST, deterministi- cally; nobody needs to re-derive it at judge time). Values appear once, first-seen order; None tail when the edge carries no node. """ src = self.db.execute("SELECT id FROM nodes WHERE norm_name=?", (norm_name(src_name),)).fetchone() if not src: return [] rows = self.db.execute( "SELECT a.value_a, a.value_b, na.norm_name, nb.norm_name " "FROM alternatives a " "LEFT JOIN edges ea ON ea.id = a.edge_a " "LEFT JOIN edges eb ON eb.id = a.edge_b " "LEFT JOIN nodes na ON na.id = ea.dst_node " "LEFT JOIN nodes nb ON nb.id = eb.dst_node " "WHERE a.node=? AND a.rel=? ORDER BY a.id", (src[0], rel)).fetchall() seen: list[tuple[str, str]] = [] for va, vb, ta, tb in rows: for val, tail in ((va, ta), (vb, tb)): key = (val, tail or "") if key not in [(s, t or "") for s, t in seen]: seen.append((val, tail or "")) return [(v, t or None) for v, t in seen] # ---- 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( eid=eid, src=sname, rel=rel, dst=dstv, quote=quote, url=url, ref_date=rd, corroboration=cor, preferred=bool(pref), conflict=bool(conflict))) # ---- membership queries (LIST path) -------------------------------------- def set_edge_vector(self, edge_id: int, model: str, text_hash: str, vec: list[float]) -> None: """Cache one edge's vector, keyed by (edge_id, model, text_hash): switching models (or the edge text changing) invalidates cleanly — the probe re-embeds, the stale row is replaced. Append-only law is kept for QUOTES and EDGES; vectors are a derived cache, upserted.""" import struct blob = struct.pack(f"{len(vec)}f", *vec) self.db.execute( "INSERT OR REPLACE INTO edge_vectors(edge_id, model, text_hash, vec) " "VALUES(?,?,?,?)", (edge_id, model, text_hash, blob)) self.db.commit() def semantic_probe(self, qvec: list[float], tau: float = 0.45, limit: int = 20) -> list[EdgeView]: """Semantic retrieval: cosine rank ALL edges with a cached vector (for the current model) against the question vector, keep >= tau. nomic does not separate 'facts about the same entity' from 'facts that answer the question' (calibration: spouse 0.67) — the semantic layer RANKS and surfaces vocabulary the lexical probe cannot see ('Prime Minister' vs 'President'), the JUDGE still decides. At hundreds of edges brute force over cached blobs is instant.""" import struct from .embeddings import cosine as _cos out: list[EdgeView] = [] rows = self.db.execute( "SELECT v.edge_id, v.vec FROM edge_vectors v").fetchall() scored: list[tuple[float, EdgeView]] = [] for eid, blob in rows: n = len(blob) // 4 vec = struct.unpack(f"{n}f", blob) d = _cos(qvec, vec) if d < tau: continue ev = self._edge_view_by_id(eid) if ev is not None: scored.append((d, ev)) scored.sort(key=lambda t: -t[0]) return [ev for _, ev in scored[:limit]] def _edge_view_by_id(self, eid: int) -> EdgeView | 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 not e: return None conflict = self.db.execute( "SELECT 1 FROM conflicts WHERE edge_a=? OR edge_b=?", (eid, eid)).fetchone() (eid_, rel, dstv, dstn, rd, cor, pref, retr, quote, url, sname) = e return EdgeView( eid=eid, src=sname, rel=rel, dst=dstv, quote=quote, url=url, ref_date=rd, corroboration=cor, preferred=bool(pref), conflict=bool(conflict)) def member_sets(self) -> list[str]: """Distinct set names that have membership edges (rel='member_of').""" rows = self.db.execute( "SELECT DISTINCT dst_value FROM edges WHERE rel='member_of' AND retracted=0" ).fetchall() return [r[0] for r in rows] def list_members(self, set_name: str, ordered: bool = False) -> list[str]: """ALL elements of a set: every member_of edge pointing at set_name. Deterministic and COMPLETE with respect to what was ingested (the ingestion writes one edge per table row, untruncated). `ordered=True` returns members in SOURCE TABLE order when the ingest recorded ordinals (ranked tables rank); sets ingested before ordinals existed return [] (the caller must NOT pretend they are ranked).""" base = ("SELECT DISTINCT e.id, n.norm_name, e.list_ord FROM edges e " "JOIN nodes n ON n.id=e.src_node " "WHERE e.rel='member_of' AND e.retracted=0 " "AND lower(e.dst_value)=lower(?)") rows = self.db.execute(base, (set_name,)).fetchall() if ordered: if any(r[2] is None for r in rows): return [] # ordinal-free set: order is unknown, never guessed return [r[1] for r in sorted(rows, key=lambda r: r[2])] return sorted(r[1] for r in rows) def list_is_ordered(self, set_name: str) -> bool: """True when every member edge of this set carries a list ordinal.""" row = self.db.execute( "SELECT COUNT(*), COUNT(list_ord) FROM edges " "WHERE rel='member_of' AND retracted=0 AND lower(dst_value)=lower(?)", (set_name,)).fetchone() return bool(row) and row[0] > 0 and row[0] == row[1] def set_origins(self) -> list[tuple[str, str]]: """(set_name, origin_question) for every membership set — the gate matches a set to its own question, never to a different one.""" rows = self.db.execute( "SELECT DISTINCT dst_value, origin_question FROM edges " "WHERE rel='member_of' AND retracted=0 AND origin_question IS NOT NULL" ).fetchall() return [(r[0], r[1]) for r in rows] def set_provenance(self, set_name: str) -> tuple[str, str]: """(quote, url) of the first member edge of a set — provenance for list answers served from the KG.""" row = self.db.execute( "SELECT q.verbatim, q.url FROM edges e JOIN quotes q ON q.id=e.quote_id " "WHERE e.rel='member_of' AND e.retracted=0 AND lower(e.dst_value)=lower(?) " "LIMIT 1", (set_name,)).fetchone() return (row[0], row[1]) if row else ("", "") def close(self) -> None: self.db.close()