Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(ultrawiki): one checklist that says whether the knowledge base works
Ruben Lütke24eaed266e43
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/HealthPanel.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/HealthPanel.tsxnew file mode 100644index 0000000000..861c25d468--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/HealthPanel.tsx@@ -0,0 +1,272 @@+/**+ * "Is my knowledge base working?" — the checklist tab.+ *+ * Written after a forensic where every surface told the truth and the whole+ * was still unreadable: sources showed "approved" (permission, not import),+ * the pipeline said "everything is processed" (of nothing — nothing had ever+ * been fetched), every capability slot was green, and seven apps showed as+ * connected in the Plugins store that UltraWiki has no reader for. The user+ * concluded, reasonably, that it was broken. Finding the one missing step took+ * a database query.+ *+ * So this is one screen that answers the question in the order a person asks+ * it, with a plain sentence per row and — where something IS fixable — the+ * button that fixes it. The states are deliberately four, not two:+ *+ * - **ok** — nothing to do.+ * - **working** — busy; it will resolve itself, so it must not look like a+ * fault (a first import or a draining backlog is progress).+ * - **attention** — the user can fix this, and the action says how.+ * - **blocked** — genuinely not possible yet. No button, because clicking+ * harder cannot help; the sentence explains what is missing instead.+ *+ * The verdict is computed in the backend (`jarvis/ultrawiki/health.py`) from+ * the same status payload the other tabs read, so this screen can never claim+ * something the rest of the UI contradicts.+ */+import { useState } from "react";+import { useQuery } from "@tanstack/react-query";+import {+ AlertTriangle,+ CheckCircle2,+ Loader2,+ MinusCircle,+ RefreshCw,+} from "lucide-react";++import { Button } from "@/components/ui/button";+import { cn } from "@/lib/utils";+import { useT } from "@/i18n";+import { useEventStore } from "@/store/events";+import {+ fetchUltraWikiHealth,+ syncAllUltraWikiSources,+ type UltraWikiHealth,+ type UltraWikiHealthCheck,+ type UltraWikiCheckState,+} from "@/lib/ultrawikiApi";++const STATE_STYLE: Record<+ UltraWikiCheckState,+ { icon: typeof CheckCircle2; tone: string; ring: string }+> = {+ ok: {+ icon: CheckCircle2,+ tone: "text-emerald-500",+ ring: "border-emerald-500/25 bg-emerald-500/[0.04]",+ },+ working: {+ icon: Loader2,+ tone: "text-primary",+ ring: "border-primary/25 bg-primary/[0.04]",+ },+ attention: {+ icon: AlertTriangle,+ tone: "text-[#ffb84d]",+ ring: "border-[#ffb84d]/30 bg-[#ffb84d]/[0.05]",+ },+ blocked: {+ icon: MinusCircle,+ tone: "text-muted-foreground",+ ring: "border-border bg-muted/20",+ },+};++export function HealthPanel({+ onOpenSources,+ onOpenSettings,+ onEnableMode,+}: {+ onOpenSources: () => void;+ onOpenSettings: () => void;+ onEnableMode?: () => void;+}): JSX.Element {+ const t = useT();+ const pushToast = useEventStore((s) => s.pushToast);+ const [busy, setBusy] = useState(false);++ const healthQuery = useQuery({+ queryKey: ["ultrawiki", "health"],+ queryFn: fetchUltraWikiHealth,+ staleTime: 2_000,+ // Follow a running import closely, idle calmly — the same cadence rule the+ // status poll uses, so the two never disagree for long.+ refetchInterval: (query) =>+ (query.state.data as UltraWikiHealth | undefined)?.checks?.some(+ (c) => c.state === "working",+ )+ ? 4_000+ : 20_000,+ });++ const health = healthQuery.data ?? null;++ async function runSyncAll() {+ setBusy(true);+ try {+ const result = await syncAllUltraWikiSources();+ pushToast(result.started.length ? "success" : "info", result.detail);+ void healthQuery.refetch();+ } catch (e) {+ pushToast("error", (e as Error).message);+ } finally {+ setBusy(false);+ }+ }++ function runAction(check: UltraWikiHealthCheck) {+ const kind = check.action?.kind;+ if (kind === "sync_all") return void runSyncAll();+ if (kind === "open_sources") return onOpenSources();+ if (kind === "open_settings") return onOpenSettings();+ if (kind === "enable_mode" && onEnableMode) return onEnableMode();+ }++ if (healthQuery.isLoading) {+ return (+ <div+ className="p-6 text-sm text-muted-foreground"+ data-testid="ultrawiki-health-loading"+ >+ {t("ultrawiki.health.loading")}+ </div>+ );+ }++ if (!health) {+ return (+ <div className="p-4">+ <div+ role="alert"+ className="rounded-md border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive"+ data-testid="ultrawiki-health-unavailable"+ >+ {t("ultrawiki.health.unavailable")}+ </div>+ </div>+ );+ }++ return (+ <div className="space-y-4 p-4" data-testid="ultrawiki-health-panel">+ <Verdict health={health} />++ <ol className="space-y-2">+ {health.checks.map((check, index) => (+ <CheckRow+ key={check.id}+ index={index + 1}+ check={check}+ busy={busy}+ onAction={() => runAction(check)}+ />+ ))}+ </ol>++ <div className="flex items-center gap-2">+ <Button+ size="sm"+ variant="outline"+ onClick={() => void healthQuery.refetch()}+ disabled={healthQuery.isFetching}+ data-testid="ultrawiki-health-refresh"+ >+ {healthQuery.isFetching ? (+ <Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" aria-hidden />+ ) : (+ <RefreshCw className="mr-1 h-3.5 w-3.5" aria-hidden />+ )}+ {t("ultrawiki.health.recheck")}+ </Button>+ </div>+ </div>+ );+}++/** The one-line answer to "can I use this right now?". */+function Verdict({ health }: { health: UltraWikiHealth }): JSX.Element {+ const t = useT();+ const working = health.checks.some((c) => c.state === "working");+ const tone = health.usable+ ? working+ ? "border-primary/30 bg-primary/[0.06] text-primary"+ : "border-emerald-500/30 bg-emerald-500/[0.06] text-emerald-500"+ : "border-[#ffb84d]/30 bg-[#ffb84d]/[0.07] text-[#ffb84d]";+ const key = health.usable+ ? working+ ? "ultrawiki.health.verdict_usable_working"+ : "ultrawiki.health.verdict_usable"+ : "ultrawiki.health.verdict_not_ready";+ return (+ <div+ className={cn("rounded-xl border px-4 py-3", tone)}+ data-testid="ultrawiki-health-verdict"+ data-overall={health.overall}+ data-usable={health.usable ? "true" : "false"}+ >+ <p className="text-sm font-medium">{t(key)}</p>+ <p className="mt-0.5 text-[11px] leading-relaxed opacity-80">+ {t("ultrawiki.health.verdict_hint")}+ </p>+ </div>+ );+}++function CheckRow({+ index,+ check,+ busy,+ onAction,+}: {+ index: number;+ check: UltraWikiHealthCheck;+ busy: boolean;+ onAction: () => void;+}): JSX.Element {+ const t = useT();+ const style = STATE_STYLE[check.state] ?? STATE_STYLE.blocked;+ const Icon = style.icon;+ return (+ <li+ className={cn("flex items-start gap-3 rounded-xl border p-3", style.ring)}+ data-testid={`ultrawiki-check-${check.id}`}+ data-state={check.state}+ >+ <span className="mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center">+ <Icon+ className={cn(+ "h-4 w-4",+ style.tone,+ check.state === "working" && "animate-spin",+ )}+ aria-hidden+ />+ </span>+ <div className="min-w-0 flex-1">+ <p className="text-sm font-medium text-foreground">+ <span className="mr-1.5 tabular-nums text-muted-foreground">+ {index}.+ </span>+ {check.title}+ </p>+ <p className="mt-0.5 text-[11px] leading-relaxed text-muted-foreground">+ {check.detail}+ </p>+ </div>+ {check.action && (+ <Button+ size="sm"+ variant={check.state === "attention" ? "default" : "outline"}+ onClick={onAction}+ disabled={busy}+ data-testid={`ultrawiki-check-action-${check.id}`}+ >+ {busy && check.action.kind === "sync_all" && (+ <Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" aria-hidden />+ )}+ {t(`ultrawiki.health.action_${check.action.kind}`)}+ </Button>+ )}+ </li>+ );+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex f926f76787..0a0d59b929 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -2731,7 +2731,8 @@"status_unavailable": "UltraWiki-Status nicht verfügbar — läuft das Backend?","embedding_dead": "Der Embedding-Slot ist nicht bereit ({0}). Stichwort- und Zeit-Antworten funktionieren weiter; die semantische Suche pausiert, bis der Slot repariert ist.","open_settings": "Einstellungen öffnen",- "tab_contents": "Inhalte"+ "tab_contents": "Inhalte",+ "tab_check": "Prüfen"},"progress": {"title": "Import-Pipeline",@@ -2961,6 +2962,19 @@"minutes": "vor {0} Min.","hours": "vor {0} Std.","days": "vor {0} Tg."+ },+ "health": {+ "loading": "Wird geprüft…",+ "unavailable": "Die Prüfung konnte nicht laufen. Die App startet möglicherweise noch — versuche es gleich noch einmal.",+ "recheck": "Erneut prüfen",+ "verdict_usable": "Deine Wissensbasis funktioniert.",+ "verdict_usable_working": "Funktioniert — und arbeitet im Hintergrund weiter.",+ "verdict_not_ready": "Kann noch nicht antworten.",+ "verdict_hint": "Die Schritte unten werden der Reihe nach geprüft. Alles, was du beheben kannst, hat einen Knopf daneben.",+ "action_sync_all": "Jetzt importieren",+ "action_open_sources": "Quellen öffnen",+ "action_open_settings": "Einstellungen öffnen",+ "action_enable_mode": "Einschalten"}}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 2c05609ecc..01cac680bc 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -2732,7 +2732,8 @@"status_unavailable": "UltraWiki status is unavailable — is the backend running?","embedding_dead": "The embedding slot is not ready ({0}). Keyword and time-based answers still work; semantic search is paused until the slot is fixed.","open_settings": "Open settings",- "tab_contents": "Contents"+ "tab_contents": "Contents",+ "tab_check": "Check"},"progress": {"title": "Import pipeline",@@ -2962,6 +2963,19 @@"minutes": "{0} min ago","hours": "{0} h ago","days": "{0} d ago"+ },+ "health": {+ "loading": "Checking…",+ "unavailable": "The check could not run. The app may still be starting — try again in a moment.",+ "recheck": "Check again",+ "verdict_usable": "Your knowledge base is working.",+ "verdict_usable_working": "Working — and still busy in the background.",+ "verdict_not_ready": "Not ready to answer yet.",+ "verdict_hint": "The steps below are checked in order. Anything you can fix has a button next to it.",+ "action_sync_all": "Import now",+ "action_open_sources": "Open sources",+ "action_open_settings": "Open settings",+ "action_enable_mode": "Turn on"}}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 5e4fc688fc..c378c077c0 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -2731,7 +2731,8 @@"status_unavailable": "El estado de UltraWiki no está disponible — ¿está funcionando el backend?","embedding_dead": "La ranura de embeddings no está lista ({0}). Las respuestas por palabras clave y por fecha siguen funcionando; la búsqueda semántica queda en pausa hasta arreglar la ranura.","open_settings": "Abrir ajustes",- "tab_contents": "Contenido"+ "tab_contents": "Contenido",+ "tab_check": "Comprobar"},"progress": {"title": "Canal de importación",@@ -2961,6 +2962,19 @@"minutes": "hace {0} min","hours": "hace {0} h","days": "hace {0} d"+ },+ "health": {+ "loading": "Comprobando…",+ "unavailable": "La comprobación no pudo ejecutarse. Puede que la aplicación aún esté arrancando: inténtalo de nuevo en un momento.",+ "recheck": "Comprobar de nuevo",+ "verdict_usable": "Tu base de conocimiento funciona.",+ "verdict_usable_working": "Funciona, y sigue trabajando en segundo plano.",+ "verdict_not_ready": "Todavía no puede responder.",+ "verdict_hint": "Los pasos de abajo se comprueban en orden. Todo lo que puedas arreglar tiene un botón al lado.",+ "action_sync_all": "Importar ahora",+ "action_open_sources": "Abrir fuentes",+ "action_open_settings": "Abrir ajustes",+ "action_enable_mode": "Activar"}}}diff --git a/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts b/jarvis/ui/web/frontend/src/lib/ultrawikiApi.tsindex aaf6d73d3b..b948e554bc 100644--- a/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts+++ b/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts@@ -405,6 +405,42 @@ export interface UltraWikiSlotModels {reason?: string;}+// Mirrors jarvis/ultrawiki/health.py::CheckState — five-layer anti-drift+// discipline (AP-4 / BUG-008): never retype these values elsewhere.+// `working` and `blocked` exist on purpose: a running import is not a fault,+// and an integration with no reader is not something a user can click away.+export const ULTRAWIKI_CHECK_STATES = [+ "ok",+ "working",+ "attention",+ "blocked",+] as const;+export type UltraWikiCheckState = (typeof ULTRAWIKI_CHECK_STATES)[number];++export interface UltraWikiHealthCheck {+ id: string;+ title: string;+ state: UltraWikiCheckState;+ detail: string;+ /** What the UI should offer; `null` when there is nothing useful to click. */+ action: { kind: string; [key: string]: unknown } | null;+ facts: Record<string, unknown>;+}++export interface UltraWikiHealth {+ /** The worst check's state — the headline colour. */+ overall: UltraWikiCheckState;+ /** Can the user get answers RIGHT NOW (a backlog does not make this false). */+ usable: boolean;+ checks: UltraWikiHealthCheck[];+}++export interface UltraWikiSyncAllResponse {+ started: { source_id: string; job_id: string }[];+ skipped: { source_id: string; reason: string }[];+ detail: string;+}+export interface SupabaseProject {ref: string;name: string;@@ -557,6 +593,25 @@ export function fetchUltraWikiCatalog(): Promise<UltraWikiCatalog> {return request<UltraWikiCatalog>("/api/ultrawiki/catalog");}+/**+ * The "is my knowledge base working?" checklist. Poll-safe like the status+ * fetch: a transient blip returns `null` rather than throwing, because this+ * screen is the one a user opens BECAUSE something looks wrong.+ */+export async function fetchUltraWikiHealth(): Promise<UltraWikiHealth | null> {+ try {+ const res = await fetch("/api/ultrawiki/health");+ if (!res.ok) return null;+ return (await res.json()) as UltraWikiHealth;+ } catch {+ return null;+ }+}++export function syncAllUltraWikiSources(): Promise<UltraWikiSyncAllResponse> {+ return postJson<UltraWikiSyncAllResponse>("/api/ultrawiki/sources/sync-all");+}+/*** The selectable models for one slot's provider, in the exact shape the* API-Keys model picker consumes — so the slots get THAT picker (searchable,diff --git a/jarvis/ui/web/frontend/src/views/ultrawiki/UltraWikiPanel.tsx b/jarvis/ui/web/frontend/src/views/ultrawiki/UltraWikiPanel.tsxindex 4cfd2b9a4c..6191f7b08f 100644--- a/jarvis/ui/web/frontend/src/views/ultrawiki/UltraWikiPanel.tsx+++ b/jarvis/ui/web/frontend/src/views/ultrawiki/UltraWikiPanel.tsx@@ -7,14 +7,20 @@* every 4 s while a sync job is active (the wiki health polling idiom).** Layout: honest degradation banner → staged import-progress strip → the- * four tabs Ask | Sources | Contents | Settings. A dead required slot banners- * the problem and links to the settings tab — the mode is never flipped- * silently (design doc 04, mode-switch rules).+ * five tabs Check | Ask | Sources | Contents | Settings. A dead required slot+ * banners the problem and links to the settings tab — the mode is never+ * flipped silently (design doc 04, mode-switch rules).+ *+ * "Check" leads on purpose. Every other tab answers a question you already+ * know to ask; a user whose knowledge base looks empty does not know which+ * one of them holds the reason, and hunting through four screens is how a+ * single missing import step went undiagnosed for days.*/import { useState } from "react";import {AlertTriangle,Database,+ ListChecks,MessageCircleQuestion,Plug,Settings2,@@ -28,12 +34,13 @@ import {hasActiveUltraWikiJobs,} from "@/lib/ultrawikiApi";import { AskPanel } from "@/components/ultrawiki/AskPanel";+import { HealthPanel } from "@/components/ultrawiki/HealthPanel";import { SourcesPanel } from "@/components/ultrawiki/SourcesPanel";import { ContentsPanel } from "@/components/ultrawiki/ContentsPanel";import { SlotsPanel } from "@/components/ultrawiki/SlotsPanel";import { ImportProgress } from "@/components/ultrawiki/ImportProgress";-type UltraTab = "ask" | "sources" | "contents" | "settings";+type UltraTab = "check" | "ask" | "sources" | "contents" | "settings";export function UltraWikiPanel(): JSX.Element {const t = useT();@@ -126,6 +133,13 @@ export function UltraWikiPanel(): JSX.Element {/><div className="flex items-stretch border-b border-border bg-card/40">+ <UltraTabButton+ active={tab === "check"}+ onClick={() => setTab("check")}+ icon={<ListChecks className="h-3.5 w-3.5" aria-hidden />}+ label={t("ultrawiki.panel.tab_check")}+ testId="ultrawiki-tab-check"+ /><UltraTabButtonactive={tab === "ask"}onClick={() => setTab("ask")}@@ -157,6 +171,12 @@ export function UltraWikiPanel(): JSX.Element {</div><div className="min-h-0 flex-1 overflow-y-auto">+ {tab === "check" && (+ <HealthPanel+ onOpenSources={() => setTab("sources")}+ onOpenSettings={() => setTab("settings")}+ />+ )}{tab === "ask" && (<AskPanelsearchLegs={status.search_legs}diff --git a/jarvis/ui/web/ultrawiki_routes.py b/jarvis/ui/web/ultrawiki_routes.pyindex 32d6e35e5f..f043d6e541 100644--- a/jarvis/ui/web/ultrawiki_routes.py+++ b/jarvis/ui/web/ultrawiki_routes.py@@ -298,6 +298,92 @@ async def get_status(request: Request) -> dict[str, Any]:}[email protected]("/health", summary="Is the knowledge base actually working?")+async def get_health(request: Request) -> dict[str, Any]:+ """One checklist answering "is this working, and if not, what do I click?".++ Assembled from the SAME status payload the settings screens read, so the+ checklist can never claim something the rest of the UI contradicts. It+ exists because every individual surface was already truthful while the+ whole remained unreadable: sources "approved" (permission, not import),+ a pipeline reporting "everything is processed" (of nothing), slots all+ green, and seven connected apps that no reader can pull from. Diagnosing+ that took a database query — see :mod:`jarvis.ultrawiki.health`.+ """+ from jarvis.ultrawiki import health as health_mod # noqa: PLC0415 — lazy (AP-26)++ status = await get_status(request)++ def _candidates() -> list[dict[str, Any]]:+ # Walks the keyring + mcp.json; keep it off the event loop.+ from jarvis.ultrawiki.connectors import plugin_bridge # noqa: PLC0415++ try:+ return plugin_bridge.list_candidates()+ except Exception: # noqa: BLE001 — a broken registry shortens the list+ log.debug("health: candidate probe failed", exc_info=True)+ return []++ candidates = await asyncio.to_thread(_candidates)+ return health_mod.build_health(status, candidates)+++ "/sources/sync-all",+ summary="Import every approved source that has never been read",+ openapi_extra={"x-jarvis-dangerous": True},+)+async def sync_all_sources(+ request: Request,+ only_never_imported: bool = Query(+ default=True,+ description=(+ "Only sources that have never finished an import (the default). "+ "Pass false to re-read every approved source."+ ),+ ),+) -> dict[str, Any]:+ """The checklist's one-click fix for "approved but never imported".++ Approving a source grants permission; before auto-import on approval+ landed, it did not fetch, and installs made earlier still carry sources+ that were allowed but never read. This starts exactly those, skipping any+ already running so a double click cannot pile up duplicate work.+ """+ service = _service(request)+ status = await service.status()+ started: list[dict[str, str]] = []+ skipped: list[dict[str, str]] = []+ for source in status.get("sources", []):+ source_id = str(source.get("id") or "")+ if not source_id:+ continue+ if source.get("consent") != "approved" or not source.get("enabled", False):+ skipped.append({"source_id": source_id, "reason": "not approved"})+ continue+ if source.get("active_job"):+ skipped.append({"source_id": source_id, "reason": "already importing"})+ continue+ if only_never_imported and source.get("last_sync_at"):+ skipped.append({"source_id": source_id, "reason": "already imported"})+ continue+ try:+ job_id = await service.start_sync(source_id)+ except Exception as exc: # noqa: BLE001 — one refusal must not stop the rest+ skipped.append({"source_id": source_id, "reason": str(exc)[:200]})+ continue+ started.append({"source_id": source_id, "job_id": job_id})+ return {+ "started": started,+ "skipped": skipped,+ "detail": (+ f"Started {len(started)} import(s)."+ if started+ else "Nothing to import — every approved source has already been read."+ ),+ }++@router.get("/providers", summary="UltraWiki provider options per slot")async def list_providers(request: Request) -> dict[str, Any]:"""Option cards for the embedding, rerank, and storage slots (readiness-probed)."""@@ -1317,13 +1403,48 @@ async def start_sync(}[email protected]("/connectors", summary="List every UltraWiki source connector offered")+async def list_connectors() -> dict[str, Any]:+ """The curated roster the add-source picker renders: built-ins and integrations.++ Static product data — the catalog, not the install. It says what UltraWiki+ OFFERS (name, brand mark, whether a reader exists yet); which of them this+ machine has actually connected is the separate ``/bridge/candidates`` call.+ """+ from jarvis.ultrawiki import connector_catalog # noqa: PLC0415 — lazy (AP-26)++ connectors = [+ connector_catalog.as_dict(spec) for spec in connector_catalog.list_connectors()+ ]+ return {+ "connectors": connectors,+ "total": len(connectors),+ "builtin": sum(1 for row in connectors if row["kind"] == "builtin"),+ "bridge": sum(1 for row in connectors if row["kind"] == "bridge"),+ }++@router.get("/bridge/candidates", summary="List plugin-bridge candidates")async def list_bridge_candidates() -> dict[str, Any]:- """Connected Jarvis integrations (plugins, MCP servers) that could become sources."""+ """Curated integrations for the picker, each flagged connected or not.++ Only roster entries appear — a connected tool UltraWiki does not curate is+ left out entirely, because offering it would promise a reader that will+ never exist. A curated integration the user has NOT connected is included+ with ``connected: false`` so the picker can show what is possible and point+ at the Plugins store, rather than pretending the roster is empty.+ """from jarvis.ultrawiki.connectors import plugin_bridge # noqa: PLC0415 — lazy- candidates = plugin_bridge.list_candidates()- return {"candidates": candidates, "total": len(candidates)}+ # Discovery walks the OS keyring and reads mcp.json — blocking work that+ # belongs in a worker thread, the same way the health route runs it.+ candidates = await asyncio.to_thread(plugin_bridge.list_offered_integrations)+ connected = sum(1 for row in candidates if row.get("connected"))+ return {+ "candidates": candidates,+ "total": len(candidates),+ "connected": connected,+ }# ---------------------------------------------------------------------------diff --git a/jarvis/ultrawiki/connectors/plugin_bridge.py b/jarvis/ultrawiki/connectors/plugin_bridge.pyindex 8a1588583b..942aadd7ff 100644--- a/jarvis/ultrawiki/connectors/plugin_bridge.py+++ b/jarvis/ultrawiki/connectors/plugin_bridge.py@@ -12,6 +12,15 @@ could turn into UltraWiki sources —flagged ``needs_reauth``, the same rule the marketplace UI applies), and- MCP servers configured (and enabled) in the user's ``mcp.json``.+Discovery finds what is INSTALLED; :mod:`jarvis.ultrawiki.connector_catalog`+decides what is OFFERED. Every candidate is matched against that curated+roster: an integration the roster does not name is dropped (noted once at+debug), and one it does name is enriched with the catalog's real product+name, brand key and status — so no raw id or drifting registry string can+reach a card. :func:`list_offered_integrations` adds the roster entries the+user has NOT connected yet, flagged as such, so the picker can show what is+possible without letting anyone add a dead source.+Every probe is wrapped so a half-configured install (no keyring service,corrupt catalog, missing mcp.json) shortens the list instead of crashingit. All imports of the marketplace/MCP machinery are lazy (AP-26).@@ -48,6 +57,7 @@ import loggingfrom collections.abc import AsyncIterator, Callablefrom typing import Any+from jarvis.ultrawiki import connector_catalogfrom jarvis.ultrawiki.types import (AuthKind,ConnectorCapabilities,@@ -83,8 +93,8 @@ def _adapter_note(integration_id: str) -> str:return "pull adapter available" if has_pull_adapter(integration_id) else "pull adapter pending"-def _marketplace_candidates() -> list[dict[str, str]]:- candidates: list[dict[str, str]] = []+def _marketplace_candidates() -> list[dict[str, Any]]:+ candidates: list[dict[str, Any]] = []try:from jarvis.marketplace.catalog_data import load_catalogfrom jarvis.marketplace.token_store import TokenStore@@ -112,13 +122,18 @@ def _marketplace_candidates() -> list[dict[str, str]]:f"connected marketplace plugin ({spec.category}); "f"{_adapter_note(integration_id)}"),+ # The machine-readable twin of the note above. Callers used to+ # have to string-match "pull adapter pending" to decide whether+ # this integration can contribute anything — a flag they can+ # branch on beats parsing an English sentence.+ "has_pull_adapter": has_pull_adapter(integration_id),})return candidates-def _mcp_candidates() -> list[dict[str, str]]:- candidates: list[dict[str, str]] = []+def _mcp_candidates() -> list[dict[str, Any]]:+ candidates: list[dict[str, Any]] = []try:from jarvis.mcp.state import load_config@@ -148,6 +163,7 @@ def _mcp_candidates() -> list[dict[str, str]]:"kind": "mcp","label": label,"detail": detail,+ "has_pull_adapter": has_pull_adapter(integration_id),})except Exception as exc:@@ -156,14 +172,103 @@ def _mcp_candidates() -> list[dict[str, str]]:return candidates-def list_candidates() -> list[dict[str, str]]:- """CONNECTED integrations a user could turn into UltraWiki sources.+def _enriched(+ candidate: dict[str, Any], spec: connector_catalog.UltraWikiConnectorSpec+) -> dict[str, Any]:+ """One discovered candidate, dressed in its catalog identity.++ The catalog label OVERWRITES whatever the registry carried: registry+ display strings are user- and vendor-authored and drift into unreadable+ shapes, while the roster holds the product's real name. ``status`` is the+ one field the runtime knows better than the catalog — a registered pull+ adapter means the integration really can be read today.+ """+ integration_id = str(candidate.get("id") or "")+ adapter_ready = has_pull_adapter(integration_id)+ return {+ **candidate,+ "label": spec.label,+ "catalog_id": spec.id,+ "brand": spec.brand,+ "connector_kind": spec.kind,+ "description_key": spec.description_key,+ "status": "available" if adapter_ready else spec.status,+ "connected": True,+ "has_pull_adapter": adapter_ready,+ }+++def list_candidates() -> list[dict[str, Any]]:+ """CONNECTED integrations the roster offers as UltraWiki sources.++ Each entry: ``{"id", "kind", "label", "detail", "has_pull_adapter",+ "catalog_id", "brand", "connector_kind", "description_key", "status",+ "connected"}`` where ``kind`` is ``"plugin"`` (marketplace) or ``"mcp"``+ (mcp.json server) — WHERE it was discovered — and ``connector_kind`` is+ always ``"bridge"``.++ Connected-only, so the count keeps meaning "apps this install can read+ from" for the health surface. Anything connected but off the roster is+ dropped. Never raises — a broken registry merely shortens the list.+ """+ # Roster order, not discovery order: the picker must not reshuffle itself+ # because a token expired or an mcp.json entry moved.+ rank = {spec.id: i for i, spec in enumerate(connector_catalog.BRIDGE_CONNECTORS)}+ offered: list[tuple[int, dict[str, Any]]] = []+ claimed: set[str] = set()+ for candidate in _marketplace_candidates() + _mcp_candidates():+ integration_id = str(candidate.get("id") or "")+ spec = connector_catalog.bridge_entry_for(integration_id)+ if spec is None:+ connector_catalog.note_excluded_candidate(+ integration_id, "no curated UltraWiki entry"+ )+ continue+ # One product, one card: a user running their own MCP server for a+ # product they also connected as a plugin gets ONE tile, and the+ # marketplace connection wins because it is the supported path.+ if spec.id in claimed:+ connector_catalog.note_excluded_candidate(+ integration_id, f"{spec.label} is already offered"+ )+ continue+ claimed.add(spec.id)+ offered.append((rank[spec.id], _enriched(candidate, spec)))+ offered.sort(key=lambda pair: pair[0])+ return [row for _, row in offered]+++def list_offered_integrations() -> list[dict[str, Any]]:+ """The full picker roster: connected entries first, then the rest.- Each entry: ``{"id", "kind", "label", "detail"}`` where ``kind`` is- ``"plugin"`` (marketplace) or ``"mcp"`` (mcp.json server). Never- raises — a broken registry merely shortens the list.+ A curated integration the user has not connected still belongs in the+ picker — that is the difference between a catalog and a list of what+ happens to be plugged in. It carries ``connected: false`` so the UI sends+ the user to the Plugins store instead of registering a source that could+ never read anything."""- return _marketplace_candidates() + _mcp_candidates()+ connected = list_candidates()+ seen = {str(row.get("catalog_id") or "") for row in connected}+ missing = [+ {+ "id": f"plugin:{spec.id}",+ "kind": "plugin",+ "label": spec.label,+ "detail": (+ "not connected yet — connect it under Plugins, then add it here"+ ),+ "has_pull_adapter": False,+ "catalog_id": spec.id,+ "brand": spec.brand,+ "connector_kind": spec.kind,+ "description_key": spec.description_key,+ "status": spec.status,+ "connected": False,+ }+ for spec in connector_catalog.BRIDGE_CONNECTORS+ if spec.id not in seen+ ]+ return connected + missingclass PluginBridgeConnector:@@ -215,6 +320,7 @@ __all__ = ["PullAdapter","has_pull_adapter","list_candidates",+ "list_offered_integrations","register_pull_adapter","unregister_pull_adapter",]diff --git a/jarvis/ultrawiki/health.py b/jarvis/ultrawiki/health.pynew file mode 100644index 0000000000..58aafabf93--- /dev/null+++ b/jarvis/ultrawiki/health.py@@ -0,0 +1,483 @@+"""The "is my knowledge base actually working?" checklist.++Why this module exists (2026-07-25 forensic): a user connected seven+integrations, activated Ultra mode, approved every source — and the knowledge+base stayed empty for days. Every individual surface was telling the truth and+the whole was still unreadable:++* the sources list showed three sources, all "approved" (permission granted —+ which reads as "done"),+* the pipeline said *"Everything ingested so far is fully processed"* (true,+ and catastrophically misleading: nothing had ever been fetched, so there was+ nothing to process),+* the settings said every capability slot was ready (also true),+* and the Plugins store said GitHub was connected (true again — but the+ UltraWiki side has no pull adapter for it, so it can never yield an item).++Nothing was broken. The user simply had no way to see that ONE step —+starting the first import — had never happened. Diagnosing it took a database+query, which is exactly what a settings screen exists to prevent.++So this module answers one question in one place, in the order a person would+ask it: is the mode on, can it store, can it read anything, has it read+anything, can it answer, and is it still busy. Every check carries a state, a+plain-English sentence, and — when the user can fix it — the action that does.++Design rules:++* **A check never guesses.** It reports what the store and the slot probes+ actually say; an unknown answer is ``attention`` with the reason, never a+ cheerful default.+* **Blocked ≠ broken.** A source whose integration has no pull adapter is+ ``blocked`` with an honest explanation, not an error the user could fix by+ clicking harder.+* **Working is its own state.** A first import running or a backlog draining+ is progress, and must not read as a fault.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from typing import Any, Literal++__all__ = [+ "CheckState",+ "HealthCheck",+ "build_health",+]++#: ``ok`` — nothing to do. ``working`` — busy, will resolve itself.+#: ``attention`` — the user can fix this, and the action says how.+#: ``blocked`` — genuinely not possible yet; clicking cannot help.+CheckState = Literal["ok", "working", "attention", "blocked"]++#: Rank for the overall verdict: the worst check wins, in this order.+_SEVERITY: dict[str, int] = {"ok": 0, "working": 1, "attention": 2, "blocked": 3}+++def _names(rows: list[dict[str, Any]], limit: int = 3) -> tuple[str, bool]:+ """A readable "A, B and C" plus whether the verb needs a plural.++ Worth the six lines: these sentences are the whole point of the checklist,+ and "GitHub are connected" undoes the care taken writing them.+ """+ labels = [str(r.get("label") or r.get("id") or "?") for r in rows[:limit]]+ extra = len(rows) - len(labels)+ if extra > 0:+ joined = ", ".join(labels) + f" and {extra} more"+ elif len(labels) > 1:+ joined = ", ".join(labels[:-1]) + f" and {labels[-1]}"+ else:+ joined = labels[0] if labels else ""+ return joined, len(rows) != 1+++@dataclass(slots=True)+class HealthCheck:+ """One row of the checklist."""++ id: str+ title: str+ state: CheckState+ detail: str+ #: What the UI should offer, e.g. ``{"kind": "sync_all"}``. ``None`` = nothing+ #: to click: the check is fine, busy, or genuinely blocked.+ action: dict[str, Any] | None = None+ #: Free-form numbers the UI may render (counts, ETA seconds).+ facts: dict[str, Any] = field(default_factory=dict)++ def as_dict(self) -> dict[str, Any]:+ return {+ "id": self.id,+ "title": self.title,+ "state": self.state,+ "detail": self.detail,+ "action": self.action,+ "facts": self.facts,+ }+++def _mode_check(status: dict[str, Any]) -> HealthCheck:+ if status.get("enabled"):+ return HealthCheck(+ id="mode",+ title="Ultra mode is on",+ state="ok",+ detail="The Wiki section answers from the UltraWiki store.",+ )+ return HealthCheck(+ id="mode",+ title="Ultra mode is off",+ state="attention",+ detail=(+ "The normal wiki is answering. Nothing is lost — switching on "+ "picks up exactly where you left off."+ ),+ action={"kind": "enable_mode"},+ )+++def _storage_check(status: dict[str, Any]) -> HealthCheck:+ if not status.get("started"):+ return HealthCheck(+ id="storage",+ title="Storage is not open",+ state="blocked",+ detail=(+ "The knowledge store could not be opened, so nothing can be "+ "saved or read. The app log says why."+ ),+ )+ in_use = str(status.get("backend_in_use") or "sqlite")+ configured = str(status.get("db_backend") or "sqlite")+ if configured != in_use:+ # The store degraded to the local floor — the wiki works, but not+ # where the user thinks it does, and that is worth saying out loud.+ return HealthCheck(+ id="storage",+ title=f"Storage fell back to {in_use}",+ state="attention",+ detail=(+ f"You chose {configured}, but it could not be reached, so the "+ f"local {in_use} store is answering. Your data is safe here."+ ),+ action={"kind": "open_settings", "tab": "storage"},+ facts={"configured": configured, "in_use": in_use},+ )+ where = "in a local file on this machine" if in_use == "sqlite" else f"in {in_use}"+ return HealthCheck(+ id="storage",+ title="Storage is working",+ state="ok",+ detail=f"Everything is stored {where}.",+ facts={"in_use": in_use},+ )+++def _sources_check(+ status: dict[str, Any], candidates: list[dict[str, Any]]+) -> HealthCheck:+ """The check that would have caught the 2026-07-25 forensic in one glance."""+ sources = list(status.get("sources") or [])+ # A source whose integration has no reader can never import, so offering+ # "start the import" for it would send the user to press a button that+ # provably does nothing. Those belong to the integrations check, which+ # explains WHY, not here among the fixable ones.+ unreadable = {+ str(c.get("id"))+ for c in candidates+ if not c.get("has_pull_adapter", False) and c.get("id")+ }++ def _can_import(source: dict[str, Any]) -> bool:+ integration = str(source.get("integration_id") or "")+ return not (integration and integration in unreadable)++ if not sources:+ return HealthCheck(+ id="sources",+ title="No sources yet",+ state="attention",+ detail="Nothing is connected to read from. Add a source to begin.",+ action={"kind": "open_sources"},+ )++ approved = [s for s in sources if s.get("consent") == "approved"]+ pending = [s for s in sources if s.get("consent") == "pending"]+ importable = [s for s in approved if _can_import(s)]+ never_imported = [+ s+ for s in importable+ if not s.get("last_sync_at") and not s.get("active_job")+ ]+ importing = [s for s in approved if s.get("active_job")]+ failed = [s for s in approved if s.get("last_error")]+ facts = {+ "total": len(sources),+ "approved": len(approved),+ "pending": len(pending),+ "never_imported": len(never_imported),+ "importing": len(importing),+ "failed": len(failed),+ "no_reader": len(approved) - len(importable),+ }++ if failed:+ names, _plural = _names(failed)+ return HealthCheck(+ id="sources",+ title=f"{len(failed)} source(s) failed to import",+ state="attention",+ detail=f"{names} stopped with an error. Opening the source shows it.",+ action={"kind": "open_sources"},+ facts=facts,+ )+ if importing:+ return HealthCheck(+ id="sources",+ title=f"Importing from {len(importing)} source(s)",+ state="working",+ detail="The first read is running. Items appear as they arrive.",+ facts=facts,+ )+ if never_imported:+ # THE defect this checklist was written for: approving grants+ # permission, it does not fetch. Before auto-import on approval landed,+ # this state was invisible and looked exactly like "all good".+ names, plural = _names(never_imported)+ return HealthCheck(+ id="sources",+ title=f"{len(never_imported)} approved source(s) never imported",+ state="attention",+ detail=(+ f"{names} {'are' if plural else 'is'} allowed to be read but "+ f"{'have' if plural else 'has'} never actually been read. "+ "Start the import and the contents come in."+ ),+ action={"kind": "sync_all"},+ facts=facts,+ )+ if pending and not approved:+ return HealthCheck(+ id="sources",+ title="No source is approved yet",+ state="attention",+ detail=(+ "Nothing is read before you approve it. Approve a source and "+ "its import starts right away."+ ),+ action={"kind": "open_sources"},+ facts=facts,+ )+ if not importable:+ return HealthCheck(+ id="sources",+ title="No source can be imported yet",+ state="blocked",+ detail=(+ "Every approved source belongs to an app UltraWiki cannot "+ "read yet. Adding a folder or the built-in wiki works today."+ ),+ action={"kind": "open_sources"},+ facts=facts,+ )+ return HealthCheck(+ id="sources",+ title=f"{len(importable)} source(s) imported",+ state="ok",+ detail="Every source that can be read has been read at least once.",+ facts=facts,+ )+++def _content_check(status: dict[str, Any]) -> HealthCheck:+ counts = dict(status.get("counts") or {})+ total = int(counts.get("total") or 0)+ if total == 0:+ return HealthCheck(+ id="content",+ title="The knowledge base is empty",+ state="attention",+ detail=(+ "Nothing has been stored yet. Import a source and its "+ "contents land here."+ ),+ action={"kind": "sync_all"},+ facts={"total": 0},+ )+ searchable = int(counts.get("keyword_indexed") or 0) + int(+ counts.get("embedded") or 0+ ) + int(counts.get("distilled") or 0)+ return HealthCheck(+ id="content",+ title=f"{total:,} item(s) stored".replace(",", " "),+ state="ok",+ detail=f"{searchable:,} of them are already searchable.".replace(",", " "),+ facts={"total": total, "searchable": searchable, **counts},+ )+++def _search_check(status: dict[str, Any]) -> HealthCheck:+ legs = dict(status.get("search_legs") or {})+ keyword = dict(legs.get("keyword") or {})+ vector = dict(legs.get("vector") or {})+ counts = dict(status.get("counts") or {})+ keyword_ready = bool(keyword.get("available"))+ vector_ready = bool(vector.get("available"))+ facts = {"keyword": keyword_ready, "vector": vector_ready}++ if not keyword_ready:+ return HealthCheck(+ id="search",+ title="Search cannot answer",+ state="blocked",+ detail=str(+ keyword.get("reason")+ or "The keyword index is unavailable, so nothing can be found."+ ),+ facts=facts,+ )+ if int(counts.get("keyword_indexed") or 0) + int(counts.get("embedded") or 0) + int(+ counts.get("distilled") or 0+ ) == 0:+ return HealthCheck(+ id="search",+ title="Nothing to search yet",+ state="working",+ detail=(+ "Search is ready, but no item has finished processing. The "+ "first results appear within a minute of an import."+ ),+ facts=facts,+ )+ if not vector_ready:+ # Keyword-only is a real, working configuration — not a failure.+ return HealthCheck(+ id="search",+ title="Search works (keyword only)",+ state="attention",+ detail=(+ str(vector.get("reason") or "Semantic search is off.")+ + " Exact words are found; questions phrased differently are not."+ ),+ action={"kind": "open_settings", "tab": "embedding"},+ facts=facts,+ )+ return HealthCheck(+ id="search",+ title="Search works",+ state="ok",+ detail="Both exact words and meaning are searchable.",+ facts=facts,+ )+++def _processing_check(status: dict[str, Any]) -> HealthCheck:+ counts = dict(status.get("counts") or {})+ pipeline = dict(status.get("pipeline") or {})+ captured = int(counts.get("captured") or 0)+ failed = int(counts.get("failed") or 0)+ state = str(pipeline.get("state") or "")+ facts = {"backlog": captured, "failed": failed, "pipeline_state": state}++ if failed:+ return HealthCheck(+ id="processing",+ title=f"{failed} item(s) could not be processed",+ state="attention",+ detail=(+ "They stay stored and keyword-searchable; only their "+ "summaries are missing. Retrying usually clears them."+ ),+ facts=facts,+ )+ if captured:+ return HealthCheck(+ id="processing",+ title=f"{captured:,} item(s) still being processed".replace(",", " "),+ state="working",+ detail=(+ "Summarising and indexing run in the background. Everything "+ "already processed is searchable now — you do not have to wait."+ ),+ facts=facts,+ )+ if state == "paused":+ return HealthCheck(+ id="processing",+ title="Background processing is paused",+ state="attention",+ detail=str(pipeline.get("reason") or "The pipeline is not running."),+ facts=facts,+ )+ return HealthCheck(+ id="processing",+ title="Everything is processed",+ state="ok",+ detail="No backlog. New items are picked up automatically.",+ facts=facts,+ )+++def _integrations_check(+ status: dict[str, Any], candidates: list[dict[str, Any]]+) -> HealthCheck:+ """Connected-but-unreadable integrations, stated plainly.++ The 2026-07-25 forensic again: seven integrations showed "connected" in the+ Plugins store, and the user reasonably expected their contents to arrive.+ UltraWiki has no pull adapter for any of them, so they never could. That is+ a missing capability, not a misconfiguration — saying so beats letting+ someone hunt for the switch that would fix it.+ """+ pending = [c for c in candidates if not c.get("has_pull_adapter", False)]+ ready = [c for c in candidates if c.get("has_pull_adapter", False)]+ facts = {+ "connected": len(candidates),+ "readable": len(ready),+ "pending": len(pending),+ }+ if not candidates:+ return HealthCheck(+ id="integrations",+ title="No connected apps to read from",+ state="ok",+ detail=(+ "Local sources are enough to start. Connecting apps in the "+ "Plugins store adds more later."+ ),+ facts=facts,+ )+ if not ready:+ names, plural = _names(pending, limit=4)+ return HealthCheck(+ id="integrations",+ title=f"{len(pending)} connected app(s) cannot be imported yet",+ state="blocked",+ detail=(+ f"{names} {'are' if plural else 'is'} connected to Jarvis, but "+ f"UltraWiki has no reader for {'them' if plural else 'it'} "+ "yet, so nothing comes in from there. Local sources and "+ "folders work today."+ ),+ facts=facts,+ )+ return HealthCheck(+ id="integrations",+ title=f"{len(ready)} connected app(s) can be imported",+ state="ok",+ detail="Add them as sources to pull their contents in.",+ facts=facts,+ )+++def build_health(+ status: dict[str, Any], candidates: list[dict[str, Any]] | None = None+) -> dict[str, Any]:+ """The full checklist plus one overall verdict.++ Ordered the way a person asks the question: is it on, can it store, what+ can it read, has it read anything, can it answer, is it still busy.+ """+ checks = [+ _mode_check(status),+ _storage_check(status),+ _integrations_check(status, list(candidates or [])),+ _sources_check(status, list(candidates or [])),+ _content_check(status),+ _search_check(status),+ _processing_check(status),+ ]+ worst = max((_SEVERITY[c.state] for c in checks), default=0)+ overall = next(k for k, v in _SEVERITY.items() if v == worst)+ # The headline answers the only question that matters at a glance: can I+ # use this right now? A draining backlog or an unreadable integration does+ # NOT make the answer no — the rest of the corpus still answers.+ usable = any(+ c.id == "search" and c.state in ("ok", "attention") for c in checks+ ) and any(c.id == "content" and c.state == "ok" for c in checks)+ return {+ "overall": overall,+ "usable": usable,+ "checks": [c.as_dict() for c in checks],+ }diff --git a/tests/unit/ultrawiki/test_connectors.py b/tests/unit/ultrawiki/test_connectors.pyindex 932f9cbc8d..650f5c0322 100644--- a/tests/unit/ultrawiki/test_connectors.py+++ b/tests/unit/ultrawiki/test_connectors.py@@ -467,9 +467,23 @@ class TestPluginBridge:result = list_candidates()assert isinstance(result, list)for entry in result:- assert set(entry) == {"id", "kind", "label", "detail"}- assert all(isinstance(value, str) for value in entry.values())+ assert set(entry) == {+ "id",+ "kind",+ "label",+ "detail",+ # The machine-readable twin of the "pull adapter pending" note.+ # Callers (the health checklist) must not have to string-match+ # an English sentence to learn whether this integration can+ # contribute anything at all.+ "has_pull_adapter",+ }assert entry["kind"] in {"plugin", "mcp"}+ assert isinstance(entry["has_pull_adapter"], bool)+ assert all(+ isinstance(entry[key], str)+ for key in ("id", "kind", "label", "detail")+ )def test_list_candidates_survives_broken_registries(self, monkeypatch: pytest.MonkeyPatchdiff --git a/tests/unit/ultrawiki/test_health.py b/tests/unit/ultrawiki/test_health.pynew file mode 100644index 0000000000..3b487313df--- /dev/null+++ b/tests/unit/ultrawiki/test_health.py@@ -0,0 +1,327 @@+"""The "is my knowledge base working?" checklist.++The anchor test is :func:`test_the_forensic_state_is_diagnosed_in_one_line` —+it replays the exact live state that left a user staring at an empty knowledge+base for days while every individual surface reported the truth. If that test+ever goes green for the wrong reason, the checklist has stopped earning its+place.+"""++from __future__ import annotations++from typing import Any++import pytest++from jarvis.ultrawiki.health import build_health+++def _status(**overrides: Any) -> dict[str, Any]:+ """A healthy, fully-imported install; tests override one thing at a time."""+ base: dict[str, Any] = {+ "enabled": True,+ "started": True,+ "db_backend": "sqlite",+ "backend_in_use": "sqlite",+ "counts": {+ "captured": 0,+ "keyword_indexed": 40,+ "embedded": 40,+ "distilled": 20,+ "failed": 0,+ "total": 100,+ },+ "pipeline": {"running": True, "state": "idle", "reason": "idle"},+ "sources": [+ {+ "id": "normal-wiki",+ "label": "Built-in Wiki",+ "consent": "approved",+ "enabled": True,+ "last_sync_at": "2026-07-25T10:00:00Z",+ }+ ],+ "search_legs": {+ "keyword": {"available": True},+ "vector": {"available": True},+ },+ }+ base.update(overrides)+ return base+++def _check(health: dict[str, Any], check_id: str) -> dict[str, Any]:+ return next(c for c in health["checks"] if c["id"] == check_id)+++def test_a_fully_imported_install_reports_ok_and_usable():+ health = build_health(_status(), [])+ assert health["overall"] == "ok"+ assert health["usable"] is True+ assert {c["state"] for c in health["checks"]} == {"ok"}+++def test_the_forensic_state_is_diagnosed_in_one_line():+ """The 2026-07-25 case: approved everywhere, imported nowhere.++ Three sources approved, none ever synced, zero items, and a pipeline+ truthfully reporting "everything is processed" — of nothing. Every surface+ was right and the user still could not tell what was wrong. The checklist+ has to name the ONE missing step and offer the button that does it.+ """+ sources = [+ {+ "id": sid,+ "label": label,+ "consent": "approved",+ "enabled": True,+ "last_sync_at": None,+ }+ for sid, label in (+ ("normal-wiki", "Built-in Wiki"),+ ("jarvis-conversations", "Jarvis Conversations"),+ )+ ]+ health = build_health(+ _status(+ sources=sources,+ counts={+ "captured": 0,+ "keyword_indexed": 0,+ "embedded": 0,+ "distilled": 0,+ "failed": 0,+ "total": 0,+ },+ search_legs={+ "keyword": {"available": True},+ "vector": {"available": False, "reason": "No vectors yet."},+ },+ ),+ [],+ )+ sources_check = _check(health, "sources")+ assert sources_check["state"] == "attention"+ assert "never" in sources_check["detail"].lower()+ # The fix must be one click away, not a hunt through four tabs.+ assert sources_check["action"] == {"kind": "sync_all"}+ assert health["usable"] is False+ # And the pipeline's "everything is processed" must NOT read as success+ # while the store is empty — the content check is what says otherwise.+ assert _check(health, "content")["state"] == "attention"+++def test_a_running_first_import_reads_as_progress_not_as_a_fault():+ """`working` exists so a busy system never looks broken."""+ health = build_health(+ _status(+ sources=[+ {+ "id": "normal-wiki",+ "label": "Built-in Wiki",+ "consent": "approved",+ "enabled": True,+ "last_sync_at": None,+ "active_job": {"job_id": "abc", "status": "running"},+ }+ ]+ ),+ [],+ )+ check = _check(health, "sources")+ assert check["state"] == "working"+ assert check["action"] is None # nothing to click — it is already happening+++def test_a_draining_backlog_still_counts_as_usable():+ """Half-processed is a working knowledge base, not a broken one.++ 4 590 items take hours to distil. Reporting "not ready" for all of it would+ be false: everything already processed answers questions right now.+ """+ health = build_health(+ _status(+ counts={+ "captured": 4000,+ "keyword_indexed": 500,+ "embedded": 80,+ "distilled": 10,+ "failed": 0,+ "total": 4590,+ }+ ),+ [],+ )+ assert health["usable"] is True+ assert _check(health, "processing")["state"] == "working"+ assert _check(health, "content")["state"] == "ok"+++def test_connected_apps_without_a_reader_are_blocked_not_broken():+ """Seven "connected" plugins that can never yield an item, said plainly."""+ health = build_health(+ _status(),+ [+ {"id": "plugin:github", "label": "GitHub", "has_pull_adapter": False},+ {"id": "plugin:gmail", "label": "Gmail", "has_pull_adapter": False},+ ],+ )+ check = _check(health, "integrations")+ assert check["state"] == "blocked"+ # No action: this is a missing capability, and offering a button would+ # send the user hunting for a switch that does not exist.+ assert check["action"] is None+ assert "GitHub and Gmail are connected" in check["detail"]+ # A missing reader must not make the rest of the corpus unusable.+ assert health["usable"] is True+++def test_a_source_with_no_reader_is_never_offered_as_importable():+ """Do not hand the user a button that provably does nothing.++ A plugin-bridge source for GitHub is "approved" and "never imported" —+ both true — but it can never import, because no reader exists. Offering+ "Import now" there sends them to press a button that starts a job yielding+ zero items, and to conclude the app is lying. The integrations check+ already explains WHY; this one must stay quiet about it.+ """+ health = build_health(+ _status(+ sources=[+ {+ "id": "plugin-bridge-1",+ "label": "GitHub",+ "integration_id": "plugin:github",+ "consent": "approved",+ "enabled": True,+ "last_sync_at": None,+ }+ ]+ ),+ [{"id": "plugin:github", "label": "GitHub", "has_pull_adapter": False}],+ )+ check = _check(health, "sources")+ assert check["state"] == "blocked"+ assert check["facts"]["never_imported"] == 0+ assert check["facts"]["no_reader"] == 1+++def test_a_source_whose_reader_exists_is_still_offered():+ """The same source becomes actionable the moment a reader is registered."""+ health = build_health(+ _status(+ sources=[+ {+ "id": "plugin-bridge-1",+ "label": "GitHub",+ "integration_id": "plugin:github",+ "consent": "approved",+ "enabled": True,+ "last_sync_at": None,+ }+ ]+ ),+ [{"id": "plugin:github", "label": "GitHub", "has_pull_adapter": True}],+ )+ check = _check(health, "sources")+ assert check["state"] == "attention"+ assert check["action"] == {"kind": "sync_all"}+++def test_an_integration_with_a_reader_is_reported_as_importable():+ health = build_health(+ _status(),+ [{"id": "plugin:github", "label": "GitHub", "has_pull_adapter": True}],+ )+ assert _check(health, "integrations")["state"] == "ok"+++def test_a_silent_storage_fallback_is_surfaced():+ """Postgres configured, SQLite answering: the wiki works, elsewhere."""+ health = build_health(+ _status(db_backend="postgres", backend_in_use="sqlite"), []+ )+ check = _check(health, "storage")+ assert check["state"] == "attention"+ assert "postgres" in check["detail"]+ assert check["action"] == {"kind": "open_settings", "tab": "storage"}+++def test_keyword_only_search_is_attention_not_failure():+ """No embedding key is a real, working configuration — say what it costs."""+ health = build_health(+ _status(+ search_legs={+ "keyword": {"available": True},+ "vector": {"available": False, "reason": "No embedding key."},+ }+ ),+ [],+ )+ check = _check(health, "search")+ assert check["state"] == "attention"+ assert "Exact words are found" in check["detail"]+ assert health["usable"] is True+++def test_a_dead_keyword_index_blocks_search():+ health = build_health(+ _status(+ search_legs={+ "keyword": {"available": False, "reason": "FTS index missing."},+ "vector": {"available": False},+ }+ ),+ [],+ )+ assert _check(health, "search")["state"] == "blocked"+ assert health["usable"] is False+++def test_mode_off_is_the_first_thing_reported():+ health = build_health(_status(enabled=False), [])+ assert health["checks"][0]["id"] == "mode"+ assert health["checks"][0]["state"] == "attention"+ assert health["checks"][0]["action"] == {"kind": "enable_mode"}+++def test_failed_items_do_not_hide_that_the_rest_works():+ health = build_health(+ _status(+ counts={+ "captured": 0,+ "keyword_indexed": 90,+ "embedded": 90,+ "distilled": 80,+ "failed": 10,+ "total": 100,+ }+ ),+ [],+ )+ check = _check(health, "processing")+ assert check["state"] == "attention"+ assert "keyword-searchable" in check["detail"]+ assert health["usable"] is True+++ "status_kwargs",+ [+ {},+ {"enabled": False},+ {"started": False},+ {"sources": []},+ {"counts": {}},+ {"pipeline": {}},+ {"search_legs": {}},+ ],+)+def test_the_checklist_never_raises_on_a_partial_status(status_kwargs):+ """The screen a user opens BECAUSE something is wrong must always render."""+ health = build_health(_status(**status_kwargs), [])+ assert health["overall"] in ("ok", "working", "attention", "blocked")+ assert len(health["checks"]) == 7+ for check in health["checks"]:+ assert check["title"].strip()+ assert check["detail"].strip()