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): write and register the Obsidian vault from the app
Ruben Lütkee5dc6c8dc7cc
diff --git a/jarvis/core/config.py b/jarvis/core/config.pyindex b4f4e83e88..f3f0d7846d 100644--- a/jarvis/core/config.py+++ b/jarvis/core/config.py@@ -2168,6 +2168,12 @@ class UltraWikiConfig(BaseModel):rerank_model: str = "" # only for rerank_provider="llm"; empty = cheap tierollama_endpoint: str = "http://localhost:11434"+ # Where the readable Markdown projection is written (the Obsidian vault).+ # Empty = "wiki/ultrawiki-vault" under the data dir — beside the normal+ # wiki's own vault and never inside it: UltraWiki writes to its own files,+ # which is what keeps the mode switch reversible.+ vault_path: str = ""+# -- ranking knobs (design: UltraWiki ranking pipeline, 2026-07-25) ------# The absolute 0-10 relevance floor an UNSOLICITED surface (context# injection, volunteered voice answers) must clear. Explicit searches --diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/ExplorePanel.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/ExplorePanel.tsxindex 3cf9b78cde..c073d7e741 100644--- a/jarvis/ui/web/frontend/src/components/ultrawiki/ExplorePanel.tsx+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/ExplorePanel.tsx@@ -37,6 +37,7 @@ import {type UltraWikiMoment,} from "@/lib/ultrawikiExploreApi";import { EntityGraph } from "@/components/ultrawiki/EntityGraph";+import { VaultBar } from "@/components/ultrawiki/VaultBar";export interface ExplorePanelProps {onOpenSources: () => void;@@ -228,6 +229,8 @@ export function ExplorePanel({</div></div>+ <VaultBar />+<p className="sr-only" data-testid="explore-corpus">{corpus.sources}/{corpus.items}/{corpus.distilled}</p>diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/VaultBar.test.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/VaultBar.test.tsxnew file mode 100644index 0000000000..5f43260b6a--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/VaultBar.test.tsx@@ -0,0 +1,187 @@+/**+ * VaultBar tests — the Obsidian half of the readable knowledge base.+ *+ * What matters here is that the bar stays truthful about a machine that does+ * not have Obsidian (every headless server, most fresh installs): the export+ * must still be offered and must still work, and the missing app must be+ * stated rather than shown as a dead button.+ */+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";++import { VaultBar } from "@/components/ultrawiki/VaultBar";++const STATUS_FRESH = {+ ok: true,+ path: "/home/me/data/ultrawiki-vault",+ exists: false,+ notes: 0,+ last_export_at: "",+ obsidian: { installed: true, registered: false, config_path: "", error: "" },+};++const STATUS_EXPORTED = {+ ...STATUS_FRESH,+ exists: true,+ notes: 3145,+ last_export_at: "2026-07-26T09:00:00Z",+};++function installRoutes(routes: Record<string, unknown>) {+ const calls: string[] = [];+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ calls.push(`${init?.method ?? "GET"} ${url}`);+ const key = Object.keys(routes)+ .sort((a, b) => b.length - a.length)+ .find((prefix) => url.startsWith(prefix));+ if (!key) throw new Error(`unrouted: ${url}`);+ const body = routes[key];+ return {+ ok: true,+ status: 200,+ json: async () => body,+ } as unknown as Response;+ }),+ );+ return calls;+}++function renderBar() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false, gcTime: 0, staleTime: 0 } },+ });+ return render(+ <QueryClientProvider client={client}>+ <VaultBar />+ </QueryClientProvider>,+ );+}++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++describe("state", () => {+ it("shows where the vault will go before anything was exported", async () => {+ installRoutes({ "/api/ultrawiki/vault/status": STATUS_FRESH });+ renderBar();++ const path = await screen.findByTestId("vault-path");+ expect(path.textContent).toContain("ultrawiki-vault");+ expect((await screen.findByTestId("vault-state")).textContent).toBeTruthy();+ });++ it("reports how many notes are on disk once exported", async () => {+ installRoutes({ "/api/ultrawiki/vault/status": STATUS_EXPORTED });+ renderBar();++ expect((await screen.findByTestId("vault-state")).textContent).toContain(+ "3145",+ );+ });+});++describe("exporting", () => {+ it("writes the vault and reports the result", async () => {+ const calls = installRoutes({+ "/api/ultrawiki/vault/status": STATUS_FRESH,+ "/api/ultrawiki/vault/export": {+ ok: true,+ path: "/home/me/data/ultrawiki-vault",+ topics: 1127,+ moments: 2092,+ written: 3223,+ unchanged: 0,+ removed: 0,+ },+ });+ renderBar();++ fireEvent.click(await screen.findByTestId("vault-export"));++ await waitFor(() =>+ expect(calls.some((c) => c.startsWith("POST") && c.includes("export"))).toBe(+ true,+ ),+ );+ expect((await screen.findByTestId("vault-result")).textContent).toContain(+ "3223",+ );+ });+});++describe("Obsidian", () => {+ it("offers registration once the vault exists", async () => {+ installRoutes({+ "/api/ultrawiki/vault/status": STATUS_EXPORTED,+ "/api/ultrawiki/vault/register": { ok: true, status: "added" },+ });+ renderBar();++ fireEvent.click(await screen.findByTestId("vault-register"));++ await waitFor(() =>+ expect(screen.getByTestId("vault-register").hasAttribute("disabled")).toBe(+ false,+ ),+ );+ });++ it("hides registration while there is nothing to register", async () => {+ installRoutes({ "/api/ultrawiki/vault/status": STATUS_FRESH });+ renderBar();++ await screen.findByTestId("vault-export");+ expect(screen.queryByTestId("vault-register")).toBeNull();+ });++ it("says Obsidian is missing instead of offering a dead button", async () => {+ installRoutes({+ "/api/ultrawiki/vault/status": {+ ...STATUS_EXPORTED,+ obsidian: {+ installed: false,+ registered: false,+ config_path: "",+ error: "",+ },+ },+ });+ renderBar();++ expect(await screen.findByTestId("vault-no-obsidian")).toBeTruthy();+ expect(screen.queryByTestId("vault-register")).toBeNull();+ // The export stays available: the files are the point, the app is not.+ expect(screen.getByTestId("vault-export")).toBeTruthy();+ });++ it("states that the vault is already known to Obsidian", async () => {+ installRoutes({+ "/api/ultrawiki/vault/status": {+ ...STATUS_EXPORTED,+ obsidian: {+ installed: true,+ registered: true,+ config_path: "",+ error: "",+ },+ },+ });+ renderBar();++ expect(await screen.findByTestId("vault-registered")).toBeTruthy();+ expect(screen.queryByTestId("vault-register")).toBeNull();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/VaultBar.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/VaultBar.tsxnew file mode 100644index 0000000000..44f707e527--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/VaultBar.tsx@@ -0,0 +1,163 @@+/**+ * The Obsidian vault: the same knowledge as Markdown files on disk.+ *+ * Deliberately a quiet strip at the bottom of Explore rather than its own+ * tab. The in-app view is the floor — it works on every machine, including a+ * headless server that will never have Obsidian — and the vault is the+ * addition for people who want their knowledge in their own editor.+ *+ * Which is also why a machine without Obsidian gets a sentence, not a+ * disabled button: the export still runs there and the files are still the+ * deliverable.+ */+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { Check, FolderOpen, Loader2 } from "lucide-react";++import { useT } from "@/i18n";+import {+ exportVault,+ fetchVaultStatus,+ registerVaultWithObsidian,+ type UltraWikiVaultExport,+} from "@/lib/ultrawikiExploreApi";++const STATUS_KEY = ["ultrawiki", "vault", "status"] as const;++export function VaultBar(): JSX.Element | null {+ const t = useT();+ const queryClient = useQueryClient();++ const statusQuery = useQuery({+ queryKey: STATUS_KEY,+ queryFn: fetchVaultStatus,+ staleTime: 10_000,+ });++ const exportMutation = useMutation<UltraWikiVaultExport, Error>({+ mutationFn: exportVault,+ onSuccess: () => queryClient.invalidateQueries({ queryKey: STATUS_KEY }),+ });++ const registerMutation = useMutation({+ mutationFn: registerVaultWithObsidian,+ onSuccess: () => queryClient.invalidateQueries({ queryKey: STATUS_KEY }),+ });++ const status = statusQuery.data;+ if (!status) return null;++ const canRegister =+ status.exists && status.obsidian.installed && !status.obsidian.registered;+ const failure = exportMutation.error ?? registerMutation.error;++ return (+ <div+ data-testid="vault-bar"+ className="border-t border-border bg-card/40 px-4 py-2.5"+ >+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5">+ <FolderOpen className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />+ <span className="text-xs text-foreground">+ {t("ultrawiki.explore.vault.title")}+ </span>++ <span+ data-testid="vault-state"+ className="text-[11px] tabular-nums text-muted-foreground"+ >+ {status.exists+ ? `${t("ultrawiki.explore.vault.notes").replace("{0}", String(status.notes))}${+ status.last_export_at+ ? ` · ${t("ultrawiki.explore.vault.last").replace(+ "{0}",+ status.last_export_at.slice(0, 10),+ )}`+ : ""+ }`+ : t("ultrawiki.explore.vault.never")}+ </span>++ <span className="flex-1" />++ <button+ type="button"+ data-testid="vault-export"+ onClick={() => exportMutation.mutate()}+ disabled={exportMutation.isPending}+ className="inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-[11px] text-foreground transition-colors hover:border-primary/50 disabled:opacity-60"+ >+ {exportMutation.isPending && (+ <Loader2 className="h-3 w-3 animate-spin" aria-hidden />+ )}+ {exportMutation.isPending+ ? t("ultrawiki.explore.vault.exporting")+ : t("ultrawiki.explore.vault.export")}+ </button>++ {canRegister && (+ <button+ type="button"+ data-testid="vault-register"+ onClick={() => registerMutation.mutate()}+ disabled={registerMutation.isPending}+ className="inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-[11px] text-foreground transition-colors hover:border-primary/50 disabled:opacity-60"+ >+ {registerMutation.isPending+ ? t("ultrawiki.explore.vault.registering")+ : t("ultrawiki.explore.vault.register")}+ </button>+ )}++ {status.obsidian.registered && (+ <span+ data-testid="vault-registered"+ className="inline-flex items-center gap-1 text-[11px] text-muted-foreground"+ >+ <Check className="h-3 w-3" aria-hidden />+ {t("ultrawiki.explore.vault.registered")}+ </span>+ )}+ </div>++ <p+ data-testid="vault-path"+ className="mt-1 truncate font-mono text-[10px] text-muted-foreground"+ title={status.path}+ >+ {status.path}+ </p>++ {!status.obsidian.installed && (+ <p+ data-testid="vault-no-obsidian"+ className="mt-1 text-[11px] text-muted-foreground"+ >+ {t("ultrawiki.explore.vault.not_installed")}+ </p>+ )}++ {exportMutation.data && (+ <p+ data-testid="vault-result"+ className="mt-1 text-[11px] tabular-nums text-muted-foreground"+ >+ {t("ultrawiki.explore.vault.exported")+ .replace("{0}", String(exportMutation.data.written))+ .replace("{1}", String(exportMutation.data.unchanged))}+ </p>+ )}++ {failure && (+ <p+ role="alert"+ data-testid="vault-error"+ className="mt-1 text-[11px] text-destructive"+ >+ {t("ultrawiki.explore.vault.error").replace("{0}", failure.message)}+ </p>+ )}+ </div>+ );+}++export default VaultBar;diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex daaa9287a9..5c2df94e6d 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -2711,6 +2711,53 @@"result_error": "Discord nicht erreichbar, bitte später erneut versuchen."},"ultrawiki": {+ "explore": {+ "vault": {+ "title": "Obsidian-Vault",+ "hint": "Dieselben Inhalte als Markdown-Dateien auf der Festplatte.",+ "export": "Exportieren",+ "exporting": "Wird geschrieben …",+ "exported": "{0} Notizen geschrieben, {1} unverändert.",+ "notes": "{0} Notizen",+ "never": "Noch nie exportiert",+ "last": "Zuletzt am {0}",+ "register": "Bei Obsidian anmelden",+ "registering": "Wird angemeldet …",+ "registered": "In Obsidian eingetragen",+ "not_installed": "Obsidian ist auf diesem Gerät nicht installiert. Die Dateien liegen trotzdem bereit — du kannst sie mit jedem Markdown-Programm öffnen.",+ "error": "Hat nicht geklappt: {0}"+ },+ "tab": "Entdecken",+ "loading": "Wissensbestand wird gelesen …",+ "error": "Der Wissensbestand konnte nicht gelesen werden.",+ "entities_title": "Begriffe",+ "entities_count": "{0} Begriffe",+ "moments_title": "Momente",+ "moments_count": "{0} Momente",+ "graph_title": "Verbindungen",+ "search_placeholder": "Begriff suchen …",+ "no_search_hits": "Kein Begriff passt zu „{0}“.",+ "mentions": "{0}×",+ "mentions_long": "{0} Erwähnungen",+ "period": "{0} bis {1}",+ "neighbors": "Taucht auf mit",+ "no_neighbors": "Kommt bisher immer allein vor.",+ "shared": "{0} gemeinsame Momente",+ "back": "Zurück zur Übersicht",+ "open_source": "Beleg öffnen",+ "source_prefix": "aus",+ "min_mentions": "Ab {0} Erwähnungen",+ "graph_shown": "{0} von {1} Begriffen",+ "graph_hint": "Weniger häufige Begriffe sind ausgeblendet — Regler nach links für alle.",+ "graph_empty": "Kein Begriff wird oft genug erwähnt. Stell den Regler auf 1.",+ "moments_of": "Momente mit {0}",+ "empty": {+ "no_sources": "Es ist noch keine Quelle verbunden. Verbinde zuerst eine Quelle, dann kann Jarvis etwas wissen.",+ "nothing_imported": "Eine Quelle ist verbunden, aber es wurde noch nichts geholt. Starte den Import bei den Quellen.",+ "nothing_distilled": "Es liegen Einträge da, aber noch keiner wurde ausgewertet. Dafür braucht es ein eingerichtetes Sprachmodell in den Einstellungen.",+ "no_entities": "Die Einträge wurden ausgewertet, aber es kamen keine Namen oder Orte darin vor. Die Momente unten kannst du trotzdem durchblättern."+ }+ },"explore": {"tab": "Entdecken","loading": "Wissensbestand wird gelesen …",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 3cb64e5a5a..892a298a7e 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -2712,6 +2712,53 @@"result_error": "Couldn't reach Discord, please try again later."},"ultrawiki": {+ "explore": {+ "vault": {+ "title": "Obsidian vault",+ "hint": "The same knowledge as Markdown files on disk.",+ "export": "Export",+ "exporting": "Writing …",+ "exported": "{0} notes written, {1} unchanged.",+ "notes": "{0} notes",+ "never": "Never exported",+ "last": "Last run {0}",+ "register": "Add to Obsidian",+ "registering": "Adding …",+ "registered": "Added to Obsidian",+ "not_installed": "Obsidian is not installed on this machine. The files are written anyway — any Markdown app can open them.",+ "error": "That did not work: {0}"+ },+ "tab": "Explore",+ "loading": "Reading the knowledge base …",+ "error": "The knowledge base could not be read.",+ "entities_title": "Topics",+ "entities_count": "{0} topics",+ "moments_title": "Moments",+ "moments_count": "{0} moments",+ "graph_title": "Connections",+ "search_placeholder": "Search a topic …",+ "no_search_hits": "No topic matches “{0}”.",+ "mentions": "{0}×",+ "mentions_long": "{0} mentions",+ "period": "{0} to {1}",+ "neighbors": "Appears with",+ "no_neighbors": "Has only ever appeared on its own.",+ "shared": "{0} shared moments",+ "back": "Back to the overview",+ "open_source": "Open the evidence",+ "source_prefix": "from",+ "min_mentions": "From {0} mentions",+ "graph_shown": "{0} of {1} topics",+ "graph_hint": "Rarer topics are hidden — move the slider left to show all.",+ "graph_empty": "No topic is mentioned often enough. Set the slider to 1.",+ "moments_of": "Moments involving {0}",+ "empty": {+ "no_sources": "No source is connected yet. Connect one first, then Jarvis has something to know.",+ "nothing_imported": "A source is connected but nothing has been fetched yet. Start the import under Sources.",+ "nothing_distilled": "Entries are stored but none has been analysed yet. That needs a language model configured in the settings.",+ "no_entities": "The entries were analysed but named no people or places. You can still browse the moments below."+ }+ },"explore": {"tab": "Explore","loading": "Reading the knowledge base …",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex ad8d95e186..b8831473ce 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -2711,6 +2711,53 @@"result_error": "No se pudo llegar a Discord, inténtalo de nuevo más tarde."},"ultrawiki": {+ "explore": {+ "vault": {+ "title": "Bóveda de Obsidian",+ "hint": "El mismo conocimiento como archivos Markdown en el disco.",+ "export": "Exportar",+ "exporting": "Escribiendo …",+ "exported": "{0} notas escritas, {1} sin cambios.",+ "notes": "{0} notas",+ "never": "Nunca exportado",+ "last": "Última vez {0}",+ "register": "Añadir a Obsidian",+ "registering": "Añadiendo …",+ "registered": "Añadido a Obsidian",+ "not_installed": "Obsidian no está instalado en este equipo. Los archivos se escriben igualmente: cualquier app de Markdown puede abrirlos.",+ "error": "No funcionó: {0}"+ },+ "tab": "Explorar",+ "loading": "Leyendo la base de conocimiento …",+ "error": "No se pudo leer la base de conocimiento.",+ "entities_title": "Temas",+ "entities_count": "{0} temas",+ "moments_title": "Momentos",+ "moments_count": "{0} momentos",+ "graph_title": "Conexiones",+ "search_placeholder": "Buscar un tema …",+ "no_search_hits": "Ningún tema coincide con «{0}».",+ "mentions": "{0}×",+ "mentions_long": "{0} menciones",+ "period": "{0} a {1}",+ "neighbors": "Aparece junto a",+ "no_neighbors": "Hasta ahora siempre aparece solo.",+ "shared": "{0} momentos compartidos",+ "back": "Volver al resumen",+ "open_source": "Abrir la evidencia",+ "source_prefix": "de",+ "min_mentions": "Desde {0} menciones",+ "graph_shown": "{0} de {1} temas",+ "graph_hint": "Los temas menos frecuentes están ocultos: mueve el control a la izquierda para verlos todos.",+ "graph_empty": "Ningún tema se menciona lo suficiente. Pon el control en 1.",+ "moments_of": "Momentos con {0}",+ "empty": {+ "no_sources": "Todavía no hay ninguna fuente conectada. Conecta una primero y Jarvis tendrá algo que saber.",+ "nothing_imported": "Hay una fuente conectada pero aún no se ha traído nada. Inicia la importación en Fuentes.",+ "nothing_distilled": "Hay entradas guardadas pero ninguna se ha analizado todavía. Para eso hace falta un modelo de lenguaje configurado en los ajustes.",+ "no_entities": "Las entradas se analizaron pero no mencionaron personas ni lugares. Aun así puedes hojear los momentos de abajo."+ }+ },"explore": {"tab": "Explorar","loading": "Leyendo la base de conocimiento …",diff --git a/jarvis/ui/web/frontend/src/lib/ultrawikiExploreApi.ts b/jarvis/ui/web/frontend/src/lib/ultrawikiExploreApi.tsindex 0ee59ce0db..202d0aab0b 100644--- a/jarvis/ui/web/frontend/src/lib/ultrawikiExploreApi.ts+++ b/jarvis/ui/web/frontend/src/lib/ultrawikiExploreApi.ts@@ -183,3 +183,68 @@ export async function fetchExploreGraph(export function exploreReasonKey(reason: UltraWikiExploreReason): string {return `ultrawiki.explore.empty.${reason}`;}++/** What Obsidian knows about the vault on this machine. */+export interface UltraWikiObsidianState {+ installed: boolean;+ registered: boolean;+ config_path: string;+ error: string;+}++export interface UltraWikiVaultStatus {+ ok: boolean;+ path: string;+ exists: boolean;+ notes: number;+ last_export_at: string;+ obsidian: UltraWikiObsidianState;+}++export interface UltraWikiVaultExport {+ ok: boolean;+ path: string;+ topics: number;+ moments: number;+ written: number;+ unchanged: number;+ removed: number;+}++export interface UltraWikiVaultRegistration {+ ok: boolean;+ status: string;+ path: string;+ error: string;+}++async function postJson<T>(path: string): Promise<T> {+ const response = await fetch(path, { method: "POST" });+ if (!response.ok) {+ let detail = "";+ try {+ const body = await response.json();+ detail = String((body as { detail?: unknown })?.detail ?? "");+ } catch {+ detail = "";+ }+ throw new UltraWikiApiError(+ detail || `HTTP ${response.status}`,+ response.status,+ detail,+ );+ }+ return (await response.json()) as T;+}++export async function fetchVaultStatus(): Promise<UltraWikiVaultStatus> {+ return getJson<UltraWikiVaultStatus>("/api/ultrawiki/vault/status");+}++export async function exportVault(): Promise<UltraWikiVaultExport> {+ return postJson<UltraWikiVaultExport>("/api/ultrawiki/vault/export");+}++export async function registerVaultWithObsidian(): Promise<UltraWikiVaultRegistration> {+ return postJson<UltraWikiVaultRegistration>("/api/ultrawiki/vault/register");+}diff --git a/jarvis/ui/web/ultrawiki_explore_routes.py b/jarvis/ui/web/ultrawiki_explore_routes.pyindex 787ea2e43c..78333b4a6d 100644--- a/jarvis/ui/web/ultrawiki_explore_routes.py+++ b/jarvis/ui/web/ultrawiki_explore_routes.py@@ -17,6 +17,7 @@ definition of "is UltraWiki answering right now", never a second opinion.from __future__ import annotations+import asyncioimport loggingfrom typing import Any@@ -217,4 +218,146 @@ async def get_explore_graph("total_entities": len(projection.entities),"corpus": corpus,"reason": _explore_reason(corpus, len(projection.entities)),- }\ No newline at end of file+ }++# ---------------------------------------------------------------------------+# Vault — the same projection as Markdown files an Obsidian can open+# ---------------------------------------------------------------------------+++def _vault_root(request: Request) -> Any:+ from jarvis.ultrawiki.vault_export import resolve_vault_root++ cfg = getattr(request.app.state, "config", None)+ memory = getattr(cfg, "memory", None)+ ultra = getattr(cfg, "ultrawiki", None)+ return resolve_vault_root(+ getattr(memory, "data_dir", None), str(getattr(ultra, "vault_path", "") or "")+ )+++def _obsidian_state(vault: Any) -> dict[str, Any]:+ """What Obsidian knows about this vault, honestly on every OS.++ Obsidian is absent on a headless server and on most fresh machines. That+ is a normal state, not an error: the files are the deliverable, and the+ app is the optional reader.+ """+ from jarvis.setup import obsidian as obsidian_mod++ try:+ detection = obsidian_mod.detect_obsidian()+ state = obsidian_mod.read_obsidian_vaults()+ registered = obsidian_mod.is_vault_registered(list(state.vaults), vault)+ config_path = str(getattr(state, "config_path", "") or "")+ error = ""+ except Exception as exc: # noqa: BLE001 — a probe must never break the page+ log.debug("obsidian probe failed: %s", exc)+ return {+ "installed": False,+ "registered": False,+ "config_path": "",+ "error": str(exc),+ }+ return {+ "installed": bool(detection.installed),+ "registered": bool(registered),+ "config_path": config_path,+ "error": error,+ }+++def _vault_stats(vault: Any) -> dict[str, Any]:+ from jarvis.ultrawiki.vault_export import MANIFEST_NAME++ if not vault.is_dir():+ return {"exists": False, "notes": 0, "last_export_at": ""}+ notes = sum(1 for _ in vault.rglob("*.md"))+ manifest = vault / MANIFEST_NAME+ stamp = ""+ if manifest.exists():+ from datetime import UTC, datetime++ stamp = (+ datetime.fromtimestamp(manifest.stat().st_mtime, tz=UTC)+ .isoformat()+ .replace("+00:00", "Z")+ )+ return {"exists": True, "notes": notes, "last_export_at": stamp}++[email protected]("/vault/status", summary="Where the Obsidian vault is and what is in it")+async def get_vault_status(request: Request) -> dict[str, Any]:+ """Path, note count, last export, and whether Obsidian knows about it."""+ _require_active(request)+ vault = _vault_root(request)+ # Both probes walk the filesystem; off the event loop so a slow disk or a+ # scanned directory cannot stall every other request.+ stats = await asyncio.to_thread(_vault_stats, vault)+ obsidian = await asyncio.to_thread(_obsidian_state, vault)+ return {"ok": True, "path": str(vault), "obsidian": obsidian, **stats}+++ "/vault/export",+ summary="Write the knowledge base to the Obsidian vault",+ openapi_extra={"x-jarvis-dangerous": True},+)+async def export_vault_now(request: Request) -> dict[str, Any]:+ """Rewrite the generated folders. Notes under "My notes/" are never touched.++ Runs in a worker thread: a first export writes thousands of files, and+ holding the event loop for that would freeze every other surface in the+ app — including a voice turn in progress.+ """+ from jarvis.ultrawiki.projection import get_projection+ from jarvis.ultrawiki.vault_export import export_vault++ service = _require_active(request)+ store = await _store_of(service)+ projection = await get_projection(store)+ vault = _vault_root(request)+ try:+ result = await asyncio.to_thread(export_vault, projection, vault)+ except OSError as exc:+ raise HTTPException(+ status_code=500,+ detail=f"could not write the vault at {vault}: {exc}",+ ) from exc+ return {+ "ok": True,+ "path": str(result.root),+ "topics": result.topics,+ "moments": result.moments,+ "written": result.written,+ "unchanged": result.unchanged,+ "removed": result.removed,+ }+++ "/vault/register",+ summary="Register the vault with the Obsidian app",+ openapi_extra={"x-jarvis-dangerous": True},+)+async def register_vault_with_obsidian(request: Request) -> dict[str, Any]:+ """Add the vault to Obsidian's own index so it appears in the app."""+ from jarvis.setup import obsidian as obsidian_mod++ _require_active(request)+ vault = _vault_root(request)+ if not vault.is_dir():+ raise HTTPException(+ status_code=409,+ detail=(+ "the vault does not exist yet — run the export first, "+ "otherwise Obsidian would open an empty folder"+ ),+ )+ result = await asyncio.to_thread(obsidian_mod.register_vault, vault)+ return {+ "ok": result.status in ("added", "already_registered"),+ "status": result.status,+ "path": str(vault),+ "error": getattr(result, "error", "") or "",+ }diff --git a/jarvis/ultrawiki/vault_export.py b/jarvis/ultrawiki/vault_export.pyindex 8c0c26d339..eda95ab20b 100644--- a/jarvis/ultrawiki/vault_export.py+++ b/jarvis/ultrawiki/vault_export.py@@ -49,6 +49,7 @@ __all__ = ["ExportResult","assign_note_names","export_vault",+ "resolve_vault_root","safe_note_name",]@@ -114,6 +115,25 @@ class ExportResult:removed: int+def resolve_vault_root(+ data_dir: str | Path | None = None, configured: str = ""+) -> Path:+ """One absolute vault path, independent of the process working directory.++ Mirrors ``resolve_ultrawiki_db_path``: a relative path (including the+ ``./data`` default) is anchored at the repo root, never at whatever+ directory the app happened to start in.+ """+ from jarvis.core.paths import repo_root # lazy: keep module import cheap++ if configured.strip():+ raw = Path(configured.strip())+ return (raw if raw.is_absolute() else repo_root() / raw).resolve(strict=False)+ base = Path(data_dir) if data_dir is not None else Path("data")+ directory = base if base.is_absolute() else repo_root() / base+ return (directory / "ultrawiki-vault").resolve(strict=False)++def safe_note_name(label: str) -> str:"""A filename stem that is legal and identical on Windows, macOS and Linux.diff --git a/tests/unit/web/test_ultrawiki_vault_routes.py b/tests/unit/web/test_ultrawiki_vault_routes.pynew file mode 100644index 0000000000..322f932a03--- /dev/null+++ b/tests/unit/web/test_ultrawiki_vault_routes.py@@ -0,0 +1,232 @@+"""Full-app tests for the /api/ultrawiki/vault REST surface.++The vault is the Obsidian half of the readable knowledge base: the same+projection written to disk as Markdown. These routes are what the UI drives —+where the vault is, what is in it, whether Obsidian knows about it, and the+two actions (export, register).++The honesty cases carry the weight. Obsidian is absent on a headless server+and on most fresh machines, and an export must still work there and say so;+a failed write must name the path and the OS error rather than a spinner that+never ends.+"""++from __future__ import annotations++import json+from pathlib import Path+from types import SimpleNamespace++import pytest+from fastapi.testclient import TestClient++from jarvis.core.bus import EventBus+from jarvis.core.config import JarvisConfig+from jarvis.ui.web.server import WebServer+from jarvis.ultrawiki import service as uw_service_mod+from jarvis.ultrawiki.service import UltraWikiService+from jarvis.ultrawiki.types import DocType, ItemState, RawItem+++def env(tmp_path: Path, monkeypatch):+ toml_path = tmp_path / "jarvis.toml"+ toml_path.write_text("", encoding="utf-8")+ monkeypatch.setenv("JARVIS_CONFIG", str(toml_path))++ cfg = JarvisConfig()+ cfg.ui.dev_mode = True+ cfg.memory.data_dir = str(tmp_path / "data")+ cfg.ultrawiki.enabled = True+ cfg.ultrawiki.vault_path = str(tmp_path / "vault")++ server = WebServer(cfg, bus=EventBus())+ service = UltraWikiService(cfg, embedding_backend_factory=lambda: None)+ server.app.state.ultrawiki = service+ uw_service_mod.clear_jobs()+ with TestClient(server.app) as client:+ yield SimpleNamespace(+ client=client, service=service, server=server, cfg=cfg, tmp=tmp_path+ )+ client.portal.call(service.shutdown)+ uw_service_mod.clear_jobs()+++def seed(env) -> None:+ async def _run() -> None:+ await env.service.ensure_started()+ store = env.service._store # noqa: SLF001 — documented test seam+ await store.upsert_source("src1", connector="local-folder", label="Docs")+ await store.upsert_items(+ "src1",+ [+ RawItem(+ external_id="a",+ body="Routes via Tahiti.",+ permalink="app://a",+ timestamp_utc="2026-03-01T10:00:00Z",+ title="Conversation on 2026-03-01",+ )+ ],+ )+ item = await store.get_item_by_external_id("src1", "a")+ await store.add_document(+ item["id"],+ DocType.SUMMARY,+ "Routes via Tahiti.",+ distill_json=json.dumps(+ {+ "question": "How do I get to Bora Bora?",+ "summary": "Routes via Tahiti.",+ "resolution": "",+ "entities": ["Bora Bora", "Tahiti"],+ "refs": [],+ }+ ),+ distill_version=1,+ )+ await store.mark_stage_done(item["id"], ItemState.DISTILLED)++ env.client.portal.call(_run)+++def stub_obsidian(monkeypatch, *, installed: bool, registered: bool = False):+ from jarvis.setup import obsidian as obsidian_mod++ monkeypatch.setattr(+ obsidian_mod,+ "detect_obsidian",+ lambda *a, **k: obsidian_mod.ObsidianDetection(installed=installed),+ )+ monkeypatch.setattr(+ obsidian_mod,+ "read_obsidian_vaults",+ lambda *a, **k: SimpleNamespace(vaults=[], config_path=Path("nowhere.json")),+ )+ monkeypatch.setattr(+ obsidian_mod, "is_vault_registered", lambda *a, **k: registered+ )+++# ---------------------------------------------------------------------------+# Status+# ---------------------------------------------------------------------------+++def test_status_names_the_path_before_anything_was_exported(env, monkeypatch):+ stub_obsidian(monkeypatch, installed=False)++ body = env.client.get("/api/ultrawiki/vault/status").json()++ assert body["ok"] is True+ assert body["path"].endswith("vault")+ assert body["exists"] is False+ assert body["notes"] == 0+ assert body["obsidian"]["installed"] is False+++def test_status_reports_what_the_export_left_behind(env, monkeypatch):+ stub_obsidian(monkeypatch, installed=True)+ seed(env)+ env.client.post("/api/ultrawiki/vault/export")++ body = env.client.get("/api/ultrawiki/vault/status").json()++ assert body["exists"] is True+ assert body["notes"] > 0+ assert body["last_export_at"]+++# ---------------------------------------------------------------------------+# Export+# ---------------------------------------------------------------------------+++def test_export_writes_the_vault_and_reports_the_numbers(env, monkeypatch):+ stub_obsidian(monkeypatch, installed=False)+ seed(env)++ response = env.client.post("/api/ultrawiki/vault/export")++ assert response.status_code == 200, response.text+ body = response.json()+ assert body["topics"] == 2+ assert body["moments"] == 1+ assert body["written"] > 0+ assert (env.tmp / "vault" / "Topics" / "Bora Bora.md").exists()+++def test_export_works_without_obsidian_installed(env, monkeypatch):+ # A headless server has no Obsidian and never will; the files are still+ # the point.+ stub_obsidian(monkeypatch, installed=False)+ seed(env)++ body = env.client.post("/api/ultrawiki/vault/export").json()++ assert body["ok"] is True+ assert (env.tmp / "vault" / "README.md").exists()+++def test_an_unwritable_vault_path_fails_with_the_reason(env, monkeypatch):+ stub_obsidian(monkeypatch, installed=False)+ seed(env)+ blocker = env.tmp / "blocked"+ blocker.write_text("not a directory", encoding="utf-8")+ env.cfg.ultrawiki.vault_path = str(blocker)++ response = env.client.post("/api/ultrawiki/vault/export")++ assert response.status_code == 500+ assert "blocked" in response.json()["detail"]+++def test_export_is_declared_dangerous(env):+ spec = env.server.app.openapi()+ operation = spec["paths"]["/api/ultrawiki/vault/export"]["post"]+ assert operation.get("x-jarvis-dangerous") is True+++# ---------------------------------------------------------------------------+# Obsidian registration+# ---------------------------------------------------------------------------+++def test_register_reports_success(env, monkeypatch):+ from jarvis.setup import obsidian as obsidian_mod++ stub_obsidian(monkeypatch, installed=True)+ seed(env)+ env.client.post("/api/ultrawiki/vault/export")+ monkeypatch.setattr(+ obsidian_mod,+ "register_vault",+ lambda *a, **k: obsidian_mod.RegisterResult(status="added"),+ )++ body = env.client.post("/api/ultrawiki/vault/register").json()++ assert body["status"] == "added"+++def test_register_refuses_before_the_vault_exists(env, monkeypatch):+ stub_obsidian(monkeypatch, installed=True)++ response = env.client.post("/api/ultrawiki/vault/register")++ # Registering a folder that is not there would make Obsidian show an+ # empty vault and the user conclude that nothing was ever exported.+ assert response.status_code == 409+ assert "export" in response.json()["detail"].lower()+++# ---------------------------------------------------------------------------+# Mode discipline+# ---------------------------------------------------------------------------+++def test_vault_routes_answer_409_while_ultra_mode_is_off(env):+ env.cfg.ultrawiki.enabled = False++ assert env.client.get("/api/ultrawiki/vault/status").status_code == 409+ assert env.client.post("/api/ultrawiki/vault/export").status_code == 409