# Knowledge expert — design (v0.1 draft, pre-implementation) Status: DESIGN FOR REVIEW — nothing built yet. This document is the "pensem-lo bé". ## 0. What this expert is One attendant of the fleet, answering per the generic expert pattern (translate → check → solve → return), where the engine is **retrieval over sources plus a persistent typed store**. Its contract with the machine unchanged from ARCHITECTURE.md §4: - in: an instantiated question (+ parent question + referenced evidence rows) - out: typed evidence rows — **verbatim quote + url + access date**, never paraphrase - the KG (`KnowledgeStore`) is the expert's private engine-side memory: persistent across runs, append-only, fully provenance-tracked. Its novelty over GraphRAG/HippoRAG-style systems is the floop law applied as a real formal check: **every extracted fact must carry a verbatim span that is string-containment-verified against the fetched document text** — a cheap, deterministic, sound check that runs today (no solver needed). Nothing enters the store without it. Nothing leaves it without provenance. Prior art with measured numbers (verified 2026-10-10, re-verify before claiming current SOTA — skill convention): | System | Mechanism | Measured | What we take | |---|---|---|---| | HippoRAG (arXiv:2405.14831, NeurIPS'24) | KG + Personalized PageRank as retrieval | up to +20% multi-hop QA vs SOTA RAG; 10–30× cheaper and 6–13× faster than IRCoT | KG-first probe; single-step graph search replaces iterative LLM retrieval | | GraphRAG (arXiv:2404.16130, MSR) | LLM entity-extraction per chunk → graph → community summaries | 72–83% comprehensiveness win-rate vs vector RAG; up to 97% fewer tokens for global summaries; **bigger chunks = fewer calls but fewer entities extracted** | map-reduce extraction; the chunk-size tradeoff is a measured finding, not a guess | | ReWOO (arXiv:2305.18323) | plan-on-slots | 5× token efficiency | already in floop's orchestration; the expert must not duplicate it | | CYC (lesson, reference file) | manual knowledge acquisition killed the project | — | tiny closed ontology, auto-extraction, never hand-built | | LLM-Modulo (arXiv:2402.01817) | LLMs propose, external verifiers decide | — | quote-containment check = the verifier here | What is floop-native: the store's laws (append-only, retraction flags, TMS-ready provenance, closed ontology sort-checks) and the verbatim-span containment as a first-class gate. Also the *engine-first, LLM-second* loop inside the expert. ## 1. The two halves, as Emili framed them 1. **Store (the KG)** — persistent knowledge: entities, typed relations between them, and verbatim quotes backing every edge. Consulted FIRST. 2. **Gather (searcher + extractor)** — fills gaps: search → fetch → chunk → extract → check → store → select. Consulted for what the KG lacks. ## 2. The store — `KnowledgeStore` Format decision (recommendation): **SQLite** (single file, stdlib, auditable, zero infra) + **JSONL mirror** for human diff/audit. Graph algorithms via NetworkX loaded from the DB on demand. No vector DB, no server. When measured recall failure justifies embeddings, that is a later decision with numbers — not now. Schema (append-only; **no UPDATE/DELETE ever** — corrections and conflicts are new rows or retraction flags, TMS-ready like the evidence table): ``` documents(id, url, source, fetched_at, sha256, trusted, text_path) chunks(id, doc_id, section_path, position, char_start, char_end, sha256) quotes(id, doc_id, chunk_id, verbatim, url, access_date) -- canonical text nodes(id, norm_name, sort, mentions++ ) -- entity index edges(src_node, rel, dst_value, dst_node?, quote_id, subject?, extraction_confidence, ref_date?, -- temporal qualifier: the value's reference time supersedes?, -- edge id this refines (subsumption, case 3) preferred, -- default: the supersedes target is preferred retracted, retraction_reason?) -- TMS flag (case 4), never a delete conflicts(nodeA, rel, valueA, valueB, nodeA_quote, nodeB_quote) -- surfaced, never resolved silently ``` - Edges are **pointers**, not prose: `(Shor's algorithm, requires, Grover→…)`. The QUOTE carries the truth; the edge is the index structure that finds it. Relation names come from the closed ontology — that is how they pass checks. - `dst_value` for literal quantities: value + **unit** fields (Quantity sort). This is the bridge to `analytic`/`numeric`: knowledge extracts typed quantities; those experts compute on them. Neuro-symbolic payoff, by design. - Duplicate edge from two sources = **corroboration count** on the edge. Same subject+relation with two different literal values = never merged — the store **classifies** (KNOWLEDGE.md §2 "the four cases"): temporal change by qualifiers (both coexist, each with its period), supersession by subsumption test (supersedes link, preferred flag), and real contradiction → a `conflicts` row, surfaced, never silently resolved — the same "never silently pick a side" law the machine uses for user rows. Untyped qualifiers default to the contradiction case: a visible conflict is preferred to a guessed temporality. - Entity node identity, draft: `(normalized_name, sort)` with normalization = casefold + punctuation strip. Entity resolution is hard; the draft merges ONLY on normalized-name equality within the same sort. Everything else stays as separate nodes until evidence forces a merge decision (later, with LLM linker, measured). - KG probe (engine, deterministic): seed = question's mentions matched to nodes (lexical, draft; LLM linker later); traversal = BFS depth-1 neighborhood with corroboration-weighted ranking (draft). **PPR is the upgrade path** — HippoRAG's exact mechanism, one function away, adopt it when BFS recall measurably fails. No LLM inside the probe. ## 3. The closed ontology (the typed grammar) Same philosophy as the orchestrator's ~5 action schemas: tiny ontology, big discipline. Seed set (Emili extends at review): - Entity sorts: `PERSON, ORGANIZATION, CONCEPT, EVENT, QUANTITY, DOCUMENT, PLACE, DATE, OTHER` - Relations (subject_sort → object_sort, checked by the sort-checker): `HAS_PROPERTY, PART_OF, INSTANCE_OF, OCCURRED_AT(→DATE), LOCATED_AT(→PLACE), CAUSED_BY, REQUIRES(→CONCEPT), MEASURES(→QUANTITY), DEFINED_AS, AUTHORED_BY(→PERSON)` Checks (all deterministic, all code, no LLM): 1. **quote containment** — `verbatim span ⊆ document text` (against the FULL fetched text, not just the chunk, so chunk-boundary facts still validate) 2. **sort check** — a relation's endpoint sorts must match its declaration 3. **source trust** — url domain ∈ trusted list (`en.wikipedia.org` + family, `arxiv.org`; list in config) 4. **dedupe** — exact (node, rel, value, doc) repeated 5. quantity well-formedness — unit string parses, value parses ## 4. Gather — the pipeline inside one knowledge call One routed knowledge question = one internal pipeline run, bounded by budget: ``` question instantiate (already done by the machine) │ ▼ TRANSLATE (LLM): question + answer_type → retrieval focus: │ keywords, entry entities, what shape of fact closes the gap ▼ KG PROBE (engine): BFS from seeds → candidate edges + linked quotes │ gap report: is the question's answer_type coverable from what's found? │ YES → skip gather, go to SELECT ▼ SEARCH (engine): Wikipedia API (draft: wiki-only; general web injectable later) │ ≤ N rounds; known-entity docs fetched directly (probe already knows the URL) ▼ FETCH→CHUNK (engine): text extraction, section-aware split, size guard ▼ EXTRACT (LLM, map over chunks): candidates with verbatim spans │ bounded retries (≤3): invalid output → error fed back (Logic-LM style) ▼ CHECK (engine): containment, sorts, trust, dedupe — invalid candidates dropped+counted ▼ MERGE (engine): into store; corroboration counts, conflict rows ▼ SELECT (engine, deterministic: lexical overlap + corroboration; reranker later) │ ▼ return: top-k rows payload {quote, url, access_date, kg_corroboration} ``` LLM calls: TRANSLATE, EXTRACT-per-chunk (+ retries), and nothing else — the probe, search, chunking, checking, merging, selecting are all engines. That is the law compliance: the LLM translates; deterministic code decides what is valid, what is dedupe, what is ranked. ## 5. Context budget & chunking (the 16–32k constraint) - Extraction call input = prompt + ontology + chunk (+section header path). Target chunk **8k tokens (~32k chars)**, hard cap **12k (~48k chars)** — comfortable inside the 16–32k window with prompt+output headroom. - Chunking is **section-aware**: Wikipedia HTML → text with heading markers → chunks split at heading boundaries, then size-guard packed (no mid-section split unless a section alone exceeds the cap; then sentence-boundary split). Heading path carried as chunk context prefix. No overlap needed for the CHECK (containment runs against full text); a 1-sentence overlap only if extraction quality measurably needs it. - **Lexical gate before spending LLM calls** (GraphRAG's tax is real): chunk-level keyword filter (question keywords + entity names, casefold) — only chunks that hit earn an extraction call, up to `max_chunks_per_article_extracted` per article. All other chunks skip; the gate is transparent (logged: chunks skipped and why). - Token counting: chars/4 estimate in the draft (conservative); a real tokenizer when we get the first measured overrun. Estimator failure mode is "chunk slightly smaller than needed" — safe direction. - Numbers to respect when measuring later: GraphRAG's finding — bigger chunks save LLM calls but extract fewer entities; our 8k/12k split sits mid-spectrum by design; revisit with our own entity-yield numbers after first runs. ## 6. Budget & config mapping The expert's internal LLM calls charge the FLOOP run budget (the engine IS the budget owner; the machine's charge callback is passed in). New config block: ```yaml knowledge: trusted_domains: [en.wikipedia.org, es.wikipedia.org, ca.wikipedia.org, arxiv.org] max_search_rounds: 2 # per knowledge call max_articles_per_round: 3 chunk_tokens_target: 8000 # ~32k chars chunk_tokens_max: 12000 # hard ceiling per extraction call gate_min_hits: 1 # lexical gate: keyword hits needed to earn extraction max_chunks_extracted_per_article: 12 max_extract_retries: 3 # bounded self-refinement (the 3-attempts law) kg_max_new_nodes_per_call: 200 kg_probe_depth: 1 # BFS; PPR upgrade is planned, not implemented kb_path: knowledge_store/kg.sqlite (+ .jsonl mirror) ``` Failure → honesty: probe miss + search/fetch fail + all candidates rejected ⇒ the expert returns an UNKNOWN row (the machine's arrival check handles the cascade, seen working in Run A). A knowledge row without a containment-verified span **cannot exist**. Honesty markers on returned rows: the draft's rows stay `verified=False` (prover stub) but carry a strong, real note: `source-verified: verbatim containment in trusted doc` (+ corroboration count). That is a meaningful upgrade over the current stub expert, which appends unprovenanced drafts. ## 7. What is deliberately NOT in the draft (name it, don't hide it) - No vector/embedding retrieval — lexical + graph first; add when recall fails measurably (a decision with numbers, v-next). - No general-web search — Wikipedia only (trusted list); web-search injectable interface exists so tests are deterministic; real general search comes after the Wikipedia vertical is measured. - No PPR — BFS probe first (n-hop, corroboration-weighted); upgrade on evidence. - No LLM entity linker — normalized-name match first. - No conflict resolution — conflicts recorded and surfaced, never resolved. - No incremental KG maintenance policy (when to re-fetch for freshness) — access-date provenance is captured now; policy later. ## 8. Law compliance check (PIPELINE/ALGORITHM) | Law | How this design holds it | |---|---| | LLMs translate, never decide/compute | LLM does query-focus + span-extraction only; validity/ranking by code | | Engines never see NL | probe takes node ids; graph ops take typed inputs; selection on typed structure | | Append-only + provenance everywhere | store schema; retraction flags; conflicts recorded | | No paraphrase | quote-containment is the load-bearing check; edges point at quotes | | Multi-hop not inside the expert's LLM | hops inside the KG are GRAPH COMPUTATION (deterministic, auditable); LLM hops stay at orchestration | | Bounded refinement ≤3 | extraction retries capped by config | | Budget partition | internal calls charged; sub-budgets per article/round | ## 9. Build order (each step independently testable, no-network until real fetch) 1. `ontology.py` + `store.py` + `check.py` + tests (containment, sorts, trust, dedupe, conflicts) — no network, no LLM 2. `chunker.py` + tests on a fixture article text — no network 3. `extract.py` (dspy signatures + map-reduce) + tests with scripted fake LLM — no network 4. `search.py` real Wikipedia fetch + live smoke (one article, real containment) 5. `expert.py` — the kg-first pipeline wired as the machine's knowledge engine (replacing stub:knowledge), machine-level test with fakes 6. E2E live runs + RUNLOG entry + config knobs as built (not as designed) Draft layout: `floop/code/knowledge/{DESIGN.md, store.py, ontology.py, chunker.py, extract.py, check.py, search.py, expert.py, tests/…}` + `floop/code/knowledge_store/` (runtime artifacts, gitignore candidate). ## 10. Open decisions for Emili (veto/extend at review) 1. **Store format**: SQLite + JSONL mirror + NetworkX (recommended) vs RDF/ SPARQL (heavier) vs Neo4j (server). Recommended for auditability and zero-infra; RDF possible later via export. 2. **Ontology seed set** (§3): extend/trim the sort+relation list before build. 3. **Draft search scope**: Wikipedia-only first (recommended) vs adding a general-web search provider in the same cut. 4. **Chunk target**: 8k tokens with 12k cap inside your 16–32k window — ## 11. Lists and tables — two different problems (2026-10-18) **Full table ingestion vs answer completeness are different problems with different owners.** Emili's distinction, formalized: 1. **Full table ingestion (mechanical, always achievable).** Every table row the parser finds is ingested — no silent truncation, no gate dropping rows. The parser (deterministic) computes `total_rows`; that number is a computed fact, not a judgement. "Bigger than the chunk" is solved structurally: in the LIST path the LLM never sees the whole table — it only picks WHICH table and WHICH column is the enumeration (one cheap call, language work); fixed code ingests ALL rows and aggregates (thinking, zero calls). The table is never "chunked"; the problem disappears by design. 2. **Answer completeness (epistemic, often NOT assure-able, always flag-able).** A fetched table is complete *per source*; whether the ANSWER is complete depends on the sources consulted (partial articles, A–M / N–Z splits). Presence of rows proves membership; it never proves absence of unseen members. Every LIST answer therefore carries a typed `coverage` record — a computed flag, not a promise: what was consulted, what fraction of the candidate space was exhausted. floop is *aware* when completeness is guaranteed (one table, fully parsed) and when it is not (search space not exhausted). Part 2 (pending): surface the flag up to the machine so the synthesizer can say "27 of 52 ingested" honestly; and the planner can open "fetch the N–Z article" as an ordinary subquestion when coverage says the space is not exhausted. ### The LIST answer path (part 1, implemented in the draft) When a question is answered by an enumeration from a fetched source: 1. **SELECT TABLE** (LLM, one call): given the question and the list of tables found in candidate articles (title + headers + row count, NOT the rows), pick the table that enumerates the answer. Output: article title + table index + the column holding the answer elements. 2. **INGEST ROWS** (code): the chosen table's rows become membership edges — one edge per element (` | member_of | `), quote = the full stored table row, containment-checked against the stored table text. All rows, no truncation, no gate. 3. **AGGREGATE** (code): the answer value = sorted unique elements; the count = `len()` — never an LLM call. The result enters the evidence table as a typed payload: ```python {"value": "27", "list_items": ["Albania", ...], "list_count": 27, "quote": "", "url": "...", "coverage": {"source": "
", "rows_ingested": 52, "rows_total": 52, "complete_per_source": true}} ``` **Why per-row membership edges (not one fat edge).** One edge per element keeps the KG honest: each element carries its own quote and URL, conflicts and corroboration work per element, and set operations (filter, difference, count) are graph queries in deterministic code — the exact operations Q2–Q4 of the Europe plan needed. The set node (e.g. `countries of Europe`) is an ordinary node; membership is an ordinary edge; nothing new in the schema. **Containment target for table rows.** The quote of a membership edge is the full stored table row (post-`_clean_cell`, the canonical text). It is checked against the stored table text — the same string the parser produced — so the check stays verbatim and deterministic. The wikitext raw form is kept in the document artifact for audit. **Budget law in the LIST path.** TRANSLATE + SELECT TABLE are the only LLM calls (2 + retries); ingestion and aggregation are free. A 500-row table costs the same LLM budget as a 5-row one — the cost of an enumeration is O(1) in the size of the list. confirm or set preferred numbers.