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
fix(ultrawiki): all 18 review findings + honest status; feat: ranking depth, provider catalog, Supabase link
Ruben Lütkedf77a810ca78
diff --git a/UltraWiki/03-retrieval-and-voice.md b/UltraWiki/03-retrieval-and-voice.mdindex 70a0b73ff6..64f2857996 100644--- a/UltraWiki/03-retrieval-and-voice.md+++ b/UltraWiki/03-retrieval-and-voice.md@@ -42,15 +42,29 @@ Stage notes:expensive stage — the deterministic floor keeps both alive.- **Fan-out.** Every list is a single indexed SQL query against the unifiedstore; they run concurrently. Recency decay and term-rarity weighting are- baked into the keyword/vector list scoring, so stale answers lose ties and- filler ("sounds good, thanks!") never surfaces on similarity alone.+ applied to the fused candidates, so stale answers lose ties and filler+ ("sounds good, thanks!") never surfaces on similarity alone.+ **Shipped (2026-07-25):** term rarity is computed from the store's own+ corpus (`term_document_frequency` + `live_item_count`, both backends), and a+ candidate covering none of the query's rare vocabulary is scaled DOWN, never+ dropped — a hard content filter is the AP-27 trap. Age decay is+ `0.5 ** (age_days / [ultrawiki].recency_half_life_days)`, default 180 days,+ `0` disables it.- **Fusion (RRF, smoothing constant 60).** Consensus beats a single strongvote: a document appearing near the top of several lists outranks one that- is first in only one. Weights are per-list and tunable; defaults to 1.0.+ is first in only one. Weights are per-list and tunable+ (`[ultrawiki].rrf_keyword_weight` / `rrf_vector_weight`); default 1.0.- **Rerank.** A small model scores each candidate against the actual question- (0–10), killing look-alikes that share vocabulary but answer a different- question. Uses the configured rerank-capable provider if present; skipped- honestly when none is configured (fusion order then stands).+ (**0–10, the same scale for every backend**), killing look-alikes that share+ vocabulary but answer a different question. Skipped honestly when no+ provider is configured or ready (fusion order then stands).+ **Universality (§3/AP-22, shipped 2026-07-25):** the default backend is+ `llm`, which grades through the key-aware cross-family provider chain — the+ same one distillation uses — so the stage works with whatever credential the+ install actually holds, including a purely local Ollama on a headless box.+ `voyage` / `cohere` remain available for installs holding those keys; their+ native 0–1 relevance is normalized ×10 onto the shared scale, because the+ relevance floor below must not depend on which backend answered.- **Context expansion.** Winners are re-hydrated with their surroundings — theneighboring wiki sections, the messages around a burst — so the synthesismodel sees complete evidence, not orphaned fragments.@@ -74,6 +88,27 @@ they must pass an **absolute relevance gate** (the wiki's three-gate pattern:score floor on the underlying leg scores, query-term overlap, and anhonest empty-result path), never the bare fusion ranking.+**Mechanism (shipped 2026-07-25).** The rerank grade IS the absolute measure+the fused score cannot provide. `hybrid_search(..., enforce_floor=True)` drops+every candidate graded below `[ultrawiki].rerank_min_score` (default 4.0, `0`+disables) and returns an empty list rather than a weak match; explicit+surfaces (Ask view, `GET /api/ultrawiki/search`, the CLI) never pass the flag.+Two honesty rules that must not be softened:++1. A candidate the rerank stage never graded (stage off, provider down, or+ below the rerank pool) arrives with `rerank_score=None` and is passed+ through UNGRADED rather than silently admitted as "good enough" — a floor+ that disappears on provider failure is worse than a visible one. The+ caller's deterministic gate (`jarvis/brain/wiki_relevance.py`) stays+ responsible for those.+2. The floor never runs on an explicit search. The user asked; hiding evidence+ from them is a different defect than volunteering it unasked.++**Wiring status:** the flag exists and is tested, but no unsolicited surface+consumes UltraWiki yet — `wiki_relevance` still guards the normal wiki vault.+Whoever wires UltraWiki into context injection or voice MUST pass+`enforce_floor=True`; that is the moment this section becomes load-bearing.+## Cross-source reconstructionThe north-star answer often exists in no single row: the chat says "19:00?",diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/AskPanel.test.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/AskPanel.test.tsxindex f86292346b..0e825c9adb 100644--- a/jarvis/ui/web/frontend/src/components/ultrawiki/AskPanel.test.tsx+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/AskPanel.test.tsx@@ -30,6 +30,10 @@ const HIT: UltraWikiSearchHit = {timestamp_utc: "2026-07-01T08:00:00Z",score: 0.87,matched_by: ["keyword", "vector"],+ // The rerank stage is optional: an ungraded hit is the DEFAULT shape, so+ // the row must render without a grade chip or a context disclosure.+ rerank_score: null,+ context: [],};function installFetchMock(routes: Record<string, () => unknown>) {@@ -111,6 +115,71 @@ describe("AskPanel — results with citations", () => {);});+ it("names the credential carrying a live leg, never the key itself", async () => {+ installFetchMock({ "/api/ultrawiki/search": () => ({ query: "", results: [], total: 0 }) });+ renderWithClient(+ <AskPanel+ searchLegs={{+ keyword: { available: true },+ vector: { available: true, backend: "gemini", model: "gemini-embedding-001" },+ rerank: { available: false, provider: "off" },+ }}+ slots={{+ embedding: {+ provider: "gemini",+ ready: true,+ reason: "",+ via: "your saved Gemini API key (gemini_api_key)",+ },+ }}+ ingestedItems={12}+ />,+ );++ const vector = screen.getByTestId("ultrawiki-leg-vector");+ expect(vector.textContent).toContain("Semantic search: on");+ expect(vector.textContent).toContain(+ "via your saved Gemini API key (gemini_api_key)",+ );+ });++ it("guides the user instead of showing a blank panel when nothing is ingested", async () => {+ installFetchMock({ "/api/ultrawiki/search": () => ({ query: "", results: [], total: 0 }) });+ const onOpenSources = vi.fn();+ renderWithClient(+ <AskPanel+ searchLegs={{ keyword: { available: true } }}+ ingestedItems={0}+ onOpenSources={onOpenSources}+ />,+ );++ const guide = screen.getByTestId("ultrawiki-ask-nothing-ingested");+ expect(guide.textContent).toContain("Nothing has been ingested yet");+ expect(guide.textContent).toContain("approve a source");+ expect(guide.textContent).toContain("Sync");+ fireEvent.click(screen.getByTestId("ultrawiki-ask-open-sources"));+ expect(onOpenSources).toHaveBeenCalledTimes(1);+ });++ it("keeps the normal empty state once items exist but a query finds nothing", async () => {+ installFetchMock({+ "/api/ultrawiki/search": () => ({ query: "zzz", results: [], total: 0 }),+ });+ renderWithClient(+ <AskPanel searchLegs={{ keyword: { available: true } }} ingestedItems={7} />,+ );+ expect(screen.queryByTestId("ultrawiki-ask-nothing-ingested")).toBeNull();++ fireEvent.change(screen.getByTestId("ultrawiki-ask-input"), {+ target: { value: "zzz" },+ });+ fireEvent.click(screen.getByTestId("ultrawiki-ask-submit"));+ await waitFor(() => {+ expect(screen.getByTestId("ultrawiki-ask-empty")).toBeDefined();+ });+ });+it("shows the honest degraded-leg reason when a query finds nothing", async () => {installFetchMock({"/api/ultrawiki/search": () => ({ query: "x", results: [], total: 0 }),diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/AskPanel.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/AskPanel.tsxindex b80923396f..f887d8f957 100644--- a/jarvis/ui/web/frontend/src/components/ultrawiki/AskPanel.tsx+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/AskPanel.tsx@@ -22,8 +22,16 @@ import {export function AskPanel({searchLegs,+ slots,+ ingestedItems = 0,+ onOpenSources,}: {searchLegs: UltraWikiStatus["search_legs"] | undefined;+ /** Capability slots — used only for the honest `via` provenance line. */+ slots?: UltraWikiStatus["slots"];+ /** Items in the store; 0 means "nothing ingested yet", not "no hits". */+ ingestedItems?: number;+ onOpenSources?: () => void;}): JSX.Element {const t = useT();const [input, setInput] = useState("");@@ -73,10 +81,36 @@ export function AskPanel({</button></form>- <SearchLegsLine legs={searchLegs} />+ <SearchLegsLine legs={searchLegs} slots={slots} /><div className="mt-3 min-h-0 flex-1 overflow-y-auto">- {searchQuery.isFetching ? (+ {!submitted && ingestedItems === 0 ? (+ // Nothing is in the store yet. A blank panel here reads as "the+ // search is broken"; the two steps that actually fill it do not.+ <div+ className="space-y-2 py-6 text-sm text-muted-foreground"+ data-testid="ultrawiki-ask-nothing-ingested"+ >+ <p className="text-foreground">+ {t("ultrawiki.ask.nothing_ingested_title")}+ </p>+ <ol className="ml-4 list-decimal space-y-1 text-xs">+ <li>{t("ultrawiki.ask.nothing_ingested_step_approve")}</li>+ <li>{t("ultrawiki.ask.nothing_ingested_step_sync")}</li>+ </ol>+ <p className="text-xs">{t("ultrawiki.ask.nothing_ingested_note")}</p>+ {onOpenSources && (+ <button+ type="button"+ onClick={onOpenSources}+ className="text-xs underline underline-offset-2 hover:text-primary"+ data-testid="ultrawiki-ask-open-sources"+ >+ {t("ultrawiki.progress.open_sources")}+ </button>+ )}+ </div>+ ) : searchQuery.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.ask.searching")}@@ -121,11 +155,17 @@ export function AskPanel({function SearchLegsLine({legs,+ slots,}: {legs: UltraWikiStatus["search_legs"] | undefined;+ slots?: UltraWikiStatus["slots"];}): JSX.Element | null {const t = useT();if (!legs) return null;+ // "via <credential path>" — which of the user's own keys/endpoints is+ // actually carrying this leg. Never a key value, only where it came from.+ const withVia = (text: string, via: string | undefined): string =>+ via ? `${text} — ${t("ultrawiki.ask.via").replace("{0}", via)}` : text;const parts: Array<{ key: string; text: string; degraded: boolean }> = [];if (legs.keyword?.available) {parts.push({@@ -137,7 +177,14 @@ function SearchLegsLine({if (legs.vector) {parts.push(legs.vector.available- ? { key: "vector", text: t("ultrawiki.ask.leg_vector_on"), degraded: false }+ ? {+ key: "vector",+ text: withVia(+ t("ultrawiki.ask.leg_vector_on"),+ slots?.embedding?.via,+ ),+ degraded: false,+ }: {key: "vector",text: t("ultrawiki.ask.leg_vector_off").replace(@@ -151,11 +198,9 @@ function SearchLegsLine({if (legs.rerank) {parts.push({key: "rerank",- text: t(- legs.rerank.available- ? "ultrawiki.ask.leg_rerank_on"- : "ultrawiki.ask.leg_rerank_off",- ),+ text: legs.rerank.available+ ? withVia(t("ultrawiki.ask.leg_rerank_on"), slots?.rerank?.via)+ : t("ultrawiki.ask.leg_rerank_off"),degraded: false,});}@@ -195,6 +240,25 @@ function ResultRow({ hit }: { hit: UltraWikiSearchHit }): JSX.Element {{hit.title || hit.snippet.slice(0, 60)}</span><span className="flex items-center gap-1.5">+ {/* The absolute 0-10 grade, when the rerank stage actually ran.+ Unlike the fused score it means something on its own, so it is+ the one number worth showing. */}+ {typeof hit.rerank_score === "number" && (+ <span+ className={cn(+ "rounded-full border px-1.5 py-0.5 text-[10px] tabular-nums",+ hit.rerank_score >= 7+ ? "border-[#5bd4a4]/40 bg-[#5bd4a4]/10 text-[#5bd4a4]"+ : hit.rerank_score >= 4+ ? "border-border text-muted-foreground"+ : "border-[#ffb84d]/40 bg-[#ffb84d]/10 text-[#ffb84d]",+ )}+ title={t("ultrawiki.ask.grade_hint")}+ data-testid={`ultrawiki-grade-${hit.item_id}`}+ >+ {hit.rerank_score.toFixed(1)}/10+ </span>+ )}{hit.matched_by.map((leg) => (<spankey={leg}@@ -216,6 +280,28 @@ function ResultRow({ hit }: { hit: UltraWikiSearchHit }): JSX.Element {{hit.snippet}</p>)}+ {/* Context expansion: the neighbouring messages/sections, so the hit+ reads as evidence instead of an orphaned fragment. */}+ {hit.context?.length > 0 && (+ <details className="mt-1.5" data-testid={`ultrawiki-context-${hit.item_id}`}>+ <summary className="cursor-pointer text-[11px] text-muted-foreground hover:text-foreground">+ {t("ultrawiki.ask.context_toggle").replace(+ "{0}",+ String(hit.context.length),+ )}+ </summary>+ <ul className="mt-1 space-y-1 border-l border-border/60 pl-2">+ {hit.context.map((line, index) => (+ <li+ key={index}+ className="text-[11px] leading-relaxed text-muted-foreground/80"+ >+ {line}+ </li>+ ))}+ </ul>+ </details>+ )}<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>}diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/ImportProgress.test.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/ImportProgress.test.tsxnew file mode 100644index 0000000000..a9a0ae6202--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/ImportProgress.test.tsx@@ -0,0 +1,144 @@+/**+ * ImportProgress tests — the honest pipeline-state headline.+ *+ * The maintainer's report: on a fresh activation with zero approved sources+ * the strip read "Pipeline running · Captured 0 · …", which sounds like data+ * is already being pulled although nothing was connected. These pin that each+ * of the four backend states renders its own honest wording, that the blanket+ * "Pipeline running" is gone, and that the waiting state offers the way out.+ */+import { afterEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen } from "@testing-library/react";++import { ImportProgress } from "@/components/ultrawiki/ImportProgress";+import type { UltraWikiCounts, UltraWikiPipeline } from "@/lib/ultrawikiApi";++const NO_COUNTS: Partial<UltraWikiCounts> = {+ captured: 0,+ keyword_indexed: 0,+ embedded: 0,+ distilled: 0,+ failed: 0,+ total: 0,+};++function renderStrip(+ pipeline: UltraWikiPipeline,+ counts: Partial<UltraWikiCounts> = NO_COUNTS,+ onOpenSources?: () => void,+) {+ return render(+ <ImportProgress+ counts={counts}+ pipeline={pipeline}+ jobs={[]}+ onChanged={() => {}}+ onOpenSources={onOpenSources}+ />,+ );+}++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});++describe("ImportProgress — honest pipeline state", () => {+ it("says it is waiting for sources instead of 'running' on a fresh activation", () => {+ const onOpenSources = vi.fn();+ renderStrip(+ {+ running: true, // the worker loop IS alive — that is why it used to lie+ state: "waiting_for_sources",+ reason:+ "No source is approved yet, so nothing is being read. Approve a source under Sources.",+ processed: {},+ },+ NO_COUNTS,+ onOpenSources,+ );++ const state = screen.getByTestId("ultrawiki-pipeline-state");+ expect(state.getAttribute("data-state")).toBe("waiting_for_sources");+ expect(state.textContent).toContain("Waiting for approved sources");+ expect(state.textContent).not.toContain("Pipeline running");+ expect(screen.queryByTestId("ultrawiki-pipeline-running")).toBeNull();++ // The honest reason is shown verbatim, and the way out is one click.+ expect(screen.getByTestId("ultrawiki-pipeline-reason").textContent).toContain(+ "No source is approved yet",+ );+ fireEvent.click(screen.getByTestId("ultrawiki-open-sources-link"));+ expect(onOpenSources).toHaveBeenCalledTimes(1);+ });++ it("counts the real backlog while processing", () => {+ renderStrip(+ {+ running: true,+ state: "processing",+ reason: "6 item(s) are queued for processing.",+ processed: { keyword: 2 },+ },+ {+ captured: 1,+ keyword_indexed: 2,+ embedded: 3,+ distilled: 40, // finished work is NOT pending+ failed: 5, // gave up — also not pending+ total: 51,+ },+ );++ const state = screen.getByTestId("ultrawiki-pipeline-state");+ expect(state.getAttribute("data-state")).toBe("processing");+ expect(state.textContent).toContain("Processing (6 pending)");+ expect(screen.getByTestId("ultrawiki-pipeline-running")).toBeDefined();+ });++ it("shows the blocking reason when a slot pauses the pipeline", () => {+ renderStrip(+ {+ running: true,+ state: "paused",+ reason:+ "12 item(s) are keyword-searchable and waiting for the embedding stage: no Gemini API key is configured",+ processed: {},+ },+ { captured: 0, keyword_indexed: 12, embedded: 0, distilled: 0, failed: 0 },+ );++ const state = screen.getByTestId("ultrawiki-pipeline-state");+ expect(state.getAttribute("data-state")).toBe("paused");+ expect(state.textContent).toContain("Paused");+ expect(screen.getByTestId("ultrawiki-pipeline-reason").textContent).toContain(+ "no Gemini API key is configured",+ );+ });++ it("reports idle when there is nothing left to do", () => {+ renderStrip(+ {+ running: true,+ state: "idle",+ reason: "Everything ingested so far is fully processed.",+ processed: { keyword: 9 },+ },+ { captured: 0, keyword_indexed: 0, embedded: 0, distilled: 9, failed: 0 },+ );++ const state = screen.getByTestId("ultrawiki-pipeline-state");+ expect(state.getAttribute("data-state")).toBe("idle");+ expect(state.textContent).toContain("Idle");+ expect(screen.queryByTestId("ultrawiki-pipeline-running")).toBeNull();+ });++ it("falls back to the running flag when the backend sends no state", () => {+ // An older backend (or a status from before the field existed) must still+ // render something sane rather than crash the strip.+ renderStrip({ running: false, processed: {} });+ expect(+ screen.getByTestId("ultrawiki-pipeline-state").getAttribute("data-state"),+ ).toBe("idle");+ });+});diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/ImportProgress.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/ImportProgress.tsxindex ddcea8426d..40e123fc8f 100644--- a/jarvis/ui/web/frontend/src/components/ultrawiki/ImportProgress.tsx+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/ImportProgress.tsx@@ -9,7 +9,7 @@* poll up to a few seconds while a job is active).*/import { useState } from "react";-import { Loader2, XCircle } from "lucide-react";+import { AlertTriangle, CheckCircle2, Loader2, PauseCircle, XCircle } from "lucide-react";import { cn } from "@/lib/utils";import { useT } from "@/i18n";@@ -19,6 +19,7 @@ import {cancelUltraWikiJob,type UltraWikiCounts,type UltraWikiJob,+ type UltraWikiPipeline,} from "@/lib/ultrawikiApi";const STAGES = [@@ -31,14 +32,16 @@ const STAGES = [export function ImportProgress({counts,- pipelineRunning,+ pipeline,jobs,onChanged,+ onOpenSources,}: {counts: Partial<UltraWikiCounts>;- pipelineRunning: boolean;+ pipeline: UltraWikiPipeline;jobs: UltraWikiJob[];onChanged: () => void;+ onOpenSources?: () => void;}): JSX.Element {const t = useT();const pushToast = useEventStore((s) => s.pushToast);@@ -66,6 +69,13 @@ export function ImportProgress({ULTRAWIKI_ACTIVE_JOB_STATUSES.includes(job.status),);+ // What is still WAITING to be processed. 'distilled' is finished work and+ // 'failed' gave up, so neither belongs in a "still to do" number.+ const pendingItems =+ (counts.captured ?? 0) ++ (counts.keyword_indexed ?? 0) ++ (counts.embedded ?? 0);+return (<sectionaria-label={t("ultrawiki.progress.title")}@@ -73,20 +83,11 @@ export function ImportProgress({data-testid="ultrawiki-import-progress"><div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px]">- <span className="flex items-center gap-1.5 font-medium text-foreground">- {pipelineRunning && (- <Loader2- className="h-3 w-3 animate-spin text-primary"- aria-hidden- data-testid="ultrawiki-pipeline-running"- />- )}- {t(- pipelineRunning- ? "ultrawiki.progress.pipeline_running"- : "ultrawiki.progress.pipeline_idle",- )}- </span>+ <PipelineState+ pipeline={pipeline}+ pending={pendingItems}+ onOpenSources={onOpenSources}+ /><dl className="flex flex-wrap items-center gap-x-3 gap-y-1 text-muted-foreground">{STAGES.map(([key, labelKey]) => {const value = counts[key] ?? 0;@@ -117,6 +118,15 @@ export function ImportProgress({</dl></div>+ {pipeline.reason && (+ <p+ className="mt-1 text-[11px] leading-relaxed text-muted-foreground"+ data-testid="ultrawiki-pipeline-reason"+ >+ {pipeline.reason}+ </p>+ )}+{activeJobs.length > 0 && (<ul className="mt-1.5 space-y-1" data-testid="ultrawiki-active-jobs">{activeJobs.map((job) => (@@ -153,3 +163,89 @@ export function ImportProgress({</section>);}++/**+ * The honest headline of the strip.+ *+ * It used to read "Pipeline running" whenever the worker LOOP was alive —+ * including on a fresh activation with zero approved sources, where it read as+ * "something is already pulling my data" although nothing had been connected.+ * The four states come from the backend (one source of truth,+ * `PIPELINE_STATES`), each with its own honest wording; "waiting for sources"+ * additionally offers the way out, a link straight to the Sources tab.+ */+function PipelineState({+ pipeline,+ pending,+ onOpenSources,+}: {+ pipeline: UltraWikiPipeline;+ pending: number;+ onOpenSources?: () => void;+}): JSX.Element {+ const t = useT();+ const state = pipeline.state ?? (pipeline.running ? "processing" : "idle");++ if (state === "waiting_for_sources") {+ return (+ <span+ className="flex flex-wrap items-center gap-1.5 font-medium text-foreground"+ data-testid="ultrawiki-pipeline-state"+ data-state={state}+ >+ <AlertTriangle className="h-3 w-3 shrink-0 text-[#ffb84d]" aria-hidden />+ {t("ultrawiki.progress.state_waiting_for_sources")}+ {onOpenSources && (+ <button+ type="button"+ onClick={onOpenSources}+ className="underline underline-offset-2 hover:text-primary"+ data-testid="ultrawiki-open-sources-link"+ >+ {t("ultrawiki.progress.open_sources")}+ </button>+ )}+ </span>+ );+ }++ const { icon, label } =+ state === "processing"+ ? {+ icon: (+ <Loader2+ className="h-3 w-3 animate-spin text-primary"+ aria-hidden+ data-testid="ultrawiki-pipeline-running"+ />+ ),+ label: t("ultrawiki.progress.state_processing").replace(+ "{0}",+ String(pending),+ ),+ }+ : state === "paused"+ ? {+ icon: (+ <PauseCircle className="h-3 w-3 shrink-0 text-[#ffb84d]" aria-hidden />+ ),+ label: t("ultrawiki.progress.state_paused"),+ }+ : {+ icon: (+ <CheckCircle2 className="h-3 w-3 shrink-0 text-[#5bd4a4]" aria-hidden />+ ),+ label: t("ultrawiki.progress.state_idle"),+ };++ return (+ <span+ className="flex items-center gap-1.5 font-medium text-foreground"+ data-testid="ultrawiki-pipeline-state"+ data-state={state}+ >+ {icon}+ {label}+ </span>+ );+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex bebd02fa56..3ee524ecda 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -75,8 +75,7 @@"taskbar": "Taskbar","contacts": "Kontakte","feedback": "Feedback",- "agent_instructions": "{name}.md",- "agentic_ide": "Agentic IDE"+ "agent_instructions": "{name}.md"},"agent_instructions": {"subtitle": "Deine persönlichen Präferenzen, wie der Assistent mit dir arbeitet — Ton, Sprache, Voreinstellungen, dauerhafte Fakten. Getrennt vom System-Prompt und hebelt niemals Sicherheit oder Bestätigungen aus.",@@ -488,7 +487,7 @@},"run_inspector": {"title": "Run Inspector",- "subtitle": "Forensik pro Run: Volltranskript, Timeline, Latenz, Entscheidungen, Tools, Fehler.",+ "subtitle": "Entwickler-Forensik pro Run: Umgebung, Entscheidungen, Latenz, Tool-Ein-/Ausgabe und der rohe Ereignisstrom.","empty": "Wähle einen Run zur Analyse.","unavailable": "Der Run-Recorder ist deaktiviert.","export_raw": "Roh-Export (JSON)",@@ -503,7 +502,52 @@"latency": "Latenz","decision": "Entscheidungspfad","tools": "Tools",- "errors": "Fehler"+ "errors": "Fehler",+ "events": "Ereignisse"+ },+ "environment": "Run-Umgebung",+ "session_events": "Ereignisse auf Sitzungsebene",+ "no_usage": "Verbrauch nicht gemessen",+ "stream": {+ "empty": "Keine Ereignisse aufgezeichnet.",+ "events": "Ereignisse",+ "filter": "filtern…",+ "copy": "Gefilterten Strom als JSONL kopieren",+ "copied": "Ereignisse als JSONL kopiert",+ "copy_failed": "Kopieren fehlgeschlagen",+ "truncated": "Dieser Turn hat mehr Ereignisse aufgezeichnet als angezeigt werden — der Strom ist auf 500 Zeilen pro Turn begrenzt."+ },+ "decision": {+ "empty": "Für diesen Turn wurden keine Entscheidungen aufgezeichnet.",+ "no_rationale": "Keine Begründung aufgezeichnet.",+ "no_source": "keine"+ },+ "tools": {+ "empty": "In diesem Turn lief kein Tool.",+ "command": "Befehl",+ "output": "Ergebnis",+ "error": "Fehler"+ },+ "facts": {+ "endpoint": "Endpunkt",+ "cache": "Prompt-Cache",+ "cache_hit": "Treffer",+ "cache_miss": "kein Treffer",+ "interrupted": "unterbrochen",+ "context": "Kontext"+ },+ "env": {+ "mode": "Modus",+ "surface": "Oberfläche",+ "started_by": "Gestartet durch",+ "ended_by": "Beendet durch",+ "language": "Sprache",+ "providers": "Anbieter",+ "models": "Modelle",+ "tiers": "Stufen",+ "voices": "Stimmen",+ "audio": "Audio",+ "empty": "Keine Umgebung aufgezeichnet."}},"voice_mode": {@@ -1005,6 +1049,16 @@"integration_bad_note": "Provider konnte nicht erreicht werden.","failed": "Test fehlgeschlagen"},+ "apikeys_base_url": {+ "label": "Server-URL",+ "placeholder_required": "z. B. http://localhost:8000 — erforderlich",+ "save": "Speichern",+ "saving": "Speichere…",+ "saved": "Server-URL gespeichert",+ "cleared": "Server-URL auf den Standard zurückgesetzt",+ "hint_default": "Leer lassen, um die oben gezeigte Standard-Adresse zu verwenden.",+ "hint_required": "Dieser Anbieter braucht eine Server-URL — trage ein, wo dein lokaler Server läuft."+ },"apikeys_model": {"heading": "Modell","recommended_tag": "Empfohlen",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex bc085c10cb..f4f40d492c 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -75,8 +75,7 @@"taskbar": "Taskbar","contacts": "Contacts","feedback": "Feedback",- "agent_instructions": "{name}.md",- "agentic_ide": "Agentic IDE"+ "agent_instructions": "{name}.md"},"agent_instructions": {"subtitle": "Your personal preferences for how the assistant works with you — tone, language, defaults, standing facts. Separate from the System Prompt, and it never overrides safety or confirmations.",@@ -488,7 +487,7 @@},"run_inspector": {"title": "Run Inspector",- "subtitle": "Per-run forensics: full transcript, timeline, latency, decisions, tools, errors.",+ "subtitle": "Developer forensics per run: environment, decisions, latency, tool I/O and the raw event stream.","empty": "Select a run to inspect.","unavailable": "Run recorder is disabled.","export_raw": "Export raw (JSON)",@@ -503,7 +502,52 @@"latency": "Latency","decision": "Decision path","tools": "Tools",- "errors": "Errors"+ "errors": "Errors",+ "events": "Events"+ },+ "environment": "Run environment",+ "session_events": "Session-level events",+ "no_usage": "usage not measured",+ "stream": {+ "empty": "No events recorded.",+ "events": "events",+ "filter": "filter…",+ "copy": "Copy the filtered stream as JSONL",+ "copied": "events copied as JSONL",+ "copy_failed": "Copy failed",+ "truncated": "This turn recorded more events than are shown — the stream is capped at 500 rows per turn."+ },+ "decision": {+ "empty": "No decisions recorded for this turn.",+ "no_rationale": "No rationale recorded.",+ "no_source": "none"+ },+ "tools": {+ "empty": "No tools ran in this turn.",+ "command": "Command",+ "output": "Result",+ "error": "Error"+ },+ "facts": {+ "endpoint": "endpoint",+ "cache": "prompt cache",+ "cache_hit": "hit",+ "cache_miss": "miss",+ "interrupted": "interrupted",+ "context": "context"+ },+ "env": {+ "mode": "Mode",+ "surface": "Surface",+ "started_by": "Started by",+ "ended_by": "Ended by",+ "language": "Language",+ "providers": "Providers",+ "models": "Models",+ "tiers": "Tiers",+ "voices": "Voices",+ "audio": "Audio",+ "empty": "No environment recorded."}},"voice_mode": {@@ -1006,6 +1050,16 @@"integration_bad_note": "The provider could not be reached.","failed": "Test failed"},+ "apikeys_base_url": {+ "label": "Server URL",+ "placeholder_required": "e.g. http://localhost:8000 — required",+ "save": "Save",+ "saving": "Saving…",+ "saved": "Server URL saved",+ "cleared": "Server URL reset to the default",+ "hint_default": "Leave empty to use the default address shown above.",+ "hint_required": "This provider needs a server URL — enter where your local server runs."+ },"apikeys_model": {"heading": "Model","recommended_tag": "Recommended",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 377e1da34f..9cccaceb92 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -75,8 +75,7 @@"taskbar": "Barra","contacts": "Contactos","feedback": "Comentarios",- "agent_instructions": "{name}.md",- "agentic_ide": "IDE agéntico"+ "agent_instructions": "{name}.md"},"agent_instructions": {"subtitle": "Tus preferencias personales sobre cómo el asistente trabaja contigo — tono, idioma, valores por defecto, hechos permanentes. Separado del System Prompt y nunca anula la seguridad ni las confirmaciones.",@@ -488,7 +487,7 @@},"run_inspector": {"title": "Run Inspector",- "subtitle": "Análisis por run: transcripción completa, cronología, latencia, decisiones, herramientas, errores.",+ "subtitle": "Análisis para desarrolladores por run: entorno, decisiones, latencia, E/S de herramientas y el flujo bruto de eventos.","empty": "Selecciona un run para analizar.","unavailable": "El grabador de runs está desactivado.","export_raw": "Exportar bruto (JSON)",@@ -503,7 +502,52 @@"latency": "Latencia","decision": "Ruta de decisión","tools": "Herramientas",- "errors": "Errores"+ "errors": "Errores",+ "events": "Eventos"+ },+ "environment": "Entorno del run",+ "session_events": "Eventos a nivel de sesión",+ "no_usage": "consumo no medido",+ "stream": {+ "empty": "No se registraron eventos.",+ "events": "eventos",+ "filter": "filtrar…",+ "copy": "Copiar el flujo filtrado como JSONL",+ "copied": "eventos copiados como JSONL",+ "copy_failed": "Error al copiar",+ "truncated": "Este turno registró más eventos de los que se muestran — el flujo se limita a 500 filas por turno."+ },+ "decision": {+ "empty": "No se registraron decisiones para este turno.",+ "no_rationale": "Sin justificación registrada.",+ "no_source": "ninguna"+ },+ "tools": {+ "empty": "No se ejecutó ninguna herramienta en este turno.",+ "command": "Comando",+ "output": "Resultado",+ "error": "Error"+ },+ "facts": {+ "endpoint": "fin de habla",+ "cache": "caché de prompt",+ "cache_hit": "acierto",+ "cache_miss": "fallo",+ "interrupted": "interrumpido",+ "context": "contexto"+ },+ "env": {+ "mode": "Modo",+ "surface": "Superficie",+ "started_by": "Iniciado por",+ "ended_by": "Finalizado por",+ "language": "Idioma",+ "providers": "Proveedores",+ "models": "Modelos",+ "tiers": "Niveles",+ "voices": "Voces",+ "audio": "Audio",+ "empty": "No se registró el entorno."}},"voice_mode": {diff --git a/jarvis/ui/web/frontend/src/views/ultrawiki/UltraWikiPanel.tsx b/jarvis/ui/web/frontend/src/views/ultrawiki/UltraWikiPanel.tsxindex 8069c481e7..4edbf75ceb 100644--- a/jarvis/ui/web/frontend/src/views/ultrawiki/UltraWikiPanel.tsx+++ b/jarvis/ui/web/frontend/src/views/ultrawiki/UltraWikiPanel.tsx@@ -110,9 +110,10 @@ export function UltraWikiPanel(): JSX.Element {<ImportProgresscounts={status.counts}- pipelineRunning={status.pipeline.running}+ pipeline={status.pipeline}jobs={status.jobs}onChanged={refetch}+ onOpenSources={() => setTab("sources")}/><div className="flex items-stretch border-b border-border bg-card/40">@@ -140,7 +141,14 @@ export function UltraWikiPanel(): JSX.Element {</div><div className="min-h-0 flex-1 overflow-y-auto">- {tab === "ask" && <AskPanel searchLegs={status.search_legs} />}+ {tab === "ask" && (+ <AskPanel+ searchLegs={status.search_legs}+ slots={status.slots}+ ingestedItems={status.counts.total ?? 0}+ onOpenSources={() => setTab("sources")}+ />+ )}{tab === "sources" && (<SourcesPanel sources={status.sources} onChanged={refetch} />)}diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex 8b600edd55..5112a5819e 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -348,7 +348,6 @@ class WebServer:from .wiki_ws import router as wiki_ws_routerfrom .workflows_routes import router as workflows_routerfrom .workspace_routes import router as workspace_router- from .agentic_ide_routes import router as agentic_ide_router# Conductor is an external package in the same monorepo. Import# defensively — anyone who checks out the repo without conductor would# otherwise get an ImportError here at server boot.@@ -418,12 +417,6 @@ class WebServer:# Provides agent detection, workspace launch planning, and PTY WebSocket# for in-app Claude Code / Codex terminals (xterm panes, not OS windows).app.include_router(workspace_router)- # Agentic IDE (/api/agentic-ide/*) — a chosen folder plus named terminals- # running Claude Code / Codex, addressable by voice ("what is Mika- # doing?") and promptable from Jarvis. Reuses the same PTY stack as the- # workspace above; adds the folder picker, call-signs, transcripts, and- # the focused coding mode.- app.include_router(agentic_ide_router)# Contacts section — user-curated address book (pure file store, no Brain dep).app.include_router(contacts_router)app.include_router(dictionary_router)@@ -487,6 +480,9 @@ class WebServer:# UltraWikiService is constructed in start() (_init_ultrawiki); None# keeps /api/ultrawiki honest (503 / degraded status) until then.app.state.ultrawiki = None+ # The named background task that opens the UltraWiki store when the+ # mode is already on at boot (see _init_ultrawiki); cancelled in stop().+ self._ultrawiki_start_task: asyncio.Task[None] | None = Noneapp.state.mission_tool_approvals = self._mission_tool_approvals# Board aggregator (personal-mastery dashboard) — the aggregator is@@ -2660,17 +2656,47 @@ class WebServer:while ``cfg.ultrawiki.enabled`` is true; a later in-app enable reaches``ensure_started()`` again through the routes (AP-26: nothing heretouches the boot-critical or voice path).++ The already-enabled case is dispatched as a NAMED BACKGROUND TASK and+ never awaited here: opening the store can mean a Postgres connect, and+ awaiting that inline put a remote host's latency (bounded, but still+ seconds) directly into the startup sequence. The task is held on an+ attribute so ``stop()`` can cancel it BEFORE the service shuts down —+ otherwise a store could finish opening after the shutdown that was+ supposed to close it, and leak the connection."""from jarvis.ultrawiki.service import UltraWikiServiceservice = UltraWikiService(self.cfg, bus=self.bus)self.app.state.ultrawiki = serviceif bool(getattr(getattr(self.cfg, "ultrawiki", None), "enabled", False)):- await service.ensure_started()- logger.info("ultrawiki: service started (mode enabled)")+ task = asyncio.create_task(+ service.ensure_started(), name="ultrawiki-start"+ )+ self._ultrawiki_start_task = task+ task.add_done_callback(self._on_ultrawiki_start_done)+ logger.info("ultrawiki: store + pipeline start dispatched (mode enabled)")else:logger.info("ultrawiki: service constructed (mode disabled — dormant)")+ def _on_ultrawiki_start_done(self, task: asyncio.Task[None]) -> None:+ """Report the background start honestly — a silent failure would look+ like a working mode with an empty store."""+ if self._ultrawiki_start_task is task:+ self._ultrawiki_start_task = None+ if task.cancelled():+ logger.info("ultrawiki: background start cancelled (shutdown)")+ return+ exc = task.exception()+ if exc is not None:+ logger.opt(exception=exc).warning(+ "ultrawiki: background start failed — /api/ultrawiki reports it "+ "as degraded until the next activation: {}",+ exc,+ )+ else:+ logger.info("ultrawiki: service started (mode enabled)")+def _init_wiki_boot_index(self, *, background: bool = False) -> None:"""Rebuild the derived FTS view against the active vault.@@ -3078,6 +3104,21 @@ class WebServer:# pipeline + every sync task (cancel, then wait_for(2 s) each), THEN# close its store. Runs before the store-dependent closes below so no# loop ever ticks against a closed connection.+ # First the boot-path start task: cancel-then-wait BEFORE shutdown, so+ # a store cannot finish opening after the shutdown meant to close it.+ ultrawiki_start_task = getattr(self, "_ultrawiki_start_task", None)+ if ultrawiki_start_task is not None and not ultrawiki_start_task.done():+ ultrawiki_start_task.cancel()+ try:+ await asyncio.wait_for(ultrawiki_start_task, timeout=2.0)+ except (TimeoutError, asyncio.CancelledError):+ pass+ except Exception as exc: # noqa: BLE001 — shutdown best-effort+ logger.opt(exception=exc).debug(+ "UltraWiki start-task cancel failed: {}", exc+ )+ self._ultrawiki_start_task = None+ultrawiki_service = getattr(self.app.state, "ultrawiki", None)if ultrawiki_service is not None:try:diff --git a/jarvis/ultrawiki/connectors/jarvis_conversations.py b/jarvis/ultrawiki/connectors/jarvis_conversations.pyindex 94dfb217e7..385bab89d9 100644--- a/jarvis/ultrawiki/connectors/jarvis_conversations.py+++ b/jarvis/ultrawiki/connectors/jarvis_conversations.py@@ -23,7 +23,11 @@ Cursor / checkpoint contract (documented honestly):maximum of the yielded values. Incremental re-chunks and re-yields theWHOLE day of every (conversation, day) touched by newer rows, so thestored chunk always reflects the complete current day (upserts are- idempotent on ``(source_id, external_id)``).+ idempotent on ``(source_id, external_id)``). Each reported+ ``max_rowid`` is CAPPED at the highest rowid the touched-day scan itself+ saw: a re-read day can contain rows written after that scan, and reporting+ one of those would advance the cursor past rows belonging to other+ conversations that were never scanned — silently losing them forever.- ``backfill(ctx, checkpoint)``: chunks stream in deterministic order(conversation id, then day). ``checkpoint`` is the ``external_id`` ofthe last persisted chunk; chunks ordering at or before it are skipped@@ -36,6 +40,8 @@ Cursor / checkpoint contract (documented honestly):from __future__ import annotations+import asyncio+import itertoolsimport loggingimport reimport sqlite3@@ -58,6 +64,11 @@ _DAY_RE = re.compile(r"\d{4}-\d{2}-\d{2}")_NS_PER_SECOND = 1_000_000_000_NS_PER_DAY = 86_400 * _NS_PER_SECOND+#: Day-chunks assembled per worker-thread hop. SQLite scans of the shared+#: message store must not run on the event loop (it also serves voice and+#: chat); a small batch amortizes the thread handoff without holding it long.+SCAN_BATCH = 16+# One honest "database missing" log per path per process — not per poll._MISSING_DB_LOGGED: set[str] = set()@@ -72,7 +83,7 @@ _BACKFILL_QUERY = ()_TOUCHED_QUERY = (- "SELECT COALESCE(NULLIF(thread_id, ''), trace_id) AS conversation_id, "+ "SELECT id, COALESCE(NULLIF(thread_id, ''), trace_id) AS conversation_id, ""timestamp_ns FROM messages WHERE id > ?")@@ -104,7 +115,18 @@ def _iso_utc_from_ns(timestamp_ns: int) -> str:)-def _chunk_item(conversation_id: str, day: str, rows: list[_Row]) -> RawItem:+def _chunk_item(+ conversation_id: str,+ day: str,+ rows: list[_Row],+ *,+ max_rowid_cap: int | None = None,+) -> RawItem:+ max_rowid = max(row[0] for row in rows)+ if max_rowid_cap is not None:+ # Never report a rowid beyond what the caller's scan actually covered+ # (see the incremental cursor contract in the module docstring).+ max_rowid = min(max_rowid, max_rowid_cap)lines = [f"{role}: {text}" for (_rowid, _conv, _ts, role, text) in rows if text]return RawItem(external_id=f"{conversation_id}:{day}",@@ -114,7 +136,7 @@ def _chunk_item(conversation_id: str, day: str, rows: list[_Row]) -> RawItem:title=f"Conversation on {day}",thread_key=conversation_id,metadata={- "max_rowid": max(row[0] for row in rows),+ "max_rowid": max_rowid,"message_count": len(rows),},)@@ -168,32 +190,55 @@ class JarvisConversationsConnector:async def backfill(self, ctx: ConnectorContext, checkpoint: str | None = None) -> AsyncIterator[RawItem]:- conn = self._open_ro(self._resolve_db_path(ctx))+ conn = await asyncio.to_thread(+ self._open_ro, self._resolve_db_path(ctx)+ )if conn is None:returntry:resume_after = _checkpoint_key(checkpoint)- for conversation_id, day, rows in _iter_day_chunks(conn):- if resume_after is not None and (conversation_id, day) <= resume_after:- continue- yield _chunk_item(conversation_id, day, rows)+ groups = _iter_day_chunks(conn)+ while True:+ # The generator is resumed inside a worker thread, one batch at+ # a time — never from two threads at once, which is what makes+ # the shared connection safe (see _open_ro).+ batch = await asyncio.to_thread(_take, groups, SCAN_BATCH)+ if not batch:+ break+ for conversation_id, day, rows in batch:+ if (+ resume_after is not None+ and (conversation_id, day) <= resume_after+ ):+ continue+ yield _chunk_item(conversation_id, day, rows)finally:- conn.close()+ await asyncio.to_thread(conn.close)async def incremental(self, ctx: ConnectorContext, cursor: str | None = None) -> AsyncIterator[RawItem]:- conn = self._open_ro(self._resolve_db_path(ctx))+ conn = await asyncio.to_thread(+ self._open_ro, self._resolve_db_path(ctx)+ )if conn is None:returntry:min_rowid = _parse_rowid_cursor(cursor)- for conversation_id, day in _touched_days(conn, min_rowid):- rows = _rows_for_day(conn, conversation_id, day)- if rows:- yield _chunk_item(conversation_id, day, rows)+ touched, scanned_max_rowid = await asyncio.to_thread(+ _touched_days, conn, min_rowid+ )+ for batch in _batched(touched, SCAN_BATCH):+ days = await asyncio.to_thread(_rows_for_days, conn, batch)+ for conversation_id, day, rows in days:+ yield _chunk_item(+ conversation_id,+ day,+ rows,+ max_rowid_cap=scanned_max_rowid,+ )finally:- conn.close()+ await asyncio.to_thread(conn.close)# ------------------------------------------------------------------# Sync helpers (blocking I/O stays out of the async frames)@@ -222,7 +267,12 @@ class JarvisConversationsConnector:return Noneuri = f"{db_path.resolve().as_uri()}?mode=ro"try:- return sqlite3.connect(uri, uri=True)+ # check_same_thread=False because every use of this read-only+ # connection is dispatched through asyncio.to_thread, and the+ # thread pool hands out whichever worker is free. Access stays+ # strictly serial (one awaited hop at a time), so no lock is+ # needed — but the connection does move between threads.+ return sqlite3.connect(uri, uri=True, check_same_thread=False)except sqlite3.Error as exc:log.warning("%s: could not open conversation store %s read-only: %s",@@ -233,6 +283,17 @@ class JarvisConversationsConnector:return None+def _take(groups: Iterator[tuple[str, str, list[_Row]]], size: int) -> list[+ tuple[str, str, list[_Row]]+]:+ """Pull up to *size* day-chunks off a running group iterator (blocking)."""+ return list(itertools.islice(groups, size))+++def _batched(values: list[tuple[str, str]], size: int) -> list[list[tuple[str, str]]]:+ return [values[start : start + size] for start in range(0, len(values), size)]++def _iter_day_chunks(conn: sqlite3.Connection,) -> Iterator[tuple[str, str, list[_Row]]]:@@ -252,13 +313,23 @@ def _iter_day_chunks(yield current_key[0], current_key[1], rows-def _touched_days(conn: sqlite3.Connection, min_rowid: int) -> list[tuple[str, str]]:- """(conversation_id, day) pairs touched by rows newer than ``min_rowid``."""- touched = {- (str(conversation_id), _day_utc(int(timestamp_ns)))- for conversation_id, timestamp_ns in conn.execute(_TOUCHED_QUERY, (min_rowid,))- }- return sorted(touched)+def _touched_days(+ conn: sqlite3.Connection, min_rowid: int+) -> tuple[list[tuple[str, str]], int]:+ """``(pairs, scanned_max_rowid)`` for rows newer than ``min_rowid``.++ ``scanned_max_rowid`` is the highest rowid this scan actually saw — the+ high-water mark the caller may safely report as the new cursor. It is 0+ when nothing is newer than ``min_rowid``.+ """+ touched: set[tuple[str, str]] = set()+ scanned_max_rowid = 0+ for rowid, conversation_id, timestamp_ns in conn.execute(+ _TOUCHED_QUERY, (min_rowid,)+ ):+ touched.add((str(conversation_id), _day_utc(int(timestamp_ns))))+ scanned_max_rowid = max(scanned_max_rowid, int(rowid))+ return sorted(touched), scanned_max_rowiddef _rows_for_day(conn: sqlite3.Connection, conversation_id: str, day: str) -> list[_Row]:@@ -269,4 +340,16 @@ def _rows_for_day(conn: sqlite3.Connection, conversation_id: str, day: str) -> l]+def _rows_for_days(+ conn: sqlite3.Connection, pairs: list[tuple[str, str]]+) -> list[tuple[str, str, list[_Row]]]:+ """Re-read a batch of whole days in one worker-thread hop (blocking)."""+ result: list[tuple[str, str, list[_Row]]] = []+ for conversation_id, day in pairs:+ rows = _rows_for_day(conn, conversation_id, day)+ if rows:+ result.append((conversation_id, day, rows))+ return result++__all__ = ["JarvisConversationsConnector"]diff --git a/jarvis/ultrawiki/connectors/local_folder.py b/jarvis/ultrawiki/connectors/local_folder.pyindex 3168b9cdd5..5203c6272a 100644--- a/jarvis/ultrawiki/connectors/local_folder.py+++ b/jarvis/ultrawiki/connectors/local_folder.py@@ -7,10 +7,14 @@ store, no LLM, no embedding (design doc 02, hard rule 1).Cursor / checkpoint contract (documented honestly):-- ``backfill(ctx, checkpoint)`` walks the tree in deterministic order- (sorted by POSIX relative path). ``checkpoint`` is the ``external_id``- of the last item the runtime persisted; files sorting at or before it- are skipped so an interrupted backfill resumes instead of restarting.+- ``backfill(ctx, checkpoint)`` walks the tree in deterministic order,+ sorted by ``external_id`` — the SAME string the checkpoint holds, which+ is what makes "skip everything at or before the checkpoint" correct for+ every subclass (a subclass that derives its ids differently, like the+ normal-wiki connector stripping ``.md``, orders by ITS ids too).+ ``checkpoint`` is the ``external_id`` of the last item the runtime+ persisted; files sorting at or before it are skipped so an interrupted+ backfill resumes instead of restarting.- ``incremental(ctx, cursor)`` uses a cursor that is the highest``st_mtime_ns`` seen so far, as a string. Every yielded item carries``metadata["mtime_ns"]`` so the runtime can advance the cursor to the@@ -29,10 +33,11 @@ Cursor / checkpoint contract (documented honestly):from __future__ import annotations+import asyncioimport loggingimport osimport re-from collections.abc import AsyncIterator+from collections.abc import AsyncIterator, Sequencefrom datetime import UTC, datetimefrom pathlib import Path@@ -49,6 +54,16 @@ log = logging.getLogger(__name__)#: Matches an H1 markdown heading ("# Title") at the start of a line._H1_RE = re.compile(r"^# +(.+?)\s*$", re.MULTILINE)+#: Files stat'ed + read per worker-thread hop. Filesystem I/O must never run+#: on the event loop (it also serves voice and chat), but one hop per file+#: would pay the handoff thousands of times over a real vault — a small batch+#: amortizes it while keeping each hop short.+READ_BATCH = 32+++def _batched(values: Sequence[Path], size: int) -> list[Sequence[Path]]:+ return [values[start : start + size] for start in range(0, len(values), size)]+def first_h1_heading(body: str) -> str:"""Return the first ``# ...`` heading of a markdown body, or ``""``."""@@ -112,32 +127,34 @@ class LocalFolderConnector:async def backfill(self, ctx: ConnectorContext, checkpoint: str | None = None) -> AsyncIterator[RawItem]:- root = self._resolve_root(ctx)+ root = await asyncio.to_thread(self._resolve_root, ctx)if root is None:returnextensions = self._extensions(ctx)- for path in self._sorted_files(root, extensions):- external_id = self._external_id_for(root, path)- if checkpoint and external_id <= checkpoint:- continue- item = self._item_for(root, path)- if item is not None:+ paths = await asyncio.to_thread(self._sorted_files, root, extensions)+ pending = [+ path+ for path in paths+ if not (checkpoint and self._external_id_for(root, path) <= checkpoint)+ ]+ for batch in _batched(pending, READ_BATCH):+ for item in await asyncio.to_thread(self._items_for_paths, root, batch):yield itemasync def incremental(self, ctx: ConnectorContext, cursor: str | None = None) -> AsyncIterator[RawItem]:- root = self._resolve_root(ctx)+ root = await asyncio.to_thread(self._resolve_root, ctx)if root is None:returnthreshold = parse_mtime_cursor(cursor, connector_id=self.id)extensions = self._extensions(ctx)- for path in self._sorted_files(root, extensions):- mtime_ns = self._mtime_ns(path)- if mtime_ns is None or mtime_ns <= threshold:- continue- item = self._item_for(root, path)- if item is not None:+ paths = await asyncio.to_thread(self._sorted_files, root, extensions)+ for batch in _batched(paths, READ_BATCH):+ items = await asyncio.to_thread(+ self._items_for_paths, root, batch, min_mtime_ns=threshold+ )+ for item in items:yield item# ------------------------------------------------------------------@@ -176,10 +193,16 @@ class LocalFolderConnector:return tuple(normalized) or self.DEFAULT_EXTENSIONSdef _sorted_files(self, root: Path, extensions: tuple[str, ...]) -> list[Path]:- """All matching files under ``root``, sorted by POSIX relative path.+ """All matching files under ``root``, sorted by ``external_id``.++ The sort key is deliberately :meth:`_external_id_for`, not the raw+ relative path: the backfill checkpoint stores an ``external_id``, so+ resuming can only be correct while walk order and checkpoint order are+ the same string ordering.Hidden directories and files (dot-prefixed) plus :attr:`SKIP_DIR_NAMES`- are excluded. Symlinked directories are not followed.+ are excluded. Symlinked directories are not followed. Blocking — call+ it through ``asyncio.to_thread``."""matches: list[tuple[str, Path]] = []for dirpath, dirnames, filenames in os.walk(root):@@ -193,9 +216,9 @@ class LocalFolderConnector:path = base / nameif path.suffix.lower() not in extensions:continue- matches.append((path.relative_to(root).as_posix(), path))+ matches.append((self._external_id_for(root, path), path))matches.sort(key=lambda pair: pair[0])- return [path for _rel, path in matches]+ return [path for _external_id, path in matches]def _external_id_for(self, root: Path, path: Path) -> str:return path.relative_to(root).as_posix()@@ -204,9 +227,33 @@ class LocalFolderConnector:return path.stem# ------------------------------------------------------------------- # Item construction (sync helpers keep blocking I/O out of async frames)+ # Item construction — every helper below BLOCKS on the filesystem and is+ # only ever called through asyncio.to_thread from the generators above.# ------------------------------------------------------------------+ def _items_for_paths(+ self,+ root: Path,+ paths: Sequence[Path],+ *,+ min_mtime_ns: int | None = None,+ ) -> list[RawItem]:+ """Stat + read one batch of files in a worker thread.++ With ``min_mtime_ns`` set (the incremental cursor) files that were not+ modified after it are skipped before their body is read at all.+ """+ items: list[RawItem] = []+ for path in paths:+ if min_mtime_ns is not None:+ mtime_ns = self._mtime_ns(path)+ if mtime_ns is None or mtime_ns <= min_mtime_ns:+ continue+ item = self._item_for(root, path)+ if item is not None:+ items.append(item)+ return items+def _mtime_ns(self, path: Path) -> int | None:try:return path.stat().st_mtime_nsdiff --git a/jarvis/ultrawiki/connectors/normal_wiki.py b/jarvis/ultrawiki/connectors/normal_wiki.pyindex a0f820ef9c..2ff1a0686b 100644--- a/jarvis/ultrawiki/connectors/normal_wiki.py+++ b/jarvis/ultrawiki/connectors/normal_wiki.py@@ -90,7 +90,13 @@ class NormalWikiConnector(LocalFolderConnector):if any(part.startswith(".") for part in rel_parts):continuematches.append(path)- matches.sort(key=lambda p: p.relative_to(root).as_posix())+ # Sorted by external_id (suffix STRIPPED), because that is what the+ # backfill checkpoint compares against. Sorting by the path WITH '.md'+ # orders 'entities/foo-bar.md' before 'entities/foo.md' ('-' < '.')+ # while the ids order 'entities/foo' before 'entities/foo-bar' — a+ # resume from 'entities/foo-bar' would then skip 'entities/foo'+ # entirely.+ matches.sort(key=lambda p: self._external_id_for(root, p))return matchesdef _external_id_for(self, root: Path, path: Path) -> str:diff --git a/jarvis/ultrawiki/distill.py b/jarvis/ultrawiki/distill.pyindex a4383dd537..886add3316 100644--- a/jarvis/ultrawiki/distill.py+++ b/jarvis/ultrawiki/distill.py@@ -45,6 +45,7 @@ __all__ = ["build_distill_prompt","distill_cache_key","distill_text",+ "extract_json_object",]#: Part of the distillation cache key — bump on EVERY prompt change.@@ -129,11 +130,13 @@ def distill_cache_key(*, title: str, body: str, model: str) -> tuple[str, int, s_JSON_FENCE_RE = re.compile(r"```(?:json)?\s*(.*?)```", re.DOTALL)-def _extract_json_object(text: str) -> tuple[str, dict[str, Any]] | None:+def extract_json_object(text: str) -> tuple[str, dict[str, Any]] | None:"""Best-effort extraction of the first JSON object from model output.Returns ``(raw_json_text, parsed_dict)`` or ``None``. Tolerates markdownfences and surrounding prose — providers wrap JSON despite instructions.+ Shared with the LLM reranker, which faces the identical strict-JSON+ contract against the identical provider chain."""candidates = [text.strip()]for match in _JSON_FENCE_RE.finditer(text):@@ -187,7 +190,7 @@ def _validate_distill_response(agg: Any) -> str | None:"""Chain validator: a transport success without parseable JSON is unusableoutput — the chain then tries the next provider family."""text = getattr(agg, "text", "") or ""- if _extract_json_object(text) is None:+ if extract_json_object(text) is None:return "distillation output holds no parseable JSON object"return None@@ -263,7 +266,7 @@ async def distill_text()agg, provider = result- extracted = _extract_json_object(getattr(agg, "text", "") or "")+ extracted = extract_json_object(getattr(agg, "text", "") or "")if extracted is None: # defensive: validate() already guaranteed thisraise DistillError(f"distillation failed: provider {provider} passed validation but "diff --git a/jarvis/ultrawiki/pipeline.py b/jarvis/ultrawiki/pipeline.pyindex 64e5680c2f..acb9f825b5 100644--- a/jarvis/ultrawiki/pipeline.py+++ b/jarvis/ultrawiki/pipeline.py@@ -16,12 +16,23 @@ identical end state. Stages, in ladder order:cache is consulted first on ``(content_hash, PROMPT_VERSION, model)``; on amiss the injected ``distill_fn`` runs, the SUMMARY document is stored withits ``distill_json``, the summary text is embedded too, and the result is- cached so identical input is never paid for twice.+ cached so identical input is never paid for twice. This stage is gated on+ BOTH slots it consumes — the embedding backend and a credential-ready chat+ provider — so an install without either pauses instead of dead-lettering+ every item (``store.requeue_failed`` recovers an already-stranded backlog).Error discipline: a per-item failure goes through ``store.mark_retry`` (60s *4^n backoff, dead-letter after 5 attempts) and the loop NEVER dies on one item-— it logs and continues. ``asyncio.CancelledError`` is always re-raised so the-service's cancel-then-wait shutdown stays honest.+— it logs and continues. A failed BATCH embed call is not a per-item failure:+its members are retried individually in the same pass so one poisoned text+cannot charge an attempt to 31 healthy ones. ``asyncio.CancelledError`` is+always re-raised so the service's cancel-then-wait shutdown stays honest.++Concurrency: a sync can reset an item to ``captured`` (content changed, derived+rows purged) between a worker's claim and its commit. Every transition is+therefore a compare-and-set against the state AND content hash seen at claim+time; a lost claim writes nothing, charges no attempt, and is simply re-run on+the next pass.This module imports only the stdlib and the dependency-free types module atimport time (AP-26); heavier modules (embedding defaults, the distill prompt@@ -46,6 +57,7 @@ __all__ = ["KEYWORD_BATCH","EMBED_BATCH","DISTILL_BATCH",+ "MAX_EMBED_CHARS","IDLE_SLEEP_S","BUSY_SLEEP_S","PipelineWorker",@@ -56,12 +68,19 @@ KEYWORD_BATCH = 200EMBED_BATCH = 32DISTILL_BATCH = 4+#: Character budget per embedded text, mirroring the distillation truncation+#: in ``jarvis/ultrawiki/distill.py``. An oversized document is a provider+#: 400/413 that would otherwise retry five times and dead-letter; an embedding+#: of the first 8000 characters is a far better answer than none.+MAX_EMBED_CHARS = 8000+#: Loop pacing: quick follow-up while there is work, gentle poll when idle.IDLE_SLEEP_S = 2.0BUSY_SLEEP_S = 0.1-#: The embedding ``ready()`` probe may hit the network (Ollama); cache its-#: verdict briefly so an idle loop does not hammer a dead endpoint.+#: The embedding ``ready()`` probe may hit the network (Ollama) and the distill+#: probe walks the keyring; cache both verdicts briefly so an idle loop does+#: not hammer a dead endpoint or re-walk the credential chain every 2 seconds._READY_PROBE_TTL_S = 30.0#: Zero-arg factory returning the CONFIGURED embedding backend (an object@@ -72,6 +91,12 @@ EmbeddingBackendFactory = Callable[[], Any]#: ``distill_fn(cfg, *, title, body, source_kind) -> DistillResult-like``.DistillFn = Callable[..., Awaitable[Any]]+#: ``() -> (usable, honest_reason_if_not)`` for the distillation slot. Injected+#: whenever ``distill_fn`` is NOT the production chain (an injected distiller+#: brings its own provider, so probing the credential chain would be wrong —+#: and would make the result depend on whatever keys the host happens to have).+DistillReadyFn = Callable[[], tuple[bool, str]]+def _summary_text(question: str, summary: str, resolution: str, entities: list[str]@@ -120,16 +145,20 @@ class PipelineWorker:embedding_backend_factory: EmbeddingBackendFactory,distill_fn: DistillFn,now_fn: Callable[[], datetime] | None = None,+ distill_ready_fn: DistillReadyFn | None = None,) -> None:self._store = storeself._cfg = cfgself._backend_factory = embedding_backend_factoryself._distill_fn = distill_fnself._now_fn = now_fn+ self._distill_ready_fn = distill_ready_fn#: Per-stage processed counters (successful transitions only).self.processed: dict[str, int] = {"keyword": 0, "embed": 0, "distill": 0}self._ready_cache: tuple[float, str, bool, str] | None = None- self._last_slot_reason: str | None = None+ self._distill_ready_cache: tuple[float, bool, str] | None = None+ #: stage -> the pause reason last logged, so a persistent gap logs once.+ self._pause_reasons: dict[str, str] = {}self._source_kind_cache: dict[str, str] = {}# -- public surface ------------------------------------------------------@@ -198,13 +227,30 @@ class PipelineWorker:"UltraWiki: mark_retry failed for item %s", item.get("id"))- def _note_slot_gap(self, reason: str) -> None:+ def _note_stage_pause(self, stage: str, reason: str) -> None:"""Log an honest 'stage paused' line once per reason change."""- if reason != self._last_slot_reason:- self._last_slot_reason = reason- log.info("UltraWiki embed/distill stages paused: %s", reason)+ if self._pause_reasons.get(stage) != reason:+ self._pause_reasons[stage] = reason+ log.info("UltraWiki %s stage paused: %s", stage, reason)++ def _clear_stage_pause(self, stage: str) -> None:+ self._pause_reasons.pop(stage, None)- def _embedding_slot(self) -> tuple[Any | None, str, str]:+ def _note_lost_claim(self, item: dict[str, Any], stage: str) -> None:+ """A concurrent content change invalidated this claim — not an error.++ The item is back at ``captured`` with its derived rows purged, so the+ next pass re-runs the whole ladder against the NEW content. Nothing is+ retried and no attempt is charged.+ """+ log.debug(+ "UltraWiki %s stage: claim on item %s lost to a concurrent content "+ "change; the next pass re-runs it",+ stage,+ item.get("id"),+ )++ async def _embedding_slot(self) -> tuple[Any | None, str, str]:"""``(backend, model, reason)`` — backend is ``None`` when the slot isunconfigured, unknown, model-less, or its ``ready()`` probe fails."""try:@@ -230,23 +276,83 @@ class PipelineWorker:f"embedding backend {getattr(backend, 'name', '?')!r} has no ""configured or default model")- ok, reason = self._backend_ready(backend)+ ok, reason = await self._backend_ready(backend)if not ok:return None, "", reasonreturn backend, model, ""- def _backend_ready(self, backend: Any) -> tuple[bool, str]:+ async def _backend_ready(self, backend: Any) -> tuple[bool, str]:name = str(getattr(backend, "name", ""))now = time.monotonic()cached = self._ready_cacheif cached is not None and cached[1] == name and now < cached[0]:return cached[2], cached[3]++ def _probe() -> tuple[bool, str]:+ try:+ ok, reason = backend.ready()+ except Exception as exc: # noqa: BLE001 — ready() must never kill the loop+ return False, (+ f"embedding readiness probe failed ({type(exc).__name__})"+ )+ return bool(ok), str(reason or "")++ # ready() is SYNCHRONOUS and may block on a socket (Ollama) or the OS+ # keyring — never on the event loop, which also serves voice and chat.+ ok, reason = await asyncio.to_thread(_probe)+ self._ready_cache = (now + _READY_PROBE_TTL_S, name, ok, reason)+ return ok, reason++ async def _distill_ready(self) -> tuple[bool, str]:+ """Is there a credential-ready chat provider for the distill stage?++ Mirrors ``UltraWikiService._distill_slot_status``. Without this gate the+ stage claimed work on an install with no chat credential at all, failed+ every item five times, and dead-lettered the entire corpus into+ ``failed`` — from which nothing ever returned. Now the stage simply+ pauses, honestly and once, and the backlog waits at ``embedded``.+ """+ now = time.monotonic()+ cached = self._distill_ready_cache+ if cached is not None and now < cached[0]:+ return cached[1], cached[2]+ if self._distill_ready_fn is not None:+ try:+ ok, reason = self._distill_ready_fn()+ except Exception as exc: # noqa: BLE001 — a broken probe pauses, never kills+ ok, reason = False, (+ f"distill readiness probe failed ({type(exc).__name__})"+ )+ ok, reason = bool(ok), str(reason or "")+ else:+ # Credential probes walk keyring / env / .env — off the loop.+ ok, reason = await asyncio.to_thread(self._probe_distill_chain)+ self._distill_ready_cache = (now + _READY_PROBE_TTL_S, ok, reason)+ return ok, reason++ def _probe_distill_chain(self) -> tuple[bool, str]:+ """Is any chat provider credential-ready? BLOCKING (keyring walk)."""try:- ok, reason = backend.ready()- except Exception as exc: # noqa: BLE001 — ready() must never kill the loop- ok, reason = False, f"embedding readiness probe failed ({type(exc).__name__})"- self._ready_cache = (now + _READY_PROBE_TTL_S, name, bool(ok), reason)- return bool(ok), reason+ from jarvis.brain.provider_registry import ( # noqa: PLC0415 — lazy+ BrainProviderRegistry,+ )+ from jarvis.memory.wiki.provider_chain import ( # noqa: PLC0415 — lazy+ credential_ready_wiki_providers,+ )++ chain = credential_ready_wiki_providers(+ available=set(BrainProviderRegistry().available()), config=self._cfg+ )+ except Exception as exc: # noqa: BLE001 — a broken probe pauses, never kills+ return False, f"distill chain probe failed ({type(exc).__name__})"+ if not chain:+ return False, (+ "no credential-ready chat provider is available for "+ "distillation - add any chat provider key (or start a local "+ "one) and the backlog resumes; keyword and semantic search "+ "keep working"+ )+ return True, ""async def _source_kind(self, source_id: str) -> str:kind = self._source_kind_cache.get(source_id)@@ -261,11 +367,25 @@ class PipelineWorker:return kind@staticmethod- def _raw_text(item: dict[str, Any]) -> str:+ def _cap_embed_input(text: str) -> str:+ """Trim an embed input to :data:`MAX_EMBED_CHARS` (provider limits)."""+ return text if len(text) <= MAX_EMBED_CHARS else text[:MAX_EMBED_CHARS]++ @classmethod+ def _raw_text(cls, item: dict[str, Any]) -> str:title = str(item.get("title") or "")body = str(item.get("body_raw") or "")text = f"{title}\n\n{body}".strip()- return text or str(item.get("external_id") or "")+ return cls._cap_embed_input(text or str(item.get("external_id") or ""))++ @staticmethod+ def _claim_guard(item: dict[str, Any]) -> dict[str, Any]:+ """The compare-and-set keys captured at claim time (see+ ``UltraStore.mark_stage_done``)."""+ return {+ "expected_state": item.get("state") or None,+ "expected_content_hash": item.get("content_hash") or None,+ }# -- stage passes --------------------------------------------------------@@ -277,13 +397,17 @@ class PipelineWorker:)for item in items:try:- await self._store.mark_stage_done(+ committed = await self._store.mark_stage_done(int(item["id"]),ItemState.KEYWORD_INDEXED,fts_title=str(item.get("title") or ""),fts_body=str(item.get("body_raw") or ""),+ **self._claim_guard(item),)- self.processed["keyword"] += 1+ if committed:+ self.processed["keyword"] += 1+ else:+ self._note_lost_claim(item, "keyword")except asyncio.CancelledError:raiseexcept Exception as exc: # noqa: BLE001 — one poisoned item blocks nothing@@ -293,11 +417,11 @@ class PipelineWorker:async def _embed_pass(self) -> int:"""``keyword_indexed -> embedded``: store the RAW document and itsvector via the configured backend. An unusable slot claims NO work."""- backend, model, reason = self._embedding_slot()+ backend, model, reason = await self._embedding_slot()if backend is None:- self._note_slot_gap(reason)+ self._note_stage_pause("embed", reason)return 0- self._last_slot_reason = None+ self._clear_stage_pause("embed")items = await self._store.claim_batch(ItemState.EMBEDDED, limit=EMBED_BATCH, now=self._claim_now())@@ -312,41 +436,95 @@ class PipelineWorker:)except asyncio.CancelledError:raise- except Exception as exc: # noqa: BLE001 — batch failure retries every member- for item in items:- await self._retry(item, "embed", exc)- return len(items)+ except Exception as exc: # noqa: BLE001 — fall back to per-item embedding+ # ONE unembeddable text (provider 400 on some content) used to+ # charge an attempt to all 32 batch members, so a single poison+ # item dead-lettered a whole healthy batch every five passes.+ # Re-embed each member ALONE in this SAME pass instead: only the+ # genuinely failing item accrues an attempt.+ log.info(+ "UltraWiki embed batch of %d failed (%s) — retrying its members "+ "individually in this pass",+ len(items),+ exc,+ )+ return await self._embed_individually(items, texts, backend, model)for item, text, vector in zip(items, texts, vectors, strict=True):try:- doc_id = await self._store.add_document(- int(item["id"]),- DocType.RAW,- text,- content_hash=str(item.get("content_hash") or ""),- )- await self._store.store_embedding(- doc_id, model=model, dim=len(vector), vector=vector- )- await self._store.mark_stage_done(int(item["id"]), ItemState.EMBEDDED)- self.processed["embed"] += 1+ await self._store_embedded(item, text, vector, model)except asyncio.CancelledError:raiseexcept Exception as exc: # noqa: BLE001 — one poisoned item blocks nothingawait self._retry(item, "embed", exc)return len(items)+ async def _embed_individually(+ self,+ items: list[dict[str, Any]],+ texts: list[str],+ backend: Any,+ model: str,+ ) -> int:+ """Per-item fallback after a failed batch call (see ``_embed_pass``)."""+ for item, text in zip(items, texts, strict=True):+ try:+ vectors = await backend.embed([text], model=model)+ if not vectors:+ raise RuntimeError("backend returned no vector for the text")+ await self._store_embedded(item, text, vectors[0], model)+ except asyncio.CancelledError:+ raise+ except Exception as exc: # noqa: BLE001 — only this item is charged+ await self._retry(item, "embed", exc)+ return len(items)++ async def _store_embedded(+ self, item: dict[str, Any], text: str, vector: Any, model: str+ ) -> None:+ """RAW document + vector + the guarded ``embedded`` transition.++ When the compare-and-set finds the item already reset by a concurrent+ content change, the document just written is stale — harmless, because+ ``add_document`` REPLACES the ``(item_id, doc_type)`` row when the next+ pass re-embeds the new content.+ """+ doc_id = await self._store.add_document(+ int(item["id"]),+ DocType.RAW,+ text,+ content_hash=str(item.get("content_hash") or ""),+ )+ await self._store.store_embedding(+ doc_id, model=model, dim=len(vector), vector=vector+ )+ committed = await self._store.mark_stage_done(+ int(item["id"]), ItemState.EMBEDDED, **self._claim_guard(item)+ )+ if committed:+ self.processed["embed"] += 1+ else:+ self._note_lost_claim(item, "embed")+async def _distill_pass(self) -> int:"""``embedded -> distilled``: cache-first distillation, SUMMARYdocument + summary embedding, result cached for determinism.- The stage needs the embedding slot too (the summary is embedded), so- an unusable slot claims no distill work either. Items can only reach- ``embedded`` while the slot works, so this gate is rarely the limiter.+ TWO gates, because the stage needs TWO slots: the embedding slot (the+ summary is embedded too) AND a credential-ready chat provider for the+ distillation call itself. Either one unusable means the stage claims NO+ work — the backlog waits honestly instead of burning five attempts per+ item and dead-lettering the corpus (a keyless install used to lose+ everything that way)."""- backend, model, reason = self._embedding_slot()+ backend, model, reason = await self._embedding_slot()if backend is None:- self._note_slot_gap(reason)+ self._note_stage_pause("distill", reason)+ return 0+ distill_ok, distill_reason = await self._distill_ready()+ if not distill_ok:+ self._note_stage_pause("distill", distill_reason)return 0+ self._clear_stage_pause("distill")items = await self._store.claim_batch(ItemState.DISTILLED, limit=DISTILL_BATCH, now=self._claim_now())@@ -354,8 +532,10 @@ class PipelineWorker:return 0for item in items:try:- await self._distill_one(item, backend, model)- self.processed["distill"] += 1+ if await self._distill_one(item, backend, model):+ self.processed["distill"] += 1+ else:+ self._note_lost_claim(item, "distill")except asyncio.CancelledError:raiseexcept Exception as exc: # noqa: BLE001 — one poisoned item blocks nothing@@ -371,7 +551,11 @@ class PipelineWorker:provider = str(getattr(ultrawiki, "distill_provider", "") or "").strip()return model or provider or "auto"- async def _distill_one(self, item: dict[str, Any], backend: Any, model: str) -> None:+ async def _distill_one(+ self, item: dict[str, Any], backend: Any, model: str+ ) -> bool:+ """One distillation; ``False`` means the claim was lost (see+ ``_note_lost_claim``)."""from jarvis.ultrawiki.distill import ( # noqa: PLC0415 — lazy (AP-26)distill_cache_key,)@@ -415,11 +599,13 @@ class PipelineWorker:fields, ensure_ascii=False, separators=(",", ":"))- text = _summary_text(- _string_field(fields, "question"),- _string_field(fields, "summary"),- _string_field(fields, "resolution"),- _list_field(fields, "entities"),+ text = self._cap_embed_input(+ _summary_text(+ _string_field(fields, "question"),+ _string_field(fields, "summary"),+ _string_field(fields, "resolution"),+ _list_field(fields, "entities"),+ )) or self._raw_text(item)doc_id = await self._store.add_document(@@ -440,4 +626,8 @@ class PipelineWorker:await self._store.distill_cache_put(content_hash, prompt_version, cache_model, raw_json)- await self._store.mark_stage_done(int(item["id"]), ItemState.DISTILLED)+ return bool(+ await self._store.mark_stage_done(+ int(item["id"]), ItemState.DISTILLED, **self._claim_guard(item)+ )+ )diff --git a/jarvis/ultrawiki/search.py b/jarvis/ultrawiki/search.pyindex 87900a474b..d170b4eacd 100644--- a/jarvis/ultrawiki/search.py+++ b/jarvis/ultrawiki/search.py@@ -1,21 +1,37 @@-"""UltraWiki hybrid search — RRF fusion over the store's legs + optional rerank.--The read path (design doc 03): the keyword leg (FTS/tsvector in the store) and-the vector leg (query embedding -> ANN in the store) run CONCURRENTLY, their-ranked lists are fused with Reciprocal Rank Fusion (smoothing constant 60 —-consensus beats a single strong vote), duplicates merge by item, results are-capped per source before the final cut, and an optional rerank model reorders-the top of the fused list.--Degradation ladder (§3 universality — never a brick):--- No embedding provider configured, a dead/keyless backend, or a store-side- vector degradation (missing sqlite-vec, nothing embedded yet, dim mismatch)- => the vector leg is skipped with a logged honest reason and keyword search- answers alone; ``matched_by`` on each result shows which legs actually ran.-- No rerank provider configured, an unknown/not-ready one, or a failing rerank- call => the fusion order stands. A rerank failure logs once and never fails- the search.+"""UltraWiki hybrid search — the ranking pipeline of design doc 03.++The read path, stage by stage (the Cerebras knowledge-base pipeline, adapted+to a single-user store):++ keyword leg · vector leg (concurrent, plus the IDF probe)+ │+ ▼+ RRF FUSION score(d) = Σ_legs weight / (60 + rank)+ × term-rarity signal × age decay + recency tiebreak+ dedupe by item · cap per source+ │+ ▼+ RERANK absolute 0-10 grade over the top ~20, keep the top ~10+ │+ ▼+ RELEVANCE FLOOR (unsolicited surfaces only)+ │+ ▼+ CONTEXT EXPANSION neighbouring messages/sections pulled back in++Two properties are load-bearing:++**RRF is ordinal, the rerank grade is absolute.** A fusion over garbage still+produces a confident-looking number one, so no fused score can ever mean+"nothing here is relevant". Only the rerank grade can, which is why+``enforce_floor`` gates on it and NOT on the fused score — the "Bugatti case"+lesson the normal wiki already paid for once.++**Nothing here may brick a search.** Every stage degrades on its own: no/dead+embedding provider => keyword answers alone; no/dead rerank provider => fusion+order stands; a store without the ranking-signal methods => neutral weights; a+failing context expansion => bare snippets. ``matched_by`` and ``rerank_score``+report honestly what actually ran.Heavy/optional pieces (httpx-backed embedding + rerank adapters) are importedlazily inside the functions (AP-26); this module itself is stdlib + types only.@@ -25,6 +41,8 @@ from __future__ import annotationsimport asyncioimport logging+import math+import refrom dataclasses import replacefrom datetime import UTC, datetimefrom typing import Any@@ -33,7 +51,7 @@ from jarvis.ultrawiki.types import SearchResultlog = logging.getLogger(__name__)-__all__ = ["hybrid_search", "search_status"]+__all__ = ["hybrid_search", "search", "search_status", "ranking_settings"]#: RRF smoothing constant (design doc 03: score(d) = sum 1 / (60 + rank)).RRF_K = 60@@ -41,17 +59,76 @@ RRF_K = 60#: How many candidates each leg contributes to the fusion pool.LEG_POOL = 20-#: How many fused candidates the optional rerank stage rescores.+#: How many fused candidates the rerank stage grades (the article's "more+#: diverse top twenty").RERANK_POOL = 20+#: How many graded candidates keep their rerank order ("keep the top ten").+#: Anything below stays available in fusion order, so a caller asking for more+#: than ten results still gets them.+RERANK_KEEP = 10+#: Maximum results per source BEFORE the final top-k cut, so one chatty#: source cannot crowd out every other voice.PER_SOURCE_CAP = 5+#: How many neighbouring snippets one winner may pull back in.+CONTEXT_NEIGHBORS = 2+#: Recency bonus ceiling — a strict tiebreak, deliberately far below any-#: realistic difference between two distinct RRF sums.+#: realistic difference between two distinct RRF sums. Independent of the+#: configurable half-life decay below._RECENCY_EPSILON = 1e-6+#: A query term counts as RARE when it occurs in no more than this fraction of+#: the live corpus. Deliberately relative: the article's absolute IDF>=4.0+#: threshold assumes a company-sized corpus and would mark nothing as rare in a+#: personal store of a few hundred items.+_RARE_DF_RATIO = 0.25++#: Lower bound of the term-rarity factor. A candidate that covers none of the+#: query's rare vocabulary is pushed DOWN, never out — a hard content-based+#: drop is the AP-27 trap (tightening on content kills recall), and the rerank+#: stage right after this is the place where real filtering belongs.+_SIGNAL_FLOOR = 0.6++#: Extra penalty for the filler case the article calls out ("sounds good,+#: thanks!"): short AND covering none of the rare query vocabulary.+_FILLER_CHARS = 200+_FILLER_PENALTY = 0.5++#: Query tokenizer: unicode-aware word characters, so German, Spanish, and any+#: other supported locale tokenize the same way (no ASCII-only class).+_TOKEN_RE = re.compile(r"\w{2,}", re.UNICODE)++_SECONDS_PER_DAY = 86400.0+++def _uw(cfg: Any) -> Any:+ return getattr(cfg, "ultrawiki", None)+++def _float_setting(cfg: Any, name: str, default: float) -> float:+ """One ``[ultrawiki]`` float knob, defaulting on anything unusable."""+ try:+ value = float(getattr(_uw(cfg), name, default))+ except (TypeError, ValueError):+ return default+ return value if math.isfinite(value) else default+++def ranking_settings(cfg: Any) -> dict[str, float]:+ """The live ranking knobs — surfaced by ``search_status`` so the CLI and+ the UI can show what the ranking is actually doing."""+ return {+ "keyword_weight": max(0.0, _float_setting(cfg, "rrf_keyword_weight", 1.0)),+ "vector_weight": max(0.0, _float_setting(cfg, "rrf_vector_weight", 1.0)),+ "recency_half_life_days": max(+ 0.0, _float_setting(cfg, "recency_half_life_days", 180.0)+ ),+ "rerank_min_score": max(0.0, _float_setting(cfg, "rerank_min_score", 4.0)),+ }+async def hybrid_search(store: Any,@@ -60,27 +137,48 @@ async def hybrid_search(*,k: int = 10,area_id: str | None = None,+ rerank: bool = True,+ enforce_floor: bool = False,+ expand_context: bool = True,) -> list[SearchResult]:"""Fused keyword + vector search over an UltraWiki store.``store`` is an :class:`~jarvis.ultrawiki.store.UltraStore` or:class:`~jarvis.ultrawiki.store.PostgresStore` (same public surface).Returns at most ``k`` :class:`SearchResult` rows, best first, each carrying- the fused score and the ``matched_by`` tuple of the legs that produced it.+ the fused score, the ``matched_by`` tuple of the legs that produced it, the+ absolute ``rerank_score`` when the stage ran, and its ``context``.++ ``rerank=False`` skips the grading stage — used by the realtime voice path,+ whose latency budget (doc 03) does not admit an extra model call.++ ``enforce_floor=True`` is for UNSOLICITED surfaces (context injection into+ the brain prompt, volunteered voice answers): candidates graded below+ ``[ultrawiki].rerank_min_score`` are dropped and an empty list is an honest+ "I have nothing on that". It never silently passes everything: when the+ grade is unavailable the caller gets results with ``rerank_score=None`` and+ must apply its own deterministic gate (``jarvis.brain.wiki_relevance``).+An empty/blank query returns ``[]`` without touching any leg."""if not query or not query.strip():return []- keyword_hits, vector_hits = await asyncio.gather(+ keyword_hits, vector_hits, signals = await asyncio.gather(store.keyword_search(query, k=LEG_POOL, area_id=area_id),_vector_leg(store, cfg, query, area_id=area_id),+ _term_signals(store, query),)- fused = _fuse(keyword_hits, vector_hits)+ fused = _fuse(keyword_hits, vector_hits, cfg=cfg, signals=signals)if not fused:return []capped = _cap_per_source(fused)- ordered = await _maybe_rerank(cfg, query, capped)- return ordered[: max(0, int(k))]+ ordered = await _maybe_rerank(cfg, query, capped) if rerank else capped+ if enforce_floor:+ ordered = _apply_relevance_floor(cfg, ordered)+ top = ordered[: max(0, int(k))]+ if expand_context and top:+ top = await _expand_context(store, top)+ return topasync def search(@@ -90,23 +188,36 @@ async def search(query: str,k: int = 10,area_id: str | None = None,+ rerank: bool = True,+ enforce_floor: bool = False,+ expand_context: bool = True,) -> list[SearchResult]:- """Keyword-only facade over :func:`hybrid_search`.+ """Keyword-argument facade over :func:`hybrid_search`.This is the seam :meth:`UltraWikiService.search` delegates to; it existsso the service and the routes never depend on positional argument order."""- return await hybrid_search(store, cfg, query, k=k, area_id=area_id)+ return await hybrid_search(+ store,+ cfg,+ query,+ k=k,+ area_id=area_id,+ rerank=rerank,+ enforce_floor=enforce_floor,+ expand_context=expand_context,+ )def search_status(cfg: Any) -> dict[str, Any]:- """Honest live report of the three retrieval legs, from config alone.+ """Honest live report of the retrieval legs + the ranking knobs.``keyword`` is always available (FTS ships with the store). ``vector``names the configured backend + model or the honest reason it is off.- ``rerank`` names the configured provider or ``"off"``.+ ``rerank`` names the configured provider or ``"off"``. ``ranking`` echoes+ the live weights, half-life, and relevance floor."""- ultrawiki = getattr(cfg, "ultrawiki", None)+ ultrawiki = _uw(cfg)status: dict[str, Any] = {"keyword": {"available": True}}provider = str(getattr(ultrawiki, "embedding_provider", "") or "").strip()@@ -169,6 +280,7 @@ def search_status(cfg: Any) -> dict[str, Any]:entry["reason"] = reasonstatus["rerank"] = entry+ status["ranking"] = ranking_settings(cfg)return status@@ -191,7 +303,7 @@ async def _vector_leg(vector degradation) returns ``[]`` with a logged honest reason — thesearch itself never fails because of the vector leg."""- ultrawiki = getattr(cfg, "ultrawiki", None)+ ultrawiki = _uw(cfg)provider = str(getattr(ultrawiki, "embedding_provider", "") or "").strip()if not provider:return []@@ -226,6 +338,76 @@ async def _vector_leg(return results+# ---------------------------------------------------------------------------+# Term rarity (IDF)+# ---------------------------------------------------------------------------+++def query_terms(query: str) -> list[str]:+ """Distinct lowercased query tokens, order preserved."""+ return list(dict.fromkeys(match.group(0).lower() for match in _TOKEN_RE.finditer(query)))+++async def _term_signals(store: Any, query: str) -> dict[str, float]:+ """IDF weight per RARE query term — the article's "separate signal from+ filler" leg, computed against this store's own corpus.++ Returns ``{}`` (neutral, no reordering) whenever the corpus is too small+ to be meaningful, the store predates these methods (third-party stores,+ fakes), or the probe fails. Never raises, never fails a search.+ """+ terms = query_terms(query)+ if not terms:+ return {}+ count_fn = getattr(store, "live_item_count", None)+ df_fn = getattr(store, "term_document_frequency", None)+ if not callable(count_fn) or not callable(df_fn):+ return {}+ try:+ total = int(await count_fn())+ if total <= 0:+ return {}+ frequencies = await df_fn(terms)+ except Exception: # noqa: BLE001 — a signal probe never fails the search+ log.debug("term-rarity probe failed — ranking without it", exc_info=True)+ return {}+ rare_cutoff = max(1.0, total * _RARE_DF_RATIO)+ weights: dict[str, float] = {}+ for term in terms:+ try:+ df = int(frequencies.get(term, 0))+ except (TypeError, ValueError):+ continue+ if df <= 0 or df > rare_cutoff:+ continue # absent from the corpus, or common enough to be filler+ weights[term] = math.log(total / df)+ return {term: weight for term, weight in weights.items() if weight > 0.0}+++def _signal_factor(hit: SearchResult, signals: dict[str, float]) -> float:+ """How much of the query's RARE vocabulary this candidate actually shows.++ Caveat worth knowing: the candidate text available here is its snippet, so+ a rare term living outside the snippet is invisible and the candidate is+ scaled down despite being relevant. That is why the factor is floored at+ :data:`_SIGNAL_FLOOR` and why the rerank stage — which sees the same text+ but judges meaning — runs immediately after.+ """+ if not signals:+ return 1.0+ text = f"{hit.title} {hit.snippet}"+ present = set(query_terms(text))+ total_weight = sum(signals.values())+ if total_weight <= 0:+ return 1.0+ covered = sum(weight for term, weight in signals.items() if term in present)+ coverage = covered / total_weight+ factor = _SIGNAL_FLOOR + (1.0 - _SIGNAL_FLOOR) * coverage+ if coverage <= 0.0 and len(text.strip()) < _FILLER_CHARS:+ factor *= _FILLER_PENALTY+ return factor++# ---------------------------------------------------------------------------# Fusion# ---------------------------------------------------------------------------@@ -242,22 +424,53 @@ def _recency_key(timestamp_utc: Any) -> float:return parsed.timestamp()-def _fuse(keyword_hits: list[SearchResult], vector_hits: list[SearchResult]) -> list[SearchResult]:+def _age_factor(timestamp_utc: Any, half_life_days: float, *, now: float) -> float:+ """``0.5 ** (age_days / half_life)`` — the article's age decay.++ ``half_life_days <= 0`` disables the decay. An unparsable or future stamp+ is never punished (factor 1.0): honesty over guessing.+ """+ if half_life_days <= 0:+ return 1.0+ stamp = _recency_key(timestamp_utc)+ if stamp == float("-inf"):+ return 1.0+ age_days = (now - stamp) / _SECONDS_PER_DAY+ if age_days <= 0:+ return 1.0+ return 0.5 ** (age_days / half_life_days)+++def _fuse(+ keyword_hits: list[SearchResult],+ vector_hits: list[SearchResult],+ *,+ cfg: Any = None,+ signals: dict[str, float] | None = None,+) -> list[SearchResult]:"""RRF-fuse the two ranked lists; merge duplicates by ``item_id``.- The fused score is ``sum(1 / (RRF_K + rank))`` over the legs the item- appeared in, plus a strictly-tiebreak-sized recency bonus derived from the- candidates themselves (newer ``timestamp_utc`` wins ties — no extra DB- query). ``matched_by`` is the union of the contributing legs; snippet and- citation fields come from the keyword occurrence when both legs matched- (its snippet is query-specific).+ The fused score is ``sum(weight / (RRF_K + rank))`` over the legs the item+ appeared in, scaled by the term-rarity signal and the age decay, plus a+ strictly-tiebreak-sized recency bonus derived from the candidates+ themselves (newer ``timestamp_utc`` wins ties — no extra DB query).+ ``matched_by`` is the union of the contributing legs; snippet and citation+ fields come from the keyword occurrence when both legs matched (its+ snippet is query-specific)."""+ knobs = ranking_settings(cfg)+ weights = {"keyword": knobs["keyword_weight"], "vector": knobs["vector_weight"]}+ half_life = knobs["recency_half_life_days"]+rrf_score: dict[int, float] = {}matched: dict[int, list[str]] = {}representative: dict[int, SearchResult] = {}for leg_name, hits in (("keyword", keyword_hits), ("vector", vector_hits)):+ weight = weights[leg_name]for rank, hit in enumerate(hits, start=1):- rrf_score[hit.item_id] = rrf_score.get(hit.item_id, 0.0) + 1.0 / (RRF_K + rank)+ rrf_score[hit.item_id] = (+ rrf_score.get(hit.item_id, 0.0) + weight / (RRF_K + rank)+ )labels = matched.setdefault(hit.item_id, [])if leg_name not in labels:labels.append(leg_name)@@ -276,10 +489,16 @@ def _fuse(keyword_hits: list[SearchResult], vector_hits: list[SearchResult]) ->for index, item_id in enumerate(by_recency)}+ now = datetime.now(UTC).timestamp()fused = [replace(base,- score=rrf_score[item_id] + recency_bonus[item_id],+ score=(+ rrf_score[item_id]+ * _signal_factor(base, signals or {})+ * _age_factor(base.timestamp_utc, half_life, now=now)+ + recency_bonus[item_id]+ ),matched_by=tuple(matched[item_id]),)for item_id, base in representative.items()@@ -302,7 +521,7 @@ def _cap_per_source(ranked: list[SearchResult]) -> list[SearchResult]:# ----------------------------------------------------------------------------# Optional rerank+# Rerank# ---------------------------------------------------------------------------@@ -311,13 +530,17 @@ def _rerank_document(hit: SearchResult) -> str:async def _maybe_rerank(cfg: Any, query: str, ranked: list[SearchResult]) -> list[SearchResult]:- """Reorder the top of the fused list with the configured reranker.-- Skipped honestly when no provider is configured / ready. Only the ORDER- changes — every result keeps its fused score. On :class:`RerankError`- the fusion order stands (logged once, the search never fails).+ """Grade the top of the fused list with the configured reranker.++ Skipped honestly when no provider is configured / ready. Graded candidates+ are reordered by their ABSOLUTE 0-10 relevance and carry it in+ ``rerank_score``; the fused ``score`` is left untouched so both signals+ stay inspectable. Only the first :data:`RERANK_KEEP` graded candidates+ take their new order — the rest stay in fusion order behind them, which is+ the article's "keep the top ten" without truncating a larger request. On+ :class:`RerankError` the fusion order stands (logged once, never fatal)."""- ultrawiki = getattr(cfg, "ultrawiki", None)+ ultrawiki = _uw(cfg)if not str(getattr(ultrawiki, "rerank_provider", "") or "").strip():return rankedfrom jarvis.ultrawiki import rerank as rerank_mod # noqa: PLC0415 — lazy (AP-26)@@ -333,13 +556,77 @@ async def _maybe_rerank(cfg: Any, query: str, ranked: list[SearchResult]) -> lisexcept rerank_mod.RerankError as exc:log.warning("rerank failed (%s) — keeping the fusion order", exc)return ranked- reordered: list[SearchResult] = []+ except Exception: # noqa: BLE001 — an optional stage never fails the search+ log.warning(+ "rerank raised unexpectedly — keeping the fusion order", exc_info=True+ )+ return ranked++ graded: list[tuple[int, SearchResult]] = []seen: set[int] = set()- for index, _score in pairs:+ for index, score in pairs:if 0 <= index < len(pool) and index not in seen:seen.add(index)- reordered.append(pool[index])- for index, hit in enumerate(pool):- if index not in seen: # providers may return fewer rows than asked- reordered.append(hit)- return reordered + ranked[RERANK_POOL:]+ graded.append((index, replace(pool[index], rerank_score=float(score))))+ # The top ten take their graded order. Everything below it — the tail of+ # the graded list and whatever the model never mentioned — falls back to+ # fusion order, so a caller asking for more than ten still gets a sane+ # ranking instead of an arbitrary one.+ head = [hit for _, hit in graded[:RERANK_KEEP]]+ tail = graded[RERANK_KEEP:] + [+ (index, hit) for index, hit in enumerate(pool) if index not in seen+ ]+ tail.sort(key=lambda pair: pair[0])+ return head + [hit for _, hit in tail] + ranked[RERANK_POOL:]+++def _apply_relevance_floor(cfg: Any, ranked: list[SearchResult]) -> list[SearchResult]:+ """Drop candidates graded below ``[ultrawiki].rerank_min_score``.++ Only GRADED candidates are judged: an ungraded one (stage skipped, failed,+ or beyond the rerank pool) has no absolute evidence for or against it and+ is passed through unchanged, because a floor that silently disappears on+ provider failure is worse than a visible one. The caller's deterministic+ gate stays responsible for those (``jarvis.brain.wiki_relevance``).+ """+ floor = ranking_settings(cfg)["rerank_min_score"]+ if floor <= 0:+ return ranked+ kept = [+ hit for hit in ranked if hit.rerank_score is None or hit.rerank_score >= floor+ ]+ dropped = len(ranked) - len(kept)+ if dropped:+ log.debug("relevance floor %.1f dropped %d graded candidate(s)", floor, dropped)+ return kept+++# ---------------------------------------------------------------------------+# Context expansion+# ---------------------------------------------------------------------------+++async def _expand_context(store: Any, top: list[SearchResult]) -> list[SearchResult]:+ """Re-hydrate the winners with their neighbouring evidence.++ Strictly best-effort and last (design doc 03): a store without+ ``neighbors_for`` — third-party implementations, test fakes — or a failing+ lookup leaves ``context=()`` and never disturbs the ranking above it.+ """+ neighbors_fn = getattr(store, "neighbors_for", None)+ if not callable(neighbors_fn):+ return top++ async def _for(hit: SearchResult) -> tuple[str, ...]:+ try:+ rows = await neighbors_fn(hit.item_id, limit=CONTEXT_NEIGHBORS)+ except Exception: # noqa: BLE001 — context is a bonus, never a failure+ log.debug("context expansion failed for item %s", hit.item_id, exc_info=True)+ return ()+ return tuple(str(row) for row in (rows or []) if str(row).strip())++ contexts = await asyncio.gather(*(_for(hit) for hit in top))+ return [+ replace(hit, context=context) if context else hit+ for hit, context in zip(top, contexts, strict=True)+ ]diff --git a/jarvis/ultrawiki/service.py b/jarvis/ultrawiki/service.pyindex aa1e07e240..769ac8f383 100644--- a/jarvis/ultrawiki/service.py+++ b/jarvis/ultrawiki/service.py@@ -53,11 +53,23 @@ __all__ = ["SYNC_CHUNK_SIZE","JOB_ACTIVE_STATUSES","JOB_TERMINAL_STATUSES",+ "PIPELINE_STATES",+ "SyncAlreadyRunningError","SyncJob","UltraWikiService","clear_jobs",]+#: The honest pipeline states reported by :meth:`UltraWikiService.status`.+#: Five-layer drift discipline (AP-4): the TypeScript union in+#: ``src/lib/ultrawikiApi.ts`` and the UI labels derive from THIS list.+PIPELINE_STATES: tuple[str, ...] = (+ "waiting_for_sources",+ "idle",+ "processing",+ "paused",+)+#: Items per ``upsert_items`` transaction / sync-state checkpoint.SYNC_CHUNK_SIZE = 200@@ -94,6 +106,24 @@ JOB_TERMINAL_STATUSES = frozenset({"done", "failed", "cancelled"})JOB_ACTIVE_STATUSES = frozenset({"queued", "running"})+class SyncAlreadyRunningError(RuntimeError):+ """One source already has an active sync job.++ Its own error type (not ``ValueError``) so the REST layer can answer 409+ with the ACTIVE job id instead of guessing from message text. Two+ concurrent syncs of one source would interleave their checkpoint and+ cursor writes and double every upsert.+ """++ def __init__(self, source_id: str, job_id: str) -> None:+ super().__init__(+ f"a sync is already running for source {source_id!r} "+ f"(job {job_id}) - wait for it or cancel it first"+ )+ self.source_id = source_id+ self.job_id = job_id++@dataclassclass SyncJob:"""One sync run's control-plane view (in-memory, not history)."""@@ -156,6 +186,14 @@ def _get_job(job_id: str) -> SyncJob | None:return _JOBS.get(job_id)+def _active_job_for(source_id: str) -> SyncJob | None:+ """The active (queued/running) job of *source_id*, if any."""+ for job in _JOBS.values():+ if job.source_id == source_id and job.status in JOB_ACTIVE_STATUSES:+ return job+ return None++def _list_job_snapshots(limit: int = 20) -> list[dict[str, Any]]:jobs = list(_JOBS.values())jobs.sort(key=lambda j: j.started_at, reverse=True)@@ -283,6 +321,14 @@ class UltraWikiService:self._cfg,embedding_backend_factory=self._embedding_backend_factory,distill_fn=self._call_distill,+ # An injected distiller brings its own provider, so the+ # credential-chain gate would be both wrong and dependent+ # on whatever keys the host happens to hold.+ distill_ready_fn=(+ (lambda: (True, ""))+ if self._injected_distill_fn is not None+ else None+ ),)self._pipeline_task = asyncio.create_task(self._pipeline.run(self._cancel_event),@@ -296,7 +342,8 @@ class UltraWikiService:if backend.strip().lower() == "postgres":from jarvis.core.config import get_secret # noqa: PLC0415 — lazy- conn_str = get_secret("ultrawiki_db_url")+ # The secret chain walks the OS keyring / .env — never on the loop.+ conn_str = await asyncio.to_thread(get_secret, "ultrawiki_db_url")if not conn_str:self._note_degradation("the Postgres backend is configured but no "@@ -308,9 +355,12 @@ class UltraWikiService:try:await pg_store.open()except Exception as exc: # noqa: BLE001 — degrade, never brick+ # psycopg echoes the DSN (password included) in several+ # failure modes and this line is shown in /status.self._note_degradation(- f"the Postgres store is unavailable ({exc}) - falling "- "back to the local SQLite store"+ "the Postgres store is unavailable "+ f"({store_mod.sanitize_conn_error(exc, conn_str)}) - "+ "falling back to the local SQLite store")else:self._backend_in_use = "postgres"@@ -393,6 +443,12 @@ class UltraWikiService:processed = (self._pipeline.processed_counts() if self._pipeline is not None else {})+ # Every slot probe walks credentials (keyring / .env) or an endpoint —+ # all three go to a worker thread together, never on the event loop.+ slots = await asyncio.to_thread(self._slot_statuses)+ state, reason = self._pipeline_state(+ counts, sources, slots, running=pipeline_running+ )return {"enabled": self._uw_enabled(),"started": started,@@ -402,19 +458,112 @@ class UltraWikiService:),"in_use": self._backend_in_use,},- "slots": {- "embedding": self._embedding_slot_status(),- "distill": self._distill_slot_status(),- "rerank": self._rerank_slot_status(),- },+ "slots": slots,"vector": vector,"counts": _counts_dict(counts),- "pipeline": {"running": pipeline_running, "processed": processed},+ "pipeline": {+ "running": pipeline_running,+ "state": state,+ "reason": reason,+ "processed": processed,+ },"sources": sources,"jobs": _list_job_snapshots(10),"degradations": list(self._degradations),}+ def _slot_statuses(self) -> dict[str, Any]:+ """The three capability-slot reports. BLOCKING (credential probes) —+ only ever called through ``asyncio.to_thread``."""+ return {+ "embedding": self._embedding_slot_status(),+ "distill": self._distill_slot_status(),+ "rerank": self._rerank_slot_status(),+ }++ def _pipeline_state(+ self,+ counts: PipelineCounts,+ sources: list[dict[str, Any]],+ slots: dict[str, Any],+ *,+ running: bool,+ ) -> tuple[str, str]:+ """``(state, honest English reason)`` for the import-progress strip.++ "Pipeline running" on a fresh activation with zero approved sources+ read as "something is already pulling my data" — the exact opposite of+ the consent contract. A live worker LOOP is not the same thing as work+ being done, so the strip states which of the four situations holds:+ nothing approved yet, nothing left to do, actually processing, or+ blocked on a slot. ``running`` is still reported separately.+ """+ approved = [+ source+ for source in sources+ if str(source.get("consent") or "") == ConsentState.APPROVED.value+ and bool(source.get("enabled"))+ ]+ pending_keyword = int(counts.captured)+ pending_embed = int(counts.keyword_indexed)+ pending_distill = int(counts.embedded)+ backlog = pending_keyword + pending_embed + pending_distill+ failed = int(counts.failed)+ failed_note = (+ f" {failed} item(s) gave up after repeated errors — use "+ "'retry failed items' once the cause is fixed."+ if failed+ else ""+ )++ if not approved:+ return "waiting_for_sources", (+ "No source is approved yet, so nothing is being read. Approve a "+ "source under Sources and start a sync — until then this store "+ "stays empty by design." + failed_note+ )+ if backlog == 0:+ return "idle", (+ "Everything ingested so far is fully processed; the pipeline is "+ "waiting for new or changed items." + failed_note+ )++ embed_ready = bool((slots.get("embedding") or {}).get("ready"))+ embed_reason = str((slots.get("embedding") or {}).get("reason") or "")+ distill_ready = bool((slots.get("distill") or {}).get("ready"))+ distill_reason = str((slots.get("distill") or {}).get("reason") or "")++ if pending_keyword > 0:+ blocked = ""+ if pending_embed and not embed_ready:+ blocked = f" The embedding stage is paused: {embed_reason}"+ elif pending_distill and not distill_ready:+ blocked = f" The distillation stage is paused: {distill_reason}"+ state, reason = "processing", (+ f"{backlog} item(s) are queued for processing." + blocked + failed_note+ )+ elif pending_embed > 0 and not embed_ready:+ state, reason = "paused", (+ f"{pending_embed} item(s) are keyword-searchable and waiting for "+ f"the embedding stage: {embed_reason}" + failed_note+ )+ elif pending_distill > 0 and pending_embed == 0 and not distill_ready:+ state, reason = "paused", (+ f"{pending_distill} item(s) are embedded and waiting for the "+ f"distillation stage: {distill_reason}" + failed_note+ )+ else:+ state, reason = "processing", (+ f"{backlog} item(s) are queued for processing." + failed_note+ )++ if state == "processing" and not running:+ return "paused", (+ f"{backlog} item(s) are queued, but the ingest pipeline is not "+ "running — UltraWiki is off or still starting." + failed_note+ )+ return state, reason+@staticmethoddef _source_summary(row: dict[str, Any]) -> dict[str, Any]:counts = row.get("counts")@@ -455,11 +604,18 @@ class UltraWikiService:ready, reason = False, f"unknown embedding provider {provider!r}"else:ready, reason = bool(row.get("ready")), str(row.get("reason") or "")+ via = ""+ if ready:+ try:+ via = embeddings_mod.credential_source(provider, self._cfg)+ except Exception: # noqa: BLE001 — provenance is decoration+ via = ""return {"provider": provider,"model": model or (str(row.get("default_model") or "") if row else ""),"ready": ready,"reason": reason,+ "via": via,"available": available,}@@ -484,6 +640,7 @@ class UltraWikiService:"model": model,"ready": False,"reason": f"distill chain probe failed ({type(exc).__name__})",+ "via": "","chain": [],}ready = bool(chain)@@ -492,16 +649,31 @@ class UltraWikiService:if readyelse "no credential-ready chat provider is available for distillation")+ # Provenance names the credential path, never a key: whatever chat+ # provider(s) the install actually holds is what carries this stage.+ if not ready:+ via = ""+ elif provider and provider in chain:+ via = f"your pinned chat provider {provider}"+ elif provider:+ via = (+ f"your pinned chat provider {provider} (not in the "+ f"credential-ready chain: {', '.join(chain)})"+ )+ else:+ via = f"chat-provider chain ({', '.join(chain)})"return {"provider": provider,"model": model,"ready": ready,"reason": reason,+ "via": via,"chain": chain,}def _rerank_slot_status(self) -> dict[str, Any]:provider = str(getattr(self._uw_cfg(), "rerank_provider", "") or "").strip()+ model = str(getattr(self._uw_cfg(), "rerank_model", "") or "").strip()try:from jarvis.ultrawiki import rerank as rerank_mod # noqa: PLC0415 — lazy@@ -509,9 +681,12 @@ class UltraWikiService:except Exception as exc: # noqa: BLE001 — status never raisesreturn {"provider": provider,+ "model": model,"ready": False,"reason": f"rerank backend probe failed ({type(exc).__name__})",+ "via": "","available": [],+ "ranking": self._ranking_knobs(),}row = next((r for r in available if r.get("name") == provider), None)if not provider:@@ -523,11 +698,47 @@ class UltraWikiService:ready, reason = bool(row.get("ready")), str(row.get("reason") or "")return {"provider": provider,+ "model": model,"ready": ready,"reason": reason,+ "via": self._rerank_via(provider, row) if ready else "","available": available,+ # The knobs ride along with the slot they govern, so the settings+ # card can show what the ranking actually does today.+ "ranking": self._ranking_knobs(),}+ def _ranking_knobs(self) -> dict[str, float]:+ """Live fusion weights / age decay / relevance floor; ``{}`` on error."""+ try:+ from jarvis.ultrawiki.search import ranking_settings # noqa: PLC0415 — lazy++ return ranking_settings(self._cfg)+ except Exception: # noqa: BLE001 — status never raises+ return {}++ def _rerank_via(self, provider: str, row: dict[str, Any] | None) -> str:+ """Key-free provenance of the rerank slot, or ``""`` when unknown.++ Asks the readiness row first and the backend adapter second (by+ capability, never by provider name), and stays EMPTY rather than+ inventing a credential path the backend never used.+ """+ if row is not None:+ declared = str(row.get("via") or "").strip()+ if declared:+ return declared+ try:+ from jarvis.ultrawiki import rerank as rerank_mod # noqa: PLC0415 — lazy++ factory = rerank_mod.RERANK_BACKENDS.get(provider)+ if factory is None:+ return ""+ describe = getattr(factory(self._cfg), "credential_source", None)+ return str(describe() or "") if callable(describe) else ""+ except Exception: # noqa: BLE001 — provenance is decoration, never a failure+ return ""+# -- activation & sources ------------------------------------------------async def activate(self, payload: dict[str, Any] | None = None) -> dict[str, Any]:@@ -617,12 +828,21 @@ class UltraWikiService:# -- sync jobs ------------------------------------------------------------ async def start_sync(self, source_id: str) -> str:+ async def start_sync(self, source_id: str, *, full: bool = False) -> str:"""Start a backfill/incremental sync as a detached named task.Refuses (``ValueError``) unless UltraWiki is enabled AND the sourceholds explicit approved consent — no connector pulls a single byte- before then.+ before then. A source that already has an active job raises+ :class:`SyncAlreadyRunningError` (the REST layer answers 409).++ ``full=True`` is the FULL REFRESH: it clears the resume checkpoint AND+ the incremental cursor, so the connector re-yields everything from the+ beginning. That is the only shape in which deletions can be detected —+ tombstoning needs the COMPLETE set of ids that still exist, which only+ a from-scratch backfill provides. Without it a source that has finished+ its first backfill only ever runs incrementally, and a file deleted+ afterwards stays in the store forever."""if not self._uw_enabled():raise ValueError(@@ -642,14 +862,30 @@ class UltraWikiService:)if not source.get("enabled", False):raise ValueError(f"source {source_id!r} is disabled")+ active = _active_job_for(source_id)+ if active is not None:+ raise SyncAlreadyRunningError(source_id, active.job_id)connector = self._build_connector(str(source.get("connector") or ""))sync_state = await store.get_sync_state(source_id) or {}+ if full:+ # Persist the reset before the job starts, so a crash mid-run+ # still resumes as a full backfill rather than a partial one.+ await store.set_sync_state(+ source_id, backfill_checkpoint=None, cursor=None+ )+ sync_state = {+ **sync_state,+ "backfill_checkpoint": None,+ "cursor": None,+ }capabilities = getattr(connector, "capabilities", None)incremental_mode = getattr(capabilities, "incremental", IncrementalMode.NONE)- use_incremental = bool(sync_state.get("backfill_complete_at")) and (- incremental_mode != IncrementalMode.NONE+ use_incremental = (+ not full+ and bool(sync_state.get("backfill_complete_at"))+ and incremental_mode != IncrementalMode.NONE)mode = "incremental" if use_incremental else "backfill"job = SyncJob(@@ -736,8 +972,16 @@ class UltraWikiService:job.tombstoned += await store.reconcile_deletes(source_id, yielded_ids)+ # Clearing the checkpoint is what makes the NEXT backfill a full+ # one. Left behind, it points at the LAST item of a completed+ # walk, so a connector that cannot run incrementally+ # (IncrementalMode.NONE) resumed at the very end and yielded+ # nothing, forever — its source looked permanently frozen.await store.set_sync_state(- source_id, backfill_complete_at=now, last_success_at=now+ source_id,+ backfill_checkpoint=None,+ backfill_complete_at=now,+ last_success_at=now,)else:await store.set_sync_state(source_id, last_success_at=now)@@ -819,6 +1063,23 @@ class UltraWikiService:def cancel_job(self, job_id: str) -> bool:return _cancel_job(job_id)+ # -- recovery ------------------------------------------------------------++ async def requeue_failed(self, source_id: str | None = None) -> int:+ """Return dead-lettered items to the pipeline; count moved.++ The counterpart to the stage gates: whatever already gave up while a+ slot was dead (no chat credential, unreachable embedding endpoint) is+ stranded in ``failed`` for good, because retries are exhausted. This is+ how a user recovers that backlog after fixing the cause — no+ re-import, no data loss, no hand-edited database.+ """+ await self.ensure_started()+ store = self._require_store()+ if source_id is not None and await store.get_source(source_id) is None:+ raise ValueError(f"unknown source {source_id!r}")+ return int(await store.requeue_failed(source_id))+# -- search --------------------------------------------------------------async def search(self, query: str, **kwargs: Any) -> Any:diff --git a/jarvis/ultrawiki/store.py b/jarvis/ultrawiki/store.pyindex 65f11275e7..758061445c 100644--- a/jarvis/ultrawiki/store.py+++ b/jarvis/ultrawiki/store.py@@ -80,11 +80,37 @@ _IN_CHUNK = 400_FTS_QUOTE_STRIP_RE = re.compile(r'"')+#: Seconds a Postgres connect attempt may take before it gives up. The store+#: opens on the app's startup path, so an unreachable host must fail fast and+#: degrade to SQLite instead of stalling the boot.+PG_CONNECT_TIMEOUT_S = 5++#: ``scheme://user:password@host`` userinfo inside any connection string a+#: driver may echo back in an error message.+_DSN_USERINFO_RE = re.compile(+ r"(?P<scheme>[A-Za-z][A-Za-z0-9+.\-]*://)(?P<userinfo>[^/@\s]+)@"+)+class UltraStoreError(RuntimeError):"""Raised for store-contract violations (e.g. embedding-dim mismatch)."""+def sanitize_conn_error(exc: BaseException, conn_str: str = "") -> str:+ """``"TypeName: message"`` with every credential scrubbed out.++ A psycopg failure routinely echoes the whole connection string — including+ the password — and that text lands in ``/api/ultrawiki/status``+ degradations and the ``/test/storage`` result. Both the stored connection+ string itself and any ``scheme://user:password@`` userinfo are replaced by+ ``***`` before the message is allowed to leave the store.+ """+ text = f"{type(exc).__name__}: {exc}"+ if conn_str:+ text = text.replace(conn_str, "***")+ return _DSN_USERINFO_RE.sub(lambda m: f"{m.group('scheme')}***@", text)++@dataclass(frozen=True, slots=True)class UpsertCounts:"""Result of one :meth:`UltraStore.upsert_items` batch."""@@ -217,6 +243,22 @@ def _snippet_of(text: str) -> str:return collapsed[:_SNIPPET_CHARS]+def _neighbors_per_side(limit: int) -> int:+ """How many neighbours to pull on EACH side for a total budget of+ ``limit`` (the article's "two neighboring sections" = one per side)."""+ return max(1, (int(limit) + 1) // 2)+++def _neighbor_snippets(before: Iterable[Any], after: Iterable[Any]) -> list[str]:+ """Interleave the preceding and following rows, nearest neighbour first."""+ out: list[str] = []+ for row in before:+ out.append(_snippet_of(f"{row['title']} {row['body_raw']}"))+ for row in after:+ out.append(_snippet_of(f"{row['title']} {row['body_raw']}"))+ return out++def _chunks(values: Sequence[Any], size: int = _IN_CHUNK) -> Iterable[Sequence[Any]]:for start in range(0, len(values), size):yield values[start : start + size]@@ -702,12 +744,29 @@ class UltraStore:*,fts_title: str | None = None,fts_body: str | None = None,- ) -> None:+ expected_state: ItemState | str | None = None,+ expected_content_hash: str | None = None,+ ) -> bool:"""Commit one state transition; retry bookkeeping resets.For the keyword stage the FTS delete+insert happens in the SAMEtransaction as the state transition (pass ``fts_title``/``fts_body``)so the index can never drift from the state column.++ **Compare-and-set (the lost-claim guard).** A sync running concurrently+ with the pipeline can reset an item to ``captured`` and purge its+ derived rows the moment its content changes (:meth:`upsert_items`) —+ between a worker's claim and its commit. An unconditional UPDATE would+ then stamp e.g. ``embedded`` onto content that is no longer keyword+ indexed and whose vector belongs to the OLD text. Passing+ ``expected_state`` (the predecessor state seen at claim time) and+ ``expected_content_hash`` narrows the UPDATE to exactly that row+ version: when it no longer matches, nothing is written (no FTS row+ either) and ``False`` says "claim lost, skip this item this pass".+ The pipeline always passes both; callers that omit them get the+ unconditional legacy behaviour.++ Returns ``True`` when the transition was committed."""state = _coerce_state(new_state)if state not in STATE_ORDER or state is ItemState.CAPTURED:@@ -716,13 +775,24 @@ class UltraStore:"stages after 'captured' are worker transitions")now = _iso_utc()+ sql = (+ "UPDATE uw_items SET state = ?, attempt_count = 0,"+ " next_retry_at = NULL, last_error = NULL, updated_at = ?"+ " WHERE id = ?"+ )+ params: list[Any] = [state.value, now, item_id]+ if expected_state is not None:+ sql += " AND state = ?"+ params.append(_coerce_state(expected_state).value)+ if expected_content_hash is not None:+ sql += " AND content_hash = ?"+ params.append(expected_content_hash)async with self._txn() as conn:- await conn.execute(- "UPDATE uw_items SET state = ?, attempt_count = 0,"- " next_retry_at = NULL, last_error = NULL, updated_at = ?"- " WHERE id = ?",- (state.value, now, item_id),- )+ cur = await conn.execute(sql, params)+ claimed = cur.rowcount != 0+ await cur.close()+ if not claimed:+ return Falseif fts_body is not None or fts_title is not None:await conn.execute("DELETE FROM uw_fts WHERE item_id = ?", (item_id,)@@ -731,6 +801,7 @@ class UltraStore:"INSERT INTO uw_fts (item_id, title, body) VALUES (?, ?, ?)",(item_id, fts_title or "", fts_body or ""),)+ return Trueasync def mark_retry(self,@@ -787,6 +858,54 @@ class UltraStore:(ItemState.FAILED.value, error, now, item_id),)+ async def requeue_failed(self, source_id: str | None = None) -> int:+ """Give every dead-lettered item another run; returns the count moved.++ Dead-lettering is permanent by design (5 attempts, then ``failed``), so+ a transient outage — a chat provider without credit while the distill+ stage ran, a dead embedding endpoint — silently strands items forever+ once the user fixes the cause. This is the recovery path.++ The state each item returns to is DERIVED from the rows it actually+ owns, never guessed: a stored embedding means the embed stage really+ finished (``embedded``), an FTS row means the keyword stage finished+ (``keyword_indexed``), and anything else restarts at ``captured``.+ Retry bookkeeping (attempt count, backoff, last error) is cleared so+ the pipeline picks the items up on its next pass.+ """+ now = _iso_utc()+ moved = 0+ async with self._txn() as conn:+ sql = (+ "SELECT i.id AS id,"+ " EXISTS (SELECT 1 FROM uw_documents d"+ " JOIN uw_embeddings e ON e.document_id = d.id"+ " WHERE d.item_id = i.id) AS has_vector,"+ " EXISTS (SELECT 1 FROM uw_fts f WHERE f.item_id = i.id) AS has_fts"+ " FROM uw_items i"+ " WHERE i.state = ? AND i.deleted_at IS NULL"+ )+ params: list[Any] = [ItemState.FAILED.value]+ if source_id is not None:+ sql += " AND i.source_id = ?"+ params.append(source_id)+ rows = await self._fetchall(conn, sql, params)+ for row in rows:+ if int(row["has_vector"]):+ target = ItemState.EMBEDDED+ elif int(row["has_fts"]):+ target = ItemState.KEYWORD_INDEXED+ else:+ target = ItemState.CAPTURED+ await conn.execute(+ "UPDATE uw_items SET state = ?, attempt_count = 0,"+ " next_retry_at = NULL, last_error = NULL, updated_at = ?"+ " WHERE id = ?",+ (target.value, now, row["id"]),+ )+ moved += 1+ return moved+async def counts(self) -> PipelineCounts:"""Per-stage backlog counts over live (non-tombstoned) items."""conn = await self._ensure_open()@@ -1177,6 +1296,93 @@ class UltraStore:breakreturn results, ""+ # -- ranking signals -----------------------------------------------------++ async def live_item_count(self) -> int:+ """Live (non-deleted) item count — the ``N`` of the IDF formula."""+ conn = await self._ensure_open()+ row = await self._fetchone(+ conn, "SELECT count(*) AS n FROM uw_items WHERE deleted_at IS NULL", ()+ )+ return int(row["n"]) if row else 0++ async def term_document_frequency(self, terms: Sequence[str]) -> dict[str, int]:+ """In how many live items does each term occur? (the ``df`` of IDF)++ One indexed FTS count per distinct term — queries carry a handful of+ terms, so this stays cheap. Unindexable tokens report 0, which the+ caller reads as "maximally rare" only after the count is compared+ against the corpus size.+ """+ conn = await self._ensure_open()+ frequencies: dict[str, int] = {}+ for term in dict.fromkeys(terms):+ match_expr = _fts_match_expr(term)+ if not match_expr:+ frequencies[term] = 0+ continue+ row = await self._fetchone(+ conn,+ "SELECT count(*) AS n FROM uw_fts"+ " JOIN uw_items i ON i.id = uw_fts.item_id"+ " WHERE uw_fts MATCH ? AND i.deleted_at IS NULL",+ (match_expr,),+ )+ frequencies[term] = int(row["n"]) if row else 0+ return frequencies++ async def neighbors_for(self, item_id: int, *, limit: int = 2) -> list[str]:+ """Surrounding evidence for one winning item (context expansion).++ Conversation-shaped sources (a ``thread_key``) return the items+ immediately before and after inside that thread; file-shaped sources+ (no thread) fall back to the item's other stored document rendition,+ so a hit that matched a short fragment still shows its fuller text.+ Returns snippets, best-effort and possibly empty.+ """+ if limit <= 0:+ return []+ conn = await self._ensure_open()+ anchor = await self._fetchone(+ conn,+ "SELECT thread_key, timestamp_utc FROM uw_items WHERE id = ?",+ (int(item_id),),+ )+ if anchor is None:+ return []+ thread_key = str(anchor["thread_key"] or "")+ stamp = str(anchor["timestamp_utc"] or "")+ out: list[str] = []+ if thread_key:+ # ISO-8601 UTC stamps sort lexicographically — no date function,+ # identical behaviour on SQLite and Postgres.+ before = await self._fetchall(+ conn,+ "SELECT title, body_raw FROM uw_items"+ " WHERE thread_key = ? AND id <> ? AND deleted_at IS NULL"+ " AND timestamp_utc <= ?"+ " ORDER BY timestamp_utc DESC LIMIT ?",+ (thread_key, int(item_id), stamp, _neighbors_per_side(limit)),+ )+ after = await self._fetchall(+ conn,+ "SELECT title, body_raw FROM uw_items"+ " WHERE thread_key = ? AND id <> ? AND deleted_at IS NULL"+ " AND timestamp_utc > ?"+ " ORDER BY timestamp_utc ASC LIMIT ?",+ (thread_key, int(item_id), stamp, _neighbors_per_side(limit)),+ )+ out = _neighbor_snippets(reversed(list(before)), after)+ if not out:+ docs = await self._fetchall(+ conn,+ "SELECT text_norm FROM uw_documents WHERE item_id = ?"+ " ORDER BY length(text_norm) DESC LIMIT ?",+ (int(item_id), int(limit)),+ )+ out = [_snippet_of(row["text_norm"] or "") for row in docs]+ return [snippet for snippet in out if snippet][:limit]+# -- sync state ----------------------------------------------------------async def get_sync_state(self, source_id: str) -> dict[str, Any] | None:@@ -1430,9 +1636,13 @@ class PostgresStore:except ImportError as exc:return False, str(exc)try:- conn = await psycopg.AsyncConnection.connect(conn_str, connect_timeout=5)+ conn = await psycopg.AsyncConnection.connect(+ conn_str, connect_timeout=PG_CONNECT_TIMEOUT_S+ )except Exception as exc:- return False, f"Connection failed: {exc}"+ # psycopg echoes the DSN — password included — in several failure+ # modes, and this message is shown in the UI.+ return False, f"Connection failed: {sanitize_conn_error(exc, conn_str)}"try:cur = await conn.execute("SELECT version()")version_row = await cur.fetchone()@@ -1449,7 +1659,10 @@ class PostgresStore:server = version_row[0] if version_row else "PostgreSQL"return True, f"Connected: {server}; {vec_note}"except Exception as exc:- return False, f"Connected, but the server probe failed: {exc}"+ return False, (+ "Connected, but the server probe failed: "+ f"{sanitize_conn_error(exc, conn_str)}"+ )finally:await conn.close()@@ -1458,8 +1671,14 @@ class PostgresStore:if self._conn is not None:returnpsycopg = _import_psycopg()+ # A bounded connect: this runs on the app's startup path, so an+ # unreachable host must fail fast into the SQLite fallback rather+ # than hang the boot (psycopg would otherwise wait on the OS).conn = await psycopg.AsyncConnection.connect(- self._conn_str, autocommit=True, row_factory=psycopg.rows.dict_row+ self._conn_str,+ autocommit=True,+ row_factory=psycopg.rows.dict_row,+ connect_timeout=PG_CONNECT_TIMEOUT_S,)async with conn.transaction():for statement in self.ddl_statements():@@ -1815,22 +2034,35 @@ class PostgresStore:*,fts_title: str | None = None, # noqa: ARG002 — tsvector is generatedfts_body: str | None = None, # noqa: ARG002 — tsvector is generated- ) -> None:- """Same contract as the SQLite twin; the ``fts_*`` arguments are- accepted and ignored because the keyword leg is a generated column."""+ expected_state: ItemState | str | None = None,+ expected_content_hash: str | None = None,+ ) -> bool:+ """Same contract as the SQLite twin — including the compare-and-set+ lost-claim guard; the ``fts_*`` arguments are accepted and ignored+ because the keyword leg is a generated column."""state = _coerce_state(new_state)if state not in STATE_ORDER or state is ItemState.CAPTURED:raise ValueError(f"mark_stage_done cannot set {state.value!r} — only forward ""stages after 'captured' are worker transitions")- conn = await self._ensure_open()- await conn.execute(+ sql = ("UPDATE uw_items SET state = %s, attempt_count = 0,"" next_retry_at = NULL, last_error = NULL, updated_at = %s"- " WHERE id = %s",- (state.value, _iso_utc(), item_id),+ " WHERE id = %s")+ params: list[Any] = [state.value, _iso_utc(), item_id]+ if expected_state is not None:+ sql += " AND state = %s"+ params.append(_coerce_state(expected_state).value)+ if expected_content_hash is not None:+ sql += " AND content_hash = %s"+ params.append(expected_content_hash)+ conn = await self._ensure_open()+ cur = await conn.execute(sql, params)+ # A driver that cannot report a row count (-1) is treated as a hit —+ # the guard may never invent a lost claim out of missing information.+ return int(getattr(cur, "rowcount", -1)) != 0async def mark_retry(self,@@ -1885,6 +2117,47 @@ class PostgresStore:(ItemState.FAILED.value, error, _iso_utc(), item_id),)+ async def requeue_failed(self, source_id: str | None = None) -> int:+ """Postgres twin of the SQLite requeue.++ One deliberate difference: the keyword leg here is a GENERATED+ ``tsvector`` column, so there is no separate index row to look for and+ no ``keyword_indexed`` evidence to find. An item without a stored+ embedding therefore restarts at ``captured`` — re-running the keyword+ transition costs a single cheap UPDATE and can never claim an item is+ searchable when it is not.+ """+ now = _iso_utc()+ moved = 0+ async with self._txn() as conn:+ sql = (+ "SELECT i.id AS id,"+ " EXISTS (SELECT 1 FROM uw_documents d"+ " JOIN uw_embeddings e ON e.document_id = d.id"+ " WHERE d.item_id = i.id) AS has_vector"+ " FROM uw_items i"+ " WHERE i.state = %s AND i.deleted_at IS NULL"+ )+ params: list[Any] = [ItemState.FAILED.value]+ if source_id is not None:+ sql += " AND i.source_id = %s"+ params.append(source_id)+ rows = await self._fetchall(conn, sql, params)+ for row in rows:+ target = (+ ItemState.EMBEDDED+ if bool(row["has_vector"])+ else ItemState.CAPTURED+ )+ await conn.execute(+ "UPDATE uw_items SET state = %s, attempt_count = 0,"+ " next_retry_at = NULL, last_error = NULL, updated_at = %s"+ " WHERE id = %s",+ (target.value, now, row["id"]),+ )+ moved += 1+ return moved+async def counts(self) -> PipelineCounts:conn = await self._ensure_open()rows = await self._fetchall(@@ -2205,6 +2478,78 @@ class PostgresStore:breakreturn results, ""+ # -- ranking signals -----------------------------------------------------++ async def live_item_count(self) -> int:+ """Live (non-deleted) item count — the ``N`` of the IDF formula."""+ conn = await self._ensure_open()+ row = await self._fetchone(+ conn, "SELECT count(*) AS n FROM uw_items WHERE deleted_at IS NULL", ()+ )+ return int(row["n"]) if row else 0++ async def term_document_frequency(self, terms: Sequence[str]) -> dict[str, int]:+ """In how many live items does each term occur? (the ``df`` of IDF)"""+ conn = await self._ensure_open()+ frequencies: dict[str, int] = {}+ for term in dict.fromkeys(terms):+ cleaned = " ".join(str(term).split())+ if not cleaned:+ frequencies[term] = 0+ continue+ row = await self._fetchone(+ conn,+ "SELECT count(*) AS n FROM uw_items"+ " WHERE search_tsv @@ websearch_to_tsquery('simple', %s)"+ " AND deleted_at IS NULL",+ (cleaned,),+ )+ frequencies[term] = int(row["n"]) if row else 0+ return frequencies++ async def neighbors_for(self, item_id: int, *, limit: int = 2) -> list[str]:+ """Surrounding evidence for one winning item (context expansion)."""+ if limit <= 0:+ return []+ conn = await self._ensure_open()+ anchor = await self._fetchone(+ conn,+ "SELECT thread_key, timestamp_utc FROM uw_items WHERE id = %s",+ (int(item_id),),+ )+ if anchor is None:+ return []+ thread_key = str(anchor["thread_key"] or "")+ stamp = str(anchor["timestamp_utc"] or "")+ out: list[str] = []+ if thread_key:+ before = await self._fetchall(+ conn,+ "SELECT title, body_raw FROM uw_items"+ " WHERE thread_key = %s AND id <> %s AND deleted_at IS NULL"+ " AND timestamp_utc <= %s"+ " ORDER BY timestamp_utc DESC LIMIT %s",+ (thread_key, int(item_id), stamp, _neighbors_per_side(limit)),+ )+ after = await self._fetchall(+ conn,+ "SELECT title, body_raw FROM uw_items"+ " WHERE thread_key = %s AND id <> %s AND deleted_at IS NULL"+ " AND timestamp_utc > %s"+ " ORDER BY timestamp_utc ASC LIMIT %s",+ (thread_key, int(item_id), stamp, _neighbors_per_side(limit)),+ )+ out = _neighbor_snippets(reversed(list(before)), after)+ if not out:+ docs = await self._fetchall(+ conn,+ "SELECT text_norm FROM uw_documents WHERE item_id = %s"+ " ORDER BY length(text_norm) DESC LIMIT %s",+ (int(item_id), int(limit)),+ )+ out = [_snippet_of(row["text_norm"] or "") for row in docs]+ return [snippet for snippet in out if snippet][:limit]+# -- sync state / areas / cache / meta ----------------------------------async def get_sync_state(self, source_id: str) -> dict[str, Any] | None:@@ -2340,11 +2685,13 @@ __all__ = ["MAX_ATTEMPTS","META_EMBED_DIM","META_EMBED_MODEL",+ "PG_CONNECT_TIMEOUT_S","PostgresStore","UltraStore","UltraStoreError","UpsertCounts","pack_vector","resolve_ultrawiki_db_path",+ "sanitize_conn_error","unpack_vector",]diff --git a/jarvis/ultrawiki/types.py b/jarvis/ultrawiki/types.pyindex f8eca14d4b..6c0bb54abc 100644--- a/jarvis/ultrawiki/types.py+++ b/jarvis/ultrawiki/types.py@@ -191,7 +191,16 @@ class EmbeddingBackend(Protocol):@dataclass(frozen=True, slots=True)class SearchResult:- """One fused hybrid-search hit with its citation."""+ """One fused hybrid-search hit with its citation.++ ``score`` is the ORDINAL fused rank score (RRF): it orders candidates+ against each other and can never say "nothing here is relevant".+ ``rerank_score`` is the ABSOLUTE 0-10 relevance grade from the rerank+ stage — the number an unsolicited surface gates on — and stays ``None``+ whenever that optional stage was skipped or failed. ``context`` carries+ the neighbouring evidence pulled back in after ranking (design doc 03,+ "context expansion"); empty when expansion was skipped or unavailable.+ """item_id: intsource_id: str@@ -201,6 +210,8 @@ class SearchResult:timestamp_utc: strscore: floatmatched_by: tuple[str, ...] = () # e.g. ("keyword", "vector")+ rerank_score: float | None = None # absolute 0-10 grade, None = not reranked+ context: tuple[str, ...] = () # neighbouring sections/messages@dataclass(frozen=True, slots=True)diff --git a/tests/unit/missions/test_api_agent_worker_providers.py b/tests/unit/missions/test_api_agent_worker_providers.pyindex 78a9f25859..5f1139126c 100644--- a/tests/unit/missions/test_api_agent_worker_providers.py+++ b/tests/unit/missions/test_api_agent_worker_providers.py@@ -25,13 +25,5 @@ def test_gemini_has_in_process_worker():def test_every_api_agent_provider_has_a_default_model():- from jarvis.brain.app_control import LOCAL_PROVIDERS-for provider in _BRAIN_BY_PROVIDER:- if provider in LOCAL_PROVIDERS:- # Local servers have no knowable catalog ahead of time — no- # documented default; the plugin discovers the first installed- # model itself (_resolve_worker_model falls to "" → discovery).- assert _DEFAULT_MODEL.get(provider) is None- continueassert _DEFAULT_MODEL.get(provider), f"{provider} has no documented default model"diff --git a/tests/unit/ultrawiki/test_connectors.py b/tests/unit/ultrawiki/test_connectors.pyindex b60273c8e4..932f9cbc8d 100644--- a/tests/unit/ultrawiki/test_connectors.py+++ b/tests/unit/ultrawiki/test_connectors.py@@ -21,6 +21,7 @@ from jarvis.ultrawiki.connectors import (builtin_connectors,discover_connectors,discovery_failures,+ jarvis_conversations,)from jarvis.ultrawiki.connectors import plugin_bridge as plugin_bridge_modulefrom jarvis.ultrawiki.connectors.jarvis_conversations import (@@ -321,6 +322,69 @@ class TestJarvisConversations:assert await _collect(connector.incremental(ctx, None)) == []assert not (tmp_path / "absent.db").exists(), "read-only probe must not create the db"+ async def test_cursor_never_advances_past_the_scanned_high_water_mark(+ self, conversations_db: Path+ ):+ """A row written DURING the incremental run must not be skipped.++ The touched-day scan runs first; re-reading a day afterwards can pick+ up rows inserted since — including rows of OTHER conversations that the+ scan never saw. Reporting one of those rowids would advance the cursor+ past them and lose them forever.+ """+ connector = JarvisConversationsConnector()+ ctx = _ctx({"db_path": str(conversations_db)})+ items = await _collect(connector.backfill(ctx))+ cursor = max(item.metadata["max_rowid"] for item in items)++ conn = sqlite3.connect(conversations_db)+ try:+ # Row A touches t1's day and IS covered by the scan below.+ conn.execute(+ "INSERT INTO messages (trace_id, thread_id, timestamp_ns, role, text)"+ " VALUES (?, ?, ?, ?, ?)",+ ("tr-1", "t1", _ns_at("2026-01-05", 10), "user", "seen by the scan"),+ )+ conn.commit()+ scanned_rowid = conn.execute(+ "SELECT MAX(id) FROM messages"+ ).fetchone()[0]+ finally:+ conn.close()++ # The interleave: a LATER row of a DIFFERENT conversation lands on the+ # same day, after the touched-day scan but before the day is re-read.+ original_rows_for_days = jarvis_conversations._rows_for_days++ def racing_rows_for_days(conn_, pairs):+ racing = sqlite3.connect(conversations_db)+ try:+ racing.execute(+ "INSERT INTO messages (trace_id, thread_id, timestamp_ns, role,"+ " text) VALUES (?, ?, ?, ?, ?)",+ ("tr-9", "t9", _ns_at("2026-01-05", 11), "user", "never scanned"),+ )+ racing.commit()+ finally:+ racing.close()+ jarvis_conversations._rows_for_days = original_rows_for_days+ return original_rows_for_days(conn_, pairs)++ jarvis_conversations._rows_for_days = racing_rows_for_days+ try:+ changed = await _collect(connector.incremental(ctx, str(cursor)))+ finally:+ jarvis_conversations._rows_for_days = original_rows_for_days++ assert [item.external_id for item in changed] == ["t1:2026-01-05"]+ reported = changed[0].metadata["max_rowid"]+ assert reported == scanned_rowid, "cursor must stop at the scanned mark"++ # Because the cursor stopped there, the unscanned conversation is+ # picked up by the NEXT run instead of being lost.+ following = await _collect(connector.incremental(ctx, str(reported)))+ assert "t9:2026-01-05" in {item.external_id for item in following}+# ---------------------------------------------------------------------------# Normal wiki@@ -368,6 +432,30 @@ class TestNormalWiki:changed = await _collect(connector.incremental(ctx, cursor))assert [item.external_id for item in changed] == ["concepts/alpha"]+ async def test_walk_order_matches_the_checkpoint_order(self, tmp_path: Path):+ """Resume must not skip a page whose id sorts differently than its path.++ The checkpoint stores an ``external_id`` (no ``.md``). Ordering the walk+ by the file PATH puts 'entities/foo-bar.md' before 'entities/foo.md'+ ('-' < '.'), while the ids order 'entities/foo' first — so resuming+ after 'entities/foo-bar' skipped 'entities/foo' entirely.+ """+ (tmp_path / "entities").mkdir()+ for name in ("foo.md", "foo-bar.md", "foo-zeta.md"):+ (tmp_path / "entities" / name).write_text(f"# {name}\n", encoding="utf-8")+ connector = NormalWikiConnector()+ ctx = _ctx({"vault_root": str(tmp_path)})++ walked = [item.external_id for item in await _collect(connector.backfill(ctx))]+ assert walked == sorted(walked), "the walk must follow external_id order"+ assert walked == ["entities/foo", "entities/foo-bar", "entities/foo-zeta"]++ resumed = await _collect(connector.backfill(ctx, checkpoint="entities/foo"))+ assert [item.external_id for item in resumed] == [+ "entities/foo-bar",+ "entities/foo-zeta",+ ]+# ---------------------------------------------------------------------------# Plugin bridgediff --git a/tests/unit/ultrawiki/test_pipeline.py b/tests/unit/ultrawiki/test_pipeline.pyindex 4f358aad43..54a3e4de9d 100644--- a/tests/unit/ultrawiki/test_pipeline.py+++ b/tests/unit/ultrawiki/test_pipeline.py@@ -19,12 +19,17 @@ from typing import Anyimport pytest-from jarvis.ultrawiki.pipeline import PipelineWorker+from jarvis.ultrawiki.pipeline import EMBED_BATCH, MAX_EMBED_CHARS, PipelineWorkerfrom jarvis.ultrawiki.store import UltraStorefrom jarvis.ultrawiki.types import ConsentState, ItemState, RawItemVECTOR = [0.1, 0.2, 0.3]+#: The distillation gate, stated explicitly in every test: these workers use an+#: INJECTED distiller, so the production credential-chain probe must never run+#: — a test whose outcome depends on the host's keys is the AP-23 trap.+DISTILL_READY = lambda: (True, "") # noqa: E731 — a one-line test seam+def make_cfg() -> SimpleNamespace:return SimpleNamespace(@@ -44,12 +49,17 @@ def make_cfg() -> SimpleNamespace:class FakeEmbeddingBackend:- """Fixed-vector backend implementing the EmbeddingBackend protocol."""+ """Fixed-vector backend implementing the EmbeddingBackend protocol.++ ``poison`` marks a substring that makes ``embed`` raise whenever a batch+ contains it — the "one bad text in a batch of 32" case.+ """name = "fake"- def __init__(self, *, usable: bool = True) -> None:+ def __init__(self, *, usable: bool = True, poison: str = "") -> None:self.usable = usable+ self.poison = poisonself.embed_calls: list[list[str]] = []def ready(self) -> tuple[bool, str]:@@ -57,6 +67,8 @@ class FakeEmbeddingBackend:async def embed(self, texts: list[str], *, model: str) -> list[list[float]]:self.embed_calls.append(list(texts))+ if self.poison and any(self.poison in text for text in texts):+ raise RuntimeError("provider rejected the request (400)")return [list(VECTOR) for _ in texts]@@ -130,6 +142,7 @@ async def test_full_ladder_captured_to_distilled(store, tmp_path):make_cfg(),embedding_backend_factory=lambda: backend,distill_fn=distill_ok,+ distill_ready_fn=DISTILL_READY,)attempted = await worker.run_once()@@ -173,6 +186,7 @@ async def test_unconfigured_slot_stops_at_keyword_indexed(store):make_cfg(),embedding_backend_factory=lambda: None, # slot unconfigureddistill_fn=distill_never,+ distill_ready_fn=DISTILL_READY,)await worker.run_once()@@ -193,6 +207,7 @@ async def test_not_ready_backend_claims_no_embed_work(store):make_cfg(),embedding_backend_factory=lambda: backend,distill_fn=distill_never,+ distill_ready_fn=DISTILL_READY,)await worker.run_once()@@ -226,6 +241,7 @@ async def test_poison_distill_dead_letters_while_others_pass(store):embedding_backend_factory=FakeEmbeddingBackend,distill_fn=flaky_distill,now_fn=lambda: clock["now"],+ distill_ready_fn=DISTILL_READY,)# Backoff ladder tops out at 3840 s before the 5th attempt dead-letters;@@ -268,6 +284,7 @@ async def test_distill_cache_hit_skips_the_provider_call(store):make_cfg(),embedding_backend_factory=FakeEmbeddingBackend,distill_fn=counting_distill,+ distill_ready_fn=DISTILL_READY,)await worker.run_once()@@ -289,6 +306,7 @@ async def test_cancel_event_stops_the_loop_cleanly(store):make_cfg(),embedding_backend_factory=lambda: None,distill_fn=distill_never,+ distill_ready_fn=DISTILL_READY,)cancel = asyncio.Event()task = asyncio.create_task(worker.run(cancel), name="test-uw-pipeline")@@ -300,12 +318,176 @@ async def test_cancel_event_stops_the_loop_cleanly(store):assert task.done() and not task.cancelled()+# ---------------------------------------------------------------------------+# One bad text must not dead-letter its whole batch+# ---------------------------------------------------------------------------+++async def test_batch_embed_failure_retries_members_individually(store):+ """31 healthy items advance; only the poisoned one accrues an attempt."""+ count = EMBED_BATCH+ items = [make_item(i) for i in range(count)]+ items[7] = make_item(7, body="this body makes the provider choke")+ await store.upsert_items("src1", items)+ backend = FakeEmbeddingBackend(poison="choke")+ worker = PipelineWorker(+ store,+ make_cfg(),+ embedding_backend_factory=lambda: backend,+ distill_fn=distill_never,+ distill_ready_fn=DISTILL_READY,+ )++ await worker._keyword_pass() # noqa: SLF001 — drive one stage deliberately+ await worker._embed_pass() # noqa: SLF001++ assert worker.processed_counts()["embed"] == count - 1+ counts = await store.counts()+ assert counts.embedded == count - 1+ assert counts.keyword_indexed == 1 # the poisoned one kept its good state++ poisoned = await store.get_item_by_external_id("src1", "ext-0007")+ assert poisoned["attempt_count"] == 1+ assert "embed" in (poisoned["last_error"] or "")+ # Every healthy neighbour is untouched by the poisoned member's failure.+ healthy = await store.get_item_by_external_id("src1", "ext-0006")+ assert healthy["state"] == ItemState.EMBEDDED.value+ assert healthy["attempt_count"] == 0+ assert healthy["last_error"] is None+ # One batch call, then one call per member (the individual retry pass).+ assert len(backend.embed_calls) == 1 + count+++async def test_embed_input_is_capped_to_the_provider_budget(store):+ await store.upsert_items(+ "src1", [make_item(1, body="x" * (MAX_EMBED_CHARS * 3))]+ )+ backend = FakeEmbeddingBackend()+ worker = PipelineWorker(+ store,+ make_cfg(),+ embedding_backend_factory=lambda: backend,+ distill_fn=distill_never,+ distill_ready_fn=DISTILL_READY,+ )++ await worker._keyword_pass() # noqa: SLF001+ await worker._embed_pass() # noqa: SLF001++ assert backend.embed_calls+ assert len(backend.embed_calls[0][0]) == MAX_EMBED_CHARS+ assert (await store.counts()).embedded == 1+++# ---------------------------------------------------------------------------+# The distillation gate — a keyless install pauses instead of dead-lettering+# ---------------------------------------------------------------------------+++async def test_unready_distill_slot_claims_no_work_and_never_fails_items(store):+ await store.upsert_items("src1", [make_item(1), make_item(2)])+ worker = PipelineWorker(+ store,+ make_cfg(),+ embedding_backend_factory=FakeEmbeddingBackend,+ distill_fn=distill_never, # asserts it is never called+ distill_ready_fn=lambda: (False, "no credential-ready chat provider"),+ )++ for _ in range(6): # more passes than MAX_ATTEMPTS would need to give up+ await worker.run_once()++ counts = await store.counts()+ assert counts.embedded == 2+ assert counts.distilled == 0+ assert counts.failed == 0 # nothing was dead-lettered+ everything = await store.get_item_by_external_id("src1", "ext-0001")+ assert everything["attempt_count"] == 0+ assert everything["last_error"] is None+++async def test_distill_resumes_once_the_slot_becomes_ready(store):+ await store.upsert_items("src1", [make_item(1)])+ slot = {"ready": False}+ worker = PipelineWorker(+ store,+ make_cfg(),+ embedding_backend_factory=FakeEmbeddingBackend,+ distill_fn=distill_ok,+ distill_ready_fn=lambda: (+ (True, "") if slot["ready"] else (False, "no chat provider yet")+ ),+ )++ await worker.run_once()+ assert (await store.counts()).embedded == 1++ slot["ready"] = True+ worker._distill_ready_cache = None # noqa: SLF001 — skip the 30 s probe TTL+ await worker.run_once()+ assert (await store.counts()).distilled == 1+++# ---------------------------------------------------------------------------+# Lost claims (a sync racing the pipeline) are skipped, never retried+# ---------------------------------------------------------------------------+++async def test_lost_claim_is_skipped_without_charging_an_attempt(store):+ """A content change mid-flight must not look like a stage failure."""+ await store.upsert_items("src1", [make_item(1)])++ class RacingStore:+ """Delegates to the real store but rewrites the item's content the+ moment the keyword stage tries to commit."""++ def __init__(self, inner: UltraStore) -> None:+ self._inner = inner+ self.raced = False++ def __getattr__(self, name: str) -> Any:+ return getattr(self._inner, name)++ async def mark_stage_done(self, item_id: int, new_state: Any, **kwargs: Any):+ if not self.raced and new_state == ItemState.KEYWORD_INDEXED:+ self.raced = True+ await self._inner.upsert_items(+ "src1", [make_item(1, body="rewritten by a racing sync")]+ )+ return await self._inner.mark_stage_done(item_id, new_state, **kwargs)++ racing = RacingStore(store)+ worker = PipelineWorker(+ racing,+ make_cfg(),+ embedding_backend_factory=FakeEmbeddingBackend,+ distill_fn=distill_ok,+ distill_ready_fn=DISTILL_READY,+ )++ await worker._keyword_pass() # noqa: SLF001 — the raced stage++ assert racing.raced is True+ assert worker.processed_counts()["keyword"] == 0 # the claim was dropped+ item = await store.get_item_by_external_id("src1", "ext-0001")+ assert item["state"] == ItemState.CAPTURED.value+ assert item["attempt_count"] == 0 # a lost claim is not a failure+ assert item["last_error"] is None++ # The next pass works on the NEW content and completes the whole ladder.+ await worker.run_once()+ item = await store.get_item_by_external_id("src1", "ext-0001")+ assert item["state"] == ItemState.DISTILLED.value+ assert len(await store.keyword_search("rewritten")) == 1++async def test_hard_cancel_reraises_cancelled_error(store):worker = PipelineWorker(store,make_cfg(),embedding_backend_factory=lambda: None,distill_fn=distill_never,+ distill_ready_fn=DISTILL_READY,)task = asyncio.create_task(worker.run(asyncio.Event()), name="test-uw-pipeline-2")await asyncio.sleep(0.02)diff --git a/tests/unit/ultrawiki/test_search.py b/tests/unit/ultrawiki/test_search.pyindex e50dfd7b02..6dbf2f5758 100644--- a/tests/unit/ultrawiki/test_search.py+++ b/tests/unit/ultrawiki/test_search.py@@ -13,6 +13,7 @@ from __future__ import annotationsimport importlib.utilimport logging+from datetime import UTC, datetime, timedeltafrom types import SimpleNamespaceimport pytest@@ -21,7 +22,12 @@ import jarvis.ultrawiki.embeddings as embeddings_modimport jarvis.ultrawiki.rerank as rerank_modfrom jarvis.ultrawiki.embeddings import EmbeddingErrorfrom jarvis.ultrawiki.rerank import RerankError-from jarvis.ultrawiki.search import hybrid_search, search_status+from jarvis.ultrawiki.search import (+ RRF_K,+ hybrid_search,+ ranking_settings,+ search_status,+)from jarvis.ultrawiki.store import UltraStorefrom jarvis.ultrawiki.types import (ConsentState,@@ -121,11 +127,19 @@ class FakeStore:def make_cfg(**overrides) -> SimpleNamespace:+ # The ranking knobs are spelled out (not left to getattr defaults) so a+ # test states the ranking it exercises and stays honest if a product+ # default moves.values = {"enabled": True,"embedding_provider": "","embedding_model": "","rerank_provider": "",+ "rerank_model": "",+ "rerank_min_score": 4.0,+ "rrf_keyword_weight": 1.0,+ "rrf_vector_weight": 1.0,+ "recency_half_life_days": 180.0,"ollama_endpoint": "http://localhost:11434",}values.update(overrides)@@ -139,12 +153,14 @@ def make_result(timestamp_utc: str = "2026-01-02T10:00:00Z",matched_by: tuple[str, ...] = ("keyword",),score: float = 0.5,+ title: str | None = None,+ snippet: str | None = None,) -> SearchResult:return SearchResult(item_id=item_id,source_id=source_id,- title=f"Item {item_id}",- snippet=f"snippet {item_id}",+ title=f"Item {item_id}" if title is None else title,+ snippet=f"snippet {item_id}" if snippet is None else snippet,permalink=f"app://item/{item_id}",timestamp_utc=timestamp_utc,score=score,@@ -315,7 +331,14 @@ async def test_rrf_consensus_beats_single_list_rank(store, monkeypatch):await embed_item(store, id_c, [1.0, 0.0, 0.0])await embed_item(store, id_a, [0.9, 0.1, 0.0])register_fake_embedding(monkeypatch, FakeEmbedding({"alpha": [1.0, 0.0, 0.0]}))- cfg = make_cfg(embedding_provider="fake", embedding_model=EMBED_MODEL)+ # Pure RRF arithmetic under test: the age decay is a separate stage with+ # its own tests, and leaving it on would make the asserted sums depend on+ # the day the suite runs.+ cfg = make_cfg(+ embedding_provider="fake",+ embedding_model=EMBED_MODEL,+ recency_half_life_days=0,+ )results = await hybrid_search(store, cfg, "alpha")@@ -415,21 +438,25 @@ async def seed_three_ranked_items(store: UltraStore) -> list[int]:async def test_rerank_reorders_when_configured_and_ready(store, monkeypatch):id_0, id_1, id_2 = await seed_three_ranked_items(store)-- baseline = await hybrid_search(store, make_cfg(), "alpha")+ # Decay off: the assertion below compares fused scores across two separate+ # searches, and a live half-life would move them between the two calls.+ baseline = await hybrid_search(store, make_cfg(recency_half_life_days=0), "alpha")assert [hit.item_id for hit in baseline] == [id_0, id_1, id_2]- fake = FakeReranker(pairs=[(2, 0.9), (1, 0.5), (0, 0.1)])+ fake = FakeReranker(pairs=[(2, 9.0), (1, 5.0), (0, 1.0)])monkeypatch.setattr(rerank_mod, "resolve_reranker", lambda cfg: fake)- cfg = make_cfg(rerank_provider="voyage")+ cfg = make_cfg(rerank_provider="voyage", recency_half_life_days=0)results = await hybrid_search(store, cfg, "alpha")assert [hit.item_id for hit in results] == [id_2, id_1, id_0]- # Only the ORDER changes — every hit keeps its fused score.+ # Only the ORDER changes — every hit keeps its fused score...assert {hit.item_id: hit.score for hit in results} == {hit.item_id: hit.score for hit in baseline}+ # ...and gains the ABSOLUTE grade the fused score could never express.+ assert [hit.rerank_score for hit in results] == [9.0, 5.0, 1.0]+ assert all(hit.rerank_score is None for hit in baseline)# The reranker saw one call with all three snippets.assert len(fake.calls) == 1assert len(fake.calls[0][1]) == 3@@ -509,3 +536,352 @@ def test_search_status_unknown_embedding_provider():assert status["vector"]["available"] is Falseassert "does-not-exist" in status["vector"]["reason"]+++def test_search_status_reports_the_live_ranking_knobs():+ status = search_status(+ make_cfg(+ rrf_keyword_weight=2.0,+ rrf_vector_weight=0.5,+ recency_half_life_days=30,+ rerank_min_score=6,+ )+ )++ assert status["ranking"] == {+ "keyword_weight": 2.0,+ "vector_weight": 0.5,+ "recency_half_life_days": 30.0,+ "rerank_min_score": 6.0,+ }+++def test_ranking_settings_fall_back_on_junk_values():+ """A hand-edited jarvis.toml must never take the ranking down."""+ knobs = ranking_settings(+ make_cfg(rrf_keyword_weight="nonsense", recency_half_life_days=-5)+ )++ assert knobs["keyword_weight"] == 1.0+ assert knobs["recency_half_life_days"] == 0.0 # negative clamps to "off"+++# ---------------------------------------------------------------------------+# Per-leg weights + age decay+# ---------------------------------------------------------------------------+++async def test_zero_weight_silences_a_leg_without_removing_its_hits(monkeypatch):+ keyword_hit = make_result(1)+ vector_hit = make_result(2, matched_by=("vector",))+ fake_store = FakeStore(keyword_hits=[keyword_hit], vector_hits=[vector_hit])+ register_fake_embedding(monkeypatch, FakeEmbedding())+ cfg = make_cfg(+ embedding_provider="fake",+ embedding_model=EMBED_MODEL,+ rrf_keyword_weight=0.0,+ recency_half_life_days=0,+ )++ results = await hybrid_search(fake_store, cfg, "alpha")++ # The vector hit outranks the silenced keyword hit, which still appears.+ assert [hit.item_id for hit in results] == [2, 1]+ by_id = {hit.item_id: hit for hit in results}+ assert by_id[1].score == pytest.approx(0.0, abs=1e-5)+ assert by_id[2].score > 0.0+++async def test_age_decay_lets_a_fresh_item_beat_a_stale_one(monkeypatch):+ """Equal leg rank, very different age — the article's age decay."""+ now = datetime.now(UTC)+ stale = make_result(+ 1, timestamp_utc=(now - timedelta(days=720)).isoformat().replace("+00:00", "Z")+ )+ fresh = make_result(+ 2,+ timestamp_utc=(now - timedelta(days=1)).isoformat().replace("+00:00", "Z"),+ matched_by=("vector",),+ )+ fake_store = FakeStore(keyword_hits=[stale], vector_hits=[fresh])+ register_fake_embedding(monkeypatch, FakeEmbedding())++ decayed = await hybrid_search(+ fake_store,+ make_cfg(+ embedding_provider="fake",+ embedding_model=EMBED_MODEL,+ recency_half_life_days=180,+ ),+ "alpha",+ )+ assert [hit.item_id for hit in decayed] == [2, 1]+ # Two years at a 180-day half-life is roughly a sixteenth of the score.+ by_id = {hit.item_id: hit for hit in decayed}+ assert by_id[1].score < by_id[2].score / 10+++async def test_half_life_zero_keeps_the_pure_fusion_order(monkeypatch):+ """The opt-out reproduces the old behaviour exactly: with the decay off,+ an ancient rank-1 hit still ties a fresh rank-1 hit (epsilon aside)."""+ now = datetime.now(UTC)+ stale = make_result(+ 1, timestamp_utc=(now - timedelta(days=720)).isoformat().replace("+00:00", "Z")+ )+ fresh = make_result(+ 2,+ timestamp_utc=(now - timedelta(days=1)).isoformat().replace("+00:00", "Z"),+ matched_by=("vector",),+ )+ fake_store = FakeStore(keyword_hits=[stale], vector_hits=[fresh])+ register_fake_embedding(monkeypatch, FakeEmbedding())++ results = await hybrid_search(+ fake_store,+ make_cfg(+ embedding_provider="fake",+ embedding_model=EMBED_MODEL,+ recency_half_life_days=0,+ ),+ "alpha",+ )++ by_id = {hit.item_id: hit for hit in results}+ assert by_id[1].score == pytest.approx(by_id[2].score, abs=1e-5)+ assert [hit.item_id for hit in results] == [2, 1] # epsilon tiebreak only+++async def test_unparsable_timestamp_is_never_punished_by_the_decay(monkeypatch):+ broken = make_result(1, timestamp_utc="not-a-date")+ fake_store = FakeStore(keyword_hits=[broken])+ cfg = make_cfg(recency_half_life_days=30)++ results = await hybrid_search(fake_store, cfg, "alpha")++ assert results[0].score == pytest.approx(1 / (RRF_K + 1), abs=1e-5)+++# ---------------------------------------------------------------------------+# Term rarity (IDF)+# ---------------------------------------------------------------------------+++class SignalStore(FakeStore):+ """A store that answers the ranking-signal probes."""++ def __init__(self, *args, corpus: int = 100, frequencies=None, neighbors=None, **kwargs):+ super().__init__(*args, **kwargs)+ self._corpus = corpus+ self._frequencies = frequencies or {}+ self._neighbors = neighbors or {}+ self.neighbor_calls: list[int] = []++ async def live_item_count(self) -> int:+ return self._corpus++ async def term_document_frequency(self, terms):+ return {term: self._frequencies.get(term, 0) for term in terms}++ async def neighbors_for(self, item_id: int, *, limit: int = 2) -> list[str]:+ self.neighbor_calls.append(item_id)+ return list(self._neighbors.get(item_id, []))+++async def test_rare_term_hit_outranks_higher_ranked_filler():+ """The article's "separate signal from filler": a short pleasantry that+ ranked first loses to the candidate actually carrying the rare words."""+ filler = make_result(1, snippet="sounds good, thanks!")+ substantive = make_result(+ 2, snippet="the bugatti chiron service interval is every two years"+ )+ store = SignalStore(+ keyword_hits=[filler, substantive], # filler ranks FIRST before signals+ frequencies={"bugatti": 1, "chiron": 1, "the": 90},+ )++ results = await hybrid_search(store, make_cfg(recency_half_life_days=0), "bugatti chiron")++ assert [hit.item_id for hit in results] == [2, 1]+++async def test_filler_is_pushed_down_never_dropped():+ """AP-27 discipline: content-based signals may reorder, never delete —+ the rerank stage is where real filtering belongs."""+ filler = make_result(1, snippet="ok")+ store = SignalStore(keyword_hits=[filler], frequencies={"bugatti": 1})++ results = await hybrid_search(store, make_cfg(recency_half_life_days=0), "bugatti")++ assert [hit.item_id for hit in results] == [1]+ assert results[0].score > 0.0+++async def test_common_query_terms_leave_the_ranking_untouched():+ """Every query term is common => no rare vocabulary => neutral factor."""+ first = make_result(1, snippet="alpha one")+ second = make_result(2, snippet="alpha two")+ store = SignalStore(+ keyword_hits=[first, second], corpus=100, frequencies={"alpha": 80}+ )++ results = await hybrid_search(store, make_cfg(recency_half_life_days=0), "alpha")++ assert [hit.item_id for hit in results] == [1, 2]+ assert results[0].score == pytest.approx(1 / (RRF_K + 1), abs=1e-5)+++async def test_store_without_ranking_signals_degrades_neutrally():+ """Third-party stores and fakes predate these methods — neutral, no crash."""+ plain = FakeStore(keyword_hits=[make_result(1, snippet="ok")])++ results = await hybrid_search(plain, make_cfg(recency_half_life_days=0), "bugatti")++ assert results[0].score == pytest.approx(1 / (RRF_K + 1), abs=1e-5)+++async def test_failing_signal_probe_never_fails_the_search():+ class ExplodingStore(SignalStore):+ async def term_document_frequency(self, terms):+ raise RuntimeError("index corrupted")++ store = ExplodingStore(keyword_hits=[make_result(1)])++ results = await hybrid_search(store, make_cfg(recency_half_life_days=0), "bugatti")++ assert [hit.item_id for hit in results] == [1]+++# ---------------------------------------------------------------------------+# Relevance floor (the "Bugatti case" guard)+# ---------------------------------------------------------------------------+++async def test_explicit_search_keeps_weakly_graded_hits(store, monkeypatch):+ """The Ask view / REST route / CLI: the user asked and sees the evidence."""+ id_0, id_1, id_2 = await seed_three_ranked_items(store)+ fake = FakeReranker(pairs=[(0, 9.0), (1, 2.0), (2, 0.0)])+ monkeypatch.setattr(rerank_mod, "resolve_reranker", lambda cfg: fake)+ cfg = make_cfg(rerank_provider="voyage", rerank_min_score=4.0)++ results = await hybrid_search(store, cfg, "alpha")++ assert [hit.item_id for hit in results] == [id_0, id_1, id_2]+++async def test_unsolicited_surface_drops_hits_below_the_floor(store, monkeypatch):+ """Context injection / volunteered voice answers: below the floor, gone."""+ id_0, _id_1, _id_2 = await seed_three_ranked_items(store)+ fake = FakeReranker(pairs=[(0, 9.0), (1, 2.0), (2, 0.0)])+ monkeypatch.setattr(rerank_mod, "resolve_reranker", lambda cfg: fake)+ cfg = make_cfg(rerank_provider="voyage", rerank_min_score=4.0)++ results = await hybrid_search(store, cfg, "alpha", enforce_floor=True)++ assert [hit.item_id for hit in results] == [id_0]+++async def test_floor_can_return_nothing_at_all(store, monkeypatch):+ """RRF alone can never say "nothing here is relevant" — the grade can."""+ await seed_three_ranked_items(store)+ fake = FakeReranker(pairs=[(0, 1.0), (1, 0.0), (2, 0.0)])+ monkeypatch.setattr(rerank_mod, "resolve_reranker", lambda cfg: fake)+ cfg = make_cfg(rerank_provider="voyage", rerank_min_score=4.0)++ assert await hybrid_search(store, cfg, "alpha", enforce_floor=True) == []+++async def test_floor_zero_disables_the_gate(store, monkeypatch):+ await seed_three_ranked_items(store)+ fake = FakeReranker(pairs=[(0, 1.0), (1, 0.0), (2, 0.0)])+ monkeypatch.setattr(rerank_mod, "resolve_reranker", lambda cfg: fake)+ cfg = make_cfg(rerank_provider="voyage", rerank_min_score=0)++ assert len(await hybrid_search(store, cfg, "alpha", enforce_floor=True)) == 3+++async def test_ungraded_hits_pass_the_floor_visibly_rather_than_silently(+ store, monkeypatch, caplog+):+ """A rerank outage must not turn the floor into a silent pass-all: the+ hits come through UNGRADED (rerank_score None) so the caller's own+ deterministic gate can still refuse them."""+ await seed_three_ranked_items(store)+ fake = FakeReranker(error=RerankError("fake: HTTP 500"))+ monkeypatch.setattr(rerank_mod, "resolve_reranker", lambda cfg: fake)+ cfg = make_cfg(rerank_provider="voyage", rerank_min_score=4.0)++ with caplog.at_level(logging.WARNING, logger="jarvis.ultrawiki.search"):+ results = await hybrid_search(store, cfg, "alpha", enforce_floor=True)++ assert len(results) == 3+ assert all(hit.rerank_score is None for hit in results)+ assert any("rerank failed" in rec.message for rec in caplog.records)+++async def test_voice_path_can_skip_the_rerank_stage(store, monkeypatch):+ """doc 03 latency budget: realtime voice degrades stages, never blocks."""+ id_0, id_1, id_2 = await seed_three_ranked_items(store)+ fake = FakeReranker(pairs=[(2, 9.0), (1, 5.0), (0, 1.0)])+ monkeypatch.setattr(rerank_mod, "resolve_reranker", lambda cfg: fake)+ cfg = make_cfg(rerank_provider="voyage")++ results = await hybrid_search(store, cfg, "alpha", rerank=False)++ assert [hit.item_id for hit in results] == [id_0, id_1, id_2]+ assert fake.calls == [] # no model call on the voice path+++# ---------------------------------------------------------------------------+# Context expansion+# ---------------------------------------------------------------------------+++async def test_context_expansion_rehydrates_the_winners():+ store = SignalStore(+ keyword_hits=[make_result(1), make_result(2)],+ neighbors={1: ["the message before", "the message after"]},+ )++ results = await hybrid_search(store, make_cfg(recency_half_life_days=0), "alpha")++ by_id = {hit.item_id: hit for hit in results}+ assert by_id[1].context == ("the message before", "the message after")+ assert by_id[2].context == ()+ assert sorted(store.neighbor_calls) == [1, 2]+++async def test_context_expansion_only_runs_for_the_returned_top_k():+ store = SignalStore(+ keyword_hits=[make_result(i) for i in range(1, 6)],+ neighbors={i: [f"ctx {i}"] for i in range(1, 6)},+ )++ results = await hybrid_search(+ store, make_cfg(recency_half_life_days=0), "alpha", k=2+ )++ assert len(results) == 2+ assert store.neighbor_calls == [1, 2] # no wasted lookups below the cut+++async def test_context_expansion_failure_leaves_bare_snippets():+ class ExplodingStore(SignalStore):+ async def neighbors_for(self, item_id: int, *, limit: int = 2) -> list[str]:+ raise RuntimeError("neighbour lookup exploded")++ store = ExplodingStore(keyword_hits=[make_result(1)])++ results = await hybrid_search(store, make_cfg(recency_half_life_days=0), "alpha")++ assert results[0].context == ()+++async def test_context_expansion_can_be_switched_off():+ store = SignalStore(keyword_hits=[make_result(1)], neighbors={1: ["ctx"]})++ results = await hybrid_search(+ store, make_cfg(recency_half_life_days=0), "alpha", expand_context=False+ )++ assert results[0].context == ()+ assert store.neighbor_calls == []diff --git a/tests/unit/ultrawiki/test_service.py b/tests/unit/ultrawiki/test_service.pyindex f0b8c30c6f..811be470ea 100644--- a/tests/unit/ultrawiki/test_service.py+++ b/tests/unit/ultrawiki/test_service.py@@ -20,6 +20,7 @@ import pytestimport jarvis.ultrawiki.connectors as connectors_modfrom jarvis.ultrawiki.service import (JOB_TERMINAL_STATUSES,+ SyncAlreadyRunningError,UltraWikiService,clear_jobs,)@@ -91,6 +92,32 @@ class FakeConnector:yield item+class ExportFileConnector:+ """Backfill-only fake (IncrementalMode.NONE) — the export-file shape."""++ id = "export-conn"+ label = "Export File"+ auth = AuthKind.EXPORT_FILE+ capabilities = ConnectorCapabilities(+ backfill=True, incremental=IncrementalMode.NONE, deletes=False+ )++ def __init__(self, items: list[RawItem], calls: list[tuple[str, Any]]) -> None:+ self._items = items+ self.calls = calls++ async def backfill(self, ctx: Any, checkpoint: str | None = None):+ self.calls.append(("backfill", checkpoint))+ for item in self._items:+ if checkpoint and item.external_id <= checkpoint:+ continue+ yield item++ async def incremental(self, ctx: Any, cursor: str | None = None):+ raise AssertionError("a NONE-mode connector is never asked for increments")+ yield # pragma: no cover — makes this an async generator++class BlockingConnector:"""Yields its items, then blocks until the test releases (or cancels) it."""@@ -241,7 +268,10 @@ async def test_approved_sync_ingests_with_checkpoints_and_cursor(service, monkeysync_state = await store.get_sync_state(source_id)assert sync_state is not Noneassert sync_state["backfill_complete_at"]- assert sync_state["backfill_checkpoint"] == "f-0449"+ # The resume checkpoint is CLEARED once the walk completes: kept, it points+ # at the last item of a finished backfill, so the next backfill would+ # resume at the end and yield nothing.+ assert sync_state["backfill_checkpoint"] is Noneassert sync_state["cursor"] == str(1000 + 449) # max mtime_ns conventionrefreshed = await store.get_source(source_id)assert refreshed["last_sync_at"]@@ -329,3 +359,241 @@ async def test_ensure_started_is_idempotent(service):await service.ensure_started()assert service._store is first_storeassert service._pipeline_task is first_task+++# ---------------------------------------------------------------------------+# Full refresh + the checkpoint that used to freeze export-file sources+# ---------------------------------------------------------------------------+++async def test_export_style_source_reingests_on_every_backfill(service, monkeypatch):+ """A connector that cannot run incrementally must not freeze after run 1.++ ``IncrementalMode.NONE`` means every sync is a backfill. While the resume+ checkpoint survived a completed walk, run 2 resumed at the END of run 1 and+ yielded nothing — forever.+ """+ calls: list[tuple[str, Any]] = []+ patch_connectors(+ monkeypatch,+ {"export-conn": lambda: ExportFileConnector(make_items(5), calls)},+ )+ source = await service.add_source("export-conn", "Export File")+ await service.approve_source(source["id"])++ first = await wait_for_job(service, await service.start_sync(source["id"]))+ assert (first["mode"], first["new"]) == ("backfill", 5)++ second = await wait_for_job(service, await service.start_sync(source["id"]))+ assert second["mode"] == "backfill"+ # Nothing NEW (the items are unchanged), but every item was seen again —+ # that is what keeps content edits and deletions detectable.+ assert second["unchanged"] == 5+ assert [checkpoint for _mode, checkpoint in calls] == [None, None]+++async def test_full_refresh_resets_the_cursor_and_reconciles_deletes(+ service, monkeypatch+):+ items = make_items(3)+ calls: list[tuple[str, Any]] = []+ connector = FakeConnector(items, calls)+ patch_connectors(monkeypatch, {"fake-conn": lambda: connector})++ source = await service.add_source("fake-conn", "Fake Source")+ source_id = source["id"]+ await service.approve_source(source_id)+ await wait_for_job(service, await service.start_sync(source_id))+ store = service._require_store()+ assert (await store.counts_for_source(source_id)).total == 3++ # The source loses an item. An INCREMENTAL run cannot see a deletion:+ # a walk only reports what still exists.+ connector._items = items[:2]+ incremental = await wait_for_job(service, await service.start_sync(source_id))+ assert incremental["mode"] == "incremental"+ assert incremental["tombstoned"] == 0+ assert (await store.counts_for_source(source_id)).total == 3++ # The full refresh re-reads everything and reconciles the difference.+ full = await wait_for_job(+ service, await service.start_sync(source_id, full=True)+ )+ assert full["mode"] == "backfill"+ assert full["tombstoned"] == 1+ assert (await store.counts_for_source(source_id)).total == 2+ sync_state = await store.get_sync_state(source_id)+ assert sync_state["backfill_checkpoint"] is None+++# ---------------------------------------------------------------------------+# One sync per source at a time+# ---------------------------------------------------------------------------+++async def test_second_sync_of_one_source_is_refused_with_the_active_job(+ service, monkeypatch+):+ gate = asyncio.Event()+ reached = asyncio.Event()+ patch_connectors(+ monkeypatch,+ {"blocking-conn": lambda: BlockingConnector(make_items(3), gate, reached)},+ )+ source = await service.add_source("blocking-conn", "Blocked Source")+ await service.approve_source(source["id"])+ job_id = await service.start_sync(source["id"])+ await asyncio.wait_for(reached.wait(), timeout=5.0)++ with pytest.raises(SyncAlreadyRunningError) as excinfo:+ await service.start_sync(source["id"])+ assert excinfo.value.job_id == job_id+ assert excinfo.value.source_id == source["id"]++ # Once it finishes, a new sync starts normally.+ service.cancel_job(job_id)+ await wait_for_job(service, job_id)+ assert await service.start_sync(source["id"]) != job_id+++# ---------------------------------------------------------------------------+# Honest pipeline state (the "Pipeline running · Captured 0" report)+# ---------------------------------------------------------------------------+++async def test_pipeline_state_waits_for_sources_before_anything_is_approved(service):+ await service.activate({})+ status = await service.status()+ assert status["pipeline"]["state"] == "waiting_for_sources"+ reason = status["pipeline"]["reason"]+ assert "approve" in reason.lower()+ # The worker loop IS alive — that is exactly why "running" alone lied.+ assert status["pipeline"]["running"] is True+++async def test_pipeline_state_is_idle_once_an_approved_source_is_drained(+ service, monkeypatch+):+ patch_connectors(monkeypatch, {"fake-conn": lambda: FakeConnector([], [])})+ source = await service.add_source("fake-conn", "Empty Source")+ await service.approve_source(source["id"])+ status = await service.status()+ assert status["pipeline"]["state"] == "idle"+ assert "processed" in status["pipeline"]+++async def test_pipeline_state_is_paused_when_the_embedding_slot_blocks(+ service, monkeypatch+):+ patch_connectors(monkeypatch, {"fake-conn": lambda: FakeConnector(make_items(2), [])})+ source = await service.add_source("fake-conn", "Fake Source")+ await service.approve_source(source["id"])+ await wait_for_job(service, await service.start_sync(source["id"]))+ # Drive the keyword stage so the backlog sits at the embedding gate.+ store = service._require_store()+ for item in await store.claim_batch("keyword_indexed", limit=10):+ await store.mark_stage_done(+ item["id"],+ "keyword_indexed",+ fts_title=item["title"],+ fts_body=item["body_raw"],+ )++ status = await service.status()+ assert status["pipeline"]["state"] == "paused"+ assert "embedding" in status["pipeline"]["reason"]+ assert status["slots"]["embedding"]["ready"] is False+++async def test_pipeline_state_is_processing_with_a_claimable_backlog(+ service, monkeypatch+):+ patch_connectors(monkeypatch, {"fake-conn": lambda: FakeConnector(make_items(4), [])})+ source = await service.add_source("fake-conn", "Fake Source")+ await service.approve_source(source["id"])+ await wait_for_job(service, await service.start_sync(source["id"]))++ status = await service.status()+ assert status["pipeline"]["state"] == "processing"+ assert "4" in status["pipeline"]["reason"]+++async def test_status_reports_the_credential_behind_a_ready_slot(service, monkeypatch):+ """Provenance names the credential path, never the key itself."""+ import jarvis.ultrawiki.embeddings as embeddings_mod++ service._cfg.ultrawiki.embedding_provider = "gemini"+ monkeypatch.setattr(+ embeddings_mod,+ "available_backends",+ lambda cfg: [+ {"name": "gemini", "ready": True, "reason": "", "default_model": "m"}+ ],+ )+ monkeypatch.setattr(+ embeddings_mod,+ "credential_source",+ lambda name, cfg: "your saved Gemini API key (gemini_api_key)",+ )+ status = await service.status()+ assert status["slots"]["embedding"]["via"] == (+ "your saved Gemini API key (gemini_api_key)"+ )+ assert "gemini_api_key" in status["slots"]["embedding"]["via"]+++# ---------------------------------------------------------------------------+# Dead-letter recovery+# ---------------------------------------------------------------------------+++async def test_requeue_failed_is_exposed_and_scoped(service, monkeypatch):+ patch_connectors(monkeypatch, {"fake-conn": lambda: FakeConnector(make_items(2), [])})+ source = await service.add_source("fake-conn", "Fake Source")+ await service.approve_source(source["id"])+ await wait_for_job(service, await service.start_sync(source["id"]))+ store = service._require_store()+ for item in await store.claim_batch("keyword_indexed", limit=10):+ await store.mark_failed(item["id"], "the distill provider was dead")+ assert (await store.counts()).failed == 2++ assert await service.requeue_failed(source["id"]) == 2+ assert (await store.counts()).failed == 0+ with pytest.raises(ValueError, match="unknown source"):+ await service.requeue_failed("no-such-source")+++# ---------------------------------------------------------------------------+# A failing Postgres store degrades WITHOUT leaking the connection string+# ---------------------------------------------------------------------------+++async def test_postgres_degradation_never_leaks_the_password(tmp_path, monkeypatch):+ import jarvis.ultrawiki.store as store_mod++ dsn = "postgresql://jarvis:[email protected]:5432/uw"++ class ExplodingStore:+ def __init__(self, conn_str: str) -> None:+ self._conn_str = conn_str++ async def open(self) -> None:+ raise OSError(f'connection to "{self._conn_str}" was refused')++ monkeypatch.setattr(store_mod, "PostgresStore", ExplodingStore)+ monkeypatch.setattr("jarvis.core.config.get_secret", lambda name: dsn)+ cfg = make_cfg(tmp_path)+ cfg.ultrawiki.db_backend = "postgres"+ svc = UltraWikiService(cfg)+ try:+ status = await svc.status()+ await svc.ensure_started()+ status = await svc.status()+ degradations = " ".join(status["degradations"])+ assert "hunter2" not in degradations+ assert dsn not in degradations+ assert "***" in degradations+ # The store still opened — on SQLite, honestly reported.+ assert status["backend"]["in_use"] == "sqlite"+ finally:+ await svc.shutdown()diff --git a/tests/unit/ultrawiki/test_store.py b/tests/unit/ultrawiki/test_store.pyindex 05b384f9fc..87d37152bd 100644--- a/tests/unit/ultrawiki/test_store.py+++ b/tests/unit/ultrawiki/test_store.py@@ -11,11 +11,13 @@ from __future__ import annotationsimport importlib.utilimport sys+from types import SimpleNamespaceimport pytestimport jarvis.ultrawiki.store as store_modfrom jarvis.ultrawiki.store import (+ MAX_ATTEMPTS,META_EMBED_DIM,META_EMBED_MODEL,PostgresStore,@@ -516,6 +518,135 @@ async def test_sync_state_partial_updates(store):assert state["backfill_complete_at"] == "2026-01-01T00:00:00Z"+# ---------------------------------------------------------------------------+# Ranking signals — term rarity + context expansion+# ---------------------------------------------------------------------------+++async def seed_indexed(store: UltraStore, items: list[RawItem], source_id: str = "src1") -> None:+ await store.upsert_items(source_id, items)+ for claimed in await store.claim_batch(ItemState.KEYWORD_INDEXED, limit=500):+ await index_keyword(store, claimed)+++async def test_live_item_count_ignores_tombstoned_items(store):+ await add_source(store)+ await seed_indexed(store, [make_item(1), make_item(2), make_item(3)])+ assert await store.live_item_count() == 3++ await store.upsert_items("src1", [make_item(2, deleted=True)])+ assert await store.live_item_count() == 2+++async def test_term_document_frequency_counts_items_not_occurrences(store):+ await add_source(store)+ await seed_indexed(+ store,+ [+ make_item(1, body="bugatti chiron chiron chiron", title=""),+ make_item(2, body="a note about the chiron", title=""),+ make_item(3, body="something else entirely", title=""),+ ],+ )++ frequencies = await store.term_document_frequency(+ ["chiron", "bugatti", "neverappears"]+ )++ # 'chiron' appears three times inside item 1 but that is ONE document.+ assert frequencies == {"chiron": 2, "bugatti": 1, "neverappears": 0}+++async def test_term_document_frequency_tolerates_punctuation_only_tokens(store):+ await add_source(store)+ await seed_indexed(store, [make_item(1)])++ assert await store.term_document_frequency(["!!!", ""]) == {"!!!": 0, "": 0}+++async def test_neighbors_for_returns_the_surrounding_thread_messages(store):+ await add_source(store)+ thread = [+ RawItem(+ external_id=f"msg-{index}",+ body=f"message {index} body",+ permalink=f"app://msg/{index}",+ timestamp_utc=f"2026-03-01T10:0{index}:00Z",+ title="",+ thread_key="thread-a",+ )+ for index in range(4)+ ]+ await seed_indexed(store, thread)+ row = await store.get_item_by_external_id("src1", "msg-2")++ neighbors = await store.neighbors_for(int(row["id"]), limit=2)++ # One before, one after — the article's "two neighboring sections".+ assert len(neighbors) == 2+ assert "message 1 body" in neighbors[0]+ assert "message 3 body" in neighbors[1]+++async def test_neighbors_for_stays_inside_its_own_thread(store):+ await add_source(store)+ await seed_indexed(+ store,+ [+ RawItem(+ external_id="a1",+ body="mine before",+ permalink="app://a1",+ timestamp_utc="2026-03-01T10:00:00Z",+ thread_key="thread-a",+ ),+ RawItem(+ external_id="a2",+ body="mine anchor",+ permalink="app://a2",+ timestamp_utc="2026-03-01T10:01:00Z",+ thread_key="thread-a",+ ),+ RawItem(+ external_id="b1",+ body="someone elses thread",+ permalink="app://b1",+ timestamp_utc="2026-03-01T10:02:00Z",+ thread_key="thread-b",+ ),+ ],+ )+ row = await store.get_item_by_external_id("src1", "a2")++ neighbors = await store.neighbors_for(int(row["id"]), limit=2)++ assert any("mine before" in text for text in neighbors)+ assert not any("someone elses thread" in text for text in neighbors)+++async def test_neighbors_for_falls_back_to_the_items_own_fuller_document(store):+ """File-shaped sources have no thread — the fuller stored rendition is+ the surrounding context instead."""+ await add_source(store)+ await seed_indexed(store, [make_item(7, body="short body", title="Note")])+ row = await store.get_item_by_external_id("src1", "ext-0007")+ item_id = int(row["id"])+ await store.add_document(item_id, DocType.SUMMARY, "the much fuller distilled text")++ neighbors = await store.neighbors_for(item_id, limit=2)++ assert neighbors == ["the much fuller distilled text"]+++async def test_neighbors_for_unknown_item_and_zero_limit_are_empty(store):+ await add_source(store)+ await seed_indexed(store, [make_item(1)])+ row = await store.get_item_by_external_id("src1", "ext-0001")++ assert await store.neighbors_for(999_999, limit=2) == []+ assert await store.neighbors_for(int(row["id"]), limit=0) == []++# ---------------------------------------------------------------------------# Postgres variant — missing driver is an honest, actionable error# ---------------------------------------------------------------------------@@ -530,3 +661,207 @@ async def test_postgres_missing_driver_names_the_extra(monkeypatch):assert ok is Falseassert "ultrawiki-postgres" in messageassert "SQLite backend keeps working" in message+++# ---------------------------------------------------------------------------+# Compare-and-set: a sync racing the pipeline must not corrupt the ladder+# ---------------------------------------------------------------------------+++async def test_lost_claim_writes_nothing_and_the_next_pass_recovers(store):+ """A content change between claim and commit invalidates the claim.++ Without the guard the worker stamped its stage onto content that had just+ been reset to 'captured' with its derived rows purged — an item marked+ keyword-indexed that no FTS row covers, or embedded with the OLD vector.+ """+ await add_source(store)+ await store.upsert_items("src1", [make_item(0)])+ claimed = (await store.claim_batch(ItemState.KEYWORD_INDEXED, limit=1))[0]++ # The interleave: a sync lands NEW content for the same external id.+ await store.upsert_items("src1", [make_item(0, body="fresh body omega")])++ committed = await store.mark_stage_done(+ claimed["id"],+ ItemState.KEYWORD_INDEXED,+ fts_title=claimed["title"],+ fts_body=claimed["body_raw"],+ expected_state=claimed["state"],+ expected_content_hash=claimed["content_hash"],+ )+ assert committed is False+ after = await store.get_item(claimed["id"])+ assert after["state"] == ItemState.CAPTURED.value+ # Neither the stale body nor the fresh one is indexed: no FTS write happened.+ assert await store.keyword_search("number0") == []+ assert await store.keyword_search("omega") == []++ # The next pass claims the CURRENT version and commits normally.+ reclaimed = (await store.claim_batch(ItemState.KEYWORD_INDEXED, limit=1))[0]+ assert reclaimed["content_hash"] != claimed["content_hash"]+ assert (+ await store.mark_stage_done(+ reclaimed["id"],+ ItemState.KEYWORD_INDEXED,+ fts_title=reclaimed["title"],+ fts_body=reclaimed["body_raw"],+ expected_state=reclaimed["state"],+ expected_content_hash=reclaimed["content_hash"],+ )+ is True+ )+ assert len(await store.keyword_search("omega")) == 1+ reindexed = await store.get_item(reclaimed["id"])+ assert reindexed["state"] == ItemState.KEYWORD_INDEXED.value+++async def test_wrong_expected_state_is_a_lost_claim(store):+ await add_source(store)+ await store.upsert_items("src1", [make_item(0)])+ claimed = (await store.claim_batch(ItemState.KEYWORD_INDEXED, limit=1))[0]+ # Another worker already advanced it (state is no longer 'captured').+ await index_keyword(store, claimed)++ committed = await store.mark_stage_done(+ claimed["id"],+ ItemState.EMBEDDED,+ expected_state=ItemState.CAPTURED,+ expected_content_hash=claimed["content_hash"],+ )+ assert committed is False+ assert (await store.get_item(claimed["id"]))["state"] == (+ ItemState.KEYWORD_INDEXED.value+ )+++async def test_mark_stage_done_without_a_guard_stays_unconditional(store):+ await add_source(store)+ await store.upsert_items("src1", [make_item(0)])+ claimed = (await store.claim_batch(ItemState.KEYWORD_INDEXED, limit=1))[0]+ assert await store.mark_stage_done(claimed["id"], ItemState.KEYWORD_INDEXED) is True+++# ---------------------------------------------------------------------------+# requeue_failed — the dead-letter recovery path+# ---------------------------------------------------------------------------+++async def test_requeue_failed_restores_each_item_to_its_last_good_stage(store):+ await add_source(store)+ await add_source(store, "src2")+ await store.upsert_items("src1", [make_item(i) for i in range(3)])+ await store.upsert_items("src2", [make_item(9)])+ claimed = await store.claim_batch(ItemState.KEYWORD_INDEXED, limit=10)+ by_ext = {item["external_id"]: item for item in claimed}++ # ext-0000 stays raw; ext-0001 is keyword indexed; ext-0002 is embedded too.+ await index_keyword(store, by_ext["ext-0001"])+ await index_keyword(store, by_ext["ext-0002"])+ doc_id = await store.add_document(+ by_ext["ext-0002"]["id"], DocType.RAW, "embedded text", content_hash="h"+ )+ await store.store_embedding(doc_id, model="m", dim=3, vector=[0.1, 0.2, 0.3])+ await store.mark_stage_done(by_ext["ext-0002"]["id"], ItemState.EMBEDDED)++ # Every one of them gives up (the classic case: no chat credential, so the+ # distill stage burned all five attempts on the whole corpus).+ for item in [*claimed]:+ for _ in range(MAX_ATTEMPTS):+ await store.mark_retry(item["id"], "provider had no credit")+ assert (await store.counts()).failed == 4++ moved = await store.requeue_failed("src1")+ assert moved == 3++ states = {+ external_id: (await store.get_item_by_external_id("src1", external_id))["state"]+ for external_id in ("ext-0000", "ext-0001", "ext-0002")+ }+ assert states == {+ "ext-0000": ItemState.CAPTURED.value,+ "ext-0001": ItemState.KEYWORD_INDEXED.value,+ "ext-0002": ItemState.EMBEDDED.value,+ }+ # Retry bookkeeping is cleared, so the pipeline claims them immediately.+ restored = await store.get_item_by_external_id("src1", "ext-0001")+ assert restored["attempt_count"] == 0+ assert restored["next_retry_at"] is None+ assert restored["last_error"] is None+ assert len(await store.claim_batch(ItemState.EMBEDDED, limit=10)) == 1++ # The other source was out of scope and is still dead-lettered.+ assert (await store.counts_for_source("src2")).failed == 1+ assert await store.requeue_failed() == 1 # None = every source+ assert (await store.counts()).failed == 0+++async def test_requeue_failed_on_a_healthy_store_is_zero(store):+ await add_source(store)+ await store.upsert_items("src1", [make_item(0)])+ assert await store.requeue_failed() == 0+++# ---------------------------------------------------------------------------+# Connection-string errors must never carry the password+# ---------------------------------------------------------------------------+++def test_sanitize_conn_error_scrubs_the_stored_dsn():+ dsn = "postgresql://jarvis:[email protected]:5432/uw"+ exc = RuntimeError(f'connection failed: dsn="{dsn}" sslmode=require')+ text = store_mod.sanitize_conn_error(exc, dsn)+ assert "sup3r-s3cret" not in text+ assert dsn not in text+ assert text.startswith("RuntimeError: ")+ assert "***" in text+++def test_sanitize_conn_error_scrubs_userinfo_without_a_stored_dsn():+ exc = ValueError("could not translate host in postgres://admin:pw123@h/db")+ text = store_mod.sanitize_conn_error(exc)+ assert "pw123" not in text+ assert "admin" not in text+ assert "postgres://***@h/db" in text+++async def test_postgres_connect_test_never_echoes_the_password(monkeypatch):+ dsn = "postgresql://jarvis:[email protected]:5432/uw"++ class _FakeConnection:+ @staticmethod+ async def connect(conn_str, **_kwargs):+ raise OSError(f'connection to "{conn_str}" refused')++ monkeypatch.setattr(+ store_mod,+ "_import_psycopg",+ lambda: SimpleNamespace(AsyncConnection=_FakeConnection),+ )+ ok, message = await PostgresStore.connect_test(dsn)+ assert ok is False+ assert "hunter2" not in message+ assert "***" in message+++async def test_postgres_open_bounds_the_connect_attempt(monkeypatch):+ seen: dict[str, object] = {}++ class _FakeConnection:+ @staticmethod+ async def connect(conn_str, **kwargs):+ seen.update(kwargs)+ raise OSError("refused")++ monkeypatch.setattr(+ store_mod,+ "_import_psycopg",+ lambda: SimpleNamespace(+ AsyncConnection=_FakeConnection, rows=SimpleNamespace(dict_row=object())+ ),+ )+ with pytest.raises(OSError, match="refused"):+ await PostgresStore("postgresql://localhost/x").open()+ # An unreachable host must fail fast into the SQLite fallback, never hang+ # the startup path waiting on the OS default timeout.+ assert seen["connect_timeout"] == store_mod.PG_CONNECT_TIMEOUT_S