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(wiki): reconcile vault index and expose repair
Ruben Lütke8f852efbecd4
diff --git a/docs/adr/0015-obsidian-setup-wizard.md b/docs/adr/0015-obsidian-setup-wizard.mdindex a1f55b63b6..8ffc33c05b 100644--- a/docs/adr/0015-obsidian-setup-wizard.md+++ b/docs/adr/0015-obsidian-setup-wizard.md@@ -45,6 +45,27 @@ the whole onboarding flow.The B9 onboarding wizard is a small, narrowly-scoped feature governedby six contracts.+### 2026-07-12 reliability amendment++Vault registration is based on reachability, not string equality. A+configured Jarvis directory is connected when it exactly matches a registered+Obsidian vault or is contained by one. This is required by existing-vault mode,+which stores Jarvis pages under `<registered-vault>/Jarvis`. When multiple+registered ancestors exist, the most specific one wins.++Deep links use `obsidian://open?path=<absolute-path>` so the same containment+rule governs status and navigation. Installation detection is optional and+platform-aware: Windows probes executable paths and the uninstall registry,+macOS probes the app bundle, and Linux probes `PATH` plus common install paths.+Missing desktop integration never prevents the Markdown wiki from operating on+a headless host.++The FTS database path is resolved once from `memory.data_dir` relative to the+repository root. Boot reconciliation and `POST /api/wiki/reindex` rebuild the+derived index from the configured vault, removing stale rows. Wiki health+compares visible Markdown pages with indexed pages and reports a stale index+without treating it as lost source data.+- **Pure detector + write split.** `detect_obsidian()`,`read_obsidian_vaults()`, and `is_vault_registered()` are read-onlyand never mutate disk. `register_vault()` is the sole mutator. Thediff --git a/docs/jarvis-cli-reference.md b/docs/jarvis-cli-reference.mdindex 5856d79e53..6936ab7e34 100644--- a/docs/jarvis-cli-reference.md+++ b/docs/jarvis-cli-reference.md@@ -185,6 +185,7 @@ _Generated from the curated command tree by `scripts/ci/gen_cli_reference.py`- `jarvis wiki health` — Show wiki subsystem health: bootstrap, last write, chain failures, backlog (spec A5).- `jarvis wiki page <slug>` — Read a wiki page by vault path / slug.- `jarvis wiki recall <query>` — Full-text search the wiki.+- `jarvis wiki reindex --preview` — Rebuild the wiki search index from the active vault.- `jarvis wiki tree` — Show the vault folder tree + stats.- `jarvis wiki vaults` — List the user's registered Obsidian vaults (connect picker, spec A6).diff --git a/docs/obsidian-setup.md b/docs/obsidian-setup.mdindex 817621765d..e87a69d0d8 100644--- a/docs/obsidian-setup.md+++ b/docs/obsidian-setup.md@@ -17,17 +17,17 @@ read or edit them by hand.-2. Open the Jarvis Desktop App and switch to the **Wiki** tab. In- the top-right corner you will see an orange pill labelled- **"Obsidian: nicht registriert"** (Obsidian: not registered). <!-- i18n-allow --> Click- it, then click **"Jetzt registrieren"** (Register now) in the dialog <!-- i18n-allow -->- that opens. Jarvis writes the vault into Obsidian's index file and- creates a timestamped backup of the previous version next to it.+2. Open the Jarvis Desktop App and switch to the **Wiki** tab. Choose+ either an existing Obsidian vault or a separate Jarvis vault. When+ an existing vault is selected, Jarvis stores its pages in a `Jarvis`+ subdirectory. The parent vault remains the registered Obsidian vault;+ Jarvis recognizes the nested directory as connected.3. Click **"In Obsidian oeffnen"** (Open in Obsidian) <!-- i18n-allow --> in the same- dialog. Obsidian opens directly into your Jarvis vault. Confirm the+ dialog. Jarvis sends the absolute page path to Obsidian, which selects+ the most specific registered parent vault and opens the page. Confirm thelive test succeeded by clicking **"Hat geklappt"** (It worked) — the <!-- i18n-allow -->wizard then closes for good and never auto-opens again on thismachine.@@ -38,8 +38,10 @@ read or edit them by hand.### "config_missing" — Obsidian not started yet-Obsidian only creates `%APPDATA%\obsidian\obsidian.json` the very-first time it launches. If the wizard reports `config_missing`, open+Obsidian only creates its vault index the first time it launches. It is+stored under `%APPDATA%\obsidian` on Windows, Application Support on+macOS, and the XDG configuration directory on Linux. If the wizard reports+`config_missing`, openObsidian once — even just briefly — close it again, then click**"Jetzt registrieren"** (Register now) in the Jarvis wizard. Thesecond attempt will find the file and succeed.@@ -67,10 +69,15 @@ but Obsidian maintains its own file cache that occasionally lags bya few seconds — especially right after the WikiCurator adds a newpage during a conversation.+If Jarvis search is stale, use **Rebuild index** in the Wiki health panel+or run `jarvis wiki reindex`. The command rebuilds the derived FTS index+from the configured vault and does not modify Markdown pages.+## Where the vault lives-The vault is on disk at `wiki/obsidian-vault/` inside the Personal-Jarvis repository. Any change you make in Obsidian appears inside+The vault location is selected during setup and stored in+`memory.wiki.vault_root`. It can be a standalone vault or the `Jarvis`+directory inside an existing Obsidian vault. Any change you make in Obsidian appears insidethe Jarvis Desktop App within seconds (the wiki-watcher monitorsthat directory). Conversely, any page Jarvis adds through itsWikiCurator appears in Obsidian on the next file-system poll.diff --git a/jarvis/cli_ctl/commands/wiki.py b/jarvis/cli_ctl/commands/wiki.pyindex 7dcd993f8c..357557dc54 100644--- a/jarvis/cli_ctl/commands/wiki.py+++ b/jarvis/cli_ctl/commands/wiki.py@@ -10,7 +10,10 @@ import typerfrom jarvis.cli_ctl import invoke-app = typer.Typer(no_args_is_help=True, help="Knowledge wiki: recall, page, tree.")+app = typer.Typer(+ no_args_is_help=True,+ help="Knowledge wiki: recall, pages, health, and search-index repair.",+)@app.command()@@ -41,3 +44,19 @@ def vaults() -> None:def health() -> None:"""Show wiki subsystem health: bootstrap, last write, chain failures, backlog (spec A5)."""invoke.run("GET", "/api/wiki/health")+++def reindex(+ preview: bool = typer.Option(+ False,+ "--preview",+ help="Inspect current and expected counts without rebuilding the index.",+ ),+) -> None:+ """Rebuild the wiki search index from the active vault."""+ invoke.run(+ "POST",+ "/api/wiki/reindex",+ params={"dry_run": str(preview).lower()},+ )diff --git a/jarvis/memory/wiki/atomic_writer.py b/jarvis/memory/wiki/atomic_writer.pyindex e7d901ce8f..81613af93c 100644--- a/jarvis/memory/wiki/atomic_writer.py+++ b/jarvis/memory/wiki/atomic_writer.py@@ -42,6 +42,7 @@ import osimport sqlite3import tempfileimport time+from collections.abc import Callablefrom dataclasses import dataclassfrom pathlib import Path@@ -112,12 +113,14 @@ class AtomicWriter:max_backups: int = DEFAULT_MAX_BACKUPS,backup_manager: BackupManager | None = None,concurrent_edit_lock_seconds: float = CONCURRENT_EDIT_LOCK_SECONDS,- clock: "callable[[], float] | None" = None,+ clock: Callable[[], float] | None = None,+ db_path: Path | None = None,) -> None:self._vault_root = Path(vault_root).resolve()self._backup_dir = Path(backup_dir).resolve()self._lock_seconds = float(concurrent_edit_lock_seconds)self._clock = clock or time.time+ self._db_path = Path(db_path).resolve(strict=False) if db_path else Noneif backup_manager is None:self._backups = BackupManager(vault_root=self._vault_root,@@ -596,16 +599,15 @@ class AtomicWriter:log.debug("atomic_writer: fts_index not available — skipping FTS upsert")return None+ if self._db_path is None:+ # Tests and standalone writers must opt into an index explicitly;+ # production injects the canonical configured DB path.+ return Noneif self._fts_conn is None:- # Derive DB path the same way search.py does: data/jarvis.db- # relative to the project root (4 levels above this file).- db_path = (- Path(__file__).resolve().parent.parent.parent.parent- / "data"- / "jarvis.db"+ self._db_path.parent.mkdir(parents=True, exist_ok=True)+ self._fts_conn = sqlite3.connect(+ str(self._db_path), check_same_thread=False,)- db_path.parent.mkdir(parents=True, exist_ok=True)- self._fts_conn = sqlite3.connect(str(db_path), check_same_thread=False)_fts.ensure_schema(self._fts_conn)return self._fts_conndiff --git a/jarvis/memory/wiki/db_path.py b/jarvis/memory/wiki/db_path.pynew file mode 100644index 0000000000..2788188717--- /dev/null+++ b/jarvis/memory/wiki/db_path.py@@ -0,0 +1,16 @@+"""Canonical SQLite path resolution for every wiki consumer."""+from __future__ import annotations++from pathlib import Path++from jarvis.core.paths import repo_root+++def resolve_wiki_db_path(data_dir: str | Path | None = None) -> Path:+ """Return one absolute ``jarvis.db`` path independent of process CWD."""+ raw = Path(data_dir) if data_dir is not None else Path("data")+ directory = raw if raw.is_absolute() else repo_root() / raw+ return (directory / "jarvis.db").resolve(strict=False)+++__all__ = ["resolve_wiki_db_path"]diff --git a/jarvis/memory/wiki/integration.py b/jarvis/memory/wiki/integration.pyindex a7fc17827c..4e8c9449b0 100644--- a/jarvis/memory/wiki/integration.py+++ b/jarvis/memory/wiki/integration.py@@ -270,10 +270,12 @@ async def bootstrap_wiki_integration(# ------------------------------------------------------------------# Build the curator stack# ------------------------------------------------------------------+ root_cfg = _load_root_config()curator = _build_curator(repo=repo,vault_root=vault_path,brain_caller=brain_caller,+ root_config=root_cfg,)# Publish the live curator so the ``wiki-ingest`` tool can find it.@@ -310,7 +312,6 @@ async def bootstrap_wiki_integration(# and to the D2 gate below — two independent load_config() calls could# diverge on a racy partial config write, making the gate inconsistent# with the worker's own wiki_write_enabled view.- root_cfg = _load_root_config()worker = _build_rollup_worker(repo=repo,vault_root=vault_path,@@ -422,11 +423,14 @@ async def bootstrap_wiki_integration(try:extractor_cfg = root_cfg.memory.wiki.extractorif bool(getattr(extractor_cfg, "enabled", True)):+ from jarvis.memory.wiki.db_path import resolve_wiki_db_pathfrom jarvis.memory.wiki.extractor import ConversationFactExtractorfrom jarvis.memory.wiki.journal import CandidateJournal- data_dir = Path(getattr(root_cfg.memory, "data_dir", "./data"))- journal = CandidateJournal(data_dir / "jarvis.db")+ db_path = resolve_wiki_db_path(+ getattr(root_cfg.memory, "data_dir", "./data")+ )+ journal = CandidateJournal(db_path)extractor = ConversationFactExtractor(config=root_cfg, journal=journal)handle._journal = journal # noqa: SLF001if scheduler is not None:@@ -450,7 +454,7 @@ async def bootstrap_wiki_integration(log.info("wiki_integration: Stage-1 fact extractor active ""(journal db=%s, journal trigger=%s)",- data_dir / "jarvis.db",+ db_path,"scheduler" if scheduler is not None else "off",)else:@@ -736,6 +740,7 @@ def _build_curator(repo: "PageRepository",vault_root: Path,brain_caller: Callable[[str, str], Awaitable[str]] | None,+ root_config: Any | None = None,) -> Any:"""Construct a :class:`~jarvis.memory.wiki.curator.WikiCurator` instance.@@ -745,18 +750,23 @@ def _build_curator(from jarvis.memory.wiki.atomic_writer import AtomicWriterfrom jarvis.memory.wiki.curator import WikiCuratorfrom jarvis.memory.wiki.curator_llm import WikiCuratorLLM+ from jarvis.memory.wiki.db_path import resolve_wiki_db_pathfrom jarvis.memory.wiki.log_writer import LogWriterfrom jarvis.memory.wiki.vault_index import VaultIndex+ if root_config is None:+ root_config = _load_root_config()++ db_path = resolve_wiki_db_path(root_config.memory.data_dir)backup_dir = vault_root.parent / "wiki-backups"- writer = AtomicWriter(vault_root=vault_root, backup_dir=backup_dir)+ writer = AtomicWriter(+ vault_root=vault_root,+ backup_dir=backup_dir,+ db_path=db_path,+ )log_writer = LogWriter(log_path=vault_root / "log.md")vault = VaultIndex(repo=repo)- # Load root config for the LLM; fall back to default config when not- # available in the current environment (logged inside the helper).- root_config = _load_root_config()-schema_path = vault_root / "schema.md"# CRIT-4 (2026-05-17 audit-7): missing schema.md silently broke every# wiki-ingest call -- WikiCuratorLLM._load_schema returned None,@@ -915,19 +925,21 @@ def _build_rollup_worker(from jarvis.memory.wiki.log_writer import LogWriterfrom jarvis.memory.wiki.session_rollup import SessionRollupWorker- backup_dir = vault_root.parent / "wiki-backups"- writer = AtomicWriter(vault_root=vault_root, backup_dir=backup_dir)- log_writer = LogWriter(log_path=vault_root / "log.md")-if root_config is None:root_config = _load_root_config()- try:- data_dir = Path(root_config.memory.data_dir)- except Exception: # noqa: BLE001- data_dir = Path("./data")+ from jarvis.memory.wiki.db_path import resolve_wiki_db_path++ db_path = resolve_wiki_db_path(root_config.memory.data_dir)+ backup_dir = vault_root.parent / "wiki-backups"+ writer = AtomicWriter(+ vault_root=vault_root,+ backup_dir=backup_dir,+ db_path=db_path,+ )+ log_writer = LogWriter(log_path=vault_root / "log.md")from jarvis.memory.recall import RecallStore- recall = RecallStore(data_dir / "jarvis.db")+ recall = RecallStore(db_path)# Schedule an async open so the connection is available when the worker# first fires. open() is idempotent — safe to call again if already open.try:diff --git a/jarvis/memory/wiki/search.py b/jarvis/memory/wiki/search.pyindex d9ddabb3b5..03dce56e7b 100644--- a/jarvis/memory/wiki/search.py+++ b/jarvis/memory/wiki/search.py@@ -288,9 +288,9 @@ def _default_db_path() -> Path:containing ``jarvis/`` as a package, then appends ``data/jarvis.db``.Falls back to a sibling ``data/`` if the walk fails."""- # This file is at jarvis/memory/wiki/search.py → project root is 3 levels up.- candidate = Path(__file__).resolve().parent.parent.parent.parent / "data" / "jarvis.db"- return candidate+ from jarvis.memory.wiki.db_path import resolve_wiki_db_path++ return resolve_wiki_db_path()__all__ = ["SearchHit", "VaultSearch"]diff --git a/jarvis/setup/obsidian.py b/jarvis/setup/obsidian.pyindex bdfdcbc3e0..6298b9dd0f 100644--- a/jarvis/setup/obsidian.py+++ b/jarvis/setup/obsidian.py@@ -94,15 +94,28 @@ class ObsidianVaultsState(BaseModel):# ---------------------------------------------------------------------------# Detection — Obsidian.exe install# ----------------------------------------------------------------------------def _candidate_install_paths() -> list[Path]:- """Return the ordered Obsidian.exe candidate paths.+def _candidate_install_paths(platform: str | None = None) -> list[Path]:+ """Return ordered platform-specific Obsidian install candidates.Order matters: per-user installs win over machine-wide installs onlybecause the per-user path is the official installer default. Order isdocumented in the public docstring of ``detect_obsidian``."""+ plat = platform if platform is not None else sys.platformcandidates: list[Path] = []+ if plat == "darwin":+ return [+ Path.home() / "Applications" / "Obsidian.app" / "Contents" / "MacOS" / "Obsidian",+ Path("/Applications/Obsidian.app/Contents/MacOS/Obsidian"),+ ]+ if plat != "win32":+ return [+ Path("/usr/bin/obsidian"),+ Path("/usr/local/bin/obsidian"),+ Path("/opt/Obsidian/obsidian"),+ ]+local_appdata = os.environ.get("LOCALAPPDATA")if local_appdata:candidates.append(Path(local_appdata) / "Programs" / "Obsidian" / "Obsidian.exe")@@ -170,8 +183,8 @@ def _read_version_best_effort(exe_path: Path) -> str | None:return None-def detect_obsidian() -> ObsidianDetection:- """Locate Obsidian.exe on this machine and return install status.+def detect_obsidian(platform: str | None = None) -> ObsidianDetection:+ """Locate Obsidian on this machine and return install status.Probe order:1. ``%LOCALAPPDATA%\\Programs\\Obsidian\\Obsidian.exe`` (per-user)@@ -185,15 +198,21 @@ def detect_obsidian() -> ObsidianDetection:``ObsidianDetection(installed=False, exe_path=None, version=None)``.This function NEVER raises and NEVER runs a subprocess."""- for candidate in _candidate_install_paths():+ plat = platform if platform is not None else sys.platform+ if plat != "win32":+ path_hit = shutil.which("obsidian")+ if path_hit:+ return ObsidianDetection(installed=True, exe_path=Path(path_hit))++ for candidate in _candidate_install_paths(platform=plat):if candidate.exists():return ObsidianDetection(installed=True,exe_path=candidate,- version=_read_version_best_effort(candidate),+ version=_read_version_best_effort(candidate) if plat == "win32" else None,)- registry_hit = _probe_uninstall_registry()+ registry_hit = _probe_uninstall_registry() if plat == "win32" else Noneif registry_hit is not None:return ObsidianDetection(installed=True,@@ -294,8 +313,8 @@ def read_obsidian_vaults(config_path: Path | None = None) -> ObsidianVaultsState# ---------------------------------------------------------------------------# Membership check — is our Jarvis vault already registered?# ----------------------------------------------------------------------------def _normalize_for_compare(path: Path) -> str:- """Normalise a path for case-insensitive Windows comparison.+def _normalize_for_compare(path: Path, platform: str | None = None) -> str:+ """Normalise a path using the host platform's case semantics.* ``Path.resolve()`` to absolutize and collapse ``..`` segments. Wecall ``resolve(strict=False)`` so non-existent paths still@@ -305,6 +324,11 @@ def _normalize_for_compare(path: Path) -> str:* Lowercase the whole string (Windows file system is case-insensitiveand this is a pure Windows feature)."""+ plat = platform if platform is not None else sys.platform+ raw = str(path)+ windows_style = plat == "win32" or (+ len(raw) >= 3 and raw[1] == ":" and raw[2] in ("\\", "/")+ )try:resolved = path.resolve(strict=False)except OSError:@@ -313,7 +337,7 @@ def _normalize_for_compare(path: Path) -> str:s = str(resolved)while s.endswith(("\\", "/")):s = s[:-1]- return s.lower()+ return s.lower() if windows_style else sdef is_vault_registered(vaults: list[VaultEntry], expected_vault_path: Path) -> bool:diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 0b317356d3..9a4b8a21e9 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -2216,6 +2216,11 @@"last_write_failed": "Letzter Schreibvorgang fehlgeschlagen: {0}","last_write_failed_unknown": "Letzter Schreibvorgang fehlgeschlagen","no_writes_yet": "Noch keine Schreibvorgänge erfasst",+ "pending_writes": "{0} Fakten warten auf das Schreiben",+ "index_stale": "Suchindex: {0}/{1} Seiten",+ "reindex": "Index neu aufbauen",+ "reindexing": "Index wird aufgebaut...",+ "reindex_failed": "Der Wiki-Suchindex konnte nicht neu aufgebaut werden.","bootstrap_failed": "Bootstrap fehlgeschlagen: {0}","bootstrap_failed_unknown": "Bootstrap fehlgeschlagen","chain_failure": "Kettenfehler: {0}",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex d53e27cf8f..82e5c35922 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -2217,6 +2217,11 @@"last_write_failed": "Last write failed: {0}","last_write_failed_unknown": "Last write failed","no_writes_yet": "No writes recorded yet",+ "pending_writes": "{0} facts are waiting to be written",+ "index_stale": "Search index: {0}/{1} pages",+ "reindex": "Rebuild index",+ "reindexing": "Rebuilding...",+ "reindex_failed": "The wiki search index could not be rebuilt.","bootstrap_failed": "Bootstrap failed: {0}","bootstrap_failed_unknown": "Bootstrap failed","chain_failure": "Chain failure: {0}",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 2bdfa12881..65f36ac229 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -2216,6 +2216,11 @@"last_write_failed": "Última escritura fallida: {0}","last_write_failed_unknown": "Última escritura fallida","no_writes_yet": "Aún no se han registrado escrituras",+ "pending_writes": "{0} hechos están pendientes de escritura",+ "index_stale": "Índice de búsqueda: {0}/{1} páginas",+ "reindex": "Reconstruir índice",+ "reindexing": "Reconstruyendo...",+ "reindex_failed": "No se pudo reconstruir el índice de búsqueda del wiki.","bootstrap_failed": "Bootstrap fallido: {0}","bootstrap_failed_unknown": "Bootstrap fallido","chain_failure": "Fallo en la cadena: {0}",diff --git a/jarvis/ui/web/frontend/src/lib/wikiApi.ts b/jarvis/ui/web/frontend/src/lib/wikiApi.tsindex cd52a874f3..9e5882847b 100644--- a/jarvis/ui/web/frontend/src/lib/wikiApi.ts+++ b/jarvis/ui/web/frontend/src/lib/wikiApi.ts@@ -125,6 +125,16 @@ export interface WikiHealthSnapshot {last_write: WikiHealthLastWrite | null;last_chain_failure: WikiHealthLastChainFailure | null;journal_backlog: number;+ indexed_pages: number;+ vault_pages: number;+ index_state: "ok" | "stale";+}++export interface WikiReindexResponse {+ ok: boolean;+ indexed_pages?: number;+ vault_pages?: number;+ error?: string;}async function getJson<T>(url: string): Promise<T> {@@ -184,3 +194,11 @@ export async function fetchWikiHealth(): Promise<WikiHealthSnapshot | null> {return null;}}++export async function rebuildWikiIndex(): Promise<WikiReindexResponse> {+ const res = await fetch("/api/wiki/reindex", { method: "POST" });+ if (!res.ok) {+ throw new Error(`HTTP ${res.status} ${res.statusText}`);+ }+ return (await res.json()) as WikiReindexResponse;+}diff --git a/jarvis/ui/web/frontend/src/views/WikiView.test.tsx b/jarvis/ui/web/frontend/src/views/WikiView.test.tsxindex 77c39b8324..f1f32f3212 100644--- a/jarvis/ui/web/frontend/src/views/WikiView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/WikiView.test.tsx@@ -217,6 +217,9 @@ describe("WikiView — health strip", () => {},last_chain_failure: null,journal_backlog: 0,+ indexed_pages: 1,+ vault_pages: 1,+ index_state: "ok",};const FAILED_HEALTH: WikiHealthSnapshot = {@@ -234,6 +237,9 @@ describe("WikiView — health strip", () => {},last_chain_failure: null,journal_backlog: 3,+ indexed_pages: 0,+ vault_pages: 1,+ index_state: "stale",};it("renders the vault path for a healthy snapshot", async () => {@@ -273,6 +279,26 @@ describe("WikiView — health strip", () => {).toBe("red");expect(screen.getByTestId("wiki-health-backlog").textContent).toContain("3");});++ it("rebuilds a stale search index from the health strip", async () => {+ const stale = { ...HEALTHY_HEALTH, indexed_pages: 0, index_state: "stale" as const };+ const fetchMock = installFetchMock({+ "/api/wiki/tree": () => EMPTY_TREE,+ "/api/wiki/health": () => ({ ok: true, health: stale }),+ "/api/wiki/reindex": () => ({ ok: true, indexed_pages: 1, vault_pages: 1 }),+ });+ renderWithClient(<WikiView />);++ const button = await screen.findByTestId("wiki-health-reindex");+ fireEvent.click(button);++ await waitFor(() => {+ expect(fetchMock).toHaveBeenCalledWith(+ "/api/wiki/reindex",+ { method: "POST" },+ );+ });+ });});describe("PageRenderer — wikilink behaviour", () => {diff --git a/jarvis/ui/web/frontend/src/views/WikiView.tsx b/jarvis/ui/web/frontend/src/views/WikiView.tsxindex c644b3e9be..4953d2a0f1 100644--- a/jarvis/ui/web/frontend/src/views/WikiView.tsx+++ b/jarvis/ui/web/frontend/src/views/WikiView.tsx@@ -14,7 +14,7 @@* Replaces the legacy `MemoryView` (`data/core_memory.json` flat memory).*/import { Suspense, lazy, useCallback, useEffect, useState } from "react";-import { Notebook, Network, FileText } from "lucide-react";+import { FileText, Network, Notebook, RefreshCw } from "lucide-react";import { useQuery } from "@tanstack/react-query";import { ViewHeader } from "@/views/ChatsView";@@ -24,6 +24,7 @@ import { useEventStore } from "@/store/events";import {fetchWikiHealth,fetchWikiTree,+ rebuildWikiIndex,type WikiHealthSnapshot,} from "@/lib/wikiApi";@@ -60,6 +61,7 @@ export function WikiView(): JSX.Element {// the dialog so step-2-vs-step-3 starts from the most recent reality.const [setupHint, setSetupHint] = useState<ObsidianStatusType | null>(null);const [dialogOpen, setDialogOpen] = useState(false);+ const [isReindexing, setIsReindexing] = useState(false);// Tree query lives both here (for header stats + empty-state detection)// and inside TreeSidebar (for the list). React Query dedupes them.@@ -139,6 +141,19 @@ export function WikiView(): JSX.Element {}, 3000);}, []);+ const handleReindex = useCallback(async () => {+ setIsReindexing(true);+ try {+ const result = await rebuildWikiIndex();+ if (!result.ok) throw new Error(result.error ?? "index rebuild failed");+ await Promise.all([healthQuery.refetch(), treeQuery.refetch()]);+ } catch {+ showToast(t("wiki_health.reindex_failed"));+ } finally {+ setIsReindexing(false);+ }+ }, [healthQuery, showToast, t, treeQuery]);+// Build the known-slug set lazily here too, so we can validate a wikilink// click before changing the URL. Single source of truth: the tree response.const knownSlugs = collectSlugs(treeQuery.data?.folders ?? []);@@ -182,7 +197,12 @@ export function WikiView(): JSX.Element {</div></div>- <WikiHealthStrip health={healthQuery.data} isLoading={healthQuery.isLoading} />+ <WikiHealthStrip+ health={healthQuery.data}+ isLoading={healthQuery.isLoading}+ isReindexing={isReindexing}+ onReindex={handleReindex}+ />{dialogOpen && setupHint && (<ObsidianSetupDialog@@ -317,7 +337,11 @@ function classifyWikiHealth(health: WikiHealthSnapshot): WikiHealthVisual {) {return "red";}- if (health.journal_backlog > 0 || health.vault_legacy_conflict) {+ if (+ health.journal_backlog > 0 ||+ health.vault_legacy_conflict ||+ health.index_state === "stale"+ ) {return "amber";}// At this point `last_write?.ok === false` and `last_chain_failure` are@@ -356,6 +380,12 @@ function describeWikiWriteStatus(const page = health.last_write.pages.join(", ") || health.last_write.source;return t("wiki_health.last_write_ok").replace("{0}", page);}+ if (health.journal_backlog > 0) {+ return t("wiki_health.pending_writes").replace(+ "{0}",+ String(health.journal_backlog),+ );+ }return t("wiki_health.no_writes_yet");}@@ -368,9 +398,13 @@ function describeWikiWriteStatus(function WikiHealthStrip({health,isLoading,+ isReindexing,+ onReindex,}: {health: WikiHealthSnapshot | null | undefined;isLoading: boolean;+ isReindexing: boolean;+ onReindex: () => void;}): JSX.Element {const t = useT();@@ -446,6 +480,28 @@ function WikiHealthStrip({)}</span>)}+ {health.index_state === "stale" && (+ <>+ <span+ data-testid="wiki-health-index-stale"+ className="rounded-full border border-[#ffb84d]/40 bg-[#ffb84d]/10 px-1.5 py-0.5 text-[#ffb84d]"+ >+ {t("wiki_health.index_stale")+ .replace("{0}", String(health.indexed_pages))+ .replace("{1}", String(health.vault_pages))}+ </span>+ <button+ type="button"+ onClick={onReindex}+ disabled={isReindexing}+ data-testid="wiki-health-reindex"+ className="inline-flex items-center gap-1 rounded-md border border-border px-1.5 py-0.5 text-foreground hover:bg-muted disabled:opacity-50"+ >+ <RefreshCw className={cn("h-3 w-3", isReindexing && "animate-spin")} />+ {t(isReindexing ? "wiki_health.reindexing" : "wiki_health.reindex")}+ </button>+ </>+ )}{health.vault_legacy_conflict && (<spandata-testid="wiki-health-legacy-conflict"diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex c98302a736..3783d9e26d 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -1752,11 +1752,10 @@ class WebServer:logger.debug("wiki health.record_bootstrap(False) failed", exc_info=True)_boot_mark("wiki_integration")- # Build the FTS5 search index once if it is empty so a pre-existing- # or restored vault returns search hits immediately (idempotent,- # guarded — never blocks boot).+ # Reconcile the derived FTS5 index after readiness. This repairs stale+ # rows after a vault switch without extending the startup critical path.try:- self._init_wiki_boot_index()+ self._init_wiki_boot_index(background=True)except Exception as exc: # noqa: BLE001logger.opt(exception=exc).warning("WikiBootIndex-Init failed — vault search may return no hits "@@ -2254,25 +2253,18 @@ class WebServer:except Exception: # noqa: BLE001 — health recording must never break bootlogger.debug("wiki health.record_bootstrap(True) failed", exc_info=True)- def _init_wiki_boot_index(self) -> None:- """One-shot FTS5 index build at boot for a pre-existing/restored vault.-- ``wiki_fts`` is only populated incrementally by- ``AtomicWriter.upsert_page`` (on write) and the manual ``reindex``- CLI. A vault that already has pages on disk at first boot — a fresh- clone, a restored backup, or a hand-edited Obsidian vault — therefore- returns zero search hits until something happens to rewrite a page.-- This runs ``index_vault`` exactly once when the FTS table is empty, so- ``wiki-recall`` / ``WikiContextInjector`` return hits immediately. It- is fully idempotent (``index_vault`` upserts by path) and guarded so a- failure can never block boot. It is **not** on the voice critical path- (AP-9): it runs synchronously during ``start()`` before the speech- pipeline accepts a turn.+ def _init_wiki_boot_index(self, *, background: bool = False) -> None:+ """Rebuild the derived FTS view against the active vault.++ Production uses a daemon thread after app readiness (AP-26). Tests and+ explicit callers may keep the synchronous default for deterministic+ verification."""import sqlite3+ import threading- from jarvis.memory.wiki.fts_index import ensure_schema, index_vault+ from jarvis.memory.wiki.db_path import resolve_wiki_db_path+ from jarvis.memory.wiki.fts_index import rebuild_indexwiki_cfg = self.cfg.wiki_integrationif not wiki_cfg.enabled:@@ -2285,28 +2277,44 @@ class WebServer:logger.info("wiki_boot_index: vault missing — skipping ({})", vault_root)return- data_dir = Path(self.cfg.memory.data_dir)- db_path = data_dir / "jarvis.db"- db_path.parent.mkdir(parents=True, exist_ok=True)+ db_path = resolve_wiki_db_path(self.cfg.memory.data_dir)- conn = sqlite3.connect(str(db_path), check_same_thread=False)- try:- ensure_schema(conn)- row_count = conn.execute("SELECT COUNT(*) FROM wiki_fts").fetchone()[0]- if row_count:+ def _reconcile() -> None:+ db_path.parent.mkdir(parents=True, exist_ok=True)+ conn = sqlite3.connect(str(db_path), check_same_thread=False)+ try:+ indexed = rebuild_index(vault_root, conn)logger.info(- "wiki_boot_index: FTS index already populated ({} rows) — skipping",- row_count,+ "wiki_boot_index: reconciled {} page(s) from {} into {}",+ indexed,+ vault_root,+ db_path,)- return- indexed = index_vault(vault_root, conn)- logger.info(- "wiki_boot_index: built FTS index for {} page(s) from {}",- indexed,- vault_root,+ except Exception as exc: # noqa: BLE001+ logger.opt(exception=exc).warning(+ "wiki_boot_index: background reconciliation failed"+ )+ try:+ from jarvis.memory.wiki.health import health as _wiki_health++ _wiki_health.record_chain_failure(+ f"wiki index reconciliation failed: {exc}"+ )+ except Exception: # noqa: BLE001+ logger.debug("wiki index health recording failed", exc_info=True)+ finally:+ conn.close()++ if background:+ thread = threading.Thread(+ target=_reconcile,+ name="jarvis-wiki-index-reconcile",+ daemon=True,)- finally:- conn.close()+ thread.start()+ self._wiki_index_thread = thread+ return+ _reconcile()def _init_wiki_watcher(self) -> None:"""Phase B3 — start the WikiWatcher for desktop live-reload.diff --git a/jarvis/ui/web/setup_routes.py b/jarvis/ui/web/setup_routes.pyindex 9a5754cf53..0431235e7e 100644--- a/jarvis/ui/web/setup_routes.py+++ b/jarvis/ui/web/setup_routes.py@@ -198,8 +198,10 @@ def _reindex_vault_fts(request: Request, jarvis_root: Path) -> None:try:config = getattr(request.app.state, "config", None)- data_dir = Path(getattr(getattr(config, "memory", None), "data_dir", "./data"))- db_path = data_dir / "jarvis.db"+ from jarvis.memory.wiki.db_path import resolve_wiki_db_path++ data_dir = getattr(getattr(config, "memory", None), "data_dir", "./data")+ db_path = resolve_wiki_db_path(data_dir)db_path.parent.mkdir(parents=True, exist_ok=True)conn = sqlite3.connect(str(db_path), check_same_thread=False)try:diff --git a/jarvis/ui/web/wiki_routes.py b/jarvis/ui/web/wiki_routes.pyindex d13b0224f9..47c98478b5 100644--- a/jarvis/ui/web/wiki_routes.py+++ b/jarvis/ui/web/wiki_routes.py@@ -613,8 +613,65 @@ async def get_telemetry(_request: Request) -> dict[str, Any]:}+def _visible_markdown_count(vault_root: Path) -> int:+ """Count indexable Markdown pages, excluding hidden directories."""+ return sum(+ 1+ for path in vault_root.rglob("*.md")+ if not any(+ part.startswith(".")+ for part in path.relative_to(vault_root).parts[:-1]+ )+ )++[email protected]("/reindex")+async def reindex_wiki(+ request: Request,+ dry_run: bool = Query(default=False),+) -> dict[str, Any]:+ """Rebuild the derived wiki search index from the active vault."""+ import sqlite3++ from jarvis.memory.wiki.db_path import resolve_wiki_db_path+ from jarvis.memory.wiki.fts_index import rebuild_index++ vault_root = _resolve_vault_root(request)+ if vault_root is None or not vault_root.is_dir():+ return {"ok": False, "error": "vault unavailable"}++ config = getattr(request.app.state, "config", None)+ data_dir = getattr(getattr(config, "memory", None), "data_dir", "./data")+ db_path = resolve_wiki_db_path(data_dir)+ vault_pages = _visible_markdown_count(vault_root)++ def _run() -> tuple[int, int]:+ db_path.parent.mkdir(parents=True, exist_ok=True)+ conn = sqlite3.connect(str(db_path), check_same_thread=False)+ try:+ try:+ before = int(conn.execute("SELECT COUNT(*) FROM wiki_fts").fetchone()[0])+ except sqlite3.OperationalError:+ before = 0+ if dry_run:+ return before, before+ return before, rebuild_index(vault_root, conn)+ finally:+ conn.close()++ before, indexed = await asyncio.to_thread(_run)+ return {+ "ok": True,+ "dry_run": dry_run,+ "vault_root": str(vault_root),+ "vault_pages": vault_pages,+ "indexed_before": before,+ "indexed_pages": indexed,+ }++@router.get("/health")-async def wiki_health(_request: Request) -> dict[str, Any]:+async def wiki_health(request: Request) -> dict[str, Any]:"""Wiki subsystem health for the Wiki tab status panel (spec A5).The wiki subsystem is fire-and-forget by design (AP-9): failures never@@ -623,9 +680,76 @@ async def wiki_health(_request: Request) -> dict[str, Any]:failures, write failures, chain exhaustion, and journal pressure becomevisible instead of only ever appearing in the logs."""+ import sqlite3++ from jarvis.memory.wiki.db_path import resolve_wiki_db_pathfrom jarvis.memory.wiki.health import health as _health- return {"ok": True, "health": _health.snapshot()}+ snapshot = _health.snapshot()+ vault_root = _resolve_vault_root(request)+ config = getattr(request.app.state, "config", None)+ data_dir = getattr(getattr(config, "memory", None), "data_dir", "./data")+ db_path = resolve_wiki_db_path(data_dir)++ def _persistent_state() -> dict[str, Any]:+ state: dict[str, Any] = {+ "journal_backlog": 0,+ "indexed_pages": 0,+ "last_write": None,+ }+ if not db_path.exists():+ return state+ conn = sqlite3.connect(str(db_path), check_same_thread=False)+ try:+ try:+ state["journal_backlog"] = int(+ conn.execute(+ "SELECT COUNT(*) FROM wiki_candidate_journal "+ "WHERE status = 'pending'"+ ).fetchone()[0]+ )+ row = conn.execute(+ "SELECT consolidated_ms, target_path, source_label "+ "FROM wiki_candidate_journal "+ "WHERE status = 'consolidated' AND target_path IS NOT NULL "+ "ORDER BY consolidated_ms DESC LIMIT 1"+ ).fetchone()+ if row and row[0]:+ state["last_write"] = {+ "ts": float(row[0]) / 1000.0,+ "ok": True,+ "pages": [str(row[1])],+ "error": None,+ "source": str(row[2]),+ }+ except sqlite3.OperationalError:+ pass+ try:+ state["indexed_pages"] = int(+ conn.execute("SELECT COUNT(*) FROM wiki_fts").fetchone()[0]+ )+ except sqlite3.OperationalError:+ pass+ finally:+ conn.close()+ return state++ persistent = await asyncio.to_thread(_persistent_state)+ if snapshot["last_write"] is None and persistent["last_write"] is not None:+ snapshot["last_write"] = persistent["last_write"]+ snapshot["journal_backlog"] = persistent["journal_backlog"]+ snapshot["indexed_pages"] = persistent["indexed_pages"]+ snapshot["vault_pages"] = (+ _visible_markdown_count(vault_root)+ if vault_root is not None and vault_root.is_dir()+ else 0+ )+ snapshot["index_state"] = (+ "ok"+ if snapshot["indexed_pages"] == snapshot["vault_pages"]+ else "stale"+ )+ return {"ok": True, "health": snapshot}__all__ = ["router"]diff --git a/tests/integration/test_wiki_boot_index.py b/tests/integration/test_wiki_boot_index.pyindex 4150261f88..e9ed706422 100644--- a/tests/integration/test_wiki_boot_index.py+++ b/tests/integration/test_wiki_boot_index.py@@ -79,9 +79,8 @@ def test_populated_vault_searchable_after_boot_index(tmp_path: Path) -> None:search.close()-def test_boot_index_idempotent_and_skips_when_populated(tmp_path: Path) -> None:- """Second call is a no-op (table already populated) — does not raise or- duplicate rows."""+def test_boot_index_reconciles_stale_populated_index(tmp_path: Path) -> None:+ """A non-empty index is rebuilt when the active vault contents change."""vault = tmp_path / "wiki" / "obsidian-vault"vault.mkdir(parents=True)_write_page(vault, "topics/sailing.md", "# Sailing\n\nThe Albatross sailboat.\n")@@ -92,11 +91,16 @@ def test_boot_index_idempotent_and_skips_when_populated(tmp_path: Path) -> None:server = WebServer.__new__(WebServer)server.cfg = _fake_cfg(vault, data_dir)server._init_wiki_boot_index()- server._init_wiki_boot_index() # second call must skip cleanly+ (vault / "topics" / "sailing.md").unlink()+ _write_page(vault, "topics/aviation.md", "# Aviation\n\nElectric aircraft.\n")+ server._init_wiki_boot_index()conn = sqlite3.connect(str(db_path))try:assert conn.execute("SELECT COUNT(*) FROM wiki_fts").fetchone()[0] == 1+ assert conn.execute("SELECT path FROM wiki_fts").fetchone()[0] == (+ "topics/aviation.md"+ )finally:conn.close()diff --git a/tests/unit/cli_ctl/test_commands_wiki.py b/tests/unit/cli_ctl/test_commands_wiki.pyindex 0e26059582..668e7f5afb 100644--- a/tests/unit/cli_ctl/test_commands_wiki.py+++ b/tests/unit/cli_ctl/test_commands_wiki.py@@ -27,3 +27,16 @@ def test_tree(capture_api):def test_vaults(capture_api):runner.invoke(app, ["wiki", "vaults"])assert capture_api["calls"][-1]["path"] == "/api/setup/obsidian/vaults"+++def test_reindex(capture_api):+ runner.invoke(app, ["wiki", "reindex"])+ call = capture_api["calls"][-1]+ assert call["method"] == "POST"+ assert call["path"] == "/api/wiki/reindex"+ assert call["query"]["dry_run"] == "false"+++def test_reindex_preview(capture_api):+ runner.invoke(app, ["wiki", "reindex", "--preview"])+ assert capture_api["calls"][-1]["query"]["dry_run"] == "true"diff --git a/tests/unit/memory/wiki/test_atomic_writer_fts_hook.py b/tests/unit/memory/wiki/test_atomic_writer_fts_hook.pyindex 571c9737c6..5989005fa8 100644--- a/tests/unit/memory/wiki/test_atomic_writer_fts_hook.py+++ b/tests/unit/memory/wiki/test_atomic_writer_fts_hook.py@@ -13,7 +13,6 @@ from __future__ import annotationsimport asyncioimport sqlite3from pathlib import Path-from unittest import mockimport pytest@@ -50,6 +49,7 @@ def writer(tmp_path: Path, db_conn: sqlite3.Connection) -> AtomicWriter:backup_dir=tmp_path / "backups",max_backups=5,concurrent_edit_lock_seconds=0.0, # bypass 30-second guard in tests+ db_path=tmp_path / "jarvis.db",)# Inject the in-memory test connection so we don't touch data/jarvis.db.w._fts_conn = db_conndiff --git a/tests/unit/setup/test_obsidian_detector.py b/tests/unit/setup/test_obsidian_detector.pyindex 7c65c35461..a02b884c30 100644--- a/tests/unit/setup/test_obsidian_detector.py+++ b/tests/unit/setup/test_obsidian_detector.py@@ -106,7 +106,7 @@ def test_detect_obsidian_finds_default_install(monkeypatch: pytest.MonkeyPatch)local_path = r"C:\Users\TestUser\AppData\Local\Programs\Obsidian\Obsidian.exe"_patch_exists(monkeypatch, {local_path})- result = detect_obsidian()+ result = detect_obsidian(platform="win32")assert isinstance(result, ObsidianDetection)assert result.installed is True@@ -127,7 +127,7 @@ def test_detect_obsidian_finds_system_wide_install(monkeypatch: pytest.MonkeyPatpf_path = r"C:\Program Files\Obsidian\Obsidian.exe"_patch_exists(monkeypatch, {pf_path})- result = detect_obsidian()+ result = detect_obsidian(platform="win32")assert result.installed is Trueassert result.exe_path is not None@@ -141,7 +141,7 @@ def test_detect_obsidian_no_install(monkeypatch: pytest.MonkeyPatch) -> None:_kill_win32api(monkeypatch)_patch_exists(monkeypatch, set())- result = detect_obsidian()+ result = detect_obsidian(platform="win32")assert result.installed is Falseassert result.exe_path is None@@ -161,7 +161,7 @@ def test_detect_obsidian_version_extraction_fails_gracefully(pf_path = r"C:\Program Files\Obsidian\Obsidian.exe"_patch_exists(monkeypatch, {pf_path})- result = detect_obsidian()+ result = detect_obsidian(platform="win32")assert result.installed is Trueassert result.exe_path is not None@@ -179,12 +179,39 @@ def test_detect_obsidian_extracts_version_when_available(pf_path = r"C:\Program Files\Obsidian\Obsidian.exe"_patch_exists(monkeypatch, {pf_path})- result = detect_obsidian()+ result = detect_obsidian(platform="win32")assert result.installed is Trueassert result.version == "1.5.12.0"+def test_detect_obsidian_linux_uses_path_lookup(monkeypatch: pytest.MonkeyPatch) -> None:+ """Linux installs exposed on PATH are detected without Windows APIs."""+ monkeypatch.setattr(+ "jarvis.setup.obsidian.shutil.which",+ lambda _name: "/usr/bin/obsidian",+ )++ result = detect_obsidian(platform="linux")++ assert result.installed is True+ assert result.exe_path == Path("/usr/bin/obsidian")+ assert result.version is None+++def test_detect_obsidian_macos_app_bundle(monkeypatch: pytest.MonkeyPatch) -> None:+ """The standard macOS app bundle is detected when no CLI is on PATH."""+ monkeypatch.setattr("jarvis.setup.obsidian.shutil.which", lambda _name: None)+ app_binary = "/Applications/Obsidian.app/Contents/MacOS/Obsidian"+ _patch_exists(monkeypatch, {str(Path(app_binary))})++ result = detect_obsidian(platform="darwin")++ assert result.installed is True+ assert result.exe_path == Path(app_binary)+ assert result.version is None++# ---------------------------------------------------------------------------# read_obsidian_vaults()# ---------------------------------------------------------------------------diff --git a/tests/unit/ui/web/test_wiki_routes.py b/tests/unit/ui/web/test_wiki_routes.pyindex 4fc37fde33..1364f99ebd 100644--- a/tests/unit/ui/web/test_wiki_routes.py+++ b/tests/unit/ui/web/test_wiki_routes.py@@ -11,7 +11,6 @@ from __future__ import annotationsfrom pathlib import Pathfrom types import SimpleNamespace-from typing import Anyimport pytestfrom fastapi import FastAPI@@ -36,7 +35,11 @@ def _make_app(vault_root: Path | None) -> FastAPI:wiki_cfg = SimpleNamespace(vault_root=None)else:wiki_cfg = SimpleNamespace(vault_root=vault_root)- app.state.config = SimpleNamespace(wiki_integration=wiki_cfg)+ data_dir = vault_root.parent / "data" if vault_root is not None else Path("data")+ app.state.config = SimpleNamespace(+ wiki_integration=wiki_cfg,+ memory=SimpleNamespace(data_dir=data_dir),+ )return app@@ -370,6 +373,53 @@ def test_search_k_parameter_caps_results(populated_vault: Path) -> None:assert len(body["hits"]) <= 1+# ----------------------------------------------------------------------+# /reindex+# ----------------------------------------------------------------------+++def test_reindex_replaces_stale_rows_with_active_vault(+ populated_vault: Path,+) -> None:+ import sqlite3++ from jarvis.memory.wiki.db_path import resolve_wiki_db_path++ app = _make_app(populated_vault)+ db_path = resolve_wiki_db_path(app.state.config.memory.data_dir)+ db_path.parent.mkdir(parents=True, exist_ok=True)+ conn = sqlite3.connect(str(db_path))+ try:+ conn.execute(+ "CREATE VIRTUAL TABLE wiki_fts USING fts5("+ "path UNINDEXED, title, frontmatter, body, mtime UNINDEXED)"+ )+ conn.execute(+ "INSERT INTO wiki_fts VALUES (?, ?, ?, ?, ?)",+ ("entities/stale.md", "Stale", "", "old", "0"),+ )+ conn.commit()+ finally:+ conn.close()++ with TestClient(app) as client:+ preview = client.post("/api/wiki/reindex", params={"dry_run": "true"}).json()+ result = client.post("/api/wiki/reindex").json()++ assert preview["indexed_before"] == 1+ assert preview["indexed_pages"] == 1+ assert result["ok"] is True+ assert result["indexed_pages"] == 3++ conn = sqlite3.connect(str(db_path))+ try:+ paths = {row[0] for row in conn.execute("SELECT path FROM wiki_fts")}+ finally:+ conn.close()+ assert "entities/stale.md" not in paths+ assert "entities/ruben.md" in paths++# ----------------------------------------------------------------------# Defensive: missing config# ----------------------------------------------------------------------@@ -403,6 +453,7 @@ def test_page_without_config_returns_error_envelope() -> None:def test_health_returns_200_with_fresh_snapshot(monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,) -> None:"""A fresh ``WikiHealth`` singleton reports the all-unknown baseline shape.@@ -416,6 +467,10 @@ def test_health_returns_200_with_fresh_snapshot(app = FastAPI()app.include_router(wiki_router)+ app.state.config = SimpleNamespace(+ wiki_integration=SimpleNamespace(vault_root=tmp_path / "vault"),+ memory=SimpleNamespace(data_dir=tmp_path / "data"),+ )with TestClient(app) as client:r = client.get("/api/wiki/health")body = r.json()@@ -425,3 +480,44 @@ def test_health_returns_200_with_fresh_snapshot(assert body["health"]["bootstrap_ok"] is Noneassert body["health"]["last_write"] is Noneassert body["health"]["last_chain_failure"] is None+++def test_health_restores_last_write_and_backlog_from_journal(tmp_path: Path) -> None:+ from jarvis.memory.wiki.journal import CandidateFact, CandidateJournal++ vault = tmp_path / "vault"+ _write_page(+ vault,+ "entities",+ "ruben",+ page_type="entity",+ body="# Ruben\n",+ )+ app = _make_app(vault)+ db_path = app.state.config.memory.data_dir / "jarvis.db"+ journal = CandidateJournal(db_path)+ assert journal.append(+ [CandidateFact(fact="A durable fact")],+ source_label="test-source",+ turn_hash="hash-1",+ ) == 1+ journal.mark(+ [1],+ status="consolidated",+ decision="add",+ target_path="entities/ruben.md",+ )+ assert journal.append(+ [CandidateFact(fact="A pending fact")],+ source_label="test-source",+ turn_hash="hash-2",+ ) == 1++ with TestClient(app) as client:+ body = client.get("/api/wiki/health").json()++ health = body["health"]+ assert health["journal_backlog"] == 1+ assert health["last_write"]["pages"] == ["entities/ruben.md"]+ assert health["vault_pages"] == 1+ assert health["index_state"] == "stale"