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): keep live FTS index in sync
Ruben Lütke38db3c465ff9
diff --git a/jarvis/memory/wiki/fts_index.py b/jarvis/memory/wiki/fts_index.pyindex 33fbb01143..5e026292bb 100644--- a/jarvis/memory/wiki/fts_index.py+++ b/jarvis/memory/wiki/fts_index.py@@ -1,13 +1,15 @@"""FTS5 index builder and maintenance for the wiki vault.-Exposes four public callables that implement the shared contract-agreed by the sqlite-architect and python-integrator sub-agents:+Exposes the mutation callables used by full reconciliation and incremental+writers:ensure_schema(conn) -- idempotent DDL (create wiki_fts if absent)index_vault(vault_root, conn) -- full walk; returns count of indexed pagesupsert_page(conn, vault_root, abs_path) -- single-page reindex (delete+insert)remove_page(conn, vault_root, abs_path) -- remove a single page by path+Read-only metadata and vault-scan helpers support the Wiki health endpoint.+All path values stored in the DB are vault-root-relative POSIX strings(forward slashes, no leading slash).@@ -43,6 +45,7 @@ import loggingimport osimport reimport sqlite3+import timefrom pathlib import Pathfrom typing import Any@@ -63,6 +66,15 @@ CREATE VIRTUAL TABLE IF NOT EXISTS wiki_fts USING fts5();"""+_CREATE_WIKI_INDEX_META = """+CREATE TABLE IF NOT EXISTS wiki_index_meta (+ singleton INTEGER PRIMARY KEY CHECK (singleton = 1),+ last_indexed_at REAL NOT NULL,+ operation TEXT NOT NULL,+ path TEXT+);+"""+# ---------------------------------------------------------------------------# Regex helpers (reused from original search.py internals — single source)# ---------------------------------------------------------------------------@@ -71,6 +83,12 @@ _FRONTMATTER_RE = re.compile(r"^---\s*\n(.*?)\n---\s*\n?", re.DOTALL)_H1_RE = re.compile(r"^\s{0,3}#\s+(.+)", re.MULTILINE)_YAML_KV_RE = re.compile(r"^(\w[\w\s\-]*):\s*(.+)$", re.MULTILINE)+# Non-content directories that are intentionally absent from search. Archived+# pages are removed by AtomicWriter and must not reappear after reconciliation.+SKIP_INDEX_DIRS: frozenset[str] = frozenset(+ {"_archive", "attachments", "99-templates"}+)+# ---------------------------------------------------------------------------# Public API@@ -89,7 +107,7 @@ def ensure_schema(conn: sqlite3.Connection) -> None:Open, writable ``sqlite3.Connection``."""_verify_fts5(conn)- conn.executescript(_CREATE_WIKI_FTS)+ conn.executescript(_CREATE_WIKI_FTS + _CREATE_WIKI_INDEX_META)conn.commit()@@ -113,10 +131,8 @@ def index_vault(vault_root: Path, conn: sqlite3.Connection) -> int:Number of pages indexed (each upserted page counts as 1)."""ensure_schema(conn)- count = 0- for abs_path in _walk_vault(vault_root):- _upsert_one(conn, vault_root, abs_path)- count += 1+ count = _index_all_pages(vault_root, conn)+ _record_index_metadata(conn, operation="index_vault")conn.commit()log.info("fts_index: indexed %d pages in %s", count, vault_root)return count@@ -142,8 +158,11 @@ def rebuild_index(vault_root: Path, conn: sqlite3.Connection) -> int:"""ensure_schema(conn)conn.execute("DELETE FROM wiki_fts")+ count = _index_all_pages(vault_root, conn)+ _record_index_metadata(conn, operation="rebuild")conn.commit()- return index_vault(vault_root, conn)+ log.info("fts_index: rebuilt %d pages in %s", count, vault_root)+ return countdef upsert_page(@@ -166,7 +185,12 @@ def upsert_page(abs_path:Absolute path of the page that was just written."""- _upsert_one(conn, vault_root, abs_path)+ if _upsert_one(conn, vault_root, abs_path):+ _record_index_metadata(+ conn,+ operation="upsert",+ path=_relative_posix(vault_root, abs_path),+ )conn.commit()@@ -188,10 +212,65 @@ def remove_page("""rel = _relative_posix(vault_root, abs_path)conn.execute("DELETE FROM wiki_fts WHERE path = ?", (rel,))+ _record_index_metadata(conn, operation="remove", path=rel)conn.commit()log.debug("fts_index: removed %s", rel)+def read_index_metadata(conn: sqlite3.Connection) -> dict[str, Any] | None:+ """Return the latest successful index mutation recorded in ``conn``.++ Older databases may contain ``wiki_fts`` without the metadata table. In+ that case this read-only helper returns ``None`` rather than mutating the+ database from a health-check path.+ """+ try:+ row = conn.execute(+ "SELECT last_indexed_at, operation, path "+ "FROM wiki_index_meta WHERE singleton = 1"+ ).fetchone()+ except sqlite3.OperationalError:+ return None+ if row is None:+ return None+ return {+ "last_indexed_at": float(row[0]),+ "operation": str(row[1]),+ "path": str(row[2]) if row[2] is not None else None,+ }+++def vault_page_mtimes(vault_root: Path) -> dict[str, float]:+ """Return indexable vault paths and their current modification times."""+ pages: dict[str, float] = {}+ for abs_path in _walk_vault(vault_root):+ try:+ pages[_relative_posix(vault_root, abs_path)] = abs_path.stat().st_mtime+ except OSError:+ # A concurrent editor may replace or delete a file during the walk.+ # The watcher will process that change; omit the transient path from+ # this snapshot instead of reporting fabricated metadata.+ continue+ return pages+++def is_indexable_path(vault_root: Path, abs_path: Path) -> bool:+ """Return whether ``abs_path`` belongs in a full or incremental index."""+ if abs_path.suffix.lower() != ".md":+ return False+ try:+ rel = abs_path.resolve().relative_to(vault_root.resolve())+ except (OSError, ValueError):+ return False+ if not rel.parts:+ return False+ directories = rel.parts[:-1]+ return not any(+ part.startswith(".") or part in SKIP_INDEX_DIRS+ for part in directories+ )++# ---------------------------------------------------------------------------# Internals# ---------------------------------------------------------------------------@@ -215,8 +294,34 @@ def _verify_fts5(conn: sqlite3.Connection) -> None:)+def _index_all_pages(vault_root: Path, conn: sqlite3.Connection) -> int:+ """Index every visible Markdown page without committing."""+ count = 0+ for abs_path in _walk_vault(vault_root):+ if _upsert_one(conn, vault_root, abs_path):+ count += 1+ return count+++def _record_index_metadata(+ conn: sqlite3.Connection,+ *,+ operation: str,+ path: str | None = None,+) -> None:+ """Record one successful derived-index mutation in the current transaction."""+ conn.execute(+ "INSERT INTO wiki_index_meta(singleton, last_indexed_at, operation, path) "+ "VALUES (1, ?, ?, ?) "+ "ON CONFLICT(singleton) DO UPDATE SET "+ "last_indexed_at = excluded.last_indexed_at, "+ "operation = excluded.operation, path = excluded.path",+ (time.time(), operation, path),+ )++def _walk_vault(vault_root: Path) -> list[Path]:- """Recursively collect ``*.md`` files, skipping hidden directories.+ """Recursively collect indexable Markdown files.Mirrors the walk logic from the original ``search.py`` so behaviouris consistent between a full reindex and a live search.@@ -224,14 +329,19 @@ def _walk_vault(vault_root: Path) -> list[Path]:results: list[Path] = []if not vault_root.exists():return results- for item in vault_root.rglob("*.md"):- # Skip anything inside a hidden directory (e.g. ``.obsidian``).- if any(- part.startswith(".")- for part in item.relative_to(vault_root).parts[:-1]- ):- continue- results.append(item)+ for current_root, dirnames, filenames in os.walk(vault_root):+ # Prune large non-content trees before descent rather than walking+ # every attachment on each health poll.+ dirnames[:] = sorted(+ dirname+ for dirname in dirnames+ if not dirname.startswith(".") and dirname not in SKIP_INDEX_DIRS+ )+ root = Path(current_root)+ for filename in sorted(filenames):+ item = root / filename+ if item.is_file() and is_indexable_path(vault_root, item):+ results.append(item)return results@@ -309,14 +419,14 @@ def _upsert_one(conn: sqlite3.Connection,vault_root: Path,abs_path: Path,-) -> None:+) -> bool:"""Delete existing row for *abs_path* then insert a fresh one.Does NOT commit — callers batch commits for efficiency."""parsed = _parse_page_data(abs_path, vault_root)if parsed is None:- return+ return Falserel_path, title, frontmatter_flat, body, mtime_str = parsed# Delete-then-insert is the canonical FTS5 upsert pattern.@@ -327,6 +437,7 @@ def _upsert_one((rel_path, title, frontmatter_flat, body, mtime_str),)log.debug("fts_index: upserted %s", rel_path)+ return True__all__ = [@@ -335,4 +446,8 @@ __all__ = ["rebuild_index","upsert_page","remove_page",+ "read_index_metadata",+ "vault_page_mtimes",+ "is_indexable_path",+ "SKIP_INDEX_DIRS",]diff --git a/jarvis/memory/wiki/health.py b/jarvis/memory/wiki/health.pyindex 143adac759..9f05a415c7 100644--- a/jarvis/memory/wiki/health.py+++ b/jarvis/memory/wiki/health.py@@ -9,8 +9,10 @@ would invert the design)."""from __future__ import annotations+import sqlite3import threadingimport time+from pathlib import Pathfrom typing import Any@@ -20,6 +22,7 @@ class WikiHealth:self._bootstrap_ok: bool | None = Noneself._bootstrap_error: str | None = Noneself._last_write: dict[str, Any] | None = None+ self._last_index: dict[str, Any] | None = Noneself._last_chain_failure: dict[str, Any] | None = Noneself._journal_backlog: int = 0@@ -44,6 +47,24 @@ class WikiHealth:with self._lock:self._last_chain_failure = {"ts": time.time(), "detail": detail}+ def record_index(+ self,+ ok: bool,+ *,+ operation: str,+ path: str | None = None,+ error: str | None = None,+ ) -> None:+ """Record the latest live index-maintenance outcome."""+ with self._lock:+ self._last_index = {+ "ts": time.time(),+ "ok": bool(ok),+ "operation": operation,+ "path": path,+ "error": error,+ }+def record_backlog(self, count: int) -> None:with self._lock:self._journal_backlog = max(0, int(count))@@ -60,6 +81,7 @@ class WikiHealth:"vault_root_source": res.source if res else None,"vault_legacy_conflict": bool(res.legacy_conflict) if res else False,"last_write": dict(self._last_write) if self._last_write else None,+ "last_index": dict(self._last_index) if self._last_index else None,"last_chain_failure": (dict(self._last_chain_failure)if self._last_chain_failure else None@@ -68,5 +90,141 @@ class WikiHealth:}+def inspect_index_health(+ vault_root: Path | None,+ db_path: Path,+) -> dict[str, Any]:+ """Compare the active vault with the derived FTS index without writes.++ The result is intentionally count-based: it reports parity and freshness+ without exposing private page names through a diagnostic endpoint.+ """+ state: dict[str, Any] = {+ "index_available": False,+ "indexed_pages": 0,+ "indexed_rows": 0,+ "vault_pages": 0,+ "missing_pages": 0,+ "orphaned_pages": 0,+ "outdated_pages": 0,+ "duplicate_index_rows": 0,+ "last_index_at": None,+ "last_index_operation": None,+ "last_index_path": None,+ "index_lag_seconds": None,+ "index_state": "stale",+ "index_state_reason": "vault_unavailable",+ "index_state_reasons": ["vault_unavailable"],+ }+ if vault_root is None or not vault_root.is_dir():+ return state++ from jarvis.memory.wiki.fts_index import (+ read_index_metadata,+ vault_page_mtimes,+ )++ vault_mtimes = vault_page_mtimes(vault_root)+ vault_paths = set(vault_mtimes)+ state["vault_pages"] = len(vault_paths)+ if not db_path.is_file():+ state["missing_pages"] = len(vault_paths)+ state["index_state_reason"] = "index_unavailable"+ state["index_state_reasons"] = ["index_unavailable"]+ return state++ try:+ conn = sqlite3.connect(+ f"{db_path.resolve(strict=False).as_uri()}?mode=ro",+ uri=True,+ check_same_thread=False,+ )+ except sqlite3.Error:+ state["missing_pages"] = len(vault_paths)+ state["index_state_reason"] = "index_unavailable"+ state["index_state_reasons"] = ["index_unavailable"]+ return state++ try:+ try:+ rows = conn.execute("SELECT path, mtime FROM wiki_fts").fetchall()+ except sqlite3.OperationalError:+ state["missing_pages"] = len(vault_paths)+ state["index_state_reason"] = "index_unavailable"+ state["index_state_reasons"] = ["index_unavailable"]+ return state++ metadata = read_index_metadata(conn)+ finally:+ conn.close()++ index_mtimes: dict[str, float | None] = {}+ for raw_path, raw_mtime in rows:+ path = str(raw_path)+ try:+ mtime: float | None = float(raw_mtime)+ except (TypeError, ValueError):+ mtime = None+ # Duplicate rows are already unhealthy; retaining the newest mtime+ # avoids also inflating the outdated-page count for the same path.+ previous = index_mtimes.get(path)+ if previous is None or (mtime is not None and mtime > previous):+ index_mtimes[path] = mtime++ index_paths = set(index_mtimes)+ missing = vault_paths - index_paths+ orphaned = index_paths - vault_paths+ outdated = {+ path+ for path in vault_paths & index_paths+ if index_mtimes[path] is None+ or abs(vault_mtimes[path] - float(index_mtimes[path])) > 1e-6+ }++ state.update(+ {+ "index_available": True,+ "indexed_pages": len(index_paths),+ "indexed_rows": len(rows),+ "missing_pages": len(missing),+ "orphaned_pages": len(orphaned),+ "outdated_pages": len(outdated),+ "duplicate_index_rows": max(0, len(rows) - len(index_paths)),+ }+ )+ if metadata is not None:+ last_index_at = float(metadata["last_indexed_at"])+ latest_vault_mtime = max(vault_mtimes.values(), default=last_index_at)+ state.update(+ {+ "last_index_at": last_index_at,+ "last_index_operation": metadata["operation"],+ "last_index_path": metadata["path"],+ "index_lag_seconds": max(0.0, latest_vault_mtime - last_index_at),+ }+ )++ reasons: list[str] = []+ if missing:+ reasons.append("missing_pages")+ if orphaned:+ reasons.append("orphaned_pages")+ if outdated:+ reasons.append("outdated_pages")+ if state["duplicate_index_rows"]:+ reasons.append("duplicate_rows")+ if reasons:+ state["index_state_reason"] = reasons[0]+ state["index_state_reasons"] = reasons+ else:+ state["index_state"] = "ok"+ state["index_state_reason"] = "in_sync"+ state["index_state_reasons"] = []+ return state++#: Process-wide singleton — import as ``from jarvis.memory.wiki.health import health``.health = WikiHealth()+++__all__ = ["WikiHealth", "health", "inspect_index_health"]diff --git a/jarvis/memory/wiki/watcher.py b/jarvis/memory/wiki/watcher.pyindex 5c01997e86..fb047ff6c8 100644--- a/jarvis/memory/wiki/watcher.py+++ b/jarvis/memory/wiki/watcher.py@@ -1,11 +1,12 @@"""WikiWatcher — filesystem observer for the Obsidian vault.-Watches the wiki vault root for ``.md`` file changes in the four content-folders (``entities/``, ``concepts/``, ``projects/``, ``sessions/``) and-publishes :class:`jarvis.core.events.WikiPageChanged` events on the-provided :class:`~jarvis.core.bus.EventBus`. Events are debounced-per-path with a 500 ms window so that a curator burst that writes ten-pages in <300 ms produces ten events, not fifty.+Watches visible ``.md`` files beneath the wiki vault and incrementally keeps+the derived FTS index synchronized. Changes in the four interactive content+folders (``entities/``, ``concepts/``, ``projects/``, ``sessions/``) also+publish :class:`jarvis.core.events.WikiPageChanged` events on the provided+:class:`~jarvis.core.bus.EventBus`. Events are debounced per-path with a 500 ms+window so that a curator burst that writes ten pages in <300 ms produces ten+events, not fifty.The class is started with :meth:`WikiWatcher.start` (synchronous, capturesthe running asyncio loop) and torn down with :meth:`WikiWatcher.shutdown`@@ -84,20 +85,26 @@ class WikiWatcher:debounce_ms:Per-path debounce window. Defaults to 500 ms which is the valuedocumented in the binding briefing.+ db_path:+ Canonical SQLite database for incremental FTS maintenance. ``None``+ keeps the watcher event-only, which is useful for standalone callers."""def __init__(self,vault_root: Path,- bus: "EventBus",+ bus: EventBus,debounce_ms: int = DEFAULT_DEBOUNCE_MS,+ db_path: Path | None = None,) -> None:self.vault_root = Path(vault_root)self.bus = busself._debounce_s = max(0.0, debounce_ms / 1000.0)+ self._db_path = Path(db_path) if db_path is not None else Noneself._observer: Any | None = Noneself._loop: asyncio.AbstractEventLoop | None = None+ self._index_lock = threading.Lock()# Per-path debounce: {absolute_path: (Timer, latest_kind)}.self._timers_lock = threading.Lock()@@ -148,23 +155,21 @@ class WikiWatcher:handler = _WatchdogBridge(self)- # Schedule one observer entry per sub-folder so a non-recursive- # vault-root listing (e.g. log.md, schema.md) is excluded from- # the stream. ``recursive=True`` is fine because the wiki sub-- # folders themselves are flat in practice, but we keep the option- # in case sessions/ later gets year-buckets.- for sub in WATCHED_SUBDIRS:- target = self.vault_root / sub- try:- observer.schedule(handler, str(target), recursive=True)- except FileNotFoundError as exc:- log.warning(- "wiki_watcher: could not schedule %s: %s", target, exc- )- except PermissionError as exc:- log.warning(- "wiki_watcher: permission denied for %s: %s", target, exc- )+ # Observe the whole vault so manual changes to root pages and archived+ # pages stay in FTS parity. Event publication remains restricted to the+ # four interactive folders below.+ try:+ observer.schedule(handler, str(self.vault_root), recursive=True)+ except FileNotFoundError as exc:+ log.warning(+ "wiki_watcher: could not schedule %s: %s", self.vault_root, exc+ )+ return False+ except PermissionError as exc:+ log.warning(+ "wiki_watcher: permission denied for %s: %s", self.vault_root, exc+ )+ return Falseobserver.daemon = Truetry:@@ -196,7 +201,7 @@ class WikiWatcher:try:timer.cancel()except Exception: # noqa: BLE001- pass+ log.debug("wiki_watcher: timer cancellation failed", exc_info=True)observer = self._observerif observer is None:@@ -236,8 +241,14 @@ class WikiWatcher:if abs_path.suffix.lower() != ".md":return- # Filter: must be under a watched sub-folder.- if not self._is_under_watched_subdir(abs_path):+ # FTS follows the same visible-Markdown rule as a full vault rebuild.+ if not self._is_indexable_path(abs_path):+ return++ # An event-only watcher has no work for paths outside the interactive+ # folders. A DB-backed watcher still indexes those paths without+ # publishing frontend events.+ if self._db_path is None and not self._is_under_watched_subdir(abs_path):return# Per-path debounce. If a timer already exists for this path,@@ -249,7 +260,10 @@ class WikiWatcher:try:existing[0].cancel()except Exception: # noqa: BLE001- pass+ log.debug(+ "wiki_watcher: debounce cancellation failed",+ exc_info=True,+ )# "deleted" wins over "modified" if both fire in the window,# because reading the file would race with the deletion.# "created" wins over "modified" similarly (a fresh file's@@ -295,6 +309,12 @@ class WikiWatcher:return Falsereturn parts[0] in WATCHED_SUBDIRS+ def _is_indexable_path(self, abs_path: Path) -> bool:+ """Return whether a path follows the full-index visibility rules."""+ from jarvis.memory.wiki.fts_index import is_indexable_path++ return is_indexable_path(self.vault_root, abs_path)+def _fire(self, abs_path: Path, kind: str) -> None:"""Debounced emit — called by the threading.Timer thread."""# Belt-and-suspenders against the shutdown race: a Timer that@@ -306,6 +326,15 @@ class WikiWatcher:with self._timers_lock:self._timers.pop(abs_path, None)+ # Editors commonly save by deleting and recreating the same path. The+ # final filesystem state is authoritative after the debounce window;+ # an intermediate delete must not remove a replacement file from FTS.+ if abs_path.is_file():+ if kind == "deleted":+ kind = "modified"+ else:+ kind = "deleted"+try:rel = abs_path.resolve().relative_to(self.vault_root.resolve())except (FileNotFoundError, ValueError):@@ -324,6 +353,13 @@ class WikiWatcher:path_posix = rel.as_posix()slug = abs_path.stem+ self._maintain_index(abs_path, kind, path_posix)++ # Root, archive, and other visible Markdown files participate in FTS+ # parity but are not interactive Wiki-page events.+ if not self._is_under_watched_subdir(abs_path):+ return+event = WikiPageChanged(slug=slug,path=path_posix,@@ -346,6 +382,58 @@ class WikiWatcher:extra={"path": path_posix, "kind": kind, "error": str(exc)},)+ def _maintain_index(self, abs_path: Path, kind: str, rel_path: str) -> None:+ """Apply one debounced filesystem change to the derived FTS index."""+ db_path = self._db_path+ if db_path is None:+ return++ import sqlite3++ from jarvis.memory.wiki import fts_index+ from jarvis.memory.wiki.health import health++ operation = "upsert" if abs_path.is_file() else "remove"+ try:+ # Different page timers may fire together. Serialize their short+ # SQLite transactions so a curator burst does not become a lock+ # storm on slower or network-backed filesystems.+ with self._index_lock:+ db_path.parent.mkdir(parents=True, exist_ok=True)+ conn = sqlite3.connect(+ str(db_path),+ timeout=5.0,+ check_same_thread=False,+ )+ try:+ fts_index.ensure_schema(conn)+ if operation == "remove":+ fts_index.remove_page(conn, self.vault_root, abs_path)+ else:+ fts_index.upsert_page(conn, self.vault_root, abs_path)+ finally:+ conn.close()+ health.record_index(+ True,+ operation=operation,+ path=rel_path,+ )+ except Exception as exc: # noqa: BLE001+ log.warning(+ "wiki_watcher_index_failed",+ exc_info=True,+ extra={"path": rel_path, "kind": kind, "error": str(exc)},+ )+ try:+ health.record_index(+ False,+ operation=operation,+ path=rel_path,+ error=str(exc),+ )+ except Exception: # noqa: BLE001+ log.debug("wiki_watcher: health recording failed", exc_info=True)+class _WatchdogBridge(FileSystemEventHandler): # type: ignore[misc]"""Adapter from watchdog's per-event callbacks to ``WikiWatcher``."""diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex 3783d9e26d..90829cf1a2 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -2324,6 +2324,7 @@ class WebServer:the desktop app must boot when the vault is empty or watchdogcannot start an observer."""+ from jarvis.memory.wiki.db_path import resolve_wiki_db_pathfrom jarvis.memory.wiki.vault_root import resolve_vault_rootfrom jarvis.memory.wiki.watcher import WikiWatcher@@ -2333,8 +2334,13 @@ class WebServer:returnvault_root = resolve_vault_root(wiki_cfg.vault_root).path+ db_path = resolve_wiki_db_path(self.cfg.memory.data_dir)- watcher = WikiWatcher(vault_root=vault_root, bus=self.bus)+ watcher = WikiWatcher(+ vault_root=vault_root,+ bus=self.bus,+ db_path=db_path,+ )try:started = watcher.start()except FileNotFoundError as exc:diff --git a/jarvis/ui/web/wiki_routes.py b/jarvis/ui/web/wiki_routes.pyindex 8a9689681c..e277cbdd18 100644--- a/jarvis/ui/web/wiki_routes.py+++ b/jarvis/ui/web/wiki_routes.py@@ -762,6 +762,7 @@ async def wiki_health(request: Request) -> dict[str, Any]:from jarvis.memory.wiki.db_path import resolve_wiki_db_pathfrom jarvis.memory.wiki.health import health as _health+ from jarvis.memory.wiki.health import inspect_index_healthsnapshot = _health.snapshot()vault_root = _resolve_vault_root(request)@@ -772,7 +773,6 @@ async def wiki_health(request: Request) -> dict[str, Any]:def _persistent_state() -> dict[str, Any]:state: dict[str, Any] = {"journal_backlog": 0,- "indexed_pages": 0,"last_write": None,}if not db_path.exists():@@ -802,31 +802,33 @@ async def wiki_health(request: Request) -> dict[str, Any]:}except sqlite3.OperationalError:pass- try:- state["indexed_pages"] = int(- conn.execute("SELECT COUNT(*) FROM wiki_fts").fetchone()[0]- )- except sqlite3.OperationalError:- passfinally:conn.close()return state- persistent = await asyncio.to_thread(_persistent_state)+ persistent, index_health = await asyncio.gather(+ asyncio.to_thread(_persistent_state),+ asyncio.to_thread(inspect_index_health, vault_root, db_path),+ )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"- )+ snapshot.update(index_health)++ last_index = snapshot.get("last_index")+ if (+ isinstance(last_index, dict)+ and last_index.get("ok") is False+ and snapshot.get("index_state") != "ok"+ and float(last_index.get("ts") or 0.0)+ >= float(snapshot.get("last_index_at") or 0.0)+ ):+ reasons = list(snapshot.get("index_state_reasons") or [])+ if "index_update_failed" not in reasons:+ reasons.insert(0, "index_update_failed")+ snapshot["index_state"] = "stale"+ snapshot["index_state_reason"] = "index_update_failed"+ snapshot["index_state_reasons"] = reasonsreturn {"ok": True, "health": snapshot}diff --git a/tests/unit/memory/wiki/test_fts_index.py b/tests/unit/memory/wiki/test_fts_index.pyindex 1e590ac2d8..4d05639225 100644--- a/tests/unit/memory/wiki/test_fts_index.py+++ b/tests/unit/memory/wiki/test_fts_index.py@@ -18,17 +18,15 @@ from __future__ import annotationsimport sqlite3from pathlib import Path-import pytest-from jarvis.memory.wiki.fts_index import (ensure_schema,index_vault,+ read_index_metadata,rebuild_index,remove_page,upsert_page,)-# ---------------------------------------------------------------------------# Helpers# ---------------------------------------------------------------------------@@ -93,7 +91,8 @@ def test_index_vault_three_pages(tmp_path: Path) -> None:# Page 3: frontmatter with a list-valued aliases field._write_md(entities / "jarvis.md",- "---\ntype: entity\nslug: jarvis\naliases: [J, Personal Jarvis, PJ]\n---\n# Jarvis\nAssistant.\n",+ "---\ntype: entity\nslug: jarvis\n"+ "aliases: [J, Personal Jarvis, PJ]\n---\n# Jarvis\nAssistant.\n",)conn = _mem_conn()@@ -126,6 +125,22 @@ def test_index_vault_idempotent(tmp_path: Path) -> None:conn.close()+def test_index_vault_matches_cross_platform_visibility_rules(tmp_path: Path) -> None:+ """Mixed-case Markdown is indexed while archive and template files are not."""+ _write_md(tmp_path / "entities" / "visible.MD", "# Visible\n")+ _write_md(tmp_path / "_archive" / "old.md", "# Archived\n")+ _write_md(tmp_path / "attachments" / "note.md", "# Attachment\n")+ _write_md(tmp_path / "99-templates" / "seed.md", "# Template\n")++ conn = _mem_conn()+ count = index_vault(tmp_path, conn)+ paths = {row[0] for row in conn.execute("SELECT path FROM wiki_fts")}++ assert count == 1+ assert paths == {"entities/visible.MD"}+ conn.close()++# ---------------------------------------------------------------------------# Test: rebuild_index clears the old vault's rows before reindexing# ---------------------------------------------------------------------------@@ -225,6 +240,27 @@ def test_remove_page_noop_when_absent(tmp_path: Path) -> None:conn.close()+def test_index_metadata_tracks_latest_incremental_mutation(tmp_path: Path) -> None:+ """Health metadata identifies the latest successful index operation."""+ page = _write_md(tmp_path / "entities" / "tracked.md", "# Tracked\n")+ conn = _mem_conn()++ upsert_page(conn, tmp_path, page)+ after_upsert = read_index_metadata(conn)+ assert after_upsert is not None+ assert after_upsert["operation"] == "upsert"+ assert after_upsert["path"] == "entities/tracked.md"++ page.unlink()+ remove_page(conn, tmp_path, page)+ after_remove = read_index_metadata(conn)+ assert after_remove is not None+ assert after_remove["operation"] == "remove"+ assert after_remove["path"] == "entities/tracked.md"+ assert after_remove["last_indexed_at"] >= after_upsert["last_indexed_at"]+ conn.close()++# ---------------------------------------------------------------------------# Test: FTS5 MATCH query returns expected row# ---------------------------------------------------------------------------diff --git a/tests/unit/memory/wiki/test_health.py b/tests/unit/memory/wiki/test_health.pyindex de40745058..f5a8d339f3 100644--- a/tests/unit/memory/wiki/test_health.py+++ b/tests/unit/memory/wiki/test_health.py@@ -1,5 +1,9 @@"""WikiHealth: silent failures must become visible state (spec A5)."""-from jarvis.memory.wiki.health import WikiHealth+import os+import sqlite3++from jarvis.memory.wiki.fts_index import ensure_schema, upsert_page+from jarvis.memory.wiki.health import WikiHealth, inspect_index_healthdef test_snapshot_starts_unknown_but_valid():@@ -7,6 +11,7 @@ def test_snapshot_starts_unknown_but_valid():snap = h.snapshot()assert snap["bootstrap_ok"] is Noneassert snap["last_write"] is None+ assert snap["last_index"] is Noneassert snap["journal_backlog"] == 0@@ -35,4 +40,58 @@ def test_snapshot_is_json_safe():h = WikiHealth()h.record_bootstrap(True)h.record_write(True, pages=["log.md"], error=None, source="bridge")+ h.record_index(True, operation="upsert", path="entities/joy.md")json.dumps(h.snapshot()) # must not raise+++def test_index_health_reports_path_and_freshness_drift(tmp_path):+ vault = tmp_path / "vault"+ current = vault / "entities" / "current.md"+ missing = vault / "concepts" / "missing.md"+ orphan = vault / "projects" / "orphan.md"+ for path in (current, missing, orphan):+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(f"# {path.stem}\n", encoding="utf-8")++ db_path = tmp_path / "data" / "jarvis.db"+ db_path.parent.mkdir(parents=True)+ conn = sqlite3.connect(str(db_path))+ try:+ ensure_schema(conn)+ upsert_page(conn, vault, current)+ upsert_page(conn, vault, orphan)+ finally:+ conn.close()++ orphan.unlink()+ future_mtime = current.stat().st_mtime + 10.0+ os.utime(current, (future_mtime, future_mtime))++ snapshot = inspect_index_health(vault, db_path)++ assert snapshot["index_available"] is True+ assert snapshot["vault_pages"] == 2+ assert snapshot["indexed_pages"] == 2+ assert snapshot["missing_pages"] == 1+ assert snapshot["orphaned_pages"] == 1+ assert snapshot["outdated_pages"] == 1+ assert snapshot["index_state"] == "stale"+ assert snapshot["index_state_reasons"] == [+ "missing_pages",+ "orphaned_pages",+ "outdated_pages",+ ]+ assert snapshot["last_index_at"] is not None+ assert snapshot["index_lag_seconds"] > 0+++def test_empty_vault_with_missing_index_is_not_reported_healthy(tmp_path):+ vault = tmp_path / "vault"+ vault.mkdir()++ snapshot = inspect_index_health(vault, tmp_path / "missing.db")++ assert snapshot["vault_pages"] == 0+ assert snapshot["index_available"] is False+ assert snapshot["index_state"] == "stale"+ assert snapshot["index_state_reason"] == "index_unavailable"diff --git a/tests/unit/memory/wiki/test_watcher.py b/tests/unit/memory/wiki/test_watcher.pyindex 77646f7f40..8a032fbffa 100644--- a/tests/unit/memory/wiki/test_watcher.py+++ b/tests/unit/memory/wiki/test_watcher.py@@ -14,6 +14,8 @@ Anti-patterns avoided:from __future__ import annotationsimport asyncio+import sqlite3+from collections.abc import Callablefrom pathlib import Pathimport pytest@@ -23,7 +25,6 @@ from jarvis.core.bus import EventBusfrom jarvis.core.events import WikiPageChangedfrom jarvis.memory.wiki.watcher import WikiWatcher-# Plenty of slack — Windows ReadDirectoryChangesW is usually <50 ms but# we have seen the test runner pause much longer under load.EVENT_WAIT_S = 5.0@@ -36,11 +37,34 @@ def _make_vault(root: Path) -> Path:return root+async def _wait_for_index(+ db_path: Path,+ predicate: Callable[[sqlite3.Connection], bool],+ *,+ wait_s: float = EVENT_WAIT_S,+) -> None:+ """Poll a real FTS database until ``predicate`` observes the change."""+ deadline = asyncio.get_running_loop().time() + wait_s+ while asyncio.get_running_loop().time() < deadline:+ if await asyncio.to_thread(db_path.is_file):+ conn = sqlite3.connect(str(db_path))+ try:+ try:+ if predicate(conn):+ return+ except sqlite3.OperationalError:+ pass+ finally:+ conn.close()+ await asyncio.sleep(0.05)+ pytest.fail("timed out waiting for the wiki FTS index")++async def _collect_events(bus: EventBus,*,count: int,- timeout: float = EVENT_WAIT_S,+ wait_s: float = EVENT_WAIT_S,) -> list[WikiPageChanged]:"""Wait for ``count`` :class:`WikiPageChanged` events on the bus.@@ -59,8 +83,8 @@ async def _collect_events(bus.subscribe(WikiPageChanged, _on_event)try:try:- await asyncio.wait_for(fut, timeout=timeout)- except asyncio.TimeoutError:+ await asyncio.wait_for(fut, timeout=wait_s)+ except TimeoutError:passfinally:bus.unsubscribe(WikiPageChanged, _on_event)@@ -195,6 +219,108 @@ async def test_burst_modifications_are_debounced(watcher_stack):assert events[0].slug == "karpathy"+async def test_manual_create_modify_delete_maintains_fts(tmp_path: Path):+ """Manual vault edits update and remove their FTS row without restart."""+ vault = _make_vault(tmp_path / "vault")+ db_path = tmp_path / "data" / "jarvis.db"+ bus = EventBus()+ watcher = WikiWatcher(+ vault_root=vault,+ bus=bus,+ debounce_ms=50,+ db_path=db_path,+ )+ assert watcher.start()+ await asyncio.sleep(0.1)+ target = vault / "entities" / "manual.md"+ try:+ target.write_text("# Manual\n\nFirst version.\n", encoding="utf-8")+ await _wait_for_index(+ db_path,+ lambda conn: conn.execute(+ "SELECT COUNT(*) FROM wiki_fts WHERE path = ? AND body LIKE ?",+ ("entities/manual.md", "%First version%"),+ ).fetchone()[0]+ == 1,+ )++ target.write_text("# Manual\n\nSecond version.\n", encoding="utf-8")+ await _wait_for_index(+ db_path,+ lambda conn: conn.execute(+ "SELECT COUNT(*) FROM wiki_fts WHERE path = ? AND body LIKE ?",+ ("entities/manual.md", "%Second version%"),+ ).fetchone()[0]+ == 1,+ )++ # Atomic-save editors may report an intermediate deletion even though+ # the replacement file exists by the end of the debounce window.+ target.write_text("# Manual\n\nAtomic replacement.\n", encoding="utf-8")+ watcher._handle_event(str(target), "deleted") # noqa: SLF001+ await _wait_for_index(+ db_path,+ lambda conn: conn.execute(+ "SELECT COUNT(*) FROM wiki_fts WHERE path = ? AND body LIKE ?",+ ("entities/manual.md", "%Atomic replacement%"),+ ).fetchone()[0]+ == 1,+ )++ target.unlink()+ await _wait_for_index(+ db_path,+ lambda conn: conn.execute(+ "SELECT COUNT(*) FROM wiki_fts WHERE path = ?",+ ("entities/manual.md",),+ ).fetchone()[0]+ == 0,+ )+ finally:+ await watcher.shutdown()+++async def test_visible_root_page_is_indexed_without_ui_event(tmp_path: Path):+ """Full-index pages outside content folders stay searchable but stay quiet."""+ vault = _make_vault(tmp_path / "vault")+ db_path = tmp_path / "data" / "jarvis.db"+ bus = EventBus()+ watcher = WikiWatcher(+ vault_root=vault,+ bus=bus,+ debounce_ms=50,+ db_path=db_path,+ )+ received: list[WikiPageChanged] = []++ async def _on_event(event: WikiPageChanged) -> None:+ received.append(event)++ bus.subscribe(WikiPageChanged, _on_event)+ assert watcher.start()+ await asyncio.sleep(0.1)+ try:+ (vault / "schema.md").write_text(+ "# Schema\n\nSearchable root page.\n",+ encoding="utf-8",+ )+ await _wait_for_index(+ db_path,+ lambda conn: conn.execute(+ "SELECT COUNT(*) FROM wiki_fts WHERE path = ?",+ ("schema.md",),+ ).fetchone()[0]+ == 1,+ )+ await asyncio.sleep(0.2)+ assert received == []+ finally:+ bus.unsubscribe(WikiPageChanged, _on_event)+ await watcher.shutdown()++@pytest.mark.asyncioasync def test_non_markdown_files_are_ignored(watcher_stack):"""Writing a .txt file produces no event."""diff --git a/tests/unit/ui/web/test_wiki_routes.py b/tests/unit/ui/web/test_wiki_routes.pyindex 60c83cf42f..6278af0534 100644--- a/tests/unit/ui/web/test_wiki_routes.py+++ b/tests/unit/ui/web/test_wiki_routes.py@@ -515,11 +515,20 @@ def test_reindex_replaces_stale_rows_with_active_vault(with TestClient(app) as client:preview = client.post("/api/wiki/reindex", params={"dry_run": "true"}).json()result = client.post("/api/wiki/reindex").json()+ health = client.get("/api/wiki/health").json()["health"]assert preview["indexed_before"] == 1assert preview["indexed_pages"] == 1assert result["ok"] is Trueassert result["indexed_pages"] == 3+ assert health["index_state"] == "ok"+ assert health["indexed_pages"] == health["vault_pages"] == 3+ assert health["missing_pages"] == 0+ assert health["orphaned_pages"] == 0+ assert health["outdated_pages"] == 0+ assert health["last_index_at"] is not None+ assert health["last_index_operation"] == "rebuild"+ assert health["index_lag_seconds"] == 0.0conn = sqlite3.connect(str(db_path))try:@@ -589,7 +598,11 @@ def test_health_returns_200_with_fresh_snapshot(assert body["health"]["journal_backlog"] == 0assert body["health"]["bootstrap_ok"] is Noneassert body["health"]["last_write"] is None+ assert body["health"]["last_index"] is Noneassert body["health"]["last_chain_failure"] is None+ assert body["health"]["index_available"] is False+ assert body["health"]["index_state"] == "stale"+ assert body["health"]["index_state_reason"] == "vault_unavailable"def test_health_restores_last_write_and_backlog_from_journal(tmp_path: Path) -> None:@@ -630,4 +643,6 @@ def test_health_restores_last_write_and_backlog_from_journal(tmp_path: Path) ->assert health["journal_backlog"] == 1assert health["last_write"]["pages"] == ["entities/ruben.md"]assert health["vault_pages"] == 1+ assert health["missing_pages"] == 1+ assert health["orphaned_pages"] == 0assert health["index_state"] == "stale"