Commit Graph
7 Commits
Author SHA1 Message Date
onibot 109885773c knowledge: typed Fact extraction via dspy native structured output
His direction: stop explaining string formats to the LLM and parsing
them back with Python — that's exactly what dspy does natively and
better. The pipe format ('subject | relation | object | quote') was
fragile (run-L verbose values, pipe-in-quote ambiguity, STOP_TABLE
string protocol).

THE CHANGE (extractor only, PR-10 scope):
- Fact(BaseModel) with subject/relation/object/quote OutputFields
- ExtractSignature.facts: list[Fact] — the adapter renders the JSON
  schema into the prompt itself (verified in a live run's prompt log)
  and parses responses back into typed Fact objects
- STOP_TABLE string protocol -> stop: bool OutputField
- expert.py consumes typed objects; the cand dict is built at the
  check_candidate boundary only (checks.py unchanged)
- parse_facts/parse_stop_table kept as LEGACY for existing tests only

VERIFIED:
- dspy 3.4.1 pattern E2E'd first with a raw-text engine: list[Fact]
  parses back as Fact objects, schema rendered in prompt (tmp probes)
- full suite 12/12 green (74 tests) — tablefrags.py updated to script
  typed Fact objects
- live E2E run (ollama-cloud glm-5.3-flash, Italy rivers): correct
  Po/Adige/Tiber answer; prompt log shows the native JSON schema;
  table rows ingested cleanly (22 rows, quotes verbatim)

NEXT (his direction, not this PR): apply the same typed-output law to
ALL floop signatures — INIT subquestions, ROUTE engine choice,
AnswerFromKG, SelectTable, SkimPromote, Translate, VerifyCount.
2026-10-22 14:21:13 +02:00
onibot 9eab127727 knowledge: table fragments for extract + exact prompt log (run G fixes)
Run G hung at call 8/80 for minutes with no way to see what was sent.
Reproducing it found TWO root causes, both fixed here:

1. THE 22K TABLE CHUNK WAS A PARSER BUG, not just a size problem. The
   world-rivers table marks each data row's leading cell with
   '!scope="row"|' (a row-label th); parse_tables flagged any row that
   touched a '!' as a header row, so all 227 data rows collapsed into ONE
   header of 1,825 cells and zero rows. tables_as_text then flattened
   that monster into a single 22,021-char prose chunk. Fix: a row is a
   header row only if ALL its cells are '!' cells; mixed rows are data
   rows. Live: the world table now parses as 8 cols x 227 rows.

2. NO PROMPT OBSERVABILITY. The log's CALL/OUTPUT lines never carried
   what the LM actually received. floop/llm.py now installs a dspy global
   callback (PromptLogCallback): every LM call's exact rendered prompt
   lands in runs/<ts>/prompts/NN-stage.txt (NN mirrors the budget counter
   -- 08-EXTRACT.txt IS call 8/80), plus size/duration lines in run.log.
   Stage comes from a module stack (dspy fires on_module_start with a
   DIFFERENT call_id than the inner LM call -- verified with DummyLM
   probes), not a call_id map.

Plus the design Emili steered (tables reach the extractor as typed
fragments, never prose dumps):
- tables_as_chunks: per-table fragments of <=40 rows, EVERY fragment
  repeats header + caption, part i/N markers; the extractor always knows
  which table ('troç 2/10') it is reading.
- STOP_TABLE: the extractor may early-skip a table whose subject is
  wrong for the question after one fragment; fixed code skips the rest
  of THAT table. ExtractSignature teaches the protocol.
- fetch_rich no longer appends the '== Tables ==' enrichment to prose
  (the giant chunk's birthplace; also let verify_count cite the table as
  'prose'). Tables reach the extract path only as fragments; LIST and
  harvest keep reading page.tables directly.
- fragment candidates pass the same containment check against prose +
  full table text; LIST answer's table never re-enters extract.

Tests: knowledge/tests/tablefrags.py (fragment generation/render,
STOP_TABLE skipping, fragment extraction with containment, prompt log
files + log lines). Live smoke: world article 10 chunks none >5k; world
table = 6 fragments (max 5,787c); Italy discharge fragment intact
(Po/1540). Full suite 47/47.
2026-10-20 20:22:29 +02:00
onibot 73fe5cc8e1 knowledge: PR-1 skim surfaces — read articles in passing (KNOWLEDGE §7)
The Italy run (Run G) failed with the data in hand: Q1's LIST ingest
early-exited on the length table and discarded the same article's 27-row
discharge table; the Adige/Tiber discharges live in infobox templates,
invisible to both the plain extract and parse_tables; and {{cvt|50|m3/s}}
cleaned to "50" — units silently dropped everywhere.

PR-1 builds the skim's surfaces and signals (deterministic, zero LLM):

- knowledge/skim.py: skim_article() builds a per-article SkimSheet —
  section headings with term hits, table identity (caption/headers/row
  count), infobox parameter keys with resolved quantity values, link
  candidates from goal-relevant regions — from material fetch_rich
  already downloads.
- quantity-unit patterns (find_quantities): "50 m3/s" is a
  vocabulary-independent signal; the Italy discharge section's heading
  says "above 50 m3/s", never "discharge" — this finds what keyword
  search cannot.
- wiki.resolve_convert: {{convert|N|unit}} resolves to "N unit" inside
  _clean_cell BEFORE the generic template pass (which kept only the first
  argument and dropped the unit). Captions and cells keep units.
- WikiPage.wikitext: fetch_rich stores the raw source (infobox surface).
- _process_page: gated chunks are RANKED by skim signals (question + goal
  terms + quantity patterns) instead of first-N in document order.

Live smoke (real Wikipedia, no LLM): the Italy sheet shows table 2
"Rivers of Italy above 50 m3/s of average flow at the mouth", 27 rows,
quantities 50/350/239/235/187/170 m3/s; the Adige sheet shows infobox
discharge1_avg = 235 m3/s.

Tests: 6 new (knowledge/tests/skim.py), suite 35/35 green.
PR-2 (opportunistic harvest + seen-index) and PR-3 (notices to the
machine) follow.
2026-10-20 14:52:38 +02:00
onibot e5482bd092 feat(logic): setop engine + set gate — the Europe count computed end-to-end
A) SET GATE: enumerations are answered only from membership sets, never from mention rows (the probe early-exit that served 'Armenia, Cyprus, Georgia, Turkey' to 'what countries are in Europe' is dead). Sets carry origin_question; the gate matches stem-Jaccard>=0.5 so a set is served to its own question only. B) SETOP ENGINE: logic's first real engine — a count over list rows is computed (difference/intersection/count over norm_name'd items, table markers 'Austria*' == 'Austria'), before ROUTE, zero LLM calls, verified=True because the computation IS the check. C) Catalog honesty: knowledge 'lists are ONE fetch', logic 'how-many over lists in evidence', floop 'NOT mere size'. Plus four substrate bugs the live runs exposed: LM-proxy prompt cache (instant answers are cache hits, never trust zero latency), _context rendering list rows as scalars ('E1: 50' routed 'those countries' to user), <br> concatenation in multi-value name cells, multi-line refs leaking into values ('franceincludes the 101 departments' -> France dropped from EU -> 24 not 23). Cold E2E: Q1 50 states ingested, Q2 27 EU members ingested, Q3 difference computed = 23, cited over E1/E2. 22/22 tests.
2026-10-18 19:49:24 +02:00
onibot 6fcb3c0a86 feat(knowledge): LIST answer path — full table ingestion, typed list payloads
Part 1 of the lists design (DESIGN.md §11): mechanical full ingestion, separated from epistemic answer-completeness. parse_tables rewritten as a GRID parser: cells accumulate until |- (both layouts), empty cells kept as placeholders (image cells clean to ''; dropping them shifted France rows to start at 'FRA'), rowspan/colspan expanded at placement, total_rows is the computed extent — no truncation. _clean_cell: refs/sup/File links dropped, citation templates (cref2/efn...) resolve empty, links take display text, attrs split first. LIST path in expert.py: deterministic enumeration detection OR planner-declared LIST; SELECT TABLE (one LLM call over table metadata, never rows); ingest ALL rows as member_of edges (quote = full row line, containment against stored table text); aggregate via len() — no LLM. AnswerType.LIST added; evidence payloads carry list_items + coverage. Verified live cold: 50 sovereign states from the Europe article table (51 rows - Total footer), every member with verbatim quote. 19/19 tests.
2026-10-18 16:53:10 +02:00
onibot 6db05fef48 fix(knowledge): cold-start gather — vertical tables, global rank, early exit
Emili's home run failed where the VPS seemed to work: warm-KG illusion; cold path never validated. Reproduced with a wiped KG. Fixes: (1) tables_as_text parses BOTH wikitext layouts (horizontal pipes and one-cell-per-line with row separators) + _clean_cell drops attrs/links/templates; (2) gather searches all queries, dedupes, ranks globally by title relevance, fetches ONE article at a time with EARLY EXIT when the KG answers; (3) hybrid order keeps each query's top-1 slot guaranteed (title relevance buries entity pages like 'Loire'). Also: NameError from refactor caught by baseline fallback; counters accumulate. Cold E2E verified: France (table quote) -> Loire (early exit, 1 article) in 2hops. RUNLOG Run D.
2026-10-17 10:39:34 +02:00
onibot 9094b2aec0 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.
2026-10-16 23:19:09 +02:00