Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(ultrawiki): word search over a meaning-neighbourhood of terms
rubenluetke10-beep5d680391cbe3
diff --git a/jarvis/core/config.py b/jarvis/core/config.pyindex c3bb4c8a33..30fa979a0d 100644--- a/jarvis/core/config.py+++ b/jarvis/core/config.py@@ -2353,6 +2353,25 @@ class UltraWikiConfig(BaseModel):# (the epsilon-sized recency tiebreak still settles exact ties).recency_half_life_days: float = 180.0+ # -- word lexicon (jarvis/ultrawiki/lexicon.py) --------------------------+ # The vocabulary index behind word search: every term the corpus uses,+ # embedded into the SAME space as the passages, so one word can be+ # expanded into the ~20 terms nearest it by meaning.+ #+ # false stops the background harvest and the term embedding. Word search+ # keeps working — it falls back to neighbours derived from which words+ # keep company with the query in real passages, which needs no provider+ # at all — it is simply blunter. Existing rows are left untouched.+ lexicon_enabled: bool = True+ # Ceiling on how many terms ever carry a vector. The vocabulary itself is+ # unbounded (a term still answers an exact lookup for free); this bounds+ # the part that costs embedding calls, most-seen terms first. ~20 000+ # covers the working vocabulary of a personal corpus in several languages+ # at roughly the cost of embedding 20 000 very short texts, once.+ lexicon_max_terms: int = 20000+ # How many neighbours a word search asks for when the caller does not say.+ word_search_neighbours: int = 20+class WikiContextConfig(BaseModel):"""Configuration for the wiki context injector (B5 Agent C).diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/AskPanel.test.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/AskPanel.test.tsxindex 6911ac636d..9ccfae126b 100644--- a/jarvis/ui/web/frontend/src/components/ultrawiki/AskPanel.test.tsx+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/AskPanel.test.tsx@@ -37,6 +37,12 @@ const HIT: UltraWikiSearchHit = {// Empty means "the item's own stamp IS timestamp_utc" — the shape every// leg but the event leg produces.recorded_utc: "",+ // Passage provenance: the vector leg names the chunk it matched, the+ // keyword leg cannot, and null is that honest "cannot say".+ document_id: null,+ chunk_index: null,+ char_start: null,+ char_end: null,};function installFetchMock(routes: Record<string, () => unknown>) {diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/WordSearchPanel.test.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/WordSearchPanel.test.tsxnew file mode 100644index 0000000000..4da4a63359--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/WordSearchPanel.test.tsx@@ -0,0 +1,265 @@+/**+ * WordSearchPanel tests.+ *+ * The load-bearing cases are the ones a blank screen would hide: each empty+ * outcome has its OWN named cause and its own way out, neighbours derived+ * from co-occurrence must not be presented as neighbours by meaning, and a+ * hit has to say WHICH passage answered — the span is the whole point of the+ * feature, and rendering only a snippet would silently undo it.+ */+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";++import { WordSearchPanel } from "@/components/ultrawiki/WordSearchPanel";++const NEIGHBOURS = [+ { term: "sailing", similarity: 0.94, doc_freq: 12 },+ { term: "mainsail", similarity: 0.88, doc_freq: 7 },+];++const HIT = {+ item_id: 11,+ source_id: "src1",+ title: "Race notes",+ snippet: "the regatta briefing",+ permalink: "app://a",+ timestamp_utc: "2026-07-08T10:00:00Z",+ score: 0.42,+ matched_by: ["word", "semantic"],+ passages: [+ {+ document_id: 91,+ chunk_index: 4,+ char_start: 3600,+ char_end: 4480,+ text: "the regatta briefing and the mainsail trim we agreed on",+ terms: ["regatta", "mainsail"],+ score: 1.88,+ },+ ],+};++const OK_RESPONSE = {+ word: "regatta",+ status: "ok",+ neighbour_source: "vector",+ reason: "",+ neighbours: NEIGHBOURS,+ results: [HIT],+ total: 1,+ lexicon: { terms: 900, embedded_terms: 900, items: 40, passages: 300 },+};++function makeClient(): QueryClient {+ return new QueryClient({+ defaultOptions: { queries: { retry: false, gcTime: 0, staleTime: 0 } },+ });+}++function renderPanel(props: Record<string, unknown> = {}) {+ return render(+ <QueryClientProvider client={makeClient()}>+ <WordSearchPanel {...props} />+ </QueryClientProvider>,+ );+}++/** Route every word-search call to `body`, recording the URLs asked for. */+function installRoute(body: unknown) {+ const urls: string[] = [];+ const fetchMock = vi.fn(async (input: RequestInfo | URL) => {+ const url = String(input);+ urls.push(url);+ if (!url.startsWith("/api/ultrawiki/word-search")) {+ throw new Error(`unrouted fetch: ${url}`);+ }+ if (body instanceof Error) throw body;+ return { ok: true, status: 200, json: async () => body } as unknown as Response;+ });+ vi.stubGlobal("fetch", fetchMock);+ return urls;+}++async function searchFor(word: string) {+ fireEvent.change(screen.getByTestId("ultrawiki-word-input"), {+ target: { value: word },+ });+ fireEvent.click(screen.getByTestId("ultrawiki-word-submit"));+}++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++describe("the neighbourhood", () => {+ it("shows the nearest words and sends the query to the backend", async () => {+ const urls = installRoute(OK_RESPONSE);+ renderPanel();+ await searchFor("regatta");++ const chips = await screen.findByTestId("ultrawiki-word-neighbours");+ expect(within(chips).getByText("sailing")).toBeTruthy();+ expect(within(chips).getByText("mainsail")).toBeTruthy();+ expect(urls.some((url) => url.includes("word=regatta"))).toBe(true);+ });++ it("re-runs the search when a neighbour chip is clicked", async () => {+ const urls = installRoute(OK_RESPONSE);+ renderPanel();+ await searchFor("regatta");+ fireEvent.click(await screen.findByTestId("ultrawiki-word-chip-sailing"));++ await waitFor(() =>+ expect(urls.some((url) => url.includes("word=sailing"))).toBe(true),+ );+ });++ it("does not present neighbours by company as neighbours by meaning", async () => {+ // The two similarity numbers are not comparable, so the heading has to+ // say which one the reader is looking at.+ installRoute({+ ...OK_RESPONSE,+ neighbour_source: "cooccurrence",+ reason: "nothing has been embedded yet",+ });+ renderPanel();+ await searchFor("regatta");++ const chips = await screen.findByTestId("ultrawiki-word-neighbours");+ expect(chips.textContent).toContain("keep company");+ expect(chips.textContent).not.toContain("Closest in meaning");+ expect(+ (await screen.findByTestId("ultrawiki-word-reason")).textContent,+ ).toContain("nothing has been embedded yet");+ });+});++describe("passages", () => {+ it("names the passage that answered, with its character span", async () => {+ installRoute(OK_RESPONSE);+ renderPanel();+ await searchFor("regatta");++ const passage = await screen.findByTestId("ultrawiki-word-passage-11-91");+ // chunk_index is zero-based on the wire and one-based on screen.+ expect(passage.textContent).toContain("passage 5");+ expect(passage.textContent).toContain("3600");+ expect(passage.textContent).toContain("4480");+ expect(passage.textContent).toContain("regatta, mainsail");+ });++ it("falls back to the snippet when the item has no stored passages", async () => {+ installRoute({ ...OK_RESPONSE, results: [{ ...HIT, passages: [] }] });+ renderPanel();+ await searchFor("regatta");++ expect(+ (await screen.findByTestId("ultrawiki-word-snippet-11")).textContent,+ ).toContain("the regatta briefing");+ });++ it("labels which leg found the hit", async () => {+ installRoute(OK_RESPONSE);+ renderPanel();+ await searchFor("regatta");++ expect(await screen.findByTestId("ultrawiki-word-leg-11-word")).toBeTruthy();+ expect(screen.getByTestId("ultrawiki-word-leg-11-semantic")).toBeTruthy();+ });+});++describe("empty outcomes name their own cause", () => {+ it("sends an empty store to the sources screen", async () => {+ installRoute({+ ...OK_RESPONSE,+ status: "empty_index",+ reason: "nothing has been imported yet",+ neighbours: [],+ results: [],+ total: 0,+ lexicon: {},+ });+ const onOpenSources = vi.fn();+ renderPanel({ onOpenSources });+ await searchFor("regatta");++ expect(+ (await screen.findByTestId("ultrawiki-word-reason")).textContent,+ ).toContain("nothing has been imported yet");+ fireEvent.click(screen.getByTestId("ultrawiki-word-open-sources"));+ expect(onOpenSources).toHaveBeenCalled();+ });++ it("tells an unknown word apart from a word that ranks nowhere", async () => {+ installRoute({+ ...OK_RESPONSE,+ status: "unknown_word",+ reason: "'zzz' does not occur anywhere in the imported text",+ neighbours: [],+ results: [],+ total: 0,+ });+ renderPanel();+ await searchFor("zzz");++ expect(+ (await screen.findByTestId("ultrawiki-word-reason")).textContent,+ ).toContain("does not occur anywhere");+ expect(screen.queryByTestId("ultrawiki-word-results")).toBeNull();+ });++ it("offers the settings screen when the neighbourhood is unavailable", async () => {+ installRoute({+ ...OK_RESPONSE,+ status: "neighbours_unavailable",+ neighbour_source: "none",+ reason: "no embedding provider is configured",+ neighbours: [],+ });+ const onOpenSettings = vi.fn();+ renderPanel({ onOpenSettings });+ await searchFor("regatta");++ fireEvent.click(await screen.findByTestId("ultrawiki-word-open-settings"));+ expect(onOpenSettings).toHaveBeenCalled();+ // The hits are still shown: the word search ran, only the expansion did not.+ expect(screen.getByTestId("ultrawiki-word-results")).toBeTruthy();+ });++ it("says the word index is still filling instead of showing nothing", async () => {+ installRoute({+ ...OK_RESPONSE,+ status: "no_matches",+ reason: "nothing survived ranking",+ results: [],+ total: 0,+ lexicon: { terms: 900, embedded_terms: 120 },+ });+ renderPanel();+ await searchFor("regatta");++ const note = await screen.findByTestId("ultrawiki-word-lexicon");+ expect(note.textContent).toContain("120");+ expect(note.textContent).toContain("900");+ });++ it("reports a failed request instead of an empty panel", async () => {+ installRoute(new Error("boom"));+ renderPanel();+ await searchFor("regatta");++ expect((await screen.findByTestId("ultrawiki-word-error")).textContent).toContain(+ "boom",+ );+ });+});diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/WordSearchPanel.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/WordSearchPanel.tsxnew file mode 100644index 0000000000..8ebbdbbe84--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/WordSearchPanel.tsx@@ -0,0 +1,395 @@+/**+ * Words view: type ONE word, see the ~20 terms nearest it by meaning, and the+ * passages that neighbourhood reaches (`GET /api/ultrawiki/word-search`).+ *+ * Why this is its own tab and not a mode of Ask: Ask answers a question and+ * shows an answer. This answers a word and shows a MAP — the neighbourhood+ * first, because half the value is discovering how the corpus actually spells+ * the thing you were hunting, and the passages second, each with the span it+ * came from rather than the head of a file.+ *+ * Honesty rules this screen keeps:+ * - every empty result names its own cause (`status`), never a blank list;+ * - neighbours derived from co-occurrence rather than from meaning say so,+ * because the two numbers are not comparable;+ * - a chip is clickable and re-runs the search on that word, which is the+ * whole point of a neighbourhood you can see.+ */+import { useState } from "react";+import { ExternalLink, Loader2, Sparkles, Type } from "lucide-react";+import { useQuery } from "@tanstack/react-query";++import { cn } from "@/lib/utils";+import { useT } from "@/i18n";+import {+ wordSearchUltraWiki,+ type UltraWikiPassage,+ type UltraWikiTermNeighbour,+ type UltraWikiWordHit,+ type UltraWikiWordSearchResponse,+} from "@/lib/ultrawikiApi";++export function WordSearchPanel({+ onOpenSources,+ onOpenSettings,+}: {+ onOpenSources?: () => void;+ onOpenSettings?: () => void;+}): JSX.Element {+ const t = useT();+ const [input, setInput] = useState("");+ const [submitted, setSubmitted] = useState("");++ const query = useQuery({+ queryKey: ["ultrawiki", "word-search", submitted],+ queryFn: () => wordSearchUltraWiki(submitted),+ enabled: submitted.length > 0,+ retry: false,+ staleTime: 5_000,+ });++ const data = query.data ?? null;+ const runWord = (word: string) => {+ setInput(word);+ setSubmitted(word);+ };++ return (+ <div className="flex h-full min-h-0 flex-col p-4" data-testid="ultrawiki-word-panel">+ <form+ className="flex items-center gap-2"+ onSubmit={(e) => {+ e.preventDefault();+ setSubmitted(input.trim());+ }}+ >+ <div className="relative flex-1">+ <Type+ className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"+ aria-hidden+ />+ <input+ type="search"+ value={input}+ onChange={(e) => setInput(e.target.value)}+ placeholder={t("ultrawiki.words.placeholder")}+ aria-label={t("ultrawiki.words.placeholder")}+ data-testid="ultrawiki-word-input"+ className="w-full rounded-lg border border-border bg-background py-2 pl-9 pr-3 text-sm text-foreground placeholder:text-muted-foreground/70 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/40"+ />+ </div>+ <button+ type="submit"+ disabled={input.trim().length === 0}+ data-testid="ultrawiki-word-submit"+ className="rounded-lg border border-border bg-card px-3 py-2 text-sm text-foreground transition-colors hover:bg-secondary disabled:cursor-not-allowed disabled:opacity-50"+ >+ {t("ultrawiki.words.submit")}+ </button>+ </form>++ <p className="mt-1.5 text-[11px] text-muted-foreground">+ {t("ultrawiki.words.explainer")}+ </p>++ <div className="mt-3 min-h-0 flex-1 overflow-y-auto">+ {!submitted ? (+ <p+ className="py-6 text-sm text-muted-foreground"+ data-testid="ultrawiki-word-idle"+ >+ {t("ultrawiki.words.idle")}+ </p>+ ) : query.isFetching ? (+ <div className="flex items-center gap-2 py-6 text-sm text-muted-foreground">+ <Loader2 className="h-4 w-4 animate-spin" aria-hidden />+ {t("ultrawiki.words.searching")}+ </div>+ ) : query.isError ? (+ <p+ className="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive"+ role="alert"+ data-testid="ultrawiki-word-error"+ >+ {t("ultrawiki.words.failed").replace(+ "{0}",+ (query.error as Error).message,+ )}+ </p>+ ) : data ? (+ <WordSearchBody+ data={data}+ onPickWord={runWord}+ onOpenSources={onOpenSources}+ onOpenSettings={onOpenSettings}+ />+ ) : null}+ </div>+ </div>+ );+}++function WordSearchBody({+ data,+ onPickWord,+ onOpenSources,+ onOpenSettings,+}: {+ data: UltraWikiWordSearchResponse;+ onPickWord: (word: string) => void;+ onOpenSources?: () => void;+ onOpenSettings?: () => void;+}): JSX.Element {+ const t = useT();+ const byMeaning = data.neighbour_source === "vector";++ return (+ <div className="space-y-4">+ {/* The neighbourhood leads: it is the answer to "how does this corpus+ spell the thing I am after", which is often all the user needed. */}+ {data.neighbours.length > 0 && (+ <section data-testid="ultrawiki-word-neighbours">+ <p className="mb-1.5 flex flex-wrap items-center gap-1.5 text-[10px] uppercase tracking-[0.14em] text-muted-foreground">+ <Sparkles className="h-3 w-3" aria-hidden />+ {(byMeaning+ ? t("ultrawiki.words.neighbours_meaning")+ : t("ultrawiki.words.neighbours_company")+ ).replace("{0}", data.word)}+ </p>+ <ul className="flex flex-wrap gap-1.5">+ {data.neighbours.map((neighbour) => (+ <NeighbourChip+ key={neighbour.term}+ neighbour={neighbour}+ byMeaning={byMeaning}+ onPick={onPickWord}+ />+ ))}+ </ul>+ </section>+ )}++ {data.reason && (+ <p+ className="rounded-md border border-[#ffb84d]/30 bg-[#ffb84d]/10 px-3 py-2 text-xs text-[#ffb84d]"+ data-testid="ultrawiki-word-reason"+ >+ {data.reason}+ {data.status === "empty_index" && onOpenSources && (+ <button+ type="button"+ onClick={onOpenSources}+ className="ml-1.5 underline underline-offset-2 hover:text-foreground"+ data-testid="ultrawiki-word-open-sources"+ >+ {t("ultrawiki.progress.open_sources")}+ </button>+ )}+ {data.status === "neighbours_unavailable" && onOpenSettings && (+ <button+ type="button"+ onClick={onOpenSettings}+ className="ml-1.5 underline underline-offset-2 hover:text-foreground"+ data-testid="ultrawiki-word-open-settings"+ >+ {t("ultrawiki.panel.open_settings")}+ </button>+ )}+ </p>+ )}++ {data.results.length > 0 ? (+ <section>+ <p className="mb-1.5 text-[10px] uppercase tracking-[0.14em] text-muted-foreground">+ {t("ultrawiki.words.passages_heading").replace(+ "{0}",+ String(data.total),+ )}+ </p>+ <ul className="space-y-2" data-testid="ultrawiki-word-results">+ {data.results.map((hit) => (+ <WordHitRow key={`${hit.item_id}-${hit.permalink}`} hit={hit} />+ ))}+ </ul>+ </section>+ ) : (+ <LexiconNote lexicon={data.lexicon} />+ )}+ </div>+ );+}++function NeighbourChip({+ neighbour,+ byMeaning,+ onPick,+}: {+ neighbour: UltraWikiTermNeighbour;+ byMeaning: boolean;+ onPick: (word: string) => void;+}): JSX.Element {+ const t = useT();+ return (+ <li>+ <button+ type="button"+ onClick={() => onPick(neighbour.term)}+ title={(byMeaning+ ? t("ultrawiki.words.chip_hint_meaning")+ : t("ultrawiki.words.chip_hint_company")+ )+ .replace("{0}", neighbour.similarity.toFixed(2))+ .replace("{1}", String(neighbour.doc_freq))}+ data-testid={`ultrawiki-word-chip-${neighbour.term}`}+ className={cn(+ "rounded-full border px-2 py-0.5 text-xs transition-colors",+ byMeaning+ ? "border-primary/40 bg-primary/10 text-primary hover:bg-primary/20"+ : "border-border text-muted-foreground hover:bg-secondary hover:text-foreground",+ )}+ >+ {neighbour.term}+ </button>+ </li>+ );+}++/**+ * The retrieval legs of jarvis/ultrawiki/word_search.py::_retrieve. Looked up+ * by membership rather than by building a key: `t()` echoes an unknown key+ * back verbatim, so a leg added on the server would render as+ * "ultrawiki.words.leg_whatever" instead of as its own name.+ */+const WORD_LEG_LABEL_KEY: Record<string, string> = {+ word: "ultrawiki.words.leg_word",+ semantic: "ultrawiki.words.leg_semantic",+ related: "ultrawiki.words.leg_related",+ neighbourhood: "ultrawiki.words.leg_neighbourhood",+};++function WordHitRow({ hit }: { hit: UltraWikiWordHit }): JSX.Element {+ const t = useT();+ return (+ <li+ className="rounded-xl border border-border bg-card/40 p-3"+ data-testid={`ultrawiki-word-hit-${hit.item_id}`}+ >+ <div className="flex flex-wrap items-center justify-between gap-2">+ <span className="text-sm font-medium text-foreground">+ {hit.title || hit.snippet.slice(0, 60)}+ </span>+ <span className="flex flex-wrap items-center gap-1.5">+ {hit.matched_by.map((leg) => (+ <span+ key={leg}+ className={cn(+ "rounded-full border px-1.5 py-0.5 text-[10px]",+ leg === "semantic" || leg === "neighbourhood"+ ? "border-primary/40 bg-primary/10 text-primary"+ : "border-border text-muted-foreground",+ )}+ data-testid={`ultrawiki-word-leg-${hit.item_id}-${leg}`}+ >+ {leg in WORD_LEG_LABEL_KEY ? t(WORD_LEG_LABEL_KEY[leg]) : leg}+ </span>+ ))}+ </span>+ </div>++ {hit.passages.length > 0 ? (+ <ul className="mt-2 space-y-1.5">+ {hit.passages.map((passage) => (+ <PassageRow+ key={passage.document_id}+ passage={passage}+ itemId={hit.item_id}+ />+ ))}+ </ul>+ ) : (+ // No stored passages for this item (nothing embedded it yet), so the+ // snippet is genuinely all there is. Saying nothing here would read as+ // a rendering bug rather than as an honest limit.+ <p+ className="mt-1 text-xs leading-relaxed text-muted-foreground"+ data-testid={`ultrawiki-word-snippet-${hit.item_id}`}+ >+ {hit.snippet}+ </p>+ )}++ <div className="mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-0.5 text-[11px] text-muted-foreground">+ <span className="font-mono">{hit.source_id}</span>+ {hit.timestamp_utc && <span>{hit.timestamp_utc}</span>}+ <a+ href={hit.permalink}+ target="_blank"+ rel="noreferrer"+ className="inline-flex items-center gap-1 text-foreground underline-offset-2 hover:underline"+ data-testid={`ultrawiki-word-permalink-${hit.item_id}`}+ >+ <ExternalLink className="h-3 w-3" aria-hidden />+ {t("ultrawiki.ask.open_source")}+ </a>+ </div>+ </li>+ );+}++function PassageRow({+ passage,+ itemId,+}: {+ passage: UltraWikiPassage;+ itemId: number;+}): JSX.Element {+ const t = useT();+ return (+ <li+ className="rounded-lg border border-border/60 bg-background/40 p-2"+ data-testid={`ultrawiki-word-passage-${itemId}-${passage.document_id}`}+ >+ <p className="text-xs leading-relaxed text-muted-foreground">+ {passage.text}+ </p>+ <p className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[10px] text-muted-foreground/80">+ {/* The span is the point: it says WHERE in a long file this sits. */}+ <span className="font-mono tabular-nums">+ {t("ultrawiki.words.span")+ .replace("{0}", String(passage.chunk_index + 1))+ .replace("{1}", String(passage.char_start))+ .replace("{2}", String(passage.char_end))}+ </span>+ {passage.terms.length > 0 && (+ <span>+ {t("ultrawiki.words.matched_terms").replace(+ "{0}",+ passage.terms.join(", "),+ )}+ </span>+ )}+ </p>+ </li>+ );+}++function LexiconNote({+ lexicon,+}: {+ lexicon: UltraWikiWordSearchResponse["lexicon"];+}): JSX.Element | null {+ const t = useT();+ const terms = lexicon.terms ?? 0;+ const embedded = lexicon.embedded_terms ?? 0;+ if (terms === 0) return null;+ return (+ <p+ className="text-xs text-muted-foreground"+ data-testid="ultrawiki-word-lexicon"+ >+ {t("ultrawiki.words.lexicon_state")+ .replace("{0}", String(embedded))+ .replace("{1}", String(terms))}+ </p>+ );+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex bb599b461a..73e3f104c7 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -3204,6 +3204,27 @@"nothing_ingested_step_sync": "Starte dort „Jetzt synchronisieren“ und sieh zu, wie sich die Importleiste füllt.","nothing_ingested_note": "Die Stichwortsuche funktioniert Sekunden nach der ersten Synchronisierung; semantische Antworten wachsen, während die Hintergrundverarbeitung einbettet und destilliert."},+ "words": {+ "tab": "Wörter",+ "placeholder": "Ein Wort — z. B. ein Begriff, den du nicht genau benennen kannst",+ "submit": "Finden",+ "explainer": "Findet die Wörter, die deinem in der Bedeutung am nächsten sind, und sucht mit allen zusammen — so zählen auch Passagen, die dein Wort gar nicht enthalten.",+ "idle": "Gib ein Wort ein, um die bedeutungsnächsten Wörter und die Passagen dahinter zu sehen.",+ "searching": "Suche verwandte Wörter und die Passagen, die sie erreichen…",+ "failed": "Wortsuche fehlgeschlagen: {0}",+ "neighbours_meaning": "Der Bedeutung von „{0}“ am nächsten",+ "neighbours_company": "Wörter, die häufig neben „{0}“ stehen",+ "chip_hint_meaning": "{0} ähnlich · in {1} Einträgen gesehen · klicken, um nach diesem Wort zu suchen",+ "chip_hint_company": "{0} charakteristisch · in {1} Einträgen gesehen · klicken, um nach diesem Wort zu suchen",+ "passages_heading": "Passagen ({0})",+ "span": "Passage {0} · Zeichen {1}–{2}",+ "matched_terms": "enthält: {0}",+ "lexicon_state": "Der Wortindex enthält bisher {0} von {1} Begriffen; er füllt sich im Hintergrund weiter.",+ "leg_word": "dein Wort",+ "leg_semantic": "Bedeutung",+ "leg_related": "verwandtes Wort",+ "leg_neighbourhood": "Umfeld"+ },"slots": {"title": "Fähigkeits-Slots","storage_title": "Speicher",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex aab13636cb..f79f9d7de5 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -3205,6 +3205,27 @@"nothing_ingested_step_sync": "Press Sync on that source and watch the import strip fill up.","nothing_ingested_note": "Keyword search works seconds after the first sync; semantic answers grow as the background pipeline embeds and distills."},+ "words": {+ "tab": "Words",+ "placeholder": "One word — e.g. a concept you cannot name exactly",+ "submit": "Find",+ "explainer": "Finds the words closest in meaning to yours, then searches with all of them — so passages count even when they never spell your word out.",+ "idle": "Type a word to see the words nearest it in meaning, and the passages they lead to.",+ "searching": "Looking for related words and the passages they reach…",+ "failed": "Word search failed: {0}",+ "neighbours_meaning": "Closest in meaning to “{0}”",+ "neighbours_company": "Words that keep company with “{0}”",+ "chip_hint_meaning": "{0} alike · seen in {1} items · click to search this word",+ "chip_hint_company": "{0} characteristic · seen in {1} items · click to search this word",+ "passages_heading": "Passages ({0})",+ "span": "passage {0} · characters {1}–{2}",+ "matched_terms": "shows: {0}",+ "lexicon_state": "The word index holds {0} of {1} terms so far; it keeps filling in the background.",+ "leg_word": "your word",+ "leg_semantic": "meaning",+ "leg_related": "related word",+ "leg_neighbourhood": "neighbourhood"+ },"slots": {"title": "Capability slots","storage_title": "Storage",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex d3607e760b..a64c269759 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -3204,6 +3204,27 @@"nothing_ingested_step_sync": "Pulsa «Sincronizar ahora» en esa fuente y observa cómo se llena la barra de importación.","nothing_ingested_note": "La búsqueda por palabras clave funciona segundos después de la primera sincronización; las respuestas semánticas crecen mientras el proceso en segundo plano genera vectores y resúmenes."},+ "words": {+ "tab": "Palabras",+ "placeholder": "Una palabra — p. ej. un concepto que no sabes nombrar con exactitud",+ "submit": "Buscar",+ "explainer": "Encuentra las palabras más cercanas en significado a la tuya y busca con todas ellas, de modo que también cuentan los pasajes que nunca escriben tu palabra.",+ "idle": "Escribe una palabra para ver las más cercanas en significado y los pasajes a los que llevan.",+ "searching": "Buscando palabras relacionadas y los pasajes que alcanzan…",+ "failed": "La búsqueda de palabras falló: {0}",+ "neighbours_meaning": "Más cercanas en significado a «{0}»",+ "neighbours_company": "Palabras que acompañan a «{0}»",+ "chip_hint_meaning": "{0} de parecido · vista en {1} elementos · haz clic para buscar esta palabra",+ "chip_hint_company": "{0} de carácter propio · vista en {1} elementos · haz clic para buscar esta palabra",+ "passages_heading": "Pasajes ({0})",+ "span": "pasaje {0} · caracteres {1}–{2}",+ "matched_terms": "muestra: {0}",+ "lexicon_state": "El índice de palabras tiene {0} de {1} términos por ahora; sigue llenándose en segundo plano.",+ "leg_word": "tu palabra",+ "leg_semantic": "significado",+ "leg_related": "palabra relacionada",+ "leg_neighbourhood": "entorno"+ },"slots": {"title": "Ranuras de capacidades","storage_title": "Almacenamiento",diff --git a/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts b/jarvis/ui/web/frontend/src/lib/ultrawikiApi.tsindex 31f10875ec..f8a0097367 100644--- a/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts+++ b/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts@@ -512,6 +512,15 @@ export interface UltraWikiSearchHit {context: string[];/** When the ITEM was recorded; "" means identical to timestamp_utc. */recorded_utc: string;+ /**+ * WHICH passage of the item answered. An item is stored as many passages+ * (migration 0001), and the vector leg knows which one matched — null means+ * the leg genuinely cannot say (a keyword hit, an event card).+ */+ document_id: number | null;+ chunk_index: number | null;+ char_start: number | null;+ char_end: number | null;}export interface UltraWikiSearchResponse {@@ -542,6 +551,75 @@ export interface UltraWikiAskResponse extends UltraWikiSearchResponse {synthesis_error?: string;}+// Mirrors jarvis/ultrawiki/types.py::WordSearchStatus. The parity test+// prevents a backend state from silently rendering as a blank word search.+export const ULTRAWIKI_WORD_SEARCH_STATUSES = [+ "ok",+ "empty_index",+ "unknown_word",+ "no_matches",+ "neighbours_unavailable",+] as const;++export type UltraWikiWordSearchStatus =+ (typeof ULTRAWIKI_WORD_SEARCH_STATUSES)[number];++/** How the meaning-neighbours were derived (jarvis/ultrawiki/lexicon.py). */+export type UltraWikiNeighbourSource = "vector" | "cooccurrence" | "none";++/** Mirrors jarvis/ultrawiki/lexicon.py::TermNeighbour. */+export interface UltraWikiTermNeighbour {+ term: string;+ /** 0-1, higher = closer. NOT comparable across neighbour_source values. */+ similarity: number;+ doc_freq: number;+}++/** Mirrors jarvis/ultrawiki/word_search.py::Passage. */+export interface UltraWikiPassage {+ document_id: number;+ chunk_index: number;+ /** Offsets into the item's body — enough to locate the span in the original. */+ char_start: number;+ char_end: number;+ text: string;+ /** Which of the searched words this span actually shows. */+ terms: string[];+ score: number;+}++/** Mirrors jarvis/ultrawiki/word_search.py::WordHit. */+export interface UltraWikiWordHit {+ item_id: number;+ source_id: string;+ title: string;+ snippet: string;+ permalink: string;+ timestamp_utc: string;+ score: number;+ matched_by: string[];+ passages: UltraWikiPassage[];+}++export interface UltraWikiWordSearchResponse {+ word: string;+ status: UltraWikiWordSearchStatus;+ neighbour_source: UltraWikiNeighbourSource;+ /** Honest sentence whenever something is degraded or empty; may be "". */+ reason: string;+ neighbours: UltraWikiTermNeighbour[];+ results: UltraWikiWordHit[];+ total: number;+ /** Vocabulary size / embedded share / harvest progress; may be empty. */+ lexicon: Partial<{+ terms: number;+ embedded_terms: number;+ items: number;+ passages: number;+ scanned_items: number;+ }>;+}+export interface UltraWikiActivateBody {db_backend?: string;embedding_provider: string;@@ -1260,6 +1338,38 @@ export function askUltraWiki(});}+/**+ * Word search: the ~20 terms nearest `word` by meaning, plus the passages+ * that neighbourhood reaches. `neighbours = 0` uses the configured default.+ */+export function wordSearchUltraWiki(+ word: string,+ { k = 10, neighbours = 0, area }: {+ k?: number;+ neighbours?: number;+ area?: string;+ } = {},+): Promise<UltraWikiWordSearchResponse> {+ const params = new URLSearchParams({+ word,+ k: String(k),+ neighbours: String(neighbours),+ });+ if (area) params.set("area", area);+ return request<UltraWikiWordSearchResponse>(+ `/api/ultrawiki/word-search?${params.toString()}`,+ );+}++/** Throw the word vocabulary away so the background pass recounts it. */+export function rebuildUltraWikiLexicon(): Promise<{+ ok: boolean;+ reason: string;+ lexicon: UltraWikiWordSearchResponse["lexicon"];+}> {+ return postJson("/api/ultrawiki/lexicon/rebuild", {});+}+/** True when any sync job is still queued or running (drives poll cadence). */export function hasActiveUltraWikiJobs(jobs: UltraWikiJob[] | undefined | null,diff --git a/jarvis/ui/web/frontend/src/views/ultrawiki/UltraWikiPanel.tsx b/jarvis/ui/web/frontend/src/views/ultrawiki/UltraWikiPanel.tsxindex 350a95fd25..d1e7731f30 100644--- a/jarvis/ui/web/frontend/src/views/ultrawiki/UltraWikiPanel.tsx+++ b/jarvis/ui/web/frontend/src/views/ultrawiki/UltraWikiPanel.tsx@@ -31,6 +31,7 @@ import {MessageCircleQuestion,Plug,Settings2,+ Type,UsersRound,} from "lucide-react";import { useQuery } from "@tanstack/react-query";@@ -49,12 +50,14 @@ import { SlotsPanel } from "@/components/ultrawiki/SlotsPanel";import { ImportProgress } from "@/components/ultrawiki/ImportProgress";import { ExplorePanel } from "@/components/ultrawiki/ExplorePanel";import { PeoplePanel } from "@/components/ultrawiki/PeoplePanel";+import { WordSearchPanel } from "@/components/ultrawiki/WordSearchPanel";type UltraTab =| "overview"| "explore"| "people"| "ask"+ | "words"| "sources"| "contents"| "settings";@@ -186,6 +189,13 @@ export function UltraWikiPanel(): JSX.Element {label={t("ultrawiki.panel.tab_ask")}testId="ultrawiki-tab-ask"/>+ <UltraTabButton+ active={tab === "words"}+ onClick={() => setTab("words")}+ icon={<Type className="h-3.5 w-3.5" aria-hidden />}+ label={t("ultrawiki.words.tab")}+ testId="ultrawiki-tab-words"+ /><UltraTabButtonactive={tab === "sources"}onClick={() => setTab("sources")}@@ -246,6 +256,12 @@ export function UltraWikiPanel(): JSX.Element {onOpenSources={() => setTab("sources")}/>)}+ {tab === "words" && (+ <WordSearchPanel+ onOpenSources={() => setTab("sources")}+ onOpenSettings={() => setTab("settings")}+ />+ )}{tab === "sources" && (<SourcesPanel sources={status.sources} onChanged={refetch} />)}diff --git a/jarvis/ui/web/ultrawiki_routes.py b/jarvis/ui/web/ultrawiki_routes.pyindex e50c1f5c93..e62031cc9b 100644--- a/jarvis/ui/web/ultrawiki_routes.py+++ b/jarvis/ui/web/ultrawiki_routes.py@@ -2440,6 +2440,73 @@ async def search_ultrawiki(return {"query": q, "results": rows, "total": len(rows)}+ "/word-search",+ summary="Find a word's nearest meaning-neighbours and the passages they reach",+)+async def word_search_ultrawiki(+ request: Request,+ word: str = Query(..., min_length=1, description="A single word or short phrase"),+ k: int = Query(default=10, ge=1, le=50, description="How many items to return"),+ neighbours: int = Query(+ default=0,+ ge=0,+ le=50,+ description="Meaning-neighbours to expand with; 0 uses the configured default",+ ),+ area: str | None = Query(default=None, description="Optional area id filter"),+) -> dict[str, Any]:+ """Expand one word into the ~20 terms nearest it by meaning, then retrieve.++ Unlike ``/search`` this answers a WORD, not a question: the neighbourhood+ drives retrieval against the chunked documents, so hits point at the+ passage that carries the vocabulary rather than at the whole item.+ ``status`` names why the result looks the way it does — an empty list is+ never left for the caller to interpret.+ """+ service = _require_active(request)+ configured = _uw_cfg(request)+ wanted = int(neighbours) or int(+ getattr(configured, "word_search_neighbours", 20) or 20+ )+ outcome = await service.word_search(+ word, k=k, neighbours=wanted, area_id=area+ )+ return {+ "word": outcome.word,+ "status": outcome.status,+ "neighbour_source": outcome.neighbour_source,+ "reason": outcome.reason,+ "neighbours": [+ dataclasses.asdict(neighbour) for neighbour in outcome.neighbours+ ],+ "results": [dataclasses.asdict(hit) for hit in outcome.hits],+ "total": len(outcome.hits),+ "lexicon": dict(outcome.lexicon),+ }+++ "/lexicon/rebuild",+ summary="Throw the word vocabulary away and let it be recounted",+ # Destructive to derived data and NOT free: refilling the lexicon costs+ # one embedding call per batch of terms. The CLI must ask before running+ # it, so the flag is declared even though the path matches no marker.+ openapi_extra={"x-jarvis-dangerous": True},+)+async def rebuild_ultrawiki_lexicon(request: Request) -> dict[str, Any]:+ """Reset the word lexicon so the background pass harvests it from scratch.++ The repair for a vocabulary whose frequencies have drifted after many+ deletions, and the way to rebuild term vectors after an embedding-model+ switch. Destructive only to derived data: nothing imported is touched, and+ word search keeps answering through the co-occurrence path while the+ lexicon refills.+ """+ service = _require_active(request)+ return await service.rebuild_lexicon()++@router.post("/ask",summary="Answer a question from UltraWiki evidence with citations",diff --git a/jarvis/ultrawiki/lexicon.py b/jarvis/ultrawiki/lexicon.pynew file mode 100644index 0000000000..de199e8881--- /dev/null+++ b/jarvis/ultrawiki/lexicon.py@@ -0,0 +1,410 @@+"""The word lexicon: turning one word into its meaning-neighbourhood.++Semantic search answers a QUESTION. It cannot answer a WORD — a passage+vector says what a passage is about, never what a single term means on its+own — and a one-word intent is exactly how people hunt a concept they cannot+name precisely. This module is the missing half: it harvests the vocabulary+the corpus actually uses, embeds it into the SAME space as the passages+(``jarvis.ultrawiki.lexicon_store``), and answers "the twenty words nearest to+X" as an ordinary nearest-neighbour query.++Two neighbour paths, and the second one is not a consolation prize+====================================================================++**By meaning (``vector``)** — the query word is embedded and compared against+the term vectors. This is the good answer: it finds words that mean something+similar even when they never appear in the same sentence.++**By company (``cooccurrence``)** — with no embedding provider, no vector+extension, or a lexicon that has not been built yet, the module samples the+passages that literally contain the word and ranks the OTHER words in them by+how much more often they appear there than in the corpus at large (a plain+lift score). It needs no provider, no key and no network, which is why it+exists: an install with a keyword-only store still gets a usable word search+instead of an empty screen. It is blunter — it finds words that keep company+with the query rather than words that mean the same thing — and the caller is+told which path answered so the surface can say so.++What is deliberately NOT here+=============================++No stopword list. A curated "ignore these" list is a per-language asset, and+a supported locale without one would silently get a worse lexicon than the+languages someone remembered (the same bias the runtime-language rule exists+to prevent). Commonness is measured instead — a term in more than+:data:`MAX_DF_RATIO` of the passages carries no information in THIS corpus,+whatever language it is in, and is skipped as a neighbour.++Nothing in this module raises for a missing provider, an empty store or an+unknown word: each is a defined, named outcome.+"""++from __future__ import annotations++import logging+import math+import re+from collections.abc import Iterable, Mapping, Sequence+from dataclasses import dataclass+from typing import Any++log = logging.getLogger(__name__)++__all__ = [+ "TermNeighbour",+ "NEIGHBOUR_SOURCE_VECTOR",+ "NEIGHBOUR_SOURCE_COOCCURRENCE",+ "NEIGHBOUR_SOURCE_NONE",+ "DEFAULT_NEIGHBOURS",+ "MAX_DF_RATIO",+ "MIN_DOC_FREQ",+ "normalize_word",+ "word_tokens",+ "passage_vocabulary",+ "resolve_neighbours",+ "harvest_pass",+ "embed_terms_pass",+ "centroid",+]++#: Unicode-aware word tokenizer, identical in shape to+#: ``search.query_terms`` — German, Spanish and every other supported locale+#: tokenize the same way, and no ASCII-only character class appears anywhere.+_TOKEN_RE = re.compile(r"\w{2,}", re.UNICODE)++#: How many neighbours a word search asks for by default. Twenty is the size+#: at which a neighbourhood reads as a THEME rather than as a list of+#: synonyms, while still fitting on one screen.+DEFAULT_NEIGHBOURS = 20++#: A term seen in more than this share of the sampled passages says nothing+#: about any of them, in any language. Used to keep the co-occurrence path+#: from answering every query with the corpus's filler words.+MAX_DF_RATIO = 0.4++#: Below this many passages a term is almost always a typo, an id or a hash.+#: Such terms are still STORED (they answer an exact lookup) but never+#: embedded, which is what keeps the lexicon's cost bounded.+MIN_DOC_FREQ = 2++#: Where a neighbour list came from — reported to the surface so a degraded+#: answer is visibly degraded instead of quietly worse.+NEIGHBOUR_SOURCE_VECTOR = "vector"+NEIGHBOUR_SOURCE_COOCCURRENCE = "cooccurrence"+NEIGHBOUR_SOURCE_NONE = "none"++#: How many passages the co-occurrence path samples. Bounded on purpose: this+#: runs on the search path and must not walk a 200 000-passage corpus.+_COOCCURRENCE_SAMPLE = 80++#: Passages harvested per background lexicon pass, and terms embedded per+#: pass. Both bounded so the lane stays a background lane (AP-26): the+#: harvest is pure CPU over text already in the database, the embed step is+#: one provider call.+HARVEST_BATCH = 400+EMBED_BATCH = 96+++@dataclass(frozen=True, slots=True)+class TermNeighbour:+ """One word near the query word, with how near and how common it is."""++ term: str+ #: 0-1, higher = closer. Cosine similarity on the vector path; a+ #: normalized lift score on the co-occurrence path. The two are NOT+ #: comparable across paths, which is why the path is always reported+ #: beside them.+ similarity: float+ #: In how many passages the term was seen while harvesting — a rarity+ #: hint for the reader, never a filter that drops a hit.+ doc_freq: int = 0+++def normalize_word(text: str) -> str:+ """The canonical form of a query word or short phrase.++ Lowercased and whitespace-collapsed, nothing else: no stemming, because a+ stemmer is per-language and a wrong one mangles the very word the user is+ hunting.+ """+ return " ".join(str(text or "").split()).lower()+++def word_tokens(text: str) -> list[str]:+ """Distinct lowercased word tokens of ``text``, order preserved."""+ return list(+ dict.fromkeys(match.group(0).lower() for match in _TOKEN_RE.finditer(text or ""))+ )+++def passage_vocabulary(texts: Iterable[str]) -> dict[str, int]:+ """Per-PASSAGE document frequencies for a batch of passage texts.++ A term is counted once per passage however often it occurs in it, which is+ what makes ``doc_freq`` a rarity measure rather than a word count.+ """+ counts: dict[str, int] = {}+ for text in texts:+ for token in word_tokens(text):+ counts[token] = counts.get(token, 0) + 1+ return counts+++# ---------------------------------------------------------------------------+# Background passes (harvest + embed)+# ---------------------------------------------------------------------------+++async def harvest_pass(store: Any, *, limit: int = HARVEST_BATCH) -> int:+ """Walk the next slice of items into the vocabulary. Returns rows read.++ Incremental and resumable: a cursor in ``uw_meta`` records the highest+ item id already seen, so a restart continues instead of recounting, and a+ 200 000-item corpus is never scanned in one go.+ """+ cursor = await store.lexicon_cursor()+ rows = await store.lexicon_scan_batch(after_item_id=cursor, limit=int(limit))+ if not rows:+ return 0+ counts = passage_vocabulary(str(row.get("text", "")) for row in rows)+ if counts:+ await store.bump_terms(counts)+ # Advance only after the terms landed: a crash between the two re-reads+ # the same items and double-counts their frequencies, which skews a+ # ranking hint. Advancing FIRST would lose that vocabulary permanently.+ await store.set_lexicon_cursor(max(int(row["item_id"]) for row in rows))+ return len(rows)+++async def embed_terms_pass(+ store: Any,+ backend: Any,+ *,+ model: str,+ dim: int,+ limit: int = EMBED_BATCH,+ max_terms: int = 20000,+ min_doc_freq: int = MIN_DOC_FREQ,+) -> int:+ """Embed the next batch of harvested terms. Returns how many landed.++ ``model``/``dim`` are the store's ACTIVE pinned space, never the config's+ current setting: embedding terms into a space the documents do not live in+ would produce neighbours that cannot be compared with anything (D-3).+ """+ if not model or int(dim) <= 0:+ return 0+ pending = await store.terms_needing_vectors(+ model=model,+ dim=int(dim),+ limit=int(limit),+ min_doc_freq=int(min_doc_freq),+ max_terms=int(max_terms),+ )+ if not pending:+ return 0+ texts = [str(row["term"]) for row in pending]+ vectors = await backend.embed(texts, model=model)+ if len(vectors) != len(texts):+ raise RuntimeError(+ f"backend returned {len(vectors)} vectors for {len(texts)} terms"+ )+ return await store.store_term_vectors(+ [(int(row["term_id"]), vector) for row, vector in zip(pending, vectors, strict=True)],+ model=model,+ dim=int(dim),+ )+++# ---------------------------------------------------------------------------+# Neighbour resolution (the read path)+# ---------------------------------------------------------------------------+++async def resolve_neighbours(+ store: Any,+ cfg: Any,+ word: str,+ *,+ limit: int = DEFAULT_NEIGHBOURS,+ area_id: str | None = None,+) -> tuple[list[TermNeighbour], str, str, list[float] | None]:+ """The ``limit`` words nearest ``word``, best first.++ Returns ``(neighbours, source, reason, query_vector)``:++ - ``source`` is one of :data:`NEIGHBOUR_SOURCE_VECTOR`,+ :data:`NEIGHBOUR_SOURCE_COOCCURRENCE`, :data:`NEIGHBOUR_SOURCE_NONE`.+ - ``reason`` is empty on the healthy path, and otherwise an honest English+ sentence naming what is missing. It is populated even when the fallback+ succeeded — the surface should be able to say "these are neighbours by+ company, because <reason>".+ - ``query_vector`` is the embedded query word when one could be produced.+ It is handed back rather than recomputed, because the retrieval stage+ right after this needs exactly the same vector.++ Never raises.+ """+ term = normalize_word(word)+ if not term or int(limit) <= 0:+ return [], NEIGHBOUR_SOURCE_NONE, "", None++ query_vector: list[float] | None = None+ vector_reason = ""+ try:+ model, dim = await store.embedding_space()+ except Exception: # noqa: BLE001 — an unreadable pin degrades, never fails+ log.debug("lexicon: embedding space unreadable", exc_info=True)+ model, dim = "", 0++ if model and dim > 0:+ from jarvis.ultrawiki.search import ( # noqa: PLC0415 — lazy (AP-26)+ embed_query_vector,+ )++ query_vector, vector_reason = await embed_query_vector(cfg, term)+ if query_vector is not None:+ try:+ rows, reason = await store.term_neighbors(+ query_vector, model=model, dim=dim, limit=int(limit),+ exclude=word_tokens(term),+ )+ except Exception as exc: # noqa: BLE001 — fall through to company+ log.warning("lexicon: term neighbour query failed", exc_info=True)+ rows, reason = [], f"the word index could not be read ({type(exc).__name__})"+ if rows:+ return (+ [+ TermNeighbour(+ term=str(row["term"]),+ similarity=float(row["similarity"]),+ doc_freq=int(row.get("doc_freq", 0) or 0),+ )+ for row in rows+ ],+ NEIGHBOUR_SOURCE_VECTOR,+ "",+ query_vector,+ )+ vector_reason = reason or vector_reason+ else:+ vector_reason = (+ "nothing has been embedded yet, so there are no word vectors to "+ "compare against — related words come from the text instead"+ )++ company, company_reason = await _neighbours_by_company(+ store, term, limit=int(limit), area_id=area_id+ )+ if company:+ return company, NEIGHBOUR_SOURCE_COOCCURRENCE, vector_reason, query_vector+ return (+ [],+ NEIGHBOUR_SOURCE_NONE,+ vector_reason or company_reason,+ query_vector,+ )+++async def _neighbours_by_company(+ store: Any, term: str, *, limit: int, area_id: str | None+) -> tuple[list[TermNeighbour], str]:+ """Provider-free neighbours: words that keep company with ``term``.++ Scored by LIFT — how much more often a word appears in the passages that+ contain the query word than in the corpus as a whole. A plain co-occurrence+ count would return the corpus's filler words for every query; lift returns+ the words that are specifically characteristic of this one.+ """+ reader = getattr(store, "text_samples_for_term", None)+ if not callable(reader):+ return [], (+ "this knowledge store cannot list the text a word occurs in, "+ "so related words are unavailable"+ )+ try:+ rows = await reader(term, limit=_COOCCURRENCE_SAMPLE, area_id=area_id)+ except Exception: # noqa: BLE001 — a fallback that raises is not a fallback+ log.warning("lexicon: co-occurrence sample failed", exc_info=True)+ return [], "the text containing this word could not be read"+ if not rows:+ return [], ""+ texts = [str(row.get("text", "")) for row in rows]+ local = passage_vocabulary(texts)+ sampled = len(texts)+ query_words = set(word_tokens(term))+ candidates = [+ (candidate, count)+ for candidate, count in local.items()+ if candidate not in query_words+ and count >= 2+ and count <= max(2, int(sampled * MAX_DF_RATIO))+ ]+ if not candidates:+ return [], ""+ # The corpus-wide frequency of the SAME words, so "common everywhere" and+ # "common right here" can be told apart. A store without the probe simply+ # ranks by local frequency, which is worse but not wrong.+ background: Mapping[str, int] = {}+ corpus_size = 0+ df_probe = getattr(store, "term_document_frequency", None)+ count_probe = getattr(store, "live_item_count", None)+ if callable(df_probe) and callable(count_probe):+ try:+ corpus_size = int(await count_probe())+ background = await df_probe([name for name, _ in candidates])+ except Exception: # noqa: BLE001 — a missing signal ranks worse, never fails+ log.debug("lexicon: background frequency probe failed", exc_info=True)+ background, corpus_size = {}, 0++ scored: list[tuple[float, str, int]] = []+ for candidate, count in candidates:+ local_rate = count / sampled+ if corpus_size > 0:+ global_rate = max(1, int(background.get(candidate, 0) or 0)) / corpus_size+ lift = local_rate / global_rate+ else:+ lift = local_rate+ # log1p keeps a word that is 500x over-represented from dwarfing the+ # rest of the list into an unreadable 0.00 tail.+ seen_in = int(background.get(candidate, count) or count)+ scored.append((math.log1p(max(lift, 0.0)), candidate, seen_in))+ if not scored:+ return [], ""+ scored.sort(key=lambda row: (-row[0], row[1]))+ top = scored[: int(limit)]+ ceiling = max(row[0] for row in top) or 1.0+ return (+ [+ TermNeighbour(+ term=candidate,+ similarity=round(min(1.0, score / ceiling), 4),+ doc_freq=doc_freq,+ )+ for score, candidate, doc_freq in top+ ],+ "",+ )+++def centroid(vectors: Sequence[Sequence[float]]) -> list[float] | None:+ """The mean of several vectors, L2-normalized. ``None`` if unusable.++ The neighbourhood's own query vector: averaging the word with its nearest+ neighbours moves the query off the exact term and onto the CONCEPT around+ it, which is what makes an expanded search find passages that never spell+ the word out. Vectors of differing width are refused rather than padded —+ a mixed-width mean is a meaningless direction.+ """+ usable = [list(map(float, vector)) for vector in vectors if vector]+ if not usable:+ return None+ width = len(usable[0])+ usable = [vector for vector in usable if len(vector) == width]+ if not usable:+ return None+ mean = [sum(values) / len(usable) for values in zip(*usable, strict=True)]+ norm = math.sqrt(sum(value * value for value in mean))+ if norm <= 0.0 or not math.isfinite(norm):+ return None+ return [value / norm for value in mean]diff --git a/jarvis/ultrawiki/lexicon_store.py b/jarvis/ultrawiki/lexicon_store.pynew file mode 100644index 0000000000..ab988bfd4e--- /dev/null+++ b/jarvis/ultrawiki/lexicon_store.py@@ -0,0 +1,716 @@+"""The SQL half of the UltraWiki word lexicon (``uw_terms``).++:class:`LexiconMixin` is inherited by BOTH store backends, so the vocabulary+rules exist exactly once. Like :class:`~jarvis.ultrawiki.event_store.EventMixin`+it relies only on the small surface both backends already provide — ``_txn()``,+``_fetchall()``, ``_fetchone()``, ``_ensure_open()``, ``_id_sql()``,+``get_meta()``/``set_meta()`` — plus one dialect hook of its own,+:attr:`LexiconMixin._LEXICON_DIALECT`, because nearest-vector search is the one+thing the two engines cannot express the same way.++What this layer is for+======================++Semantic search answers a QUESTION. It cannot answer a WORD: a passage vector+says what a passage is about, never what a single term means on its own. So the+lexicon embeds the vocabulary itself — every term the corpus actually uses gets+one vector in the SAME space as the documents — and "the twenty words nearest+to X" becomes an ordinary nearest-neighbour query.++The contract this module keeps:++- **Harvesting is incremental and bounded.** A cursor in ``uw_meta`` records+ the highest passage id already walked; each pass reads the next slice. A+ 200 000-passage corpus is therefore never scanned in one go, and a restart+ resumes where it stopped instead of starting over.+- **The lexicon never grows without limit.** Only terms above a document+ frequency floor are ever embedded, capped by+ ``[ultrawiki].lexicon_max_terms``, most-seen first. A corpus of ids, hashes+ and typos costs nothing: those terms are stored (they still answer an exact+ lookup) but never embedded.+- **One vector space, never mixed.** Term vectors are keyed by+ ``(model, dim)`` exactly like ``uw_embeddings`` (design rule D-3). The+ neighbour query reads the ACTIVE space only; a model switch simply leaves+ the old rows behind and re-embeds into the new space on the next pass.+- **A missing vector index is a degradation, not a failure.** Without+ sqlite-vec / pgvector there are no vector neighbours, and+ :meth:`term_neighbors` says so honestly instead of raising — the caller+ falls back to the co-occurrence path, which needs no provider at all.+- **The store stays policy-free.** Nothing here tokenizes, scores or decides+ what a "word" is; that is :mod:`jarvis.ultrawiki.lexicon`. This module moves+ rows.++Nothing here calls a model or touches the network.+"""++from __future__ import annotations++import logging+import struct+from collections.abc import Mapping, Sequence+from datetime import UTC, datetime+from typing import Any++log = logging.getLogger(__name__)++__all__ = [+ "LexiconMixin",+ "META_LEXICON_CURSOR",+]++#: ``uw_meta`` key holding the highest ``uw_items.id`` the vocabulary+#: harvester has already walked. Monotonic; reset by :meth:`reset_lexicon`.+#:+#: ITEMS, not passages, and that is load bearing: passages (``uw_documents``)+#: only come into existence when the embed stage runs, so a store with no+#: embedding provider would have an empty vocabulary — and the word search+#: fallback that exists precisely FOR that store would have nothing to fall+#: back to. Items exist the moment a sync lands, and their text is the same+#: text the passages are cut from, so the vocabulary is identical either way.+META_LEXICON_CURSOR = "lexicon_scan_item_id"++#: Rows per SQL ``IN (...)`` batch, mirroring ``store._IN_CHUNK``.+_IN_CHUNK = 400+++def _pack_vector(vector: Sequence[float]) -> bytes:+ """Little-endian float32 BLOB.++ Duplicated from ``store.pack_vector`` deliberately rather than imported:+ ``store`` imports this module, and the cycle would make both unimportable+ (the same reason ``event_store`` carries its own ``_match_expr``).+ """+ return struct.pack(f"<{len(vector)}f", *[float(value) for value in vector])+++def _unpack_vector(blob: bytes) -> list[float]:+ return list(struct.unpack(f"<{len(blob) // 4}f", blob))+++def _utc_now_iso() -> str:+ return datetime.now(UTC).replace(microsecond=0).isoformat().replace("+00:00", "Z")+++def _cosine_similarity_from_distance(distance: float) -> float:+ """sqlite-vec / pgvector report cosine DISTANCE (0 = identical, 2 = opposite).++ The surface shows a similarity, because "0.91 alike" is readable and+ "0.09 apart" is not. Clamped, so a provider that returns a hair outside+ the theoretical range cannot produce a similarity above 1.+ """+ return max(0.0, min(1.0, 1.0 - float(distance)))+++class LexiconMixin:+ """Vocabulary + term-vector SQL shared by both UltraWiki store backends."""++ #: ``"sqlite"`` (default) or ``"postgres"`` — set on the store class.+ _LEXICON_DIALECT: str = "sqlite"++ #: Cached ``(usable, reason)`` of the term-vector search path, per store+ #: instance. Mirrors ``_vec_state``: the verdict only changes when the+ #: process gains the extension, which it cannot do mid-run.+ _term_vec_state: tuple[bool, str] | None = None+ _term_vec_dim: int | None = None++ # -- small dialect-aware helpers ----------------------------------------++ async def _lex_all(+ self, conn: Any, sql: str, params: Sequence[Any] = ()+ ) -> list[Any]:+ return await self._fetchall(conn, self._id_sql(sql), params) # type: ignore[attr-defined]++ async def _lex_one(+ self, conn: Any, sql: str, params: Sequence[Any] = ()+ ) -> Any:+ return await self._fetchone(conn, self._id_sql(sql), params) # type: ignore[attr-defined]++ async def _lex_exec(+ self, conn: Any, sql: str, params: Sequence[Any] = ()+ ) -> None:+ await conn.execute(self._id_sql(sql), params)++ def _lex_marks(self, count: int) -> str:+ mark = "?" if self._LEXICON_DIALECT == "sqlite" else "%s"+ return ",".join([mark] * count)++ async def _lex_conn(self) -> Any:+ """A connection for READS.++ The SQLite backend keeps a pool of read-only connections precisely so+ a search leg does not queue behind the ingest writer (one aiosqlite+ connection = one worker thread). Two of the queries below run on the+ search path, so they take that pool when it exists and the writer+ otherwise — which is also what a store fake without a pool gets.+ """+ reader = getattr(self, "_read_conn", None)+ if callable(reader):+ return await reader()+ return await self._ensure_open() # type: ignore[attr-defined]++ async def _lex_vec_conn(self) -> Any:+ """A connection that can evaluate vector distances.++ sqlite-vec loads per CONNECTION while the readiness verdict is cached+ per STORE, so a pooled reader has to be prepared before it can run the+ scan — the same trap ``_vec_ready_conn`` exists for on the document+ leg. Reuses that helper rather than repeating its fallback.+ """+ conn = await self._lex_conn()+ prepare = getattr(self, "_vec_ready_conn", None)+ if callable(prepare):+ return await prepare(conn)+ return conn++ # -- vocabulary harvesting ----------------------------------------------++ async def lexicon_cursor(self) -> int:+ """Highest item id the vocabulary harvester has already walked."""+ raw = await self.get_meta(META_LEXICON_CURSOR) # type: ignore[attr-defined]+ try:+ return int(raw or 0)+ except (TypeError, ValueError):+ # A cursor nobody can parse means "start over", and starting over+ # is the correct, complete repair: the harvest is idempotent per+ # slice, so re-walking the corpus costs one background pass and+ # loses nothing. There is no failure here worth reporting.+ return 0++ async def set_lexicon_cursor(self, item_id: int) -> None:+ await self.set_meta(META_LEXICON_CURSOR, str(int(item_id))) # type: ignore[attr-defined]++ async def lexicon_scan_batch(+ self, *, after_item_id: int, limit: int+ ) -> list[dict[str, Any]]:+ """The next slice of items to harvest vocabulary from.++ Ordered by id so the cursor above is a complete record of what has+ been seen. Tombstoned items are skipped — their text is gone from the+ corpus and its words have no business entering the vocabulary. Title+ and body are returned together because a title is where a document+ names its own subject, which is exactly the vocabulary worth having.+ """+ if limit <= 0:+ return []+ conn = await self._lex_conn()+ rows = await self._lex_all(+ conn,+ "SELECT id AS item_id, title, body_raw FROM uw_items"+ " WHERE id > ? AND deleted_at IS NULL"+ " ORDER BY id LIMIT ?",+ (int(after_item_id), int(limit)),+ )+ return [+ {+ "item_id": int(row["item_id"]),+ "text": f"{row['title'] or ''} {row['body_raw'] or ''}",+ }+ for row in rows+ ]++ async def bump_terms(self, counts: Mapping[str, int]) -> int:+ """Add ``counts`` to the vocabulary, inserting terms it has not seen.++ Returns the number of distinct terms touched. Idempotent per BATCH,+ not per corpus: the caller must only ever pass a slice of passages it+ has not passed before, which is what the harvest cursor guarantees.+ """+ rows = [+ (term, int(count))+ for term, count in counts.items()+ if term and int(count) > 0+ ]+ if not rows:+ return 0+ now = _utc_now_iso()+ # ON CONFLICT is spelled identically in both engines for this shape.+ sql = (+ "INSERT INTO uw_terms (term, doc_freq, created_at, updated_at)"+ " VALUES (?, ?, ?, ?)"+ " ON CONFLICT (term) DO UPDATE SET"+ " doc_freq = uw_terms.doc_freq + EXCLUDED.doc_freq,"+ " updated_at = EXCLUDED.updated_at"+ )+ async with self._txn() as conn: # type: ignore[attr-defined]+ for term, count in rows:+ await self._lex_exec(conn, sql, (term, count, now, now))+ return len(rows)++ async def lexicon_counts(self, *, model: str = "", dim: int = 0) -> dict[str, int]:+ """Honest size report: vocabulary, embedded share, harvest progress."""+ conn = await self._lex_conn()+ terms_row = await self._lex_one(conn, "SELECT COUNT(*) AS n FROM uw_terms")+ items_row = await self._lex_one(+ conn, "SELECT COUNT(*) AS n FROM uw_items WHERE deleted_at IS NULL"+ )+ passages_row = await self._lex_one(+ conn,+ "SELECT COUNT(*) AS n FROM uw_documents d"+ " JOIN uw_items i ON i.id = d.item_id WHERE i.deleted_at IS NULL",+ )+ embedded = 0+ if model and int(dim) > 0:+ embedded_row = await self._lex_one(+ conn,+ "SELECT COUNT(*) AS n FROM uw_term_embeddings"+ " WHERE model = ? AND dim = ?",+ (model, int(dim)),+ )+ embedded = int(embedded_row["n"]) if embedded_row else 0+ return {+ "terms": int(terms_row["n"]) if terms_row else 0,+ "embedded_terms": embedded,+ "items": int(items_row["n"]) if items_row else 0,+ # Passages, so a surface can say whether hits will carry a located+ # span at all: zero means nothing has been embedded yet and every+ # hit will point at its item rather than at a paragraph of it.+ "passages": int(passages_row["n"]) if passages_row else 0,+ "scanned_items": await self.lexicon_cursor(),+ }++ async def reset_lexicon(self) -> None:+ """Drop the whole vocabulary and rewind the harvest cursor.++ The one repair for a ``doc_freq`` that has drifted after many+ tombstones, and the way a user asks for a fresh count. Vectors go with+ it (``ON DELETE CASCADE``) and are re-earned by the background pass —+ which costs embedding calls, so this is never automatic.+ """+ async with self._txn() as conn: # type: ignore[attr-defined]+ if self._LEXICON_DIALECT == "postgres":+ # DERIVED, and possibly not created yet — dropping it is both+ # the correct reset and the only spelling that cannot abort+ # this transaction on a store that never ran a word search.+ await self._lex_exec(conn, "DROP TABLE IF EXISTS uw_term_vec")+ await self._lex_exec(conn, "DELETE FROM uw_term_embeddings")+ await self._lex_exec(conn, "DELETE FROM uw_terms")+ await self.set_lexicon_cursor(0)+ self._term_vec_state = None+ self._term_vec_dim = None++ # -- term vectors --------------------------------------------------------++ async def terms_needing_vectors(+ self,+ *,+ model: str,+ dim: int,+ limit: int,+ min_doc_freq: int = 2,+ max_terms: int = 20000,+ ) -> list[dict[str, Any]]:+ """The next terms to embed: most-seen first, above the rarity floor.++ ``max_terms`` is the ceiling on the whole embedded vocabulary, not on+ this batch: once that many terms carry a vector in this space, the+ pass is done and returns nothing. Without it a corpus of build logs+ would queue every hex id it ever printed.+ """+ if limit <= 0 or not model or int(dim) <= 0:+ return []+ conn = await self._lex_conn()+ embedded_row = await self._lex_one(+ conn,+ "SELECT COUNT(*) AS n FROM uw_term_embeddings WHERE model = ? AND dim = ?",+ (model, int(dim)),+ )+ embedded = int(embedded_row["n"]) if embedded_row else 0+ remaining = max(0, int(max_terms) - embedded)+ if remaining <= 0:+ return []+ rows = await self._lex_all(+ conn,+ "SELECT t.id AS term_id, t.term AS term FROM uw_terms t"+ " WHERE t.doc_freq >= ?"+ " AND NOT EXISTS (SELECT 1 FROM uw_term_embeddings e"+ " WHERE e.term_id = t.id AND e.model = ? AND e.dim = ?)"+ " ORDER BY t.doc_freq DESC, t.id LIMIT ?",+ (int(min_doc_freq), model, int(dim), min(int(limit), remaining)),+ )+ return [+ {"term_id": int(row["term_id"]), "term": str(row["term"])} for row in rows+ ]++ async def store_term_vectors(+ self,+ rows: Sequence[tuple[int, Sequence[float]]],+ *,+ model: str,+ dim: int,+ ) -> int:+ """Persist one vector per term id. Returns how many landed.++ A vector whose width disagrees with ``dim`` is DROPPED with a warning+ rather than stored: a mixed-width lexicon would make every neighbour+ query fail on a row nobody can point at.+ """+ usable = [+ (int(term_id), list(vector))+ for term_id, vector in rows+ if vector is not None and len(vector) == int(dim)+ ]+ dropped = len(rows) - len(usable)+ if dropped:+ log.warning(+ "lexicon: dropped %d term vector(s) whose width was not %d",+ dropped,+ int(dim),+ )+ if not usable:+ return 0+ now = _utc_now_iso()+ async with self._txn() as conn: # type: ignore[attr-defined]+ for term_id, vector in usable:+ blob = _pack_vector(vector)+ if self._LEXICON_DIALECT == "postgres":+ await self._lex_exec(+ conn,+ "INSERT INTO uw_term_embeddings"+ " (term_id, model, dim, vector, created_at)"+ " VALUES (?, ?, ?, ?, ?)"+ " ON CONFLICT (term_id, model, dim) DO UPDATE SET"+ " vector = EXCLUDED.vector, created_at = EXCLUDED.created_at",+ (term_id, model, int(dim), blob, now),+ )+ else:+ await self._lex_exec(+ conn,+ "INSERT OR REPLACE INTO uw_term_embeddings"+ " (term_id, model, dim, vector, created_at)"+ " VALUES (?, ?, ?, ?, ?)",+ (term_id, model, int(dim), blob, now),+ )+ # The Postgres neighbour table is DERIVED from the rows just written;+ # invalidate the cached readiness so the next query refreshes it.+ if self._LEXICON_DIALECT == "postgres":+ self._term_vec_state = None+ return len(usable)++ async def term_vectors_for(+ self, terms: Sequence[str], *, model: str, dim: int+ ) -> dict[str, list[float]]:+ """Stored vectors for specific terms, keyed by term. Missing = absent.++ This is what lets the expansion build a centroid out of neighbours+ that were embedded once, at harvest time, instead of paying a provider+ call per neighbour on every search.+ """+ wanted = [term for term in dict.fromkeys(terms) if term]+ if not wanted or not model or int(dim) <= 0:+ return {}+ conn = await self._lex_conn()+ out: dict[str, list[float]] = {}+ for start in range(0, len(wanted), _IN_CHUNK):+ block = wanted[start : start + _IN_CHUNK]+ rows = await self._lex_all(+ conn,+ "SELECT t.term AS term, e.vector AS vector" # noqa: S608 — placeholder marks only+ " FROM uw_term_embeddings e JOIN uw_terms t ON t.id = e.term_id"+ f" WHERE e.model = ? AND e.dim = ? AND t.term IN ({self._lex_marks(len(block))})",+ (model, int(dim), *block),+ )+ for row in rows:+ out[str(row["term"])] = _unpack_vector(bytes(row["vector"]))+ return out++ async def _ensure_term_vec(self, dim: int) -> tuple[bool, str]:+ """Make the term-vector nearest-neighbour path usable, or say why not.++ SQLite needs nothing but the sqlite-vec extension: the scan runs as a+ plain ``vec_distance_cosine`` over the stored BLOBs, so there is no+ second index to keep in step with anything. Postgres needs a real+ ``vector`` column, so a small ``uw_term_vec`` table is DERIVED from+ ``uw_term_embeddings`` the same way ``uw_vec`` is derived from+ ``uw_embeddings``.+ """+ if self._term_vec_state is not None and self._term_vec_dim == int(dim):+ return self._term_vec_state+ # Both engines gate on the SAME probe the document vector leg uses, so+ # a host without vectors gives one reason, not two different ones.+ ok, reason = await self._ensure_vec(None) # type: ignore[attr-defined]+ if not ok:+ self._term_vec_state = (False, reason)+ self._term_vec_dim = int(dim)+ return self._term_vec_state+ if self._LEXICON_DIALECT == "postgres":+ conn = await self._ensure_open() # type: ignore[attr-defined]+ await conn.execute(+ "CREATE TABLE IF NOT EXISTS uw_term_vec ("+ " term_id BIGINT PRIMARY KEY"+ " REFERENCES uw_terms(id) ON DELETE CASCADE,"+ f" embedding vector({int(dim)}) NOT NULL)"+ )+ # Drop what no longer belongs to the active space, then backfill.+ await conn.execute(+ "DELETE FROM uw_term_vec WHERE term_id NOT IN"+ " (SELECT term_id FROM uw_term_embeddings"+ " WHERE model = %s AND dim = %s)",+ (await self._active_embed_model(), int(dim)),+ )+ missing = await self._fetchall( # type: ignore[attr-defined]+ conn,+ "SELECT term_id, vector FROM uw_term_embeddings"+ " WHERE model = %s AND dim = %s"+ " AND term_id NOT IN (SELECT term_id FROM uw_term_vec)",+ (await self._active_embed_model(), int(dim)),+ )+ for row in missing:+ literal = (+ "["+ + ",".join(+ f"{value:.8g}" for value in _unpack_vector(bytes(row["vector"]))+ )+ + "]"+ )+ await conn.execute(+ "INSERT INTO uw_term_vec (term_id, embedding)"+ " VALUES (%s, %s::vector) ON CONFLICT (term_id) DO NOTHING",+ (row["term_id"], literal),+ )+ self._term_vec_dim = int(dim)+ self._term_vec_state = (True, "")+ return self._term_vec_state++ async def _active_embed_model(self) -> str:+ model, _ = await self._pinned_space() # type: ignore[attr-defined]+ return model or ""++ async def embedding_space(self) -> tuple[str, int]:+ """The ACTIVE ``(model, dim)`` pin, or ``("", 0)`` when nothing is+ embedded yet.++ Public because the lexicon has to embed its terms into exactly the+ space the documents already live in — asking the CONFIG instead would+ silently build a second, incompatible geometry the moment someone+ switches models mid-rebuild (design rule D-3).+ """+ model, dim = await self._pinned_space() # type: ignore[attr-defined]+ return (model or ""), int(dim or 0)++ async def term_neighbors(+ self,+ query_vector: Sequence[float],+ *,+ model: str,+ dim: int,+ limit: int = 20,+ exclude: Sequence[str] = (),+ ) -> tuple[list[dict[str, Any]], str]:+ """The vocabulary nearest ``query_vector``, best first.++ Returns ``(neighbours, reason)``. ``reason`` is empty on the healthy+ path and an honest English sentence whenever the list is empty for a+ structural cause (no vector extension, nothing embedded yet, a query+ vector from a different space). Never raises: the caller has a+ provider-free fallback and must be able to reach it.+ """+ if limit <= 0:+ return [], ""+ if not model or int(dim) <= 0:+ return [], (+ "the embedding space is not pinned yet — nothing has been "+ "embedded, so there are no word vectors to compare against"+ )+ if len(query_vector) != int(dim):+ return [], (+ f"the query vector has {len(query_vector)} components but this "+ f"store's embedding space is pinned to dim={int(dim)}"+ )+ ok, reason = await self._ensure_term_vec(int(dim))+ if not ok:+ return [], reason+ skip = {str(term).strip().lower() for term in exclude if str(term).strip()}+ # Ask for a few extra rows so excluding the query's own words cannot+ # shorten the answer below what the caller asked for.+ fetch = int(limit) + len(skip) + 4+ conn = await self._lex_vec_conn()+ if self._LEXICON_DIALECT == "postgres":+ rows = await self._fetchall( # type: ignore[attr-defined]+ conn,+ "SELECT t.term AS term, t.doc_freq AS doc_freq,"+ " (v.embedding <=> %s::vector) AS distance"+ " FROM uw_term_vec v JOIN uw_terms t ON t.id = v.term_id"+ " ORDER BY distance LIMIT %s",+ (+ "["+ + ",".join(f"{value:.8g}" for value in query_vector)+ + "]",+ fetch,+ ),+ )+ else:+ try:+ rows = await self._fetchall( # type: ignore[attr-defined]+ conn,+ "SELECT t.term AS term, t.doc_freq AS doc_freq,"+ " vec_distance_cosine(e.vector, ?) AS distance"+ " FROM uw_term_embeddings e JOIN uw_terms t ON t.id = e.term_id"+ " WHERE e.model = ? AND e.dim = ?"+ " ORDER BY distance LIMIT ?",+ (_pack_vector(query_vector), model, int(dim), fetch),+ )+ except Exception as exc: # noqa: BLE001 — degrade, never fail a search+ log.info("lexicon: term nearest-neighbour scan unavailable (%s)", exc)+ self._term_vec_state = (+ False,+ "this SQLite build cannot compare word vectors "+ f"({type(exc).__name__}); related words fall back to "+ "co-occurrence in the text",+ )+ return [], self._term_vec_state[1]+ neighbours: list[dict[str, Any]] = []+ for row in rows:+ term = str(row["term"])+ if term.lower() in skip:+ continue+ neighbours.append(+ {+ "term": term,+ "similarity": round(+ _cosine_similarity_from_distance(row["distance"]), 4+ ),+ "doc_freq": int(row["doc_freq"] or 0),+ }+ )+ if len(neighbours) >= int(limit):+ break+ if not neighbours:+ return [], (+ "no word vectors are stored yet — the background lexicon pass "+ "builds them once an embedding provider is configured"+ )+ return neighbours, ""++ # -- provider-free fallback + passage lookup ----------------------------++ async def text_samples_for_term(+ self, term: str, *, limit: int = 60, area_id: str | None = None+ ) -> list[dict[str, Any]]:+ """A bounded sample of the text that contains ``term`` (keyword, not vector).++ The input of the co-occurrence fallback: with no embedding provider,+ the words that keep company with the query word in real text are still+ a genuine, if blunter, notion of "related". Bounded on purpose — this+ SAMPLES the corpus, it does not walk it.++ Passages are preferred when the item has been embedded, because a+ 900-character window is a much sharper measure of "keeps company with"+ than a whole file. A store with no passages yet — precisely the+ keyword-only install this fallback exists for — is sampled at item+ level instead, so the path is never simply dead.+ """+ cleaned = " ".join(str(term or "").split())+ if not cleaned or limit <= 0:+ return []+ conn = await self._lex_conn()+ postgres = self._LEXICON_DIALECT == "postgres"+ if postgres:+ match_clause = "i.search_tsv @@ websearch_to_tsquery('simple', %s)"+ match_param: Any = cleaned+ area_clause = " AND i.areas_json::jsonb @> to_jsonb(%s::text)"+ mark = "%s"+ source = " FROM uw_documents d JOIN uw_items i ON i.id = d.item_id WHERE "+ else:+ match_clause = "uw_fts MATCH ?"+ match_param = '"' + cleaned.replace('"', "") + '"'+ area_clause = (+ " AND EXISTS (SELECT 1 FROM json_each(i.areas_json)"+ " WHERE json_each.value = ?)"+ )+ mark = "?"+ source = (+ " FROM uw_fts JOIN uw_items i ON i.id = uw_fts.item_id"+ " JOIN uw_documents d ON d.item_id = i.id WHERE "+ )++ passage_sql = (+ "SELECT d.id AS document_id, d.item_id AS item_id, d.text_norm AS text"+ + source+ + match_clause+ + " AND i.deleted_at IS NULL"+ )+ params: list[Any] = [match_param]+ if area_id is not None:+ passage_sql += area_clause+ params.append(area_id)+ passage_sql += f" ORDER BY d.id DESC LIMIT {mark}"+ params.append(int(limit))+ rows = await self._fetchall(conn, passage_sql, params) # type: ignore[attr-defined]+ if rows:+ return [+ {+ "document_id": int(row["document_id"]),+ "item_id": int(row["item_id"]),+ "text": str(row["text"] or ""),+ }+ for row in rows+ ]++ item_source = (+ " FROM uw_items i WHERE "+ if postgres+ else " FROM uw_fts JOIN uw_items i ON i.id = uw_fts.item_id WHERE "+ )+ item_sql = (+ "SELECT i.id AS item_id, i.title AS title, i.body_raw AS body_raw"+ + item_source+ + match_clause+ + " AND i.deleted_at IS NULL"+ )+ params = [match_param]+ if area_id is not None:+ item_sql += area_clause+ params.append(area_id)+ item_sql += f" ORDER BY i.id DESC LIMIT {mark}"+ params.append(int(limit))+ rows = await self._fetchall(conn, item_sql, params) # type: ignore[attr-defined]+ return [+ {+ "document_id": None,+ "item_id": int(row["item_id"]),+ "text": f"{row['title'] or ''} {row['body_raw'] or ''}",+ }+ for row in rows+ ]++ async def passages_for_items(+ self, item_ids: Sequence[int], *, limit: int = 400+ ) -> list[dict[str, Any]]:+ """Every stored passage of the given items, with its char span.++ The raw material of passage localization: a keyword hit knows its item+ but not WHERE in it the answer sits, and this is the only table that+ can say. Bounded by ``limit`` across the whole call — a single 200 KB+ file is hundreds of passages and the ranking above needs a sample, not+ the file.+ """+ ids = [int(value) for value in dict.fromkeys(item_ids)]+ if not ids or limit <= 0:+ return []+ conn = await self._lex_conn()+ out: list[dict[str, Any]] = []+ for start in range(0, len(ids), _IN_CHUNK):+ block = ids[start : start + _IN_CHUNK]+ rows = await self._fetchall( # type: ignore[attr-defined]+ conn,+ "SELECT id AS document_id, item_id, chunk_index, char_start," # noqa: S608 — placeholder marks only+ " char_end, text_norm"+ f" FROM uw_documents WHERE item_id IN ({self._lex_marks(len(block))})"+ " ORDER BY item_id, chunk_index"+ f" LIMIT {int(limit)}",+ block,+ )+ for row in rows:+ out.append(+ {+ "document_id": int(row["document_id"]),+ "item_id": int(row["item_id"]),+ "chunk_index": int(row["chunk_index"] or 0),+ "char_start": int(row["char_start"] or 0),+ "char_end": int(row["char_end"] or 0),+ "text_norm": str(row["text_norm"] or ""),+ }+ )+ if len(out) >= int(limit):+ break+ return out[: int(limit)]diff --git a/jarvis/ultrawiki/migrations/0005_term_lexicon.sql b/jarvis/ultrawiki/migrations/0005_term_lexicon.sqlnew file mode 100644index 0000000000..3633166abc--- /dev/null+++ b/jarvis/ultrawiki/migrations/0005_term_lexicon.sql@@ -0,0 +1,43 @@+-- Word-level lexicon: the corpus vocabulary, one row per term, with one+-- vector per term in the SAME embedding space as the documents.+--+-- Why: UltraWiki could already answer a QUESTION by meaning, but not a WORD.+-- "Show me what sits near this term" needs a vocabulary that is itself+-- embedded — the document index cannot answer it, because a passage vector+-- says what a passage is about, never what a word means on its own.+--+-- `doc_freq` counts the PASSAGES a term was seen in while the harvester+-- walked them. It is a rarity signal, not an exact count: a tombstoned item+-- takes its passages with it and this number is not decremented, so it drifts+-- high over a long-lived corpus. That is deliberate — the exact count costs a+-- full re-scan and nothing here is a filter that could drop a term, only an+-- ordering hint. `POST /api/ultrawiki/lexicon/rebuild` resets and recounts.+--+-- Term vectors are keyed by (model, dim) like `uw_embeddings`, so a model+-- switch does not mix vector spaces (design rule D-3): the neighbour query+-- reads the ACTIVE space only, and terms of a retired space are simply+-- re-embedded on the next lexicon pass.++CREATE TABLE IF NOT EXISTS uw_terms (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ term TEXT NOT NULL UNIQUE,+ doc_freq INTEGER NOT NULL DEFAULT 0,+ created_at TEXT NOT NULL,+ updated_at TEXT NOT NULL+);++-- The embed candidate order: the most-seen vocabulary first, so a bounded+-- lexicon holds the words the corpus actually talks about.+CREATE INDEX IF NOT EXISTS idx_uw_terms_freq ON uw_terms(doc_freq DESC, id);++CREATE TABLE IF NOT EXISTS uw_term_embeddings (+ term_id INTEGER NOT NULL REFERENCES uw_terms(id) ON DELETE CASCADE,+ model TEXT NOT NULL,+ dim INTEGER NOT NULL,+ vector BLOB NOT NULL,+ created_at TEXT NOT NULL,+ PRIMARY KEY (term_id, model, dim)+);++CREATE INDEX IF NOT EXISTS idx_uw_term_embeddings_space+ ON uw_term_embeddings(model, dim);diff --git a/jarvis/ultrawiki/pipeline.py b/jarvis/ultrawiki/pipeline.pyindex 6ad127ef06..990793d168 100644--- a/jarvis/ultrawiki/pipeline.py+++ b/jarvis/ultrawiki/pipeline.py@@ -491,6 +491,14 @@ class PipelineWorker:# deference; it does not raise the batch size.if not attempted or self._media_mode() == "eager":attempted += await self._media_pass()+ # The word lexicon runs LAST, in whatever gap is left. Like the event+ # backfill it TERMINATES — once the vocabulary is harvested and+ # embedded it costs one cursor read per pass — but building it over a+ # large corpus takes many passes, and placing it above the media lane+ # would starve that lane for the whole build. Word search degrades+ # gracefully while it fills; a photo nobody described stays invisible.+ if not attempted:+ attempted += await self._lexicon_pass()await self._promote_pass()attempted += await self._legacy_tombstone_repair_pass()# Sample AFTER every pass, including passes that achieved nothing: a@@ -1381,6 +1389,92 @@ class PipelineWorker:await self._store.set_meta(key, str(cursor))return len(items)+ # -- word lexicon --------------------------------------------------------++ async def _lexicon_pass(self) -> int:+ """Harvest vocabulary, then embed the terms word search compares against.++ Two bounded steps per pass, harvest first: embedding a term the corpus+ has not been walked for yet would be paying for a word nobody can+ search. Both are resumable — the harvest by a cursor, the embedding by+ "which terms have no vector in this space" — so a restart continues+ instead of starting over, and a finished lexicon costs one cursor read+ per pass.++ Every capability is probed, so a third-party store or a test fake+ simply has no lexicon lane (and no error). An embedding slot that is+ unusable pauses only THIS lane: word search still answers through the+ provider-free co-occurrence path.+ """+ ultrawiki = getattr(self._cfg, "ultrawiki", None)+ if not bool(getattr(ultrawiki, "lexicon_enabled", True)):+ return 0+ if not callable(getattr(self._store, "lexicon_scan_batch", None)):+ return 0+ from jarvis.ultrawiki import lexicon as lexicon_mod # noqa: PLC0415 — lazy (AP-26)++ try:+ harvested = await lexicon_mod.harvest_pass(+ self._store, limit=lexicon_mod.HARVEST_BATCH+ )+ except asyncio.CancelledError:+ raise+ except Exception: # noqa: BLE001 — an optional lane never kills ingestion+ log.warning(+ "UltraWiki lexicon harvest failed; retrying next pass", exc_info=True+ )+ return 0+ if harvested:+ return harvested++ # Vocabulary is up to date — spend the pass on term vectors instead.+ # A rebuild in flight is left alone: its shadow space is incomplete, so+ # embedding terms into it would pin the lexicon to a geometry no search+ # answers from yet (D-3).+ if await self._reembed_is_running():+ return 0+ try:+ model, dim = await self._store.embedding_space()+ except Exception: # noqa: BLE001 — an unreadable pin pauses the lane only+ log.debug("UltraWiki lexicon: embedding space unreadable", exc_info=True)+ return 0+ if not model or int(dim) <= 0:+ return 0 # nothing embedded yet; the document lanes go first+ backend, _configured_model, reason = await self._embedding_slot()+ if backend is None:+ self._note_stage_pause("lexicon", reason)+ return 0+ if self._embed_cooldown_reason():+ return 0 # the provider asked everyone to wait; this lane can+ self._clear_stage_pause("lexicon")+ try:+ embedded = await lexicon_mod.embed_terms_pass(+ self._store,+ backend,+ # The store's ACTIVE pin, never the configured model: term+ # vectors have to live in the same space as the passages they+ # will be compared against.+ model=model,+ dim=int(dim),+ limit=lexicon_mod.EMBED_BATCH,+ max_terms=int(getattr(ultrawiki, "lexicon_max_terms", 20000) or 20000),+ )+ except asyncio.CancelledError:+ raise+ except Exception as exc: # noqa: BLE001 — a provider outage pauses, never kills+ if _global_embed_failure(exc):+ self._begin_embed_cooldown(exc)+ else:+ log.info(+ "UltraWiki lexicon: term embedding failed (%s); "+ "retrying next pass",+ exc,+ )+ return 0+ if embedded:+ log.debug("UltraWiki lexicon: embedded %d term(s)", embedded)+ return embedded+# -- media enrichment ----------------------------------------------------async def _media_pass(self) -> int:diff --git a/jarvis/ultrawiki/search.py b/jarvis/ultrawiki/search.pyindex 73857c354f..0a422e8154 100644--- a/jarvis/ultrawiki/search.py+++ b/jarvis/ultrawiki/search.py@@ -54,6 +54,7 @@ import loggingimport mathimport reimport time+from collections.abc import Sequencefrom dataclasses import replacefrom datetime import UTC, datetimefrom typing import Any@@ -63,7 +64,15 @@ from jarvis.ultrawiki.types import SearchResultlog = logging.getLogger(__name__)-__all__ = ["hybrid_search", "search", "search_status", "ranking_settings"]+__all__ = [+ "hybrid_search",+ "search",+ "search_status",+ "ranking_settings",+ "embed_query_vector",+ "fuse_legs",+ "query_terms",+]#: RRF smoothing constant (design doc 03: score(d) = sum 1 / (60 + rank)).RRF_K = 60@@ -527,6 +536,77 @@ async def _bounded_vector_leg(return []+async def embed_query_vector(+ cfg: Any, query: str, *, timings: dict[str, float] | None = None+) -> tuple[list[float] | None, str]:+ """Embed one piece of QUERY text through the configured backend.++ Returns ``(vector, reason)``. ``vector`` is ``None`` whenever the+ embedding could not be produced, and ``reason`` then carries an honest,+ credential-free English sentence — no caller of this function may fail+ because embeddings are unavailable, they must degrade.++ Shared by the vector leg and the word lexicon on purpose: both embed short+ query text, both benefit from the same in-process cache, and both must see+ the identical verdict about whether the slot is usable. ``timings``, when+ given, records the call under ``vector_embed_ms``.+ """+ sink: dict[str, float] = timings if timings is not None else {}+ ultrawiki = _uw(cfg)+ provider = str(getattr(ultrawiki, "embedding_provider", "") or "").strip()+ if not provider:+ return None, (+ "no embedding provider is configured — pick one in the UltraWiki "+ "settings; keyword search keeps working"+ )+ from jarvis.ultrawiki.embeddings import ( # noqa: PLC0415 — lazy (AP-26)+ DEFAULT_MODELS,+ EMBEDDING_BACKENDS,+ EmbeddingError,+ )++ factory = EMBEDDING_BACKENDS.get(provider)+ if factory is None:+ return None, f"unknown embedding provider {provider!r}"+ model = _configured_model(ultrawiki, provider, DEFAULT_MODELS)+ cache_key = _query_cache_key(provider, model, query)+ cached = _cached_query_vector(cache_key)+ if cached is not None:+ log.debug("query vector served from the in-process cache")+ return cached, ""+ try:+ vectors = await _timed(+ "vector_embed_ms",+ _embed_query_once(cache_key, factory(cfg), query, model),+ sink,+ )+ except EmbeddingError as exc:+ # Not swallowed: the provider's own honest sentence becomes this+ # function's ``reason`` and every caller either logs it or shows it to+ # the user. Logging here as well would print the same outage twice per+ # search — the noise that hid a real one once.+ return None, str(exc)+ except Exception as exc: # noqa: BLE001 — degrade, never fail the caller+ log.warning(+ "query embedding raised unexpectedly", exc_info=True+ )+ return None, f"the embedding provider failed ({type(exc).__name__})"+ if not vectors or not vectors[0]:+ return None, f"{provider} returned no query vector"+ query_vector = list(vectors[0])+ _remember_query_vector(cache_key, query_vector)+ return query_vector, ""+++def query_vector_cache_key(cfg: Any, query: str) -> tuple[str, str, str]:+ """The cache identity of one query text — also the ANN result cache key."""+ ultrawiki = _uw(cfg)+ provider = str(getattr(ultrawiki, "embedding_provider", "") or "").strip()+ from jarvis.ultrawiki.embeddings import DEFAULT_MODELS # noqa: PLC0415 — lazy (AP-26)++ return _query_cache_key(provider, _configured_model(ultrawiki, provider, DEFAULT_MODELS), query)++async def _vector_leg(store: Any,cfg: Any,@@ -547,46 +627,13 @@ async def _vector_leg(a slow database."""sink: dict[str, float] = timings if timings is not None else {}- ultrawiki = _uw(cfg)- provider = str(getattr(ultrawiki, "embedding_provider", "") or "").strip()- if not provider:- return []- from jarvis.ultrawiki.embeddings import ( # noqa: PLC0415 — lazy (AP-26)- DEFAULT_MODELS,- EMBEDDING_BACKENDS,- EmbeddingError,- )-- factory = EMBEDDING_BACKENDS.get(provider)- if factory is None:- log.warning("vector leg skipped: unknown embedding provider %r", provider)+ if not str(getattr(_uw(cfg), "embedding_provider", "") or "").strip():return []- model = _configured_model(ultrawiki, provider, DEFAULT_MODELS)- cache_key = _query_cache_key(provider, model, query)- query_vector = _cached_query_vector(cache_key)+ query_vector, reason = await embed_query_vector(cfg, query, timings=sink)if query_vector is None:- try:- vectors = await _timed(- "vector_embed_ms",- _embed_query_once(cache_key, factory(cfg), query, model),- sink,- )- except EmbeddingError as exc:- log.info("vector leg skipped: %s", exc)- return []- except Exception: # noqa: BLE001 — degrade to keyword-only, never fail the search- log.warning(- "vector leg skipped: query embedding raised unexpectedly",- exc_info=True,- )- return []- if not vectors or not vectors[0]:- log.info("vector leg skipped: %s returned no query vector", provider)- return []- query_vector = list(vectors[0])- _remember_query_vector(cache_key, query_vector)- else:- log.debug("query vector served from the in-process cache")+ log.info("vector leg skipped: %s", reason)+ return []+ cache_key = query_vector_cache_key(cfg, query)result_key = (*cache_key, str(area_id or ""))results, reason = await _timed("vector_ann_ms",@@ -762,22 +809,40 @@ def _fuse(having remembered something old."""knobs = ranking_settings(cfg)- weights = {- "event": knobs["event_weight"],- "keyword": knobs["keyword_weight"],- "vector": knobs["vector_weight"],- }- half_life = knobs["recency_half_life_days"]+ return fuse_legs(+ [+ ("event", knobs["event_weight"], list(event_hits or [])),+ ("keyword", knobs["keyword_weight"], keyword_hits),+ ("vector", knobs["vector_weight"], vector_hits),+ ],+ cfg=cfg,+ signals=signals,+ )+++def fuse_legs(+ legs: Sequence[tuple[str, float, list[SearchResult]]],+ *,+ cfg: Any = None,+ signals: dict[str, float] | None = None,+) -> list[SearchResult]:+ """RRF-fuse an ORDERED list of ``(leg_name, weight, hits)`` triples.++ The generalization of :func:`_fuse`, which is the three-leg hybrid case.+ A caller with a different leg set — the word search fuses four: the exact+ word, its meaning-neighbours, and two vector queries — gets the identical+ ranking rules (one vote per item per leg, dense ranks, term-rarity signal,+ age decay, recency tiebreak) instead of a second, subtly different fusion.++ Leg ORDER decides the representative row when an item appears in several+ legs, so the leg with the most informative snippet belongs first.+ """+ half_life = ranking_settings(cfg)["recency_half_life_days"]rrf_score: dict[int, float] = {}matched: dict[int, list[str]] = {}representative: dict[int, SearchResult] = {}- for leg_name, hits in (- ("event", list(event_hits or [])),- ("keyword", keyword_hits),- ("vector", vector_hits),- ):- weight = weights[leg_name]+ for leg_name, weight, hits in legs:rank = 0for hit in hits:labels = matched.setdefault(hit.item_id, [])diff --git a/jarvis/ultrawiki/service.py b/jarvis/ultrawiki/service.pyindex df249a8edf..50ce4c389b 100644--- a/jarvis/ultrawiki/service.py+++ b/jarvis/ultrawiki/service.py@@ -2075,6 +2075,46 @@ class UltraWikiService:store=self._require_store(), cfg=self._cfg, query=query, **kwargs)+ async def word_search(self, word: str, **kwargs: Any) -> Any:+ """Expand one word into its meaning-neighbourhood and retrieve passages.++ Same seam as :meth:`search`: the retrieval module owns the logic and is+ imported lazily (AP-26). Returns a+ :class:`~jarvis.ultrawiki.word_search.WordSearchOutcome`, which carries+ its own honest status instead of raising on a thin index.+ """+ await self.ensure_started()+ from jarvis.ultrawiki import word_search as word_search_mod # noqa: PLC0415 — lazy (AP-26)++ return await word_search_mod.word_search(+ self._require_store(), self._cfg, word, **kwargs+ )++ async def rebuild_lexicon(self) -> dict[str, Any]:+ """Throw the word vocabulary away so the background pass recounts it.++ The one repair for a ``doc_freq`` that has drifted after many deletions+ and the way a user asks for a fresh vocabulary after changing the+ embedding model. Deliberately manual: it costs the embedding calls of+ rebuilding the whole term index.+ """+ await self.ensure_started()+ store = self._require_store()+ reset = getattr(store, "reset_lexicon", None)+ if not callable(reset):+ return {+ "ok": False,+ "reason": "this knowledge store has no word lexicon",+ "lexicon": {},+ }+ await reset()+ model, dim = await store.embedding_space()+ return {+ "ok": True,+ "reason": "",+ "lexicon": dict(await store.lexicon_counts(model=model, dim=dim)),+ }+# ---------------------------------------------------------------------------# Active-service seamdiff --git a/jarvis/ultrawiki/store.py b/jarvis/ultrawiki/store.pyindex 89d81ac341..080bc1556b 100644--- a/jarvis/ultrawiki/store.py+++ b/jarvis/ultrawiki/store.py@@ -63,6 +63,7 @@ from jarvis.ultrawiki.identity import (QueueStatus,)from jarvis.ultrawiki.identity_store import IdentityMixin+from jarvis.ultrawiki.lexicon_store import LexiconMixinfrom jarvis.ultrawiki.types import (STATE_ORDER,ConsentState,@@ -464,6 +465,15 @@ _ADDITIVE_COLUMNS: tuple[tuple[str, str, str], ...] = (# exactly the items that need re-embedding LAST — on a 236 k-item store# that is the difference between minutes and days.("uw_items", "reembed_pending", "INTEGER NOT NULL DEFAULT 0"),+ # Multi-chunk documents (migrations/0001_document_chunk_index.sql). SQLite+ # gains them from that migration; every OTHER database — a Postgres store+ # created before the feature, and a fresh one, since ``ddl_statements``+ # writes the base table — has to gain them here, or ``replace_documents``+ # inserts into columns that do not exist and the embed stage fails on+ # every single item.+ ("uw_documents", "chunk_index", "INTEGER NOT NULL DEFAULT 0"),+ ("uw_documents", "char_start", "INTEGER NOT NULL DEFAULT 0"),+ ("uw_documents", "char_end", "INTEGER NOT NULL DEFAULT 0"),)#: Indexes that belong to :data:`_ADDITIVE_COLUMNS` — created after the columns@@ -492,6 +502,10 @@ _ADDITIVE_INDEXES: tuple[str, ...] = (# like the rest of this tuple."CREATE INDEX IF NOT EXISTS idx_uw_items_reembed_pending"" ON uw_items(state, deleted_at) WHERE reembed_pending = 1",+ # What makes "replace this item's passages" atomic and idempotent on the+ # backend that did not get migration 0001.+ "CREATE UNIQUE INDEX IF NOT EXISTS idx_uw_documents_chunk"+ " ON uw_documents(item_id, doc_type, chunk_index)",)#: The persisted per-source outcome of the last finished sync.@@ -540,7 +554,7 @@ _DISTILLED_FINGERPRINT_SQL = (# ----------------------------------------------------------------------------class UltraStore(IdentityMixin, EventMixin):+class UltraStore(IdentityMixin, EventMixin, LexiconMixin):"""Async SQLite store for UltraWiki (the universal reference backend).One instance = one ``aiosqlite`` connection, opened lazily on first use@@ -2397,12 +2411,38 @@ class UltraStore(IdentityMixin, EventMixin):*,area_id: str | None = None,) -> tuple[list[SearchResult], str]:- """ANN leg via the derived ``uw_vec`` index.+ """ANN leg via the derived ``uw_vec`` index — one hit per item.Returns ``(results, reason)`` — ``reason`` is an empty string on thehealthy path and an honest English explanation whenever the vectorleg is degraded (extension unavailable, nothing embedded yet, or aquery-vector/pin mismatch).++ Each hit carries the passage that actually matched (``document_id`` /+ ``chunk_index`` / ``char_start`` / ``char_end``), so a caller can+ locate it inside a 200 KB file instead of being told only which file+ it was.+ """+ return await self.vector_search_passages(+ query_vector, k, area_id=area_id, per_item=1+ )++ async def vector_search_passages(+ self,+ query_vector: Sequence[float],+ k: int = 10,+ *,+ area_id: str | None = None,+ per_item: int = 1,+ ) -> tuple[list[SearchResult], str]:+ """The ANN leg at PASSAGE granularity.++ ``per_item`` is how many passages of one item may appear. ``1`` is the+ classic behaviour (:meth:`vector_search`): one vote per item, which is+ what fusion wants, because five passages of one file would otherwise+ stack five RRF contributions against everyone else's one. A word+ search asks for more, because "where in this document" is precisely+ the question it is answering."""ok, reason = await self._ensure_vec(None)if not ok:@@ -2414,7 +2454,11 @@ class UltraStore(IdentityMixin, EventMixin):f"store's embedding space is pinned to dim={self._vec_dim}")conn = await self._vec_ready_conn(await self._read_conn())- fetch_k = min(max(int(k) * 4, int(k) + 8), 200)+ cap = max(1, int(per_item))+ # Widen the KNN pool with the per-item allowance: asking for k rows+ # when up to `cap` of them may belong to one item would return fewer+ # distinct items the moment a single document dominates.+ fetch_k = min(max(int(k) * 4 * cap, int(k) + 8), 400)knn_rows = await self._fetchall(conn,"SELECT rowid, distance FROM uw_vec WHERE embedding MATCH ? AND k = ?",@@ -2428,6 +2472,8 @@ class UltraStore(IdentityMixin, EventMixin):for chunk in _chunks(doc_ids):sql = ("SELECT d.id AS doc_id, d.text_norm AS text_norm," # noqa: S608 — the interpolation below is placeholder marks only+ " d.chunk_index AS chunk_index, d.char_start AS char_start,"+ " d.char_end AS char_end,"" i.id AS item_id, i.source_id AS source_id, i.title AS title,"" i.permalink AS permalink, i.timestamp_utc AS timestamp_utc"" FROM uw_documents d JOIN uw_items i ON i.id = d.item_id"@@ -2445,12 +2491,13 @@ class UltraStore(IdentityMixin, EventMixin):joined.append((distance_by_doc[int(row["doc_id"])], row))joined.sort(key=lambda pair: pair[0])results: list[SearchResult] = []- seen_items: set[int] = set()+ per_item_seen: dict[int, int] = {}for distance, row in joined:item_id = int(row["item_id"])- if item_id in seen_items:- continue # dedupe multiple documents of one item to the best- seen_items.add(item_id)+ taken = per_item_seen.get(item_id, 0)+ if taken >= cap:+ continue+ per_item_seen[item_id] = taken + 1results.append(SearchResult(item_id=item_id,@@ -2461,6 +2508,10 @@ class UltraStore(IdentityMixin, EventMixin):timestamp_utc=row["timestamp_utc"],score=round(_distance_score(distance), 4),matched_by=("vector",),+ document_id=int(row["doc_id"]),+ chunk_index=int(row["chunk_index"] or 0),+ char_start=int(row["char_start"] or 0),+ char_end=int(row["char_end"] or 0),))if len(results) >= int(k):@@ -2749,7 +2800,7 @@ class UltraStore(IdentityMixin, EventMixin):# ----------------------------------------------------------------------------class PostgresStore(IdentityMixin, EventMixin):+class PostgresStore(IdentityMixin, EventMixin, LexiconMixin):"""Postgres backend behind the same public surface as :class:`UltraStore`.- The keyword leg is a generated ``tsvector`` column with a GIN index,@@ -2772,6 +2823,10 @@ class PostgresStore(IdentityMixin, EventMixin):#: generated ``tsvector`` column here, an FTS5 side table on SQLite._EVENT_DIALECT = "postgres"+ #: Nearest-vector search over the word lexicon: a derived pgvector table+ #: here, a ``vec_distance_cosine`` scan over the stored BLOBs on SQLite.+ _LEXICON_DIALECT = "postgres"+def __init__(self, conn_str: str) -> None:self._conn_str = conn_strself._conn: Any = None@@ -2893,6 +2948,24 @@ class PostgresStore(IdentityMixin, EventMixin):"END $$","CREATE INDEX IF NOT EXISTS idx_uw_embeddings_space"" ON uw_embeddings(model, dim)",+ # Word lexicon (jarvis/ultrawiki/lexicon_store.py) — the Postgres+ # twin of migrations/0005_term_lexicon.sql. The pgvector twin of+ # the SQLite scan (uw_term_vec) is DERIVED lazily on first use,+ # exactly like uw_vec, so a server without the extension still+ # accumulates term vectors and gains word neighbours later.+ "CREATE TABLE IF NOT EXISTS uw_terms ("+ " id BIGSERIAL PRIMARY KEY, term TEXT NOT NULL UNIQUE,"+ " doc_freq INTEGER NOT NULL DEFAULT 0,"+ " created_at TEXT NOT NULL, updated_at TEXT NOT NULL)",+ "CREATE INDEX IF NOT EXISTS idx_uw_terms_freq"+ " ON uw_terms(doc_freq DESC, id)",+ "CREATE TABLE IF NOT EXISTS uw_term_embeddings ("+ " term_id BIGINT NOT NULL REFERENCES uw_terms(id) ON DELETE CASCADE,"+ " model TEXT NOT NULL, dim INTEGER NOT NULL,"+ " vector BYTEA NOT NULL, created_at TEXT NOT NULL,"+ " PRIMARY KEY (term_id, model, dim))",+ "CREATE INDEX IF NOT EXISTS idx_uw_term_embeddings_space"+ " ON uw_term_embeddings(model, dim)","CREATE TABLE IF NOT EXISTS uw_distill_cache ("" content_hash TEXT NOT NULL, prompt_version INTEGER NOT NULL,"" model TEXT NOT NULL, result_json TEXT NOT NULL,"@@ -4344,6 +4417,19 @@ class PostgresStore(IdentityMixin, EventMixin):*,area_id: str | None = None,) -> tuple[list[SearchResult], str]:+ return await self.vector_search_passages(+ query_vector, k, area_id=area_id, per_item=1+ )++ async def vector_search_passages(+ self,+ query_vector: Sequence[float],+ k: int = 10,+ *,+ area_id: str | None = None,+ per_item: int = 1,+ ) -> tuple[list[SearchResult], str]:+ """Postgres twin of :meth:`UltraStore.vector_search_passages`."""ok, reason = await self._ensure_vec(None)if not ok:return [], reason@@ -4355,8 +4441,10 @@ class PostgresStore(IdentityMixin, EventMixin):)conn = await self._ensure_open()literal = self._pgvector_literal(query_vector)+ cap = max(1, int(per_item))sql = (- "SELECT d.item_id, i.source_id, i.title, d.text_norm,"+ "SELECT d.id AS doc_id, d.item_id, i.source_id, i.title, d.text_norm,"+ " d.chunk_index, d.char_start, d.char_end,"" i.permalink, i.timestamp_utc,"" (v.embedding <=> %s::vector) AS distance"" FROM uw_vec v"@@ -4369,15 +4457,16 @@ class PostgresStore(IdentityMixin, EventMixin):sql += " AND i.areas_json::jsonb @> to_jsonb(%s::text)"params.append(area_id)sql += " ORDER BY distance LIMIT %s"- params.append(min(max(int(k) * 4, int(k) + 8), 200))+ params.append(min(max(int(k) * 4 * cap, int(k) + 8), 400))rows = await self._fetchall(conn, sql, params)results: list[SearchResult] = []- seen_items: set[int] = set()+ per_item_seen: dict[int, int] = {}for row in rows:item_id = int(row["item_id"])- if item_id in seen_items:+ taken = per_item_seen.get(item_id, 0)+ if taken >= cap:continue- seen_items.add(item_id)+ per_item_seen[item_id] = taken + 1results.append(SearchResult(item_id=item_id,@@ -4388,6 +4477,10 @@ class PostgresStore(IdentityMixin, EventMixin):timestamp_utc=row["timestamp_utc"],score=round(_distance_score(float(row["distance"])), 4),matched_by=("vector",),+ document_id=int(row["doc_id"]),+ chunk_index=int(row["chunk_index"] or 0),+ char_start=int(row["char_start"] or 0),+ char_end=int(row["char_end"] or 0),))if len(results) >= int(k):diff --git a/jarvis/ultrawiki/types.py b/jarvis/ultrawiki/types.pyindex aed60a5a8c..d0819a64dd 100644--- a/jarvis/ultrawiki/types.py+++ b/jarvis/ultrawiki/types.py@@ -23,6 +23,7 @@ __all__ = ["DocType","ConsentState","ExploreReason",+ "WordSearchStatus","IncrementalMode","AuthKind","RawItem",@@ -101,6 +102,32 @@ class ExploreReason(StrEnum):NO_ENTITIES = "no_entities"+class WordSearchStatus(StrEnum):+ """Why a word search returned what it returned.++ A word search can come back empty for four unrelated reasons, and the+ user cannot tell them apart by looking at an empty list: the store holds+ nothing yet, the word is not in this corpus at all, the word IS known but+ nothing it points at survived ranking, or the lexicon that turns a word+ into its neighbourhood has not been built (no embedding provider, or the+ background pass has not reached it). Each one has a different next step,+ so the server names the cause rather than leaving the surface to guess.++ ``OK`` means hits were returned. ``NEIGHBOURS_UNAVAILABLE`` is NOT a+ failure: the search still ran on the word itself and may well have hits —+ it only says the meaning-neighbourhood could not be computed.++ Five-layer discipline (AP-4 / BUG-008): this is the CANONICAL list. The+ TypeScript union in ``lib/ultrawikiApi.ts`` is parity-tested against it.+ """++ OK = "ok"+ EMPTY_INDEX = "empty_index"+ UNKNOWN_WORD = "unknown_word"+ NO_MATCHES = "no_matches"+ NEIGHBOURS_UNAVAILABLE = "neighbours_unavailable"++class IncrementalMode(StrEnum):"""How a connector keeps a source fresh after backfill."""@@ -254,6 +281,17 @@ class SearchResult:rerank_score: float | None = None # absolute 0-10 grade, None = not rerankedcontext: tuple[str, ...] = () # neighbouring sections/messagesrecorded_utc: str = "" # when the ITEM was recorded; "" = same as timestamp_utc+ # -- passage provenance --------------------------------------------------+ # WHICH passage of the item answered (migration 0001: an item holds many+ # documents, one per chunk of its text). The vector leg has always known+ # this and threw it away, so a hit on page 40 of a file was reported as a+ # hit on "the file" and the reader had to search it by hand. ``None``+ # means the leg genuinely cannot say — a keyword hit before passage+ # localization, an event card, a third-party store.+ document_id: int | None = None+ chunk_index: int | None = None+ char_start: int | None = None+ char_end: int | None = None@dataclass(frozen=True, slots=True)diff --git a/jarvis/ultrawiki/word_search.py b/jarvis/ultrawiki/word_search.pynew file mode 100644index 0000000000..16f9529854--- /dev/null+++ b/jarvis/ultrawiki/word_search.py@@ -0,0 +1,660 @@+"""Word search — one word in, the passages its meaning-neighbourhood reaches.++The shape of the problem+========================++Hybrid search (``jarvis.ultrawiki.search``) is built around a QUESTION: it has+enough words to fuse a keyword leg with a vector leg and grade the result. A+single word gives it almost nothing to work with. Yet a one-word query is how+people actually hunt a concept they cannot name exactly — they know roughly+what it is *about* and nothing about how the corpus spells it.++So this module inverts the order. It first asks the word lexicon+(:mod:`jarvis.ultrawiki.lexicon`) for the ~20 terms nearest the query word by+meaning, and only THEN retrieves — with four legs instead of two:++ word the exact term, keyword leg (what you typed)+ semantic the term's own vector, over PASSAGES (what it means)+ related the neighbour terms, keyword leg (how the corpus spells it)+ neighbourhood the neighbourhood's centroid vector (the concept around it)+ │+ ▼+ RRF FUSION (jarvis.ultrawiki.search.fuse_legs — the same ranking rules+ as hybrid search: one vote per item per leg, term rarity,+ age decay, recency tiebreak)+ │+ ▼+ PASSAGE LOCALIZATION which chunk of each winning item actually carries+ the vocabulary, with its char span++Passage localization is the point+=================================++An item can be a 200 KB file. Migration 0001 already stores it as many+passages with ``chunk_index``/``char_start``/``char_end``, but retrieval+collapsed every hit back to one row per item and threw the span away, so the+answer was "it is somewhere in this file". Here every hit carries the passages+that actually hold the vocabulary, with the offsets to find them — which is+also what makes the neighbour expansion worth anything: a neighbour term+usually matches ONE paragraph of a long document, not the document.++Deliberately absent+===================++**No rerank.** The rerank stage grades "how well does this answer the+question", and a word is not a question — the grade would be noise wearing a+number. Fusion order stands, and ``rerank_score`` is honestly ``None``.++**No relevance floor.** This is an explicit exploration surface: the user+typed the word and can see the evidence. Floors belong to unsolicited+surfaces (design doc 03).++Every degraded path is a NAMED outcome (:class:`WordSearchStatus`), never an+empty list the reader has to interpret: an empty store, an unknown word, a+known word whose matches all lost, and a lexicon that could not produce+neighbours are four different situations with four different next steps.+"""++from __future__ import annotations++import asyncio+import logging+from dataclasses import dataclass, field+from typing import Any++from jarvis.ultrawiki.lexicon import (+ DEFAULT_NEIGHBOURS,+ NEIGHBOUR_SOURCE_NONE,+ TermNeighbour,+ centroid,+ normalize_word,+ word_tokens,+)+from jarvis.ultrawiki.types import SearchResult, WordSearchStatus++log = logging.getLogger(__name__)++__all__ = [+ "Passage",+ "WordHit",+ "WordSearchOutcome",+ "word_search",+ "MAX_NEIGHBOURS",+ "MAX_PASSAGES_PER_HIT",+]++#: Candidates each leg contributes to the fusion pool, matching+#: ``search.LEG_POOL`` so no leg can dominate by returning more rows.+_LEG_POOL = 20++#: Hard ceiling on the neighbourhood a caller may request. Twenty is the+#: default and the useful size; the cap exists so a REST parameter cannot turn+#: one search into a corpus-wide term dump.+MAX_NEIGHBOURS = 50++#: How many neighbour terms enter the KEYWORD expansion. Fewer than the list+#: the user is shown, on purpose: an FTS query ORs its tokens, so every extra+#: term widens the candidate set, and past roughly a dozen the weakest+#: neighbours contribute noise instead of recall. The full list still drives+#: passage scoring, where a weak term costs nothing.+_EXPANSION_TERMS = 12++#: Passages reported per hit. Three is enough to show that an answer spans a+#: document without turning one hit into a wall of text.+MAX_PASSAGES_PER_HIT = 3++#: Total passages loaded for localization across ALL hits of one search. One+#: large file is hundreds of passages, and the scoring below needs a sample of+#: the winners, never the corpus.+_PASSAGE_BUDGET = 600++#: A neighbour term never counts as much as the word that was actually typed,+#: however similar it is. These are the RRF leg weights, expressed as a share+#: of the corresponding hybrid-search knob so a user who silences the keyword+#: or vector leg silences it here too.+_RELATED_LEG_SHARE = 0.6+_NEIGHBOURHOOD_LEG_SHARE = 0.7++#: Floor under a neighbour's weight in passage scoring. Even the twentieth+#: neighbour is evidence that a passage is on topic; it just is not much.+_MIN_TERM_WEIGHT = 0.2++#: Passages per item pulled from the vector legs. More than one, because+#: "which part of this document" is exactly what a word search is asking.+_VECTOR_PER_ITEM = 2++#: How much a passage gains for being the one a vector leg actually matched.+#: Additive and small: it breaks ties in favour of the passage the embedding+#: model chose, without letting it outrank a passage that visibly carries more+#: of the vocabulary.+_VECTOR_MATCH_BONUS = 0.25++#: The score an UNRELATED passage gets. Both backends measure cosine+#: distance and the store maps it with ``1 / (1 + distance)``, so a vector at+#: right angles to the query (cosine similarity 0 — no relation either way)+#: lands exactly here, anything positively related above, anything actively+#: opposed below. It is a property of that transform, not a tuned number.+_UNRELATED_SCORE = 0.5++#: How much of the BEST hit's relatedness a vector hit must keep to stay.+#:+#: Why a floor exists here at all: the hybrid path can hand a weak candidate+#: to the rerank model, which grades it absolutely and drops it. A word search+#: has no rerank (a word is not a question), so without a floor the ANN leg+#: would return its k nearest passages no matter how far away they are, and+#: "no matches" could never be said honestly — a search for a word this corpus+#: knows nothing about would answer with its twenty least-unrelated passages.+#: Relative rather than absolute on purpose: embedding models disagree wildly+#: about what an absolute cosine of 0.3 means, but "less than a third as+#: related as the best thing I found" travels across all of them.+_VECTOR_RELATIVE_FLOOR = 0.35+++@dataclass(frozen=True, slots=True)+class Passage:+ """One located span of an item's text.++ ``char_start``/``char_end`` are offsets into the item's body, so a surface+ can jump to it or highlight it. ``terms`` names which of the searched+ words this span actually shows — the difference between "this file is+ relevant" and "here is the sentence".+ """++ document_id: int+ chunk_index: int+ char_start: int+ char_end: int+ text: str+ terms: tuple[str, ...] = ()+ score: float = 0.0+++@dataclass(frozen=True, slots=True)+class WordHit:+ """One item the word neighbourhood reached, with its located passages."""++ item_id: int+ source_id: str+ title: str+ snippet: str+ permalink: str+ timestamp_utc: str+ score: float+ matched_by: tuple[str, ...] = ()+ passages: tuple[Passage, ...] = ()+++@dataclass(frozen=True, slots=True)+class WordSearchOutcome:+ """Everything one word search produced, including WHY it produced it."""++ word: str+ status: str = WordSearchStatus.OK.value+ #: ``"vector"`` | ``"cooccurrence"`` | ``"none"`` — how the neighbours+ #: were derived. See :mod:`jarvis.ultrawiki.lexicon`.+ neighbour_source: str = NEIGHBOUR_SOURCE_NONE+ #: Honest English explanation whenever something is degraded or empty.+ reason: str = ""+ neighbours: tuple[TermNeighbour, ...] = ()+ hits: tuple[WordHit, ...] = ()+ #: Vocabulary size / embedded share / harvest progress, so the surface can+ #: say "the word index is still being built" instead of "no results".+ lexicon: dict[str, int] = field(default_factory=dict)+++async def word_search(+ store: Any,+ cfg: Any,+ word: str,+ *,+ k: int = 10,+ neighbours: int = DEFAULT_NEIGHBOURS,+ area_id: str | None = None,+) -> WordSearchOutcome:+ """Expand ``word`` into its meaning-neighbourhood and retrieve passages.++ ``k`` bounds the items returned; ``neighbours`` the size of the+ neighbourhood (capped at :data:`MAX_NEIGHBOURS`). Never raises for a+ missing provider, an empty corpus or an unknown word — each is a named+ :class:`~jarvis.ultrawiki.types.WordSearchStatus`.+ """+ term = normalize_word(word)+ wanted = max(0, min(int(neighbours), MAX_NEIGHBOURS))+ if not term:+ return WordSearchOutcome(+ word="",+ status=WordSearchStatus.NO_MATCHES.value,+ reason="the search word was blank",+ )++ lexicon_counts = await _lexicon_counts(store)+ if not await _corpus_has_items(store):+ return WordSearchOutcome(+ word=term,+ status=WordSearchStatus.EMPTY_INDEX.value,+ reason=(+ "nothing has been imported yet — approve a source and run a "+ "sync, then word search has something to look through"+ ),+ lexicon=lexicon_counts,+ )++ from jarvis.ultrawiki.lexicon import resolve_neighbours # noqa: PLC0415 — lazy (AP-26)++ neighbour_list, source, reason, query_vector = await resolve_neighbours(+ store, cfg, term, limit=wanted, area_id=area_id+ )++ weights = _term_weights(term, neighbour_list)+ hits = await _retrieve(+ store,+ cfg,+ term,+ neighbour_list,+ query_vector=query_vector,+ k=int(k),+ area_id=area_id,+ )+ located = await _localize(store, hits, weights) if hits else []++ status = _status_for(+ hits=located,+ neighbour_source=source,+ word_is_known=await _word_is_known(store, term),+ )+ # The status explains the RESULT and leads; a degraded neighbour path is+ # secondary context. Told the other way round, "no word vectors yet" reads+ # as the reason a word the corpus has never seen found nothing, which+ # sends the reader to fix a provider instead of trying another word.+ reason = _join_reasons(_status_reason(status, term), reason)+ return WordSearchOutcome(+ word=term,+ status=status,+ neighbour_source=source,+ reason=reason,+ neighbours=tuple(neighbour_list),+ hits=tuple(located),+ lexicon=lexicon_counts,+ )+++# ---------------------------------------------------------------------------+# Retrieval+# ---------------------------------------------------------------------------+++def _term_weights(term: str, neighbours: list[TermNeighbour]) -> dict[str, float]:+ """How much each searched word counts when scoring a passage.++ The typed word (and every token of a typed phrase) counts fully; a+ neighbour counts as much as it is similar, floored so the tail of the list+ still contributes something.+ """+ weights = {token: 1.0 for token in word_tokens(term)}+ for neighbour in neighbours:+ for token in word_tokens(neighbour.term):+ weight = max(_MIN_TERM_WEIGHT, min(1.0, float(neighbour.similarity)))+ weights[token] = max(weights.get(token, 0.0), weight)+ return weights+++async def _retrieve(+ store: Any,+ cfg: Any,+ term: str,+ neighbours: list[TermNeighbour],+ *,+ query_vector: list[float] | None,+ k: int,+ area_id: str | None,+) -> list[SearchResult]:+ """Run the four legs concurrently and fuse them.++ Every leg degrades to an empty list on its own: no vector provider means+ the two vector legs are simply absent and the keyword legs answer alone,+ which is the same contract the hybrid path keeps.+ """+ from jarvis.ultrawiki.search import fuse_legs, ranking_settings # noqa: PLC0415 — lazy (AP-26)++ expansion = [+ neighbour.term for neighbour in neighbours[:_EXPANSION_TERMS] if neighbour.term+ ]+ knobs = ranking_settings(cfg)+ keyword_weight = knobs["keyword_weight"]+ vector_weight = knobs["vector_weight"]++ neighbourhood_vector = await _neighbourhood_vector(+ store, query_vector, neighbours+ )+ word_hits, related_hits, semantic_hits, concept_hits = await asyncio.gather(+ _keyword_leg(store, term, area_id=area_id),+ _keyword_leg(store, " ".join(expansion), area_id=area_id),+ _vector_leg(store, query_vector, area_id=area_id),+ _vector_leg(store, neighbourhood_vector, area_id=area_id),+ )+ # Leg ORDER decides which row survives the merge as the representative.+ # The exact-word keyword hit leads because its snippet is rendered around+ # the match; the vector hit follows because it carries passage provenance.+ fused = fuse_legs(+ [+ ("word", keyword_weight, word_hits),+ ("semantic", vector_weight, semantic_hits),+ ("related", keyword_weight * _RELATED_LEG_SHARE, related_hits),+ (+ "neighbourhood",+ vector_weight * _NEIGHBOURHOOD_LEG_SHARE,+ concept_hits,+ ),+ ],+ cfg=cfg,+ # No term-rarity signal here, deliberately: that factor scales a+ # candidate by how much of the query's RARE vocabulary its snippet+ # shows, and an EXPANDED query has no stable rare vocabulary — a+ # neighbour term absent from a snippet would push down exactly the+ # passages the expansion was meant to surface.+ signals=None,+ )+ return fused[: max(0, int(k))]+++async def _keyword_leg(+ store: Any, query: str, *, area_id: str | None+) -> list[SearchResult]:+ """Keyword hits for one query string; empty and logged on any failure."""+ if not query.strip():+ return []+ try:+ return list(await store.keyword_search(query, k=_LEG_POOL, area_id=area_id))+ except Exception: # noqa: BLE001 — one leg never fails the search+ log.warning("word search: keyword leg failed", exc_info=True)+ return []+++async def _vector_leg(+ store: Any, query_vector: list[float] | None, *, area_id: str | None+) -> list[SearchResult]:+ """Passage-level ANN hits, or nothing when there is no vector to run.++ Uses ``vector_search_passages`` when the store has it so one document can+ contribute more than its opening passage; an older or third-party store+ falls back to ``vector_search`` and simply reports fewer passages.+ """+ if not query_vector:+ return []+ passages = getattr(store, "vector_search_passages", None)+ try:+ if callable(passages):+ results, reason = await passages(+ query_vector, _LEG_POOL, area_id=area_id, per_item=_VECTOR_PER_ITEM+ )+ else:+ results, reason = await store.vector_search(+ query_vector, _LEG_POOL, area_id=area_id+ )+ except Exception: # noqa: BLE001 — one leg never fails the search+ log.warning("word search: vector leg failed", exc_info=True)+ return []+ if reason:+ log.info("word search: vector leg degraded: %s", reason)+ return _drop_unrelated(list(results))+++def _drop_unrelated(hits: list[SearchResult]) -> list[SearchResult]:+ """Keep the vector hits that are actually related to the query.++ Two gates, both cheap and both necessary (see+ :data:`_VECTOR_RELATIVE_FLOOR`): a passage at right angles to the query is+ dropped outright, and one far behind the best hit of the SAME leg is+ dropped as well. The list is already sorted best-first, so this only ever+ trims a tail — it can never reorder anything.+ """+ if not hits:+ return hits+ best = hits[0].score+ if best <= _UNRELATED_SCORE:+ return []+ threshold = _UNRELATED_SCORE + (best - _UNRELATED_SCORE) * _VECTOR_RELATIVE_FLOOR+ return [hit for hit in hits if hit.score > _UNRELATED_SCORE and hit.score >= threshold]+++async def _neighbourhood_vector(+ store: Any, query_vector: list[float] | None, neighbours: list[TermNeighbour]+) -> list[float] | None:+ """The centroid of the word and its nearest neighbours, or ``None``.++ Built from the term vectors the lexicon ALREADY stored, never from fresh+ provider calls: one search must cost at most one embedding round trip, not+ one per neighbour. When no term vectors are available the centroid is+ simply absent and that leg does not run.+ """+ if not query_vector or not neighbours:+ return None+ lookup = getattr(store, "term_vectors_for", None)+ if not callable(lookup):+ return None+ try:+ model, dim = await store.embedding_space()+ if not model or dim <= 0:+ return None+ stored = await lookup(+ [neighbour.term for neighbour in neighbours], model=model, dim=dim+ )+ except Exception: # noqa: BLE001 — the concept leg is a bonus, never a failure+ log.debug("word search: neighbour vectors unavailable", exc_info=True)+ return None+ if not stored:+ return None+ vector = centroid([query_vector, *stored.values()])+ if vector is None or vector == list(query_vector):+ return None+ return vector+++# ---------------------------------------------------------------------------+# Passage localization+# ---------------------------------------------------------------------------+++async def _localize(+ store: Any, hits: list[SearchResult], weights: dict[str, float]+) -> list[WordHit]:+ """Attach the passages of each hit that actually carry the vocabulary.++ Best-effort and last: a store without ``passages_for_items`` — a+ third-party backend, a test fake — yields hits whose ``passages`` are+ empty, and the snippet still stands. Nothing here can change the ranking+ above it.+ """+ by_item: dict[int, list[dict[str, Any]]] = {}+ reader = getattr(store, "passages_for_items", None)+ if callable(reader):+ try:+ rows = await reader(+ [hit.item_id for hit in hits], limit=_PASSAGE_BUDGET+ )+ except Exception: # noqa: BLE001 — localization is evidence, never a failure+ log.warning("word search: passage lookup failed", exc_info=True)+ rows = []+ for row in rows or []:+ by_item.setdefault(int(row["item_id"]), []).append(row)++ located: list[WordHit] = []+ for hit in hits:+ passages = _rank_passages(by_item.get(hit.item_id, []), weights, hit)+ located.append(+ WordHit(+ item_id=hit.item_id,+ source_id=hit.source_id,+ title=hit.title,+ snippet=hit.snippet,+ permalink=hit.permalink,+ timestamp_utc=hit.timestamp_utc,+ score=hit.score,+ matched_by=hit.matched_by,+ passages=passages,+ )+ )+ return located+++def _rank_passages(+ rows: list[dict[str, Any]], weights: dict[str, float], hit: SearchResult+) -> tuple[Passage, ...]:+ """The best :data:`MAX_PASSAGES_PER_HIT` passages of one item.++ Scored on how much of the searched vocabulary a passage visibly shows,+ weighted by how close each word is to the one that was typed, plus a small+ bonus for the passage a vector leg matched. Ties keep document order, so+ two equally-good passages read top to bottom.+ """+ if not rows:+ # The vector leg already told us WHICH passage matched even when the+ # passage table is unreadable — reporting that beats reporting nothing.+ if hit.document_id is not None:+ return (+ Passage(+ document_id=int(hit.document_id),+ chunk_index=int(hit.chunk_index or 0),+ char_start=int(hit.char_start or 0),+ char_end=int(hit.char_end or 0),+ text=hit.snippet,+ terms=(),+ score=0.0,+ ),+ )+ return ()+ scored: list[tuple[float, int, Passage]] = []+ for row in rows:+ text = str(row.get("text_norm", ""))+ present = set(word_tokens(text))+ matched = tuple(+ token for token in weights if token in present+ )+ score = sum(weights[token] for token in matched)+ if hit.document_id is not None and int(row["document_id"]) == int(hit.document_id):+ score += _VECTOR_MATCH_BONUS+ if score <= 0.0:+ continue+ scored.append(+ (+ score,+ int(row.get("chunk_index", 0) or 0),+ Passage(+ document_id=int(row["document_id"]),+ chunk_index=int(row.get("chunk_index", 0) or 0),+ char_start=int(row.get("char_start", 0) or 0),+ char_end=int(row.get("char_end", 0) or 0),+ text=_trim(text),+ terms=matched,+ score=round(score, 4),+ ),+ )+ )+ if not scored:+ return ()+ scored.sort(key=lambda entry: (-entry[0], entry[1]))+ return tuple(passage for _, _, passage in scored[:MAX_PASSAGES_PER_HIT])+++#: Passage text handed to the surface. Long enough to read as a paragraph,+#: short enough that three of them per hit stay scannable.+_PASSAGE_CHARS = 420+++def _trim(text: str) -> str:+ collapsed = " ".join(text.split())+ if len(collapsed) <= _PASSAGE_CHARS:+ return collapsed+ return collapsed[:_PASSAGE_CHARS].rstrip() + "…"+++# ---------------------------------------------------------------------------+# Honest outcomes+# ---------------------------------------------------------------------------+++def _status_reason(status: str, term: str) -> str:+ """The sentence that explains a status on its own."""+ if status == WordSearchStatus.UNKNOWN_WORD.value:+ return (+ f"'{term}' does not occur anywhere in the imported text, and no "+ "related word led anywhere either"+ )+ if status == WordSearchStatus.NO_MATCHES.value:+ return (+ f"'{term}' occurs in the corpus, but nothing it points at "+ "survived ranking — try a broader word"+ )+ return ""+++def _join_reasons(*parts: str) -> str:+ """Chain the honest sentences that apply, most important first."""+ kept = [part.strip() for part in parts if part and part.strip()]+ return " — ".join(dict.fromkeys(kept))+++def _status_for(+ *, hits: list[WordHit], neighbour_source: str, word_is_known: bool+) -> str:+ if hits:+ if neighbour_source == NEIGHBOUR_SOURCE_NONE:+ # Hits, but the neighbourhood is missing: the user got a plain+ # word search and should be told the expansion did not run.+ return WordSearchStatus.NEIGHBOURS_UNAVAILABLE.value+ return WordSearchStatus.OK.value+ if not word_is_known:+ return WordSearchStatus.UNKNOWN_WORD.value+ return WordSearchStatus.NO_MATCHES.value+++async def _corpus_has_items(store: Any) -> bool:+ """Is there anything to search at all? Unknown counts as yes.++ A store that cannot answer must not be reported as empty — "nothing+ imported" sends the user to the Sources screen, and sending them there+ over a missing probe would be a lie.+ """+ probe = getattr(store, "live_item_count", None)+ if not callable(probe):+ return True+ try:+ return int(await probe()) > 0+ except Exception: # noqa: BLE001 — an unreadable count is not an empty store+ log.debug("word search: item count probe failed", exc_info=True)+ return True+++async def _word_is_known(store: Any, term: str) -> bool:+ """Does the word occur in the imported text at all?++ Distinguishes "I have never seen this word" from "I know it but nothing+ it points at ranked" — two empty screens with different next steps.+ Unknown counts as KNOWN, so a missing probe never accuses the user of+ typing a word the corpus might well contain.+ """+ probe = getattr(store, "term_document_frequency", None)+ if not callable(probe):+ return True+ tokens = word_tokens(term)+ if not tokens:+ return False+ try:+ frequencies = await probe(tokens)+ except Exception: # noqa: BLE001 — an unreadable probe never accuses the user+ log.debug("word search: term frequency probe failed", exc_info=True)+ return True+ return any(int(frequencies.get(token, 0) or 0) > 0 for token in tokens)+++async def _lexicon_counts(store: Any) -> dict[str, int]:+ """Vocabulary size + embedded share, or ``{}`` when unavailable."""+ probe = getattr(store, "lexicon_counts", None)+ if not callable(probe):+ return {}+ try:+ model, dim = await store.embedding_space()+ return dict(await probe(model=model, dim=dim))+ except Exception: # noqa: BLE001 — a size report never fails a search+ log.debug("word search: lexicon counts unavailable", exc_info=True)+ return {}diff --git a/tests/unit/ultrawiki/test_word_search.py b/tests/unit/ultrawiki/test_word_search.pynew file mode 100644index 0000000000..264ba55a8b--- /dev/null+++ b/tests/unit/ultrawiki/test_word_search.py@@ -0,0 +1,435 @@+"""Word search over a REAL UltraStore — vocabulary, neighbours, passages.++Everything here runs against an actual SQLite store with real FTS5 and real+multi-chunk documents; only the embedding backend is a deterministic offline+fake. What is being pinned:++* the lexicon is harvested from the item table and embedded into the store's+ ACTIVE space, and word neighbours come back ordered by meaning;+* the neighbourhood drives retrieval, so an item that never spells the query+ word out is still reachable through a neighbour;+* every hit names the PASSAGE that carries the vocabulary, with its character+ span — not the head of the item;+* each degraded path is a NAMED status: empty store, unknown word, a known+ word that ranks nowhere, and a lexicon that could not produce neighbours;+* a dead embedding provider degrades to the provider-free co-occurrence path+ and writes nothing.++No network, no credentials, no models.+"""++from __future__ import annotations++import importlib.util+from types import SimpleNamespace++import pytest++import jarvis.ultrawiki.embeddings as embeddings_mod+from jarvis.ultrawiki.chunking import Chunk+from jarvis.ultrawiki.embeddings import EmbeddingError+from jarvis.ultrawiki.lexicon import (+ NEIGHBOUR_SOURCE_COOCCURRENCE,+ NEIGHBOUR_SOURCE_VECTOR,+ embed_terms_pass,+ harvest_pass,+)+from jarvis.ultrawiki.store import UltraStore+from jarvis.ultrawiki.types import (+ ConsentState,+ DocType,+ ItemState,+ RawItem,+ WordSearchStatus,+)+from jarvis.ultrawiki.word_search import word_search++HAS_SQLITE_VEC = importlib.util.find_spec("sqlite_vec") is not None++EMBED_MODEL = "fake-model"+EMBED_DIM = 4++#: A tiny hand-built "semantic space": each word sits on a named axis, and+#: words that belong to one topic share an axis, so nearest-neighbour order is+#: something the test states rather than something it hopes for.+#: axis 0 = sailing axis 1 = cooking axis 2 = money axis 3 = filler+_SPACE: dict[str, list[float]] = {+ "regatta": [1.0, 0.0, 0.0, 0.0],+ "sailing": [0.97, 0.0, 0.0, 0.24],+ "mainsail": [0.94, 0.0, 0.0, 0.34],+ "harbour": [0.90, 0.0, 0.0, 0.44],+ "risotto": [0.0, 1.0, 0.0, 0.0],+ "saffron": [0.0, 0.96, 0.0, 0.28],+ "invoice": [0.0, 0.0, 1.0, 0.0],+ "vat": [0.0, 0.0, 0.95, 0.31],+}+++class FakeEmbedding:+ """Deterministic offline backend over :data:`_SPACE`."""++ name = "fake"++ def __init__(self, *, error: Exception | None = None) -> None:+ self._error = error+ self.calls: list[list[str]] = []++ def ready(self) -> tuple[bool, str]:+ if self._error is not None:+ return False, "fake backend is unavailable"+ return True, ""++ async def embed(self, texts: list[str], *, model: str) -> list[list[float]]:+ self.calls.append(list(texts))+ if self._error is not None:+ raise self._error+ return [list(_vector_for(text)) for text in texts]+++def _vector_for(text: str) -> list[float]:+ """A text's vector: the mean of the known words in it, else pure filler."""+ known = [_SPACE[word] for word in text.lower().split() if word in _SPACE]+ if not known:+ return [0.0, 0.0, 0.0, 1.0]+ return [sum(values) / len(known) for values in zip(*known, strict=True)]+++def make_cfg(**overrides) -> SimpleNamespace:+ values = {+ "enabled": True,+ "embedding_provider": "fake",+ "embedding_model": EMBED_MODEL,+ "rerank_provider": "",+ "rerank_min_score": 4.0,+ "rrf_keyword_weight": 1.0,+ "rrf_vector_weight": 1.0,+ "rrf_event_weight": 1.0,+ "recency_half_life_days": 0.0, # decay off: these fixtures share a date+ "lexicon_enabled": True,+ "lexicon_max_terms": 20000,+ "word_search_neighbours": 20,+ }+ values.update(overrides)+ return SimpleNamespace(ultrawiki=SimpleNamespace(**values))+++async def store(tmp_path):+ instance = UltraStore(tmp_path / "ultrawiki.db")+ yield instance+ await instance.close()+++async def seed(store: UltraStore, items: list[tuple[str, str, str]]) -> dict[str, int]:+ """Import ``(external_id, title, body)`` triples and keyword-index them."""+ await store.upsert_source("src1", connector="local-folder", label="Test source")+ await store.set_consent("src1", ConsentState.APPROVED)+ await store.upsert_items(+ "src1",+ [+ RawItem(+ external_id=external_id,+ body=body,+ permalink=f"app://{external_id}",+ timestamp_utc="2026-01-02T10:00:00Z",+ title=title,+ )+ for external_id, title, body in items+ ],+ )+ for claimed in await store.claim_batch(ItemState.KEYWORD_INDEXED, limit=500):+ await store.mark_stage_done(+ claimed["id"],+ ItemState.KEYWORD_INDEXED,+ fts_title=claimed["title"],+ fts_body=claimed["body_raw"],+ )+ ids: dict[str, int] = {}+ for external_id, _title, _body in items:+ row = await store.get_item_by_external_id("src1", external_id)+ assert row is not None+ ids[external_id] = int(row["id"])+ return ids+++async def embed_passages(store: UltraStore, item_id: int, passages: list[str]) -> list[int]:+ """Store ``passages`` as real chunk documents, one vector each."""+ chunks: list[Chunk] = []+ offset = 0+ for index, text in enumerate(passages):+ chunks.append(+ Chunk(index=index, text=text, char_start=offset, char_end=offset + len(text))+ )+ offset += len(text) + 1+ doc_ids = await store.replace_documents(item_id, DocType.RAW, chunks)+ for doc_id, text in zip(doc_ids, passages, strict=True):+ await store.store_embedding(+ doc_id, model=EMBED_MODEL, dim=EMBED_DIM, vector=_vector_for(text)+ )+ return doc_ids+++async def build_lexicon(store: UltraStore, backend: FakeEmbedding) -> None:+ """Run the background passes to completion, exactly as the pipeline does."""+ while await harvest_pass(store, limit=200):+ pass+ while await embed_terms_pass(+ store, backend, model=EMBED_MODEL, dim=EMBED_DIM, limit=64, min_doc_freq=1+ ):+ pass+++def register(monkeypatch, backend: FakeEmbedding) -> None:+ monkeypatch.setitem(embeddings_mod.EMBEDDING_BACKENDS, "fake", lambda cfg: backend)+++# ---------------------------------------------------------------------------+# The happy path+# ---------------------------------------------------------------------------++[email protected](not HAS_SQLITE_VEC, reason="sqlite-vec is not installed")+async def test_neighbours_are_ordered_by_meaning(store, monkeypatch):+ backend = FakeEmbedding()+ register(monkeypatch, backend)+ ids = await seed(+ store,+ [+ ("a", "Race log", "regatta sailing mainsail harbour"),+ ("b", "Kitchen", "risotto saffron"),+ ("c", "Books", "invoice vat"),+ ],+ )+ await embed_passages(store, ids["a"], ["regatta sailing mainsail harbour"])+ await embed_passages(store, ids["b"], ["risotto saffron"])+ await embed_passages(store, ids["c"], ["invoice vat"])+ await build_lexicon(store, backend)++ outcome = await word_search(store, make_cfg(), "regatta", neighbours=5)++ assert outcome.status == WordSearchStatus.OK.value+ assert outcome.neighbour_source == NEIGHBOUR_SOURCE_VECTOR+ terms = [neighbour.term for neighbour in outcome.neighbours]+ # The sailing axis comes first, in similarity order; the query word itself+ # is never returned as its own neighbour.+ assert terms[:3] == ["sailing", "mainsail", "harbour"]+ assert "regatta" not in terms+ assert all(0.0 <= neighbour.similarity <= 1.0 for neighbour in outcome.neighbours)++[email protected](not HAS_SQLITE_VEC, reason="sqlite-vec is not installed")+async def test_a_neighbour_reaches_an_item_that_never_spells_the_word(store, monkeypatch):+ backend = FakeEmbedding()+ register(monkeypatch, backend)+ ids = await seed(+ store,+ [+ ("a", "Race log", "regatta results and crew notes"),+ # Never contains "regatta" — only reachable through a neighbour.+ ("b", "Rigging", "mainsail repair after the storm"),+ ("c", "Kitchen", "risotto saffron stock"),+ ],+ )+ await embed_passages(store, ids["a"], ["regatta results and crew notes"])+ await embed_passages(store, ids["b"], ["mainsail repair after the storm"])+ await embed_passages(store, ids["c"], ["risotto saffron stock"])+ await build_lexicon(store, backend)++ outcome = await word_search(store, make_cfg(), "regatta", neighbours=5)++ reached = [hit.item_id for hit in outcome.hits]+ assert ids["a"] in reached+ assert ids["b"] in reached, "the mainsail item must be reachable via expansion"+ assert reached.index(ids["a"]) < reached.index(ids["b"]), (+ "the exact word must still outrank a neighbour-only match"+ )+ # And the unrelated topic must not be dragged in by the expansion.+ assert ids["c"] not in reached++[email protected](not HAS_SQLITE_VEC, reason="sqlite-vec is not installed")+async def test_hits_point_at_the_passage_not_the_head_of_the_item(store, monkeypatch):+ backend = FakeEmbedding()+ register(monkeypatch, backend)+ head = "an opening paragraph about nothing in particular at all"+ middle = "filler prose that mentions neither topic whatsoever here"+ answer = "the regatta briefing and the mainsail trim we agreed on"+ ids = await seed(store, [("a", "Long file", f"{head}\n{middle}\n{answer}")])+ doc_ids = await embed_passages(store, ids["a"], [head, middle, answer])+ await build_lexicon(store, backend)++ outcome = await word_search(store, make_cfg(), "regatta", neighbours=5)++ assert outcome.hits, outcome.reason+ hit = outcome.hits[0]+ assert hit.passages, "a chunked item must report which passage answered"+ best = hit.passages[0]+ assert best.document_id == doc_ids[2], "the answering passage, not the head"+ assert best.chunk_index == 2+ # The span has to be usable to locate the text in the original body.+ assert best.char_start == len(head) + 1 + len(middle) + 1+ assert best.char_end > best.char_start+ assert "regatta" in best.terms+ assert "regatta" in best.text+++# ---------------------------------------------------------------------------+# Degradation — every one of them NAMED+# ---------------------------------------------------------------------------+++async def test_empty_store_says_so(store, monkeypatch):+ register(monkeypatch, FakeEmbedding())+ outcome = await word_search(store, make_cfg(), "regatta")++ assert outcome.status == WordSearchStatus.EMPTY_INDEX.value+ assert outcome.hits == ()+ assert "imported" in outcome.reason+++async def test_unknown_word_is_told_apart_from_a_word_that_ranks_nowhere(+ store, monkeypatch+):+ register(monkeypatch, FakeEmbedding())+ await seed(store, [("a", "Race log", "regatta sailing mainsail")])++ unknown = await word_search(store, make_cfg(), "zzqqxunlikelytoken")++ assert unknown.status == WordSearchStatus.UNKNOWN_WORD.value+ assert unknown.hits == ()+ assert "does not occur" in unknown.reason+++async def test_no_embedding_provider_falls_back_to_company(store, monkeypatch):+ """No provider at all: neighbours come from the text, and search still works."""+ ids = await seed(+ store,+ [+ ("a", "Race one", "regatta mainsail mainsail crew"),+ ("b", "Race two", "regatta mainsail harbour crew"),+ ("c", "Kitchen", "risotto saffron stock"),+ ],+ )+ outcome = await word_search(store, make_cfg(embedding_provider=""), "regatta")++ assert outcome.neighbour_source == NEIGHBOUR_SOURCE_COOCCURRENCE+ assert outcome.status == WordSearchStatus.OK.value+ terms = [neighbour.term for neighbour in outcome.neighbours]+ assert "mainsail" in terms+ assert "risotto" not in terms+ assert {hit.item_id for hit in outcome.hits} >= {ids["a"], ids["b"]}+ assert outcome.reason, "a degraded neighbour path must say why"+++async def test_dead_provider_degrades_and_writes_nothing(store, monkeypatch):+ """A raising embed call must not fail the search or corrupt the lexicon."""+ backend = FakeEmbedding(error=EmbeddingError("fake: HTTP 429 (rate_limit)"))+ register(monkeypatch, backend)+ await seed(store, [("a", "Race log", "regatta mainsail harbour crew")])++ before = await store.lexicon_counts(model=EMBED_MODEL, dim=EMBED_DIM)+ outcome = await word_search(store, make_cfg(), "regatta")+ after = await store.lexicon_counts(model=EMBED_MODEL, dim=EMBED_DIM)++ assert outcome.status in {+ WordSearchStatus.OK.value,+ WordSearchStatus.NEIGHBOURS_UNAVAILABLE.value,+ }+ assert after["embedded_terms"] == before["embedded_terms"] == 0+ assert outcome.neighbour_source != NEIGHBOUR_SOURCE_VECTOR+++async def test_blank_word_is_refused_without_touching_the_store(store):+ outcome = await word_search(store, make_cfg(), " ")++ assert outcome.status == WordSearchStatus.NO_MATCHES.value+ assert outcome.word == ""+ assert outcome.hits == ()+++# ---------------------------------------------------------------------------+# Lexicon bookkeeping+# ---------------------------------------------------------------------------+++async def test_harvest_is_incremental_and_resumable(store, monkeypatch):+ register(monkeypatch, FakeEmbedding())+ ids = await seed(store, [("a", "One", "alpha beta"), ("b", "Two", "gamma delta")])+ await embed_passages(store, ids["a"], ["alpha beta"])+ await embed_passages(store, ids["b"], ["gamma delta"])++ first = await harvest_pass(store, limit=1)+ assert first == 1+ cursor_after_first = await store.lexicon_cursor()+ assert cursor_after_first > 0++ second = await harvest_pass(store, limit=10)+ assert second == 1, "the second pass must not re-read the first passage"+ assert await harvest_pass(store, limit=10) == 0, "a finished harvest is a no-op"++ counts = await store.lexicon_counts()+ # Two bodies (4 words) plus the two titles the harvest reads with them.+ assert counts["terms"] == 6+ assert counts["scanned_items"] >= cursor_after_first+++async def test_rebuild_rewinds_the_whole_lexicon(store, monkeypatch):+ backend = FakeEmbedding()+ register(monkeypatch, backend)+ ids = await seed(store, [("a", "One", "regatta mainsail")])+ await embed_passages(store, ids["a"], ["regatta mainsail"])+ await build_lexicon(store, backend)+ assert (await store.lexicon_counts(model=EMBED_MODEL, dim=EMBED_DIM))["terms"] > 0++ await store.reset_lexicon()++ counts = await store.lexicon_counts(model=EMBED_MODEL, dim=EMBED_DIM)+ assert counts["terms"] == 0+ assert counts["embedded_terms"] == 0+ assert counts["scanned_items"] == 0+ # The corpus itself is untouched — only derived rows went away.+ assert counts["items"] == 1+ assert counts["passages"] == 1+++async def test_the_embedded_vocabulary_is_capped(store, monkeypatch):+ backend = FakeEmbedding()+ register(monkeypatch, backend)+ ids = await seed(store, [("a", "One", "alpha beta gamma delta epsilon")])+ await embed_passages(store, ids["a"], ["alpha beta gamma delta epsilon"])+ while await harvest_pass(store, limit=100):+ pass++ embedded = await embed_terms_pass(+ store, backend, model=EMBED_MODEL, dim=EMBED_DIM, limit=64,+ min_doc_freq=1, max_terms=2,+ )+ assert embedded == 2+ assert (+ await embed_terms_pass(+ store, backend, model=EMBED_MODEL, dim=EMBED_DIM, limit=64,+ min_doc_freq=1, max_terms=2,+ )+ == 0+ ), "the cap is on the whole embedded vocabulary, not on one batch"+++async def test_rare_terms_are_stored_but_never_embedded(store, monkeypatch):+ """The cost bound: a corpus full of ids costs vocabulary rows, not calls."""+ backend = FakeEmbedding()+ register(monkeypatch, backend)+ ids = await seed(store, [("a", "One", "common word"), ("b", "Two", "common a1b2c3d4")])+ await embed_passages(store, ids["a"], ["common word"])+ await embed_passages(store, ids["b"], ["common a1b2c3d4"])+ while await harvest_pass(store, limit=100):+ pass++ await embed_terms_pass(+ store, backend, model=EMBED_MODEL, dim=EMBED_DIM, limit=64, min_doc_freq=2+ )++ # "one"/"two" from the titles, "common", "word", "a1b2c3d4".+ assert (await store.lexicon_counts())["terms"] == 5+ embedded_texts = [text for call in backend.calls for text in call]+ assert "common" in embedded_texts+ assert "a1b2c3d4" not in embedded_textsdiff --git a/tests/unit/ultrawiki/test_word_search_parity.py b/tests/unit/ultrawiki/test_word_search_parity.pynew file mode 100644index 0000000000..10d61f2a72--- /dev/null+++ b/tests/unit/ultrawiki/test_word_search_parity.py@@ -0,0 +1,125 @@+"""Five-layer drift guard for word search (AP-4 / BUG-008).++Two things cross Python → REST → TypeScript → i18n → UI here, and both fail+SILENTLY when one hop is forgotten:++* ``WordSearchStatus`` — a status the frontend does not know renders as a+ blank panel, which is the precise failure the named statuses exist to end.+* ``SearchResult``'s passage provenance — the whole point of the feature is+ that a hit says WHICH passage answered, and a field added on one side and+ forgotten on the other quietly turns that back into "somewhere in this file".++The retrieval leg names are pinned too: the panel labels them from a lookup+map, and ``t()`` echoes an unknown key back verbatim, so a leg renamed in+Python would render as a raw i18n key on screen.+"""++from __future__ import annotations++import dataclasses+import json+import re+from pathlib import Path++from jarvis.ultrawiki.types import SearchResult, WordSearchStatus++FRONTEND = Path(__file__).resolve().parents[3] / "jarvis/ui/web/frontend/src"+API_TS = FRONTEND / "lib/ultrawikiApi.ts"+PANEL_TSX = FRONTEND / "components/ultrawiki/WordSearchPanel.tsx"+LOCALES = FRONTEND / "i18n/locales"+SUPPORTED_LOCALES = ("de", "en", "es")+++def _ts_union_values(name: str) -> set[str]:+ source = API_TS.read_text(encoding="utf-8")+ match = re.search(rf"{name}\s*=\s*\[(.*?)\]\s*as const", source, re.DOTALL)+ assert match is not None, f"{name} array not found"+ return set(re.findall(r'"([^"]+)"', match.group(1)))+++def _locale(name: str) -> dict:+ return json.loads((LOCALES / f"{name}.json").read_text(encoding="utf-8"))+++def _nested(data: dict, dotted: str) -> object | None:+ node: object = data+ for part in dotted.split("."):+ if not isinstance(node, dict) or part not in node:+ return None+ node = node[part]+ return node+++def test_typescript_status_union_matches_the_python_enum():+ assert _ts_union_values("ULTRAWIKI_WORD_SEARCH_STATUSES") == {+ status.value for status in WordSearchStatus+ }+++def test_the_search_hit_interface_carries_every_python_field():+ """``dataclasses.asdict`` puts EVERY field on the wire, so a field added in+ Python without its TypeScript twin is invisible to the UI rather than a+ type error anyone would notice."""+ source = API_TS.read_text(encoding="utf-8")+ match = re.search(+ r"export interface UltraWikiSearchHit \{(.*?)\n\}", source, re.DOTALL+ )+ assert match is not None, "UltraWikiSearchHit interface not found"+ declared = set(re.findall(r"^\s*(\w+)[?]?:", match.group(1), re.MULTILINE))+ expected = {field.name for field in dataclasses.fields(SearchResult)}+ assert expected - declared == set(), (+ f"UltraWikiSearchHit is missing: {sorted(expected - declared)}"+ )+++def test_every_retrieval_leg_has_a_label_in_every_locale():+ """The legs of ``word_search._retrieve``, as the panel labels them."""+ from jarvis.ultrawiki import word_search as word_search_mod++ source = Path(word_search_mod.__file__).read_text(encoding="utf-8")+ legs = set(re.findall(r'\(\s*"(\w+)",\s*(?:keyword|vector)_weight', source))+ legs |= set(re.findall(r'^\s+"(\w+)",\n\s+vector_weight', source, re.MULTILINE))+ assert legs, "no retrieval legs found — the extraction regex went stale"++ panel = PANEL_TSX.read_text(encoding="utf-8")+ mapped = set(re.findall(r'^\s*(\w+): "ultrawiki\.words\.leg_', panel, re.MULTILINE))+ assert legs <= mapped, f"WordSearchPanel does not label: {sorted(legs - mapped)}"+ for locale in SUPPORTED_LOCALES:+ data = _locale(locale)+ missing = sorted(+ leg+ for leg in legs+ if not isinstance(_nested(data, f"ultrawiki.words.leg_{leg}"), str)+ )+ assert not missing, f"{locale}.json has no label for legs: {missing}"+++def test_every_string_the_words_view_asks_for_exists_in_every_locale():+ """A missing key renders as the raw dotted key on screen."""+ sources = [PANEL_TSX.read_text(encoding="utf-8")]+ sources.append(+ (FRONTEND / "views/ultrawiki/UltraWikiPanel.tsx").read_text(encoding="utf-8")+ )+ used: set[str] = set()+ for source in sources:+ used |= set(re.findall(r't\(\s*"(ultrawiki\.words\.[^"]+)"', source))+ assert used, "no i18n keys found — the extraction regex went stale"+ for locale in SUPPORTED_LOCALES:+ data = _locale(locale)+ missing = sorted(key for key in used if not isinstance(_nested(data, key), str))+ assert not missing, f"{locale}.json is missing: {missing}"+++def test_the_words_locale_blocks_agree():+ """No locale may carry a word-search key the others lack."""+ blocks = {+ locale: _nested(_locale(locale), "ultrawiki.words")+ for locale in SUPPORTED_LOCALES+ }+ for locale, block in blocks.items():+ assert isinstance(block, dict) and block, f"{locale}.json has no words block"+ reference = set(blocks["en"]) # type: ignore[arg-type]+ for locale, block in blocks.items():+ assert set(block) == reference, ( # type: ignore[arg-type]+ f"{locale}.json word keys differ from en.json"+ )