"""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 # ---- phase 2: valid-time windows (RESEARCH-derived-answers Part 2) ----------- # A window is (start, end) with None = OPEN. Granularity is compared as # text (ISO-like, left-padded by the extractor: '2018' < '2018-06' < # '2018-06-02' all compare correctly as strings when normalized to the # finest stated granularity — a year window is the interval # [2018, 2019), honest to its precision). def _window(start: str | None, end: str | None) -> tuple[str | None, str | None] | None: """The window, or None when the fact states NO time at all (empty windows stay empty — no invention, no pretending).""" if not start and not end: return None return (start or None, end or None) def _overlaps(a: tuple[str | None, str | None], b: tuple[str | None, str | None]) -> bool: """Two valid-time windows overlap? None endpoints are OPEN (±inf). The boundary law (year granularity, honest to its precision): an end year CLOSES the window and the next start year OPENS there — [2014,2018) vs [2018,None) is SUCCESSION (the mandate changed hands in 2018), not coexistence. Overlap is max(starts) < min(ends); the open sides degenerate correctly: both starts None (share the indefinite past) or both ends None (both ongoing) always overlap. """ lo = max(a[0] or "-inf", b[0] or "-inf") hi = min(a[1] or "9999", b[1] or "9999") if lo == "-inf" or hi == "9999": return True return lo < hi # strict: touching at one year = succession 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 2: temporal windows (RESEARCH-derived-answers Part 2) ---- for col in ("t_start", "t_end"): if col not in cols: self.db.execute(f"ALTER TABLE edges ADD COLUMN {col} TEXT") self.db.commit() # fact_order: order assertions BETWEEN facts (edges are addressable; # reification is free). rel in {before, after, concurrent}. self.db.execute( "CREATE TABLE IF NOT EXISTS fact_order (" " id INTEGER PRIMARY KEY, edge_a INTEGER, edge_b INTEGER, " " rel TEXT, quote_id INTEGER, " " UNIQUE(edge_a, edge_b, rel))") 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, t_start: str | None = None, t_end: str | None = None) -> int | None: """Add an edge, applying the taxonomy (KNOWLEDGE.md §2 + the RESEARCH-derived-answers parts 1-2). t_start/t_end: the fact's VALID-TIME window as stated in the source ('since 2018' -> t_start='2018', t_end=None = OPEN). None/None when the text states no time — empty windows stay empty, no invention. 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, t_start, t_end " "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, t_start, t_end) " "VALUES(?,?,?,?,?,?,?,?,0,?,?,?)", (src, rel, dst_value, dst_node, quote_id, confidence, origin_question, ref_date, list_ord, t_start, t_end)) edge_id = cur.lastrowid for other_id, other_val, other_date, other_dn, other_q, o_ts, o_te 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, new_start=t_start, new_end=t_end, old_start=o_ts, old_end=o_te) 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 in ("temporal", "coasserted", "succession"): # both dated (series) / one sentence asserts both / disjoint # windows: the world holds or moves on — never a conflict pass 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 def add_fact_order(self, edge_a: int, edge_b: int, rel: str, quote_id: int | None = None) -> None: """Record a temporal-order assertion BETWEEN two facts (phase 2). The text asserts the order with a connective ('before becoming', 'at the same time as'); the extractor transcribes it as an order restriction, code verifies the connective's quote and stores it here. Edges are addressable — reification is free. rel is one of {before, after, concurrent} (the extractor's vocabulary; Allen's finer relations are computed views over the windows, never labels). """ if rel not in ("before", "after", "concurrent"): raise ValueError(f"unknown order relation {rel!r}") self.db.execute( "INSERT OR IGNORE INTO fact_order(edge_a, edge_b, rel, quote_id) " "VALUES(?,?,?,?)", (edge_a, edge_b, rel, quote_id)) self.db.commit() @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, new_start: str | None = None, new_end: str | None = None, old_start: str | None = None, old_end: str | None = None) -> str: """Deterministic taxonomy (KNOWLEDGE.md §2 + RESEARCH-derived-answers parts 1-2). 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 (ref_date), different dates — time series paraphrase tails resolve to the SAME node — the same fact alternatives co-true readings: overlapping VALID-TIME windows (two open ends overlap), or entity-ish values with different tails contradiction the residue: functional values, disjoint windows on a functional relation Interval arithmetic (phase 2): windows come from the text via the extractor (t_start/t_end, end=None = OPEN). Two windows OVERLAP -> coexistence -> alternatives. DISJOINT -> succession (never a conflict; the world just moved on). The comparison is honest: a window with no endpoints does not pretend to overlap. """ nv, ov = norm_name(new_val), norm_name(old_val) if nv == ov: return "duplicate" if new_quote is not None and new_quote == old_quote: return "coasserted" if ov and ov in nv and (new_date or old_date): return "supersedes" if new_date and old_date and new_date != old_date: return "temporal" # ---- phase 2: interval arithmetic over valid-time windows ------- new_w = _window(new_start, new_end) old_w = _window(old_start, old_end) if new_w and old_w: if _overlaps(new_w, old_w): return "alternatives" # coexistence is provable # disjoint: succession — not a conflict, not co-true either return "succession" if new_node and old_node and new_node == old_node: return "paraphrase" 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()