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(brain): ultrawiki-search router tool + live worker gate (ADR-0011/0030)
Ruben Lütke2a825d9aea8f
diff --git a/docs/adr/0011-router-pure-dispatcher.md b/docs/adr/0011-router-pure-dispatcher.mdindex 9015623d97..735b784fb8 100644--- a/docs/adr/0011-router-pure-dispatcher.md+++ b/docs/adr/0011-router-pure-dispatcher.md@@ -1034,3 +1034,23 @@ reports that as a network problem instead of implying a bad credential.- `tests/unit/plugins/tool/test_home_assistant_rest.py`- `tests/unit/marketplace/test_instance_url.py`- `tests/unit/brain/test_routing.py` (ROUTER_TOOLS parity)++## Amendment: UltraWiki Search (2026-07-25)++`ultrawiki-search` joins `ROUTER_TOOLS`: the read-only pull primitive over+the UltraWiki semantic store (fused keyword + vector retrieval with citation+permalinks, `jarvis/plugins/tool/ultrawiki_search.py`). Direct safe-gated+read, never a spawn (AP-5/AP-14). Resolver-not-instance wiring (the+UltraWikiService is built by the WebServer after the brain — the wiki-ingest+lazy-curator precedent); the tool loads even while UltraWiki mode is+disabled and answers with an honest steer to the classic `wiki-*` tools, so+the router's tool surface stays stable across mode toggles. Mission workers+reach it only through the ADR-0025 broker grant once the ADR-0030 gate is+live. A dedicated `who_is` primitive stays DEFERRED until the UltraWiki P5+identity layer exists; until then `ultrawiki-search` answers "who is X"+queries via hybrid search.++### Regression guards++- `tests/unit/plugins/tool/test_ultrawiki_search_tool.py`+- `tests/unit/brain/test_routing.py` (ROUTER_TOOLS exact set)diff --git a/docs/adr/0030-worker-knowledge-surface-parity.md b/docs/adr/0030-worker-knowledge-surface-parity.mdindex 8003d8fa26..04f9e0cba7 100644--- a/docs/adr/0030-worker-knowledge-surface-parity.md+++ b/docs/adr/0030-worker-knowledge-surface-parity.md@@ -48,7 +48,7 @@ the static wiki triple stays exported for read-compat. Per tool:| `awareness-recall` | **granted** | `[awareness].enabled`, fail closed || `search_web` | **granted** | none (keyless, safe-tier) || `contact-lookup` | **granted** | none (degrades to a clean "contacts unavailable" error) |-| `ultrawiki-search` | **planned** | gate ships fail-closed OFF; flips when the router tool + `UltraWikiService` exist (`cfg.ultrawiki.enabled` ∧ live service) |+| `ultrawiki-search` | **granted** | `cfg.ultrawiki.enabled` ∧ live `UltraWikiService` on the web-app state, fail closed (gate went live 2026-07-25 together with the router tool, ADR-0011 amendment "UltraWiki Search") || `awareness-snapshot` | **excluded** | live-desktop read: near-zero value in an isolated worktree, pure privacy leakage of current screen activity into external CLI transcripts || `contact-upsert` | **excluded (deferred)** | unattended write to the contact store; least privilege — not part of a knowledge surface |diff --git a/jarvis/brain/factory.py b/jarvis/brain/factory.pyindex 137021e925..af105ed759 100644--- a/jarvis/brain/factory.py+++ b/jarvis/brain/factory.py@@ -118,6 +118,14 @@ ROUTER_TOOLS = frozenset({# explicitly store a fact ("merk dir: …") rather than relying on the# aggressive-mode VoiceFactBridge heuristic."wiki-ingest",+ # UltraWiki semantic search (2026-07-25): fused keyword+vector retrieval+ # with citations over the UltraWiki store — the pull primitive for the+ # semantic memory mode. Read-only, honest-degradation ladder (disabled+ # mode steers to the classic wiki-* tools). Direct safe-gated read,+ # never a spawn; mission workers reach it only through the ADR-0025+ # broker once the ADR-0030 gate is live (AP-5/AP-14). See ADR-0011+ # amendment "UltraWiki Search".+ "ultrawiki-search",# CLI-Integration (2026-05-24): virtual loader that expands to one# ``cli_<name>`` tool per connected & usable CLI (gcloud, gh, docker, …).# This is the MCP/plugin model for command-line tools: only connected@@ -497,6 +505,18 @@ def _load_tools_for_tier(from jarvis.plugins.tool.wiki_ingest import WikiIngestToolinst = WikiIngestTool(curator_resolver=get_running_curator)+ elif ep.name == "ultrawiki-search":+ # UltraWiki search: resolver-not-instance — the+ # UltraWikiService is built by the WebServer AFTER the brain+ # (mirrors wiki-ingest's lazy curator). Loads even while the+ # mode is disabled; execute() then answers with the honest+ # steer-to-wiki error, keeping the tool surface stable+ # across mode toggles (awareness-recall precedent).+ from jarvis.plugins.tool.ultrawiki_search import (+ build_ultrawiki_service_resolver,+ )++ inst = cls(service_resolver=build_ultrawiki_service_resolver())elif ep.name == "update-profile":# Profile-write tool: mutate the SAME live UserProfile instance# the BrainManager renders from (factory passes one instance todiff --git a/jarvis/missions/workers/capabilities.py b/jarvis/missions/workers/capabilities.pyindex 6633409ee4..517ea2ef0b 100644--- a/jarvis/missions/workers/capabilities.py+++ b/jarvis/missions/workers/capabilities.py@@ -222,14 +222,24 @@ def _awareness_recall_available() -> bool:def _ultrawiki_worker_tool_available() -> bool:- """Gate for the ``ultrawiki-search`` grant — deliberately OFF for now.+ """``ultrawiki-search`` joins the grant only when it can actually answer.- Flips live once the ``ultrawiki-search`` router tool ships: the honest- condition is ``cfg.ultrawiki.enabled`` AND a running ``UltraWikiService``- on the web app state. Until then this returns False so the name never- enters a grant (phantom-tool rule, ADR-0030).+ Honest grant condition (ADR-0030): UltraWiki mode is enabled AND the+ ``UltraWikiService`` is live on the web-app state. The startup race is+ covered by ``ensure_started()`` inside ``service.search()``; the+ gateway-catalog intersection remains the structural backstop for a tool+ that never loaded. Fails closed on any error (phantom-tool rule)."""- return False+ try:+ from jarvis.core import runtime_refs # noqa: PLC0415 — lazy, boot-safe+ from jarvis.core.config import load_config # noqa: PLC0415++ if not load_config().ultrawiki.enabled:+ return False+ app = runtime_refs.get_web_app()+ return getattr(getattr(app, "state", None), "ultrawiki", None) is not None+ except Exception: # noqa: BLE001 - config/runtime drift must not break missions+ return Falsedef restricted_worker_knowledge_tools() -> tuple[str, ...]:diff --git a/jarvis/plugins/tool/ultrawiki_search.py b/jarvis/plugins/tool/ultrawiki_search.pynew file mode 100644index 0000000000..6704a4df98--- /dev/null+++ b/jarvis/plugins/tool/ultrawiki_search.py@@ -0,0 +1,186 @@+"""``ultrawiki-search`` tool — hybrid semantic search over the UltraWiki store.++Router-tier pull tool (ADR-0011 amendment "UltraWiki Search"); mission workers+reach it only through the ADR-0025 broker grant once the ADR-0030 gate is live.++Why this tool exists+--------------------+UltraWiki is the semantic memory mode of the Wiki section (``UltraWiki/*.md``,+roadmap P4): fused keyword + vector retrieval with RRF, optional rerank, and+citation permalinks. The engine and REST surface exist; this tool is the+brain-facing primitive so voice/chat can PULL from the store when the user+asks a knowledge question while UltraWiki mode is active.++Pull-only by design: this tool never injects unsolicited context. The+relevance floor (``rerank_min_score``) governs unsolicited surfaces; an+explicit search on the user's behalf shows what matched, best first+(``enforce_floor`` stays off — the Ask-view semantics).++Resolution+----------+``service_resolver`` returns the live :class:`~jarvis.ultrawiki.service.+UltraWikiService` or ``None``. Resolver-not-instance because the service is+constructed by the WebServer AFTER the brain build (the wiki-ingest lazy+curator precedent). The tool loads even when UltraWiki mode is disabled and+answers with an honest steer-to-wiki error — a stable tool surface across+mode toggles (the awareness-recall precedent).++Honesty ladder (anti-confabulation, 2026-06-18 lesson)+------------------------------------------------------+* no service → ``success=False`` "not running" (bootstrap in flight)+* mode disabled → ``success=False`` steer to the classic ``wiki-*`` tools+* search raised → ``success=False`` with the exception text+* zero hits → ``success=True`` with a sentence that AFFIRMS the store+ was searched — an honest "empty" must never escalate into a false+ "unavailable" claim.+"""++from __future__ import annotations++import logging+from collections.abc import Callable+from typing import Any++from jarvis.core.protocols import ToolResult++log = logging.getLogger(__name__)++_MAX_SNIPPET_CHARS = 220+_MAX_OUTPUT_CHARS = 4000+++def build_ultrawiki_service_resolver() -> Callable[[], Any]:+ """Default resolver: the live service the WebServer parked on app state."""++ def _resolve() -> Any:+ from jarvis.core import runtime_refs # noqa: PLC0415 — lazy, boot-safe++ app = runtime_refs.get_web_app()+ return getattr(getattr(app, "state", None), "ultrawiki", None)++ return _resolve+++def _render_hit(hit: Any) -> str:+ """One compact markdown line per fused hit, citation included."""+ title = str(getattr(hit, "title", "") or "(untitled)").strip()+ snippet = " ".join(str(getattr(hit, "snippet", "") or "").split())+ if len(snippet) > _MAX_SNIPPET_CHARS:+ snippet = snippet[:_MAX_SNIPPET_CHARS].rstrip() + "…"+ source = str(getattr(hit, "source_id", "") or "?")+ stamp = str(getattr(hit, "timestamp_utc", "") or "")+ permalink = str(getattr(hit, "permalink", "") or "")+ matched = getattr(hit, "matched_by", ()) or ()+ matched_note = f" [{', '.join(str(m) for m in matched)}]" if matched else ""+ cite = f" ({permalink})" if permalink else ""+ when = f", {stamp}" if stamp else ""+ return f"- [{source}{when}] **{title}** — {snippet}{cite}{matched_note}"+++class UltraWikiSearchTool:+ """Router-tier hybrid search over the UltraWiki semantic store."""++ name: str = "ultrawiki-search"+ description: str = (+ "Search the UltraWiki semantic knowledge base (fused keyword + vector "+ "retrieval with citations). Call this for knowledge questions when "+ "UltraWiki mode is active — e.g. facts about people, projects, past "+ "decisions, or anything the user stored. Returns up to k ranked hits, "+ "each with a citation permalink. Read-only. When UltraWiki mode is "+ "disabled, use the classic wiki tools (wiki-recall, wiki-page-read) "+ "instead."+ )+ risk_tier: str = "safe"+ schema: dict[str, Any] = {+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "description": "The search query — a short phrase or keywords.",+ },+ "k": {+ "type": "integer",+ "default": 5,+ "minimum": 1,+ "maximum": 10,+ "description": "Maximum number of ranked hits to return.",+ },+ "area": {+ "type": "string",+ "description": "Optional area id to restrict the search to.",+ },+ },+ "required": ["query"],+ }++ def __init__(self, service_resolver: Callable[[], Any] | None = None) -> None:+ self._resolve_service = service_resolver or build_ultrawiki_service_resolver()++ @staticmethod+ def _mode_enabled() -> bool:+ try:+ from jarvis.core.config import load_config # noqa: PLC0415 — lazy++ return bool(load_config().ultrawiki.enabled)+ except Exception: # noqa: BLE001 — config drift must not crash the turn+ return False++ async def execute(self, args: dict[str, Any], ctx: Any) -> ToolResult:+ query = str(args.get("query", "")).strip()+ if not query:+ return ToolResult(+ success=True,+ output="(empty query — nothing searched; provide a phrase or keywords)",+ )+ k = max(1, min(int(args.get("k", 5) or 5), 10))+ area = str(args.get("area", "") or "").strip() or None++ if not self._mode_enabled():+ return ToolResult(+ success=False,+ output="",+ error=(+ "UltraWiki mode is disabled — use the classic wiki tools "+ "(wiki-recall, wiki-page-read, wiki-list) instead."+ ),+ )+ service = self._resolve_service()+ if service is None:+ return ToolResult(+ success=False,+ output="",+ error="UltraWiki service is not running (bootstrap may still be in flight).",+ )++ try:+ hits = await service.search(query, k=k, area_id=area)+ except Exception as exc: # noqa: BLE001 — surface honestly, never crash the turn+ log.warning("ultrawiki-search failed for %r: %s", query, exc)+ return ToolResult(+ success=False,+ output="",+ error=f"UltraWiki search failed: {exc}",+ )++ hits = list(hits or ())+ if not hits:+ # Affirm reachability so an honest "empty" can never be narrated+ # as the store being down.+ return ToolResult(+ success=True,+ output=(+ f"UltraWiki was searched successfully for '{query}' — "+ "no stored item matched."+ ),+ )++ lines = [f"UltraWiki hits for '{query}' (best first):"]+ lines.extend(_render_hit(hit) for hit in hits[:k])+ output = "\n".join(lines)+ if len(output) > _MAX_OUTPUT_CHARS:+ output = output[:_MAX_OUTPUT_CHARS].rstrip() + "…"+ log.info("ultrawiki-search: %d hit(s) for %r", len(hits), query)+ return ToolResult(success=True, output=output)+++__all__ = ["UltraWikiSearchTool", "build_ultrawiki_service_resolver"]diff --git a/tests/missions/test_worker_capability_parity.py b/tests/missions/test_worker_capability_parity.pyindex 7d6bf088ab..a2cb190d02 100644--- a/tests/missions/test_worker_capability_parity.py+++ b/tests/missions/test_worker_capability_parity.py@@ -136,17 +136,36 @@ def test_awareness_gate_adds_session_memory(monkeypatch: pytest.MonkeyPatch) ->assert "awareness-recall" in restricted_worker_knowledge_tools()-def test_ultrawiki_gate_ships_fail_closed(monkeypatch: pytest.MonkeyPatch) -> None:- """The ultrawiki-search grant stays OFF until the router tool + service- exist — a phantom tool must never enter a grant (ADR-0030)."""+def test_ultrawiki_gate_requires_mode_and_live_service(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The ultrawiki-search grant is honest: only when UltraWiki mode is ON+ and the service is live does the name enter a grant — a phantom tool+ must never reach a worker (ADR-0030)."""+ from types import SimpleNamespace++ from jarvis.core import runtime_refsfrom jarvis.missions.workers import capabilities+ # Test environment: no live service (and default mode off) → closed.assert capabilities._ultrawiki_worker_tool_available() is Falseassert "ultrawiki-search" not in restricted_worker_knowledge_tools()- monkeypatch.setattr(capabilities, "_ultrawiki_worker_tool_available", lambda: True)+ # Mode enabled + live service on the web-app state → granted.+ cfg = SimpleNamespace(ultrawiki=SimpleNamespace(enabled=True))+ monkeypatch.setattr("jarvis.core.config.load_config", lambda *a, **k: cfg)+ monkeypatch.setattr(+ runtime_refs,+ "get_web_app",+ lambda: SimpleNamespace(state=SimpleNamespace(ultrawiki=object())),+ )+ assert capabilities._ultrawiki_worker_tool_available() is Trueassert "ultrawiki-search" in restricted_worker_knowledge_tools()+ # Mode enabled but the service is absent → still closed.+ monkeypatch.setattr(runtime_refs, "get_web_app", lambda: None)+ assert capabilities._ultrawiki_worker_tool_available() is False+def test_every_granted_knowledge_tool_passes_the_broker_denylist(monkeypatch: pytest.MonkeyPatch,diff --git a/tests/unit/brain/test_routing.py b/tests/unit/brain/test_routing.pyindex b4b4541d5f..47bcab8f40 100644--- a/tests/unit/brain/test_routing.py+++ b/tests/unit/brain/test_routing.py@@ -1874,6 +1874,12 @@ def test_router_tools_is_pure_dispatcher_set() -> None:# "what is in my wiki" in one round. Read-only, never a spawn.# ADR-0011 amendment "wiki-list tool"."wiki-list",+ # UltraWiki semantic search (2026-07-25): fused keyword+vector+ # retrieval with citations — the pull primitive of the semantic+ # memory mode. Read-only, never a spawn (AP-5/AP-14); workers+ # reach it only via the ADR-0025 broker (ADR-0030 gate).+ # ADR-0011 amendment "UltraWiki Search".+ "ultrawiki-search",# CLI-Integration (2026-05-24): virtual loader that expands to one# cli_<name> tool per connected & usable CLI. Router-tier only — a# cli_<name> tool is a direct safe-gated action, never a recursivediff --git a/tests/unit/plugins/tool/test_ultrawiki_search_tool.py b/tests/unit/plugins/tool/test_ultrawiki_search_tool.pynew file mode 100644index 0000000000..6b8bb5e1a8--- /dev/null+++ b/tests/unit/plugins/tool/test_ultrawiki_search_tool.py@@ -0,0 +1,129 @@+"""``ultrawiki-search`` — router-tier hybrid search with an honesty ladder.++Pins the ADR-0011 amendment "UltraWiki Search": ROUTER_TOOLS membership, the+safe read-only contract, and the anti-confabulation ladder (no service /+disabled mode / search failure / honest empty vs. rendered hits).+"""++from __future__ import annotations++from dataclasses import dataclass, field+from typing import Any++import pytest++import jarvis.plugins.tool.ultrawiki_search as mod+from jarvis.plugins.tool.ultrawiki_search import UltraWikiSearchTool+++@dataclass+class _Hit:+ item_id: int = 1+ source_id: str = "obsidian_vault"+ title: str = "Project Phoenix"+ snippet: str = "Phoenix is the rewrite of the ingestion layer started in June."+ permalink: str = "uw://item/1"+ timestamp_utc: str = "2026-07-20T10:00:00Z"+ score: float = 0.03+ matched_by: tuple[str, ...] = field(default_factory=lambda: ("keyword", "vector"))+++class _FakeService:+ def __init__(self, hits: list[Any] | None = None, error: Exception | None = None) -> None:+ self._hits = hits or []+ self._error = error+ self.calls: list[dict[str, Any]] = []++ async def search(self, query: str, *, k: int, area_id: str | None) -> list[Any]:+ self.calls.append({"query": query, "k": k, "area_id": area_id})+ if self._error is not None:+ raise self._error+ return self._hits+++def _tool(service: Any, *, enabled: bool = True) -> UltraWikiSearchTool:+ tool = UltraWikiSearchTool(service_resolver=lambda: service)+ tool._mode_enabled = staticmethod(lambda: enabled) # type: ignore[method-assign]+ return tool+++def test_registered_in_router_tools() -> None:+ from jarvis.brain.factory import ROUTER_TOOLS++ assert "ultrawiki-search" in ROUTER_TOOLS+++def test_contract_is_safe_read_only() -> None:+ tool = UltraWikiSearchTool(service_resolver=lambda: None)+ assert tool.name == "ultrawiki-search"+ assert tool.risk_tier == "safe"+ assert tool.schema["required"] == ["query"]+++async def test_no_service_is_an_honest_error() -> None:+ tool = _tool(None, enabled=True)+ result = await tool.execute({"query": "phoenix"}, ctx=None)+ assert result.success is False+ assert "not running" in (result.error or "")+++async def test_disabled_mode_steers_to_classic_wiki() -> None:+ tool = _tool(_FakeService(), enabled=False)+ result = await tool.execute({"query": "phoenix"}, ctx=None)+ assert result.success is False+ assert "wiki-recall" in (result.error or "")+++async def test_search_failure_surfaces_honestly() -> None:+ tool = _tool(_FakeService(error=RuntimeError("store gone")), enabled=True)+ result = await tool.execute({"query": "phoenix"}, ctx=None)+ assert result.success is False+ assert "store gone" in (result.error or "")+++async def test_empty_result_affirms_reachability() -> None:+ """An honest 'empty' must never be narratable as 'the store is down'."""+ tool = _tool(_FakeService(hits=[]), enabled=True)+ result = await tool.execute({"query": "phoenix"}, ctx=None)+ assert result.success is True+ assert "searched successfully" in result.output+++async def test_hits_render_with_citation_and_legs() -> None:+ service = _FakeService(hits=[_Hit()])+ tool = _tool(service, enabled=True)+ result = await tool.execute({"query": "phoenix", "k": 3, "area": "work"}, ctx=None)+ assert result.success is True+ assert "Project Phoenix" in result.output+ assert "uw://item/1" in result.output # citation permalink+ assert "keyword" in result.output # matched_by legs stay visible+ assert service.calls == [{"query": "phoenix", "k": 3, "area_id": "work"}]+++async def test_k_is_clamped_to_schema_bounds() -> None:+ service = _FakeService(hits=[_Hit()])+ tool = _tool(service, enabled=True)+ await tool.execute({"query": "phoenix", "k": 99}, ctx=None)+ assert service.calls[0]["k"] == 10+++async def test_empty_query_is_a_clean_no_op() -> None:+ service = _FakeService()+ tool = _tool(service, enabled=True)+ result = await tool.execute({"query": " "}, ctx=None)+ assert result.success is True+ assert service.calls == []+++def test_default_resolver_reads_web_app_state(monkeypatch: pytest.MonkeyPatch) -> None:+ from types import SimpleNamespace++ from jarvis.core import runtime_refs++ sentinel = object()+ monkeypatch.setattr(+ runtime_refs,+ "get_web_app",+ lambda: SimpleNamespace(state=SimpleNamespace(ultrawiki=sentinel)),+ )+ assert mod.build_ultrawiki_service_resolver()() is sentinel