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
chore: auto-save WIP via Claude stop-hook safety net (2026-07-14 09:49)
Ruben Lütke8f361098dc4e
diff --git a/jarvis/brain/factory.py b/jarvis/brain/factory.pyindex 777946f3e0..54833f330b 100644--- a/jarvis/brain/factory.py+++ b/jarvis/brain/factory.py@@ -107,6 +107,12 @@ ROUTER_TOOLS = frozenset({# wiki-recall when the brain has narrowed to one page and needs the# complete content, not the 240-char snippet."wiki-page-read",+ # Grounded vault listing (2026-07-14): deterministic ground-truth answer+ # for "what is in my wiki" in ONE round. Without it the brain probed+ # blindly (index.md/SOUL.md → not found, ~14 rounds, 66 s) and recited+ # schema.md's example layout as actual content. Read-only, safe — never+ # in a worker set (AP-5/AP-14). See ADR-0011 amendment "wiki-list tool".+ "wiki-list",# Phase B5 follow-up: deterministic ingest path. Lets the brain# explicitly store a fact ("merk dir: …") rather than relying on the# aggressive-mode VoiceFactBridge heuristic.@@ -462,6 +468,12 @@ def _load_tools_for_tier(from jarvis.plugins.tool.wiki_page_read import _build_page_read_toolinst = _build_page_read_tool()+ elif ep.name == "wiki-list":+ # Grounded vault listing: same vault-root resolution as the+ # other wiki tools.+ from jarvis.plugins.tool.wiki_list import _build_wiki_list_tool++ inst = _build_wiki_list_tool()elif ep.name == "wiki-ingest":# Phase B5 follow-up: lazy curator resolver — the curator is# constructed by ``bootstrap_wiki_integration`` after the braindiff --git a/jarvis/plugins/tool/wiki_list.py b/jarvis/plugins/tool/wiki_list.pynew file mode 100644index 0000000000..8140dd16c2--- /dev/null+++ b/jarvis/plugins/tool/wiki_list.py@@ -0,0 +1,187 @@+"""``wiki-list`` tool — deterministic listing of the long-term Obsidian wiki.++Forensic origin (voice session 2026-07-14 09:29, 66 s turn)+-----------------------------------------------------------+Asked "what is in my wiki", the delegated router brain had no way to SEE+the vault. It probed blindly — ``wiki-recall`` → ``wiki-page-read+index.md`` (not found) → ``SOUL.md`` (not found) — burning ~14 LLM+rounds, then recited the *example* directory layout from ``schema.md``+(the vault's editing contract) as if it were the actual vault content.+Every named file in the spoken answer was invented.++A listing question needs a listing tool: this one walks the real vault+once and returns ground truth in a single round — path, size, first+heading — so the model neither probes nor guesses.++Placement rule+--------------+Router-tier only, read-only, risk ``safe``. Never in any worker tool set+(AP-5/AP-14).++Privacy rule (matches ``wiki-recall`` / ``wiki-page-read``):+ Only paths, sizes, and first headings are returned/logged — never+ page bodies.+"""+from __future__ import annotations++import logging+from pathlib import Path+from typing import Any++from jarvis.core.protocols import ToolResult++log = logging.getLogger(__name__)++# Upper bound on listed pages so a pathological vault cannot flood the+# brain context (the tool-use loop additionally caps every tool result).+_MAX_ENTRIES: int = 500++# Only this many leading bytes are read per file to extract the first+# heading and detect a meta page — never the full body.+_HEAD_BYTES: int = 2048+++def _first_heading_and_meta(path: Path) -> tuple[str, bool]:+ """Return ``(first_heading, is_meta)`` from a page's leading bytes.++ ``is_meta`` is True when a YAML frontmatter block declares+ ``type: meta`` — those pages (e.g. ``schema.md``) are the vault's+ maintenance contract, not user content, and get flagged in the+ listing so the model cannot present the contract's example layout+ as actual vault contents (live incident 2026-07-14).+ """+ try:+ head = path.read_text(encoding="utf-8", errors="replace")[:_HEAD_BYTES]+ except OSError:+ return "", False++ is_meta = False+ lines = head.splitlines()+ if lines and lines[0].strip() == "---":+ for line in lines[1:32]:+ if line.strip() == "---":+ break+ key, _, value = line.partition(":")+ if key.strip().lower() == "type" and value.strip().lower() == "meta":+ is_meta = True+ break++ heading = ""+ for line in lines:+ if line.startswith("# "):+ heading = line[2:].strip()+ break+ return heading, is_meta+++class WikiListTool:+ """Router-tier ground-truth listing of the long-term Obsidian wiki vault."""++ name: str = "wiki-list"+ description: str = (+ "List what ACTUALLY exists in the user's long-term Obsidian wiki "+ "vault: every markdown page with its vault-relative path, size, and "+ "title. Call this FIRST for overview questions like 'what is in my "+ "wiki / notes / vault', before guessing any page path, and whenever "+ "wiki-page-read reported 'not found'. This listing is the ground "+ "truth — a page absent here does not exist, regardless of what the "+ "schema/contract page describes."+ )+ risk_tier: str = "safe"+ schema: dict[str, Any] = {+ "type": "object",+ "properties": {},+ }+ input_examples: list[dict[str, Any]] = [{}]++ def __init__(self, vault_root: Path) -> None:+ # Resolve once at construction time so symlink games cannot move+ # the vault out from under us mid-session (matches wiki-page-read).+ self._vault_root = vault_root.resolve()++ async def execute(self, args: dict[str, Any], ctx: Any) -> ToolResult:+ root = self._vault_root+ if not root.is_dir():+ return ToolResult(+ success=True,+ output=(+ "The wiki vault directory does not exist yet — the wiki "+ "is empty. Nothing has been saved so far."+ ),+ )++ pages: list[tuple[str, int]] = []+ truncated = False+ for path in sorted(root.rglob("*.md")):+ rel = path.relative_to(root)+ # Skip hidden trees (.obsidian app config, .trash, …).+ if any(part.startswith(".") for part in rel.parts):+ continue+ if not path.is_file():+ continue+ if len(pages) >= _MAX_ENTRIES:+ truncated = True+ break+ try:+ size = path.stat().st_size+ except OSError:+ continue+ pages.append((rel.as_posix(), size))++ if not pages:+ return ToolResult(+ success=True,+ output="The wiki vault is empty — no markdown pages exist yet.",+ )++ lines = [f"Wiki vault listing ({len(pages)} page(s)):"]+ for rel_posix, size in pages:+ heading, is_meta = _first_heading_and_meta(root / rel_posix)+ suffix = f" — {heading}" if heading else ""+ marker = (+ " [system file — the vault's editing contract, NOT user "+ "content; its example layout is not the real vault]"+ if is_meta+ else ""+ )+ lines.append(f"- {rel_posix} ({size} bytes){suffix}{marker}")+ if truncated:+ lines.append(+ f"… [truncated: more than {_MAX_ENTRIES} pages exist; "+ f"showing the first {_MAX_ENTRIES}]"+ )++ log.info("wiki-list: served %d page(s)%s",+ len(pages), " (truncated)" if truncated else "")+ return ToolResult(success=True, output="\n".join(lines))+++def _build_wiki_list_tool() -> "WikiListTool":+ """Construct a :class:`WikiListTool` with the configured vault root.++ Mirrors ``wiki_page_read._build_page_read_tool`` so the factory can+ wire all wiki tools the same way (resolves through+ :func:`jarvis.memory.wiki.vault_root.resolve_vault_root`, spec A7).+ """+ from jarvis.memory.wiki.vault_root import resolve_vault_root++ raw: str | Path | None = None+ try:+ from jarvis.core import config as cfg++ loaded = cfg.load_config()+ wiki_cfg = getattr(loaded, "wiki_integration", None)+ if wiki_cfg is not None:+ raw = wiki_cfg.vault_root+ except Exception as exc: # noqa: BLE001+ log.debug("wiki-list: config load skipped: %s", exc)++ vault_root = resolve_vault_root(raw).path+ if raw is None:+ log.warning(+ "wiki-list: cfg.wiki_integration.vault_root not found; "+ "defaulting to %s",+ vault_root,+ )++ return WikiListTool(vault_root=vault_root)diff --git a/jarvis/plugins/tool/wiki_page_read.py b/jarvis/plugins/tool/wiki_page_read.pyindex f177547962..ed9bfa6530 100644--- a/jarvis/plugins/tool/wiki_page_read.py+++ b/jarvis/plugins/tool/wiki_page_read.py@@ -43,6 +43,32 @@ log = logging.getLogger(__name__)# normal wiki page is a few KB; 64 KB is generous head-room._MAX_PAGE_BYTES: int = 64 * 1024+# Provenance warning prepended to meta/contract pages (``type: meta``+# frontmatter, e.g. schema.md). Live incident 2026-07-14: the delegated+# brain read schema.md and presented its EXAMPLE directory layout as the+# actual vault contents — every file it named was invented. The warning+# is deterministic (no LLM involved) so the model always sees it.+_META_PAGE_WARNING: str = (+ "[system file — this page is the vault's editing CONTRACT, not user "+ "content. Any directory layout or file names below are EXAMPLES of the "+ "intended structure, NOT a listing of what exists. Use wiki-list for "+ "the real vault contents.]\n\n"+)+++def _frontmatter_declares_meta(content: str) -> bool:+ """True when a leading YAML frontmatter block declares ``type: meta``."""+ lines = content.splitlines()+ if not lines or lines[0].strip() != "---":+ return False+ for line in lines[1:32]:+ if line.strip() == "---":+ return False+ key, _, value = line.partition(":")+ if key.strip().lower() == "type" and value.strip().lower() == "meta":+ return True+ return False+class WikiPageReadTool:"""Router-tier full-page reader for the long-term Obsidian wiki vault."""@@ -147,6 +173,8 @@ class WikiPageReadTool:# Prefix with the relative path so the brain has unambiguous# provenance in the prompt without having to remember the request.header = f"# {rel.as_posix()}\n\n"+ if _frontmatter_declares_meta(content):+ header = _META_PAGE_WARNING + headerreturn ToolResult(success=True, output=header + content)diff --git a/pyproject.toml b/pyproject.tomlindex d1b2f14e45..19af3a21d3 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -479,6 +479,9 @@ run-skill = "jarvis.plugins.tool.run_skill:RunSkillTool"wiki-recall = "jarvis.plugins.tool.wiki_recall:WikiRecallTool"# Phase B5 follow-up — full-page reader (router-tier, read-only).wiki-page-read = "jarvis.plugins.tool.wiki_page_read:WikiPageReadTool"+# Grounded vault listing (2026-07-14) — deterministic "what is in my wiki"+# answer in one round (router-tier, read-only).+wiki-list = "jarvis.plugins.tool.wiki_list:WikiListTool"# Phase B5 follow-up — deterministic ingest tool (router-tier, write).wiki-ingest = "jarvis.plugins.tool.wiki_ingest:WikiIngestTool"# Profile-write (2026-05-30) — deterministic writer for the structured USER.mddiff --git a/tests/unit/brain/test_routing.py b/tests/unit/brain/test_routing.pyindex aa51a5a28a..893ebdd47d 100644--- a/tests/unit/brain/test_routing.py+++ b/tests/unit/brain/test_routing.py@@ -1744,6 +1744,10 @@ def test_router_tools_is_pure_dispatcher_set() -> None:# + deterministic ingest (write via WikiCurator). Both router-tier only."wiki-page-read","wiki-ingest",+ # Grounded vault listing (2026-07-14): ground-truth answer for+ # "what is in my wiki" in one round. Read-only, never a spawn.+ # ADR-0011 amendment "wiki-list tool".+ "wiki-list",# 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_wiki_list.py b/tests/unit/plugins/tool/test_wiki_list.pynew file mode 100644index 0000000000..8cf5718cf3--- /dev/null+++ b/tests/unit/plugins/tool/test_wiki_list.py@@ -0,0 +1,126 @@+"""Tests for the ``wiki-list`` tool — grounded vault listings.++Forensic origin (voice session 2026-07-14 09:29): asked "what is in my+wiki", the delegated brain had no listing tool, so it probed blindly+(``wiki-recall`` → ``wiki-page-read index.md`` → not found → ``SOUL.md``+→ not found, ~14 LLM rounds, 66 s) and finally recited the *example*+directory layout from ``schema.md`` as if it were the actual vault+content — pure hallucination. A deterministic listing answers the+question in ONE round and is ground truth by construction.++Hard-negatives:+ 1. ``wiki-list`` MUST be in ROUTER_TOOLS (and never in any worker set).+ 2. The listing MUST reflect the real filesystem — files that exist are+ present, files that do not exist are absent.+ 3. Meta/contract pages (``type: meta`` frontmatter) MUST be flagged so+ the model cannot mistake the schema contract for user content.+ 4. An empty vault MUST produce an honest "empty" answer, not an error.+"""+from __future__ import annotations++from pathlib import Path++import pytest++from jarvis.brain.factory import ROUTER_TOOLS+from jarvis.plugins.tool.wiki_list import WikiListTool+++def vault(tmp_path: Path) -> Path:+ """Minimal realistic vault: content pages + a meta contract page."""+ (tmp_path / "entities").mkdir()+ (tmp_path / "entities" / "ruben.md").write_text(+ "# Ruben\n\nThe maintainer.\n", encoding="utf-8"+ )+ (tmp_path / "projects").mkdir()+ (tmp_path / "projects" / "personal-jarvis.md").write_text(+ "# Personal Jarvis\n\nThe project.\n", encoding="utf-8"+ )+ (tmp_path / "log.md").write_text("# Log\n", encoding="utf-8")+ (tmp_path / "schema.md").write_text(+ "---\ntype: meta\npurpose: wiki-maintenance-contract\n---\n\n"+ "# Wiki Schema\n\nExample layout: USER.md, SOUL.md, people/…\n",+ encoding="utf-8",+ )+ # Obsidian app config must never appear in the listing.+ (tmp_path / ".obsidian").mkdir()+ (tmp_path / ".obsidian" / "workspace.json").write_text("{}", encoding="utf-8")+ return tmp_path+++def test_wiki_list_is_in_router_tools() -> None:+ assert "wiki-list" in ROUTER_TOOLS+++def test_wiki_list_surface(vault: Path) -> None:+ tool = WikiListTool(vault_root=vault)+ assert tool.name == "wiki-list"+ assert tool.risk_tier == "safe"+ assert tool.schema["type"] == "object"+++async def test_wiki_list_lists_real_files_only(vault: Path) -> None:+ tool = WikiListTool(vault_root=vault)+ result = await tool.execute({}, ctx=None)+ assert result.success is True+ out = result.output+ assert "entities/ruben.md" in out+ assert "projects/personal-jarvis.md" in out+ assert "log.md" in out+ # The hallucinated names from the live incident must NOT appear.+ assert "USER.md" not in out.replace("schema.md", "")+ assert "SOUL.md" not in out+ # Hidden app config is excluded.+ assert ".obsidian" not in out+++async def test_wiki_list_flags_meta_pages(vault: Path) -> None:+ tool = WikiListTool(vault_root=vault)+ result = await tool.execute({}, ctx=None)+ assert result.success is True+ schema_line = next(+ line for line in result.output.splitlines() if "schema.md" in line+ )+ assert "system file" in schema_line.lower()+ content_line = next(+ line for line in result.output.splitlines() if "ruben.md" in line+ )+ assert "system file" not in content_line.lower()+++async def test_wiki_list_shows_page_titles(vault: Path) -> None:+ tool = WikiListTool(vault_root=vault)+ result = await tool.execute({}, ctx=None)+ assert "Ruben" in result.output+ assert "Personal Jarvis" in result.output+++async def test_wiki_list_empty_vault_is_honest(tmp_path: Path) -> None:+ tool = WikiListTool(vault_root=tmp_path)+ result = await tool.execute({}, ctx=None)+ assert result.success is True+ assert "empty" in result.output.lower()+++async def test_wiki_list_missing_vault_is_honest(tmp_path: Path) -> None:+ tool = WikiListTool(vault_root=tmp_path / "does-not-exist")+ result = await tool.execute({}, ctx=None)+ assert result.success is True+ assert "empty" in result.output.lower() or "not" in result.output.lower()+++async def test_wiki_list_caps_huge_vaults(tmp_path: Path) -> None:+ for i in range(520):+ (tmp_path / f"note-{i:04d}.md").write_text(f"# Note {i}\n", encoding="utf-8")+ tool = WikiListTool(vault_root=tmp_path)+ result = await tool.execute({}, ctx=None)+ assert result.success is True+ assert result.output.count(".md") <= 501+ assert "truncated" in result.output.lower()diff --git a/tests/unit/plugins/tool/test_wiki_tools.py b/tests/unit/plugins/tool/test_wiki_tools.pyindex 9f1c7b454e..2163e72ead 100644--- a/tests/unit/plugins/tool/test_wiki_tools.py+++ b/tests/unit/plugins/tool/test_wiki_tools.py@@ -104,6 +104,36 @@ async def test_wiki_page_read_rejects_absolute_path(vault: Path) -> None:assert result.success is False+async def test_wiki_page_read_flags_meta_contract_pages(tmp_path: Path) -> None:+ """A ``type: meta`` page (schema.md) must carry a provenance warning.++ Live incident 2026-07-14: the delegated brain read schema.md (the+ vault's editing contract) and presented its EXAMPLE layout as the+ actual vault contents. The served page must state, deterministically,+ that it is contract — not content.+ """+ tmp_path.joinpath("schema.md").write_text(+ "---\ntype: meta\npurpose: wiki-maintenance-contract\n---\n\n"+ "# Wiki Schema\n\nExample layout: USER.md, people/…\n",+ encoding="utf-8",+ )+ tool = WikiPageReadTool(vault_root=tmp_path)+ result = await tool.execute({"path": "schema.md"}, ctx=None)+ assert result.success is True+ warning = result.output.splitlines()[0].lower()+ assert "system file" in warning or "contract" in warning+ assert "not" in warning # "... NOT user content" phrasing+++async def test_wiki_page_read_leaves_content_pages_unflagged(vault: Path) -> None:+ tool = WikiPageReadTool(vault_root=vault)+ result = await tool.execute({"path": "people/harald.md"}, ctx=None)+ assert result.success is True+ assert "system file" not in result.output.lower()++@pytest.mark.asyncioasync def test_wiki_page_read_rejects_oversized_file(tmp_path: Path) -> None:tmp_path.joinpath("big.md").write_bytes(b"x" * (65 * 1024))