Commit Graph
18 Commits
Author SHA1 Message Date
emili 3d541ec8d6 TypeClaim does not need to rewrite the quote/verbatim 2026-11-01 17:12:32 +01:00
emili 4e7229c92c Extract verbatim in ExtractClaims not in TypeClaim 2026-11-01 16:47:47 +01:00
onibot a9837981b3 fix: two-pass Pass 2 needs the chunk text (quotes were invented) + claim cap
Live cloud run 20261026-164236 found both on the wire:
1. TypeClaim carried ONLY the claim — the model could not copy the
   verbatim quote from anywhere, so it invented one and the containment
   check rejected 69/70 candidates (the safety net working, the
   CONTRACT wrong). Fix: TypeClaim gains the chunk text; the model finds
   the real quote there ('find the VERBATIM quote here, copied exactly').
2. One charge per claim starved the budget: ~70 claims ate all 80
   llm_calls before Q2 (80/80, baseline fallback, no FINAL). Fix:
   max_claims_per_chunk=6 (each claim costs a TYPE call; without a cap
   one big article starves the run).

The speed win is real and kept: CLAIMS 14-20s/chunk, TYPE 2.8-8s/claim
(the 40-minute output budget is gone). Honest note: the cap bounds per
chunk, not the whole run (3 articles x 6 chunks x 7 calls ~ 126 > 80)
— if the run starves again, next lever is claim selection or a lower
cap, his call.

TDD: two_pass_extract 5/5 on the new contract (TypeClaim fields
{claim,text,fact}). Suite: 29 test files green.
2026-10-26 17:05:10 +01:00
onibot f6e9164e92 feat: two-pass EXTRACT (claims -> typed Facts) for prose chunks
His diagnosis accepted (26/10): the single-pass EXTRACT's giant typed
JSON array (verbatim quotes + temporal restrictions + sibling orders)
is the output budget behind the 40-minute arithmetic on slow local
models. Two-pass shortens EVERY output:

- Pass 1 ExtractClaims: plain claim strings, coreferences resolved
  (entities named, never pronouns) — near-zero format tax.
- Pass 2 TypeClaim: ONE claim -> one typed Fact per call (same Fact
  schema the store eats; temporal fields optional, containment-checked
  downstream as always). Orders NEVER produced here: one claim at a
  time has no siblings — the legacy Fact keeps orders for the
  single-pass path and table frags, untouched.
- extract_mode: two_pass (default) | single (legacy) — config-driven,
  read from config.yaml's knowledge block by run_app.
- Budget: Pass 1 charges once per chunk; Pass 2 charges once per
  claim. Table frags keep the legacy single-pass call.
- Prompt log: CLAIMS/TYPE stage labels added.

TDD: two_pass_extract 5/5 (signatures, coref law, honest empties) +
two_pass_wiring 2/2 (end-to-end on a real store: two_pass ingests
typed facts with windows kept; single-pass control green). Suite: 29
test files green. The router from #26 makes the upcoming
extraction-model swap a pure config edit.
2026-10-26 16:42:22 +01:00
onibot 99f8b6e9db knowledge: temporal restrictions layer (phase 2, RESEARCH-derived-answers Part 2)
The extractor's temporal vocabulary is RESTRICTIONS, never Allen labels:
typed Fact gains start/end/point (optional, ISO-ish) + granularity +
orders [{rel: before|after|concurrent, other: <sibling index>}] — the
text's connectives transcribed, not classified. The Allen algebra stays
a COMPUTED VIEW over endpoints.

- checks.py: every stated date must be CONTAINED IN THE QUOTE — an
  invented date rejects the whole candidate (LLM proposes, code
  verifies against the source surface).
- store.py: edges gain t_start/t_end (valid-time window, None end =
  OPEN, honest to 'since 2018'); fact_order table (order assertions
  between addressable facts — reification is free); _classify consumes
  interval arithmetic: overlapping open windows -> alternatives
  (coexistence provable, no statistics), disjoint windows ->
  succession (never a conflict). Boundary law at year granularity:
  [2014,2018) vs [2018,None) = succession — the mandate changed hands
  in 2018. add_fact_order validates rel in {before, after, concurrent}.
- expert.py: _ingest_candidate returns (merged, eid) and passes the
  windows; the prose path collects positional fact_ids and wires the
  orders' sibling references to real edge ids (malformed refs skip
  honestly).

Tests: temporal.py 6/6 (typed fields, containment rejection, open-
window overlap -> alternatives, touch-at-year -> succession, empty
stays empty, fact_order ingest) + 7/7 interval cases incl. the
open-past degenerate. Suite: all green.

LIVE (run 20261025-205018, cold KG, glm-5.3-flash): 29 edges carry
windows (Spain 2018 / PSOE 2017 / SI 2022 all open-ended), 25
fact_order rows (Madrid before Congress of Deputies...), 8 invented
end-dates REJECTED by the containment check (the footballer Pedro
articles — the check catching exactly what it should), 0 conflicts.
The run itself answered UNKNOWN on its Q1 ("what DATE did he take
office") — honest: the blind extractor did not transcribe the exact
date this run and the noisy re-probe view (four Pedros) is the known
branch weakness, not a phase-2 regression. Design note for phase 4:
the three presidencies live under DIFFERENT rels, so the alternatives
substrate must be queried trans-rel by the consumer (alternatives_of
is per-rel by construction).
2026-10-25 21:07:34 +01:00
onibot 096326e3a3 merge main (phase 0: K5 fix, --no-cache, import assert) into research/semantic-kg
Conflict resolutions, the honest way:
- extract/expert gap-step: main's deterministic COMPOSE wins over the
  branch's TRANSLATE LLM (main removed it 23/10 with measurement: the
  model was putting the ANSWER into retrieval queries). The branch's
  _extract_entities contract (question-blind extractor) is fed from
  compose's entities.
- tablefrags/semantic tests: restored the branch's adapted versions +
  fixed their single-insert sys.path bug (parent.parent resolved to
  knowledge/, not code/ — the tests were silently importing MAIN's
  expert.py through the venv pth; same class as the run-085457 trap).
2026-10-25 20:04:47 +01:00
onibot 985aec2f60 Phase 0 — judge value cleanup + --no-cache + import assert
The (K5) bug fix (his 24-25/10 session): glm-5.3-flash glues row
citations and glosses onto the judge's value field, killing the ablation
audit silently ("the judge invented it: nothing to ablate") and leaking
LLM prose into typed payloads. Fixed at the judge's output boundary
(_answer_from_rows): trailing-only, marker-anchored cleanup (_clean_value)
that strips the three live citation shapes and survives legitimate
parentheticals ("(PSOE)", "(since 2018)"). The AnswerFromKG value desc
now says what the value must be.

--no-cache CLI flag (his ruling: the dspy disk cache is not a bug, the
default stays; the flag exists for A/B and freshness testing) — builds
dspy.LM with cache=False for the process; verified live: repeated runs
re-run real inference instead of replaying.

Import assert at startup: floop/knowledge SUBMODULE files must resolve
inside this repo's tree. Namespace-package __path__ lies (it recomputes
dynamically and lists every tree), so the check pins the actual module
files (run 085457 was main's pipeline inside the branch worktree, no
signal). Abort loudly, don't log.
2026-10-25 20:00:34 +01:00
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
onibot 872d4b9d42 research(knowledge): semantic KG retrieval + question-blind extraction
Implements his design (RESEARCH-semantic-kg.md) on the research branch:

1. EMBEDDINGS (knowledge/embeddings.py): local ollama /api/embed,
   nomic-embed-text 768d — the only proven endpoint (ollama.com has
   NO embeddings API). Honest failure: EmbedderDown -> lexical probe
   fallback, never a dead run.

2. SEMANTIC PROBE: edge_vectors cache in the store (keyed edge_id +
   model + text_hash; upsert, last model wins), cosine rank over all
   cached edges, tau=0.45 from real calibration (rivers 0.49-0.52 must
   pass; cross-question Pedro-vs-rivers 0.35-0.38 must not). Hybrid
   _probe: lexical UNION semantic, dedup by eid. EdgeView gains eid.

3. QUESTION-BLIND EXTRACTION: ExtractSignature loses 'question' and
   stop_table — it receives ENTITIES only (from TRANSLATE + evidence
   + proper nouns) and transcribes their facts, capped per chunk
   (max_facts_per_chunk=12). Facts cache vectors at ingest. The KG
   fattens per-entity, reusable across questions (his cacheability
   argument).

4. STOP MOVES TO THE SKIM: SkimTableSignature decides per table from
   caption+header+row count+first rows (one LLM call per page) BEFORE
   any extraction spend; tables that literally name an entity skip the
   call. The extractor itself never judges relevance.

VERIFIED: knowledge suite 8/8 (semantic.py new 4/4: lexical-missed edge
surfaced, hybrid dedup, embedder-down degradation, cache upsert;
tablefrags adapted: skim kills tables pre-extract). floop suite 9/9.
Live E2E (glm): semantic probe fires live (+1 lexical-missed edge);
blind extractor ingests 12-fact chunks; Pedro run answers 'himself'
(3rd gov succeeded his 2nd — a reading trap, NOT a retrieval failure;
INIT degraded honestly on garbage); rivers run burned budget on
fan-out ROUTE calls (22x2) — both findings logged as open work on the
research doc, not regressions of this PR.
2026-10-23 08:44:36 +02:00
onibot c257e9fe88 knowledge: rename ExtractSignature.stop -> stop_table (his review)
The field's purpose was unclear from its name; stop_table says what it
stops. Renamed across the signature, its desc/docstring, the caller
(raw.stop_table), the wiki.py legacy note, and the test fakes.
2026-10-22 16:26:03 +02:00
onibot 65d42d1942 knowledge: typed outputs for all 5 remaining signatures (block PR)
The typed-output migration completes: every knowledge signature now
declares its structure as Python types and dspy renders/parses it.

- TranslateSignature: queries/entities as list[str] — the
  'QUERIES:'/'ENTITIES:' line protocol and its prefix-scraping parser
  are gone
- AnswerFromKG: confidence is a local Confidence(str, Enum)
  (knowledge stays decoupled from floop)
- SelectTableSignature: chosen is TableChoice | None (index int,
  column, set_name) — 'NONE' string handling gone; origin_question
  dropped (it duplicated the input)
- SkimPromoteSignature: decisions as list[PromotionDecision]
  (table_index int, promote bool, column) — the 'idx: YES col' regex
  parser gone
- VerifyCountSignature: unchanged shape (quote str + NOQUOTE
  convention predates typed migration; kept — it is an answer-shaped
  field, not a format protocol)

Callers consume typed objects directly. Test fakes updated to the new
contracts (promote/store/guards).

VERIFIED:
- suite 14/14 green (84 tests)
- live E2E (ollama-cloud glm-5.3-flash, Italy rivers, fresh KG):
  correct answer 2014 m3/s (Po 1540 + Adige 235 + Tiber 239) with
  verified join; wire prompts show list[str]/TableChoice/Confidence/
  list[Fact] schemas rendered natively
2026-10-22 15:11:33 +02:00
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 1ebb4cfc0d knowledge: PR-3 skim notices to the loop + bounded lead promotion
PR-1 made the skim SEE (surfaces + signals); PR-2 made it HARVEST
deterministically. PR-3 closes the loop (KNOWLEDGE.md §7):

- Skim notices: every knowledge answer's stats carry what the fetched
  articles contained beyond the answer (table identities, infobox
  quantities, link candidates, goal-filtered). The engine copies them
  into payload['skim']; the machine renders them to the ROUTER context
  ('seen in passing (E1): ...') and to the run notes — later steps know
  what exists and where it lives instead of re-searching blind. A notice
  is a pointer, never evidence: it answers nothing by itself.
- Bounded lead promotion (Emili's 'deterministic + LLM fallback'):
  quantity tables that match NO goal word are queued as leads (PR-2);
  now ONE dspy call (SkimPromoteSignature) decides over the tables'
  IDENTITY lines (caption/headers/rows/quantities — never the rows),
  per fetched page with leads, only when leads exist. The LLM proposes;
  fixed code disposes: a promoted table still passes the entity-overlap
  check (a world discharge table is refused for Po/Adige/Tiber), the
  named column must exist, and ingestion goes through the same
  containment-checked _ingest_scalar_table as the deterministic path.
- Refactor: row ingestion extracted to _ingest_scalar_table (shared by
  harvest + promotion); _entity_overlap_count shared; skim state
  (_skim_notices/_skim_leads/_current_goal_question) reset per call.
- find_quantities: fix plain-digit quantities ('1540 m3/s', '1000 m3/s')
  — the thousands-separator-only regex missed them, and caption+header
  now join with a space ('m3/sRiver' broke the unit boundary).

Live smoke (real Wikipedia, scripted decision): goal terms without
'flow' queue both Italy tables as leads; the promoted 'Flow at the
mouth' table ingests all 27 rivers (Po 1540, Adige 235, Tiber 239
m3/s) containment-checked; promotion of the length table with a
'Flow' column name is refused (column does not exist).

Tests: 4 new (knowledge/tests/promote.py); suite 43/43 green.
2026-10-20 16:24:43 +02:00
onibot 852db78c99 knowledge: answer-level count corroboration (DESIGN §12) — LIST rows verified via prose
- VerifyCountSignature: LLM finds ONE verbatim sentence in the article prose
  (tables excluded by construction) stating the set's count
- _verify_count: code checks containment + digit equality — no LLM compares
  numbers; NOQUOTE -> count_corroborated=false (honest, one call, never loops)
- row verified <=> complete_per_source AND count_corroborated
- DESIGN §12 documents now vs deferred (extension, criteria, cross-article)
- live: EU question cold — E1 (50) + E2 (27) both corroborated with quotes,
  23 computed; 25/25 tests
2026-10-19 14:47:18 +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 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