Files
floop/code/knowledge/DESIGN.md
T
onibot dec1fccb53 knowledge: remove the TRANSLATE LLM — deterministic query composition
His 23/10 weights-tightness audit found the TRANSLATE step composing
search queries from its own knowledge of the entities: 'Pedro Sánchez
2018 investiture President of the Government of Spain' for a term-start
question (the '2018' IS the answer, steered into retrieval from weights),
'Po, Adige, Tiber' proposed as entities for a question that named only
Italy. Measured over every logged TRANSLATE call of runs 22-23/10: 5/10
calls carried untraceable query terms, 6/10 untraceable entity terms.

Probed against real Wikipedia before deciding: queries composed
deterministically from question ∪ evidence put the decisive article at
top-1/2 of the search in 8 of 9 cases — the LLM's world knowledge was
never load-bearing; the search engine's own relevance was. So the step
becomes code (the law: LLMs translate, fixed code composes — and here
nothing is left to translate).

- NEW knowledge/queries.py: compose_queries() + proper_nouns/keywords
  (moved here, single source — the expert delegates). Laws: every query
  token traces to the question or an evidence row; deterministic; never
  empty. Top-N asks slice the FIRST N evidence members by source order
  (never dump all members); enumerations with one subject NE get the
  list-article shape ('List of rivers of Italy'); sentence-initial
  capitals are dropped when other NEs exist ('During', 'Ranked').
- DELETED TranslateSignature + the Predict + the stage map entry;
  the gather charges one LLM call less.
- expert.py: COMPOSE at the gather head; the context var (rendered
  only for the dead prompt) removed — evidence feeds the probe seeds,
  the composer and the guards directly.
- Tests: knowledge/tests/queries.py (12) — the sonde's cases as the
  contract, incl. the traceback law over the logged questions.
- DESIGN.md §4 + code/README honest map updated.

Suite 17/17. Live probe (real Wikipedia): rivers/Pedro/France/Po all
fetch the decisive article at top-1.
2026-10-23 15:15:02 +02:00

383 lines
22 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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)
│
▼ COMPOSE (engine, 23/10 — the old TRANSLATE LLM removed): question ∪
│ evidence → queries + entity terms. Every token traces to the
│ question or an evidence row; the model's own knowledge of the
│ entities can no longer steer retrieval (it was putting the
│ ANSWER into queries). Top-N asks slice the first N evidence
│ members by source order; enumerations get the list-article
│ shape ('List of rivers of Italy').
▼ 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: EXTRACT-per-chunk (+ retries), SELECT TABLE (lists), VERIFY
COUNT, SKIM PROMOTE, and ANSWER — and nothing else. The query
composition, 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 — and since
23/10 even the retrieval focus is code (the old TRANSLATE LLM became
`knowledge/queries.py`: every query token traces to question ∪ evidence,
so no model weight ever steers retrieval).
## 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 (`<element> | member_of | <set>`), 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": "<first row>", "url": "...",
"coverage": {"source": "<article>", "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.** SELECT TABLE (and the optional VERIFY
COUNT) are the only LLM calls; ingestion and aggregation are free (the
query composition is engine since 23/10). 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.
## 12. Answer-level verification — the CHECK step for answers (2026-10-19)
Emili's case: the EU member list is 27 rows ingested from a table, AND the
same article's prose says "a supranational union of 27 member states" — two
independent statements of the same count. When the corroborating sentence
exists, the count is not just complete-per-source; it is **corroborated**.
The LIST path now runs this check (one bounded LLM call, never a loop):
```
ingested N members from table T (coverage: complete_per_source)
│
▼ VERIFY COUNT (LLM): given set_name + N + the article PROSE (the extract
│ text — tables live in a separate structure, so the source table is
│ excluded BY CONSTRUCTION), find ONE verbatim sentence stating the
│ count of that set. NOQUOTE if none exists.
▼ CHECK (code): containment of the sentence in the prose (same law as
every quote) AND the digits the sentence states == N. No LLM ever
compares numbers.
│
▼ verified row ⇔ complete_per_source AND count_corroborated
```
**Law split, again.** The LLM finds language (one sentence); fixed code
decides validity. `count_corroborated=False` is an HONEST state, not an
error: many lists have no prose count, and floop must never loop looking
for one. The row's payload carries the flag + the corroborating quote, so
the synthesizer can say "50, corroborated by the article's own prose" vs
"27, no independent count statement found".
**What this is NOT (scope honesty).** Same-article prose and table often
derive from the same primary data — corroboration here is *structural
independence* (two statements in different forms), not *source
independence*. Cross-article corroboration (fetch a second article and
find the same count) is future work: it costs another gather round and
most questions will never have the redundancy for it. We do not pretend
to strictness we do not have. Not every question will have a Wikipedia
page, let alone redundant sources — the design target is honest answers
grounded in fetched sources, not strict verification everywhere.
### Deferred (name it, don't hide it)
- **Extension verification** (proving exactly WHICH members, not just how
many): needs per-member confirmation, expensive; only when a question
asks "which ones" and stakes justify it.
- **Definitional criteria** (the 46/48/50 Europe case): when an independent
counter disagrees with our count, the LLM extracts the *criterion* each
citation uses, code compares the numbers, and a criterion-mismatch is a
*definition-dependent count* answer ("50 per the EOC definition, 46 per
the Council of Europe") — NOT a conflict row. Same criterion + different
number → conflict row, surfaced.
- **Prose-list completeness** (lists with no dedicated page, assembled from
prose extraction): a corroborating count is the only signal that says
"you missed members"; a mismatch means `partial`, a legitimate honest
state. Negative knowledge ("this list is not exhaustive") is itself a
verbatim quotable claim.
- **Cross-article corroboration** as a second, stronger check level.
Build order: count-corroboration now (cheap, saves the EU case), criteria
later (needs the extractor to output criterion labels), extension last.