Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(obsidian): make vault failures legible instead of opaque

Bingxi Zhao (Frank)8450a928c401
diff --git a/deeptutor/capabilities/obsidian/tools.py b/deeptutor/capabilities/obsidian/tools.py
index 00c89c6c0..c58ddd1fd 100644
--- a/deeptutor/capabilities/obsidian/tools.py
+++ b/deeptutor/capabilities/obsidian/tools.py
@@ -14,13 +14,17 @@ never supplies or sees it, so it cannot read or write outside the vault.
from __future__ import annotations
+import datetime
import json
+import logging
from pathlib import Path
from typing import Any
from deeptutor.capabilities.obsidian import vault as vault_ops
from deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResult
+logger = logging.getLogger(__name__)
+
# Tool names mounted together when an Obsidian turn is active. Single source of
# truth so the mount policy and the registration list can't disagree.
OBSIDIAN_TOOL_NAMES: tuple[str, ...] = (
@@ -51,8 +55,26 @@ def _no_vault_result() -> ToolResult:
)
+def _json_default(value: Any) -> str:
+ """Render a frontmatter scalar ``json`` has no encoder for.
+
+ YAML parses an unquoted ``created: 2026-08-11`` into a ``datetime.date``,
+ and Obsidian's own Templates plugin writes dates that way. Dates and times
+ serialise as ISO-8601 — ``str()`` alone renders a ``datetime`` as
+ ``2026-08-11 00:00:00``, which is not a form the model can feed back as a
+ date. Anything else degrades to its string form rather than failing the
+ whole tool call.
+ """
+ if isinstance(value, (datetime.date, datetime.time)):
+ return value.isoformat()
+ return str(value)
+
+
def _ok(payload: Any) -> ToolResult:
- return ToolResult(content=json.dumps(payload, ensure_ascii=False, default=str), success=True)
+ return ToolResult(
+ content=json.dumps(payload, ensure_ascii=False, default=_json_default),
+ success=True,
+ )
def _err(message: str) -> ToolResult:
@@ -70,6 +92,14 @@ class _ObsidianTool(BaseTool):
return await self._run(root, kwargs)
except vault_ops.VaultError as exc:
return _err(str(exc))
+ except Exception as exc:
+ # A tool failure the model cannot see is one it cannot route around:
+ # an opaque "unknown error" sent it inventing workarounds for a
+ # cause it had no information about. Name the cause for the model
+ # and keep the traceback for the operator.
+ name = self.get_definition().name
+ logger.exception("Obsidian tool %s failed", name)
+ return _err(f"{name} failed: {type(exc).__name__}: {exc}")
async def _run(self, root: Path, kwargs: dict[str, Any]) -> ToolResult: # pragma: no cover
raise NotImplementedError
diff --git a/deeptutor/capabilities/obsidian/vault.py b/deeptutor/capabilities/obsidian/vault.py
index 7caae7c9c..d18f401f0 100644
--- a/deeptutor/capabilities/obsidian/vault.py
+++ b/deeptutor/capabilities/obsidian/vault.py
@@ -52,6 +52,39 @@ def _iter_markdown(root: Path):
yield path
+def _read_text(path: Path) -> str:
+ """Decode a note for reading, tolerating bytes that are not valid UTF-8.
+
+ Vaults edited across editors, synced from Windows, or holding non-Latin
+ prose routinely carry a few mangled bytes — invisible in Obsidian itself.
+ Strict decoding would let one such note abort an operation that spans the
+ whole vault, so undecodable bytes are replaced and every decodable
+ character is kept.
+
+ Reads only. A read-modify-write must use :func:`_read_text_exact`, which
+ refuses to launder those bytes back onto disk.
+ """
+ return path.read_text(encoding="utf-8", errors="replace")
+
+
+def _read_text_exact(path: Path) -> str:
+ """Decode a note that is about to be written back, without substitution.
+
+ Rewriting a note we could only partially decode would replace the user's
+ bytes with U+FFFD, so writes stay strict. Raising ``VaultError`` (rather
+ than letting ``UnicodeDecodeError`` escape) is what makes the refusal
+ legible: the tool layer turns it into a message naming the note and the
+ fix, instead of an opaque failure.
+ """
+ try:
+ return path.read_text(encoding="utf-8")
+ except UnicodeDecodeError as exc:
+ raise VaultError(
+ f"Note {path.name!r} is not valid UTF-8 (byte offset {exc.start}); "
+ "editing it would corrupt the undecodable bytes. Fix its encoding first."
+ ) from exc
+
+
def _safe_join(root: Path, rel: str) -> Path:
"""Resolve ``rel`` under ``root``, refusing anything that escapes the vault."""
root_resolved = root.resolve()
@@ -132,7 +165,7 @@ def read_note(root: Path, ref: str) -> dict[str, Any]:
path = resolve_note(root, ref)
if path is None:
raise VaultError(f"Note {ref!r} not found in the vault.")
- text = path.read_text(encoding="utf-8", errors="replace")
+ text = _read_text(path)
frontmatter, body = split_frontmatter(text)
return {"path": _rel(root, path), "frontmatter": frontmatter, "body": body}
@@ -146,7 +179,7 @@ def search_notes(root: Path, query: str, limit: int = 20) -> list[dict[str, str]
hits: list[dict[str, str]] = []
for path in _iter_markdown(root):
try:
- text = path.read_text(encoding="utf-8", errors="replace")
+ text = _read_text(path)
except OSError:
continue
if needle in path.stem.lower() or needle in text.lower():
@@ -191,7 +224,7 @@ def backlinks(root: Path, ref: str, limit: int = 50) -> list[dict[str, str]]:
if path == target:
continue
try:
- text = path.read_text(encoding="utf-8", errors="replace")
+ text = _read_text(path)
except OSError:
continue
if any(t.strip().lower() == stem for t in _WIKILINK_RE.findall(text)):
@@ -212,7 +245,7 @@ def collect_tags(root: Path, limit: int = 200) -> list[dict[str, Any]]:
for path in _iter_markdown(root):
try:
- text = path.read_text(encoding="utf-8", errors="replace")
+ text = _read_text(path)
except OSError:
continue
frontmatter, body = split_frontmatter(text)
@@ -254,7 +287,7 @@ def append_note(root: Path, ref: str, content: str) -> str:
path = resolve_note(root, ref)
if path is None:
raise VaultError(f"Note {ref!r} not found; create it first.")
- existing = path.read_text(encoding="utf-8")
+ existing = _read_text_exact(path)
separator = "" if existing.endswith("\n") or not existing else "\n"
path.write_text(existing + separator + (content or ""), encoding="utf-8")
return _rel(root, path)
@@ -268,7 +301,7 @@ def set_property(root: Path, ref: str, key: str, value: Any) -> str:
path = resolve_note(root, ref)
if path is None:
raise VaultError(f"Note {ref!r} not found; create it first.")
- frontmatter, body = split_frontmatter(path.read_text(encoding="utf-8"))
+ frontmatter, body = split_frontmatter(_read_text_exact(path))
frontmatter[key] = value
path.write_text(_compose_note(frontmatter, body), encoding="utf-8")
return _rel(root, path)
diff --git a/tests/capabilities/test_obsidian_capability.py b/tests/capabilities/test_obsidian_capability.py
index a3f32248b..525e373ad 100644
--- a/tests/capabilities/test_obsidian_capability.py
+++ b/tests/capabilities/test_obsidian_capability.py
@@ -273,3 +273,70 @@ def test_obsidian_vault_refs_enumerates_every_selected_vault(monkeypatch, tmp_pa
monkeypatch.setattr("deeptutor.multi_user.knowledge_access.resolve_kb_metadata", fake)
ctx = UnifiedContext(user_message="hi", knowledge_bases=["vaultA", "kb1", "vaultB"])
assert obsidian_binding.obsidian_vault_refs(ctx) == {"vaultA", "vaultB"}
+
+
+# ---- failures must be legible, and must not corrupt the vault ----------------
+
+
+def _write_undecodable(root: Path, name: str = "broken.md") -> Path:
+ path = root / name
+ path.write_bytes(b"hello \xe5\xaa world\n")
+ return path
+
+
+def test_vault_refuses_to_rewrite_an_undecodable_note(tmp_path: Path) -> None:
+ """Lenient reads have a strict counterpart: a read-modify-write must not
+ launder undecodable bytes into U+FFFD, and must say so as a VaultError so
+ the tool layer can explain it instead of failing opaquely."""
+ path = _write_undecodable(tmp_path)
+ original = path.read_bytes()
+
+ for operation in (
+ lambda: V.append_note(tmp_path, "broken", "more"),
+ lambda: V.set_property(tmp_path, "broken", "status", "draft"),
+ ):
+ with pytest.raises(V.VaultError, match="not valid UTF-8"):
+ operation()
+
+ assert path.read_bytes() == original
+
+
+async def test_append_to_undecodable_note_explains_itself(tmp_path: Path) -> None:
+ """The model gets a message it can act on, not an unknown error."""
+ _write_undecodable(tmp_path)
+
+ res = await ObsidianAppendTool().execute(
+ note="broken.md", content="x", _vault_path=str(tmp_path)
+ )
+
+ assert res.success is False
+ assert "not valid UTF-8" in res.content and "encoding" in res.content
+
+
+async def test_datetime_frontmatter_serialises_as_iso(tmp_path: Path) -> None:
+ """A YAML timestamp is a datetime; str() would render it with a space."""
+ (tmp_path / "stamped.md").write_text(
+ "---\ncreated: 2026-08-11 09:30:00\n---\n\nbody\n", encoding="utf-8"
+ )
+
+ res = await ObsidianReadTool().execute(note="stamped.md", _vault_path=str(tmp_path))
+
+ assert json.loads(res.content)["frontmatter"]["created"] == "2026-08-11T09:30:00"
+
+
+async def test_unexpected_tool_failure_names_its_cause(tmp_path: Path, monkeypatch) -> None:
+ """Issue #914: a non-VaultError escaping the tool left the model with
+ "An unknown error occurred" and nothing to act on."""
+
+ def boom(*_args, **_kwargs):
+ raise RuntimeError("disk went away")
+
+ monkeypatch.setattr(V, "read_note", boom)
+
+ res = await ObsidianReadTool().execute(note="whatever", _vault_path=str(tmp_path))
+
+ assert res.success is False
+ assert "RuntimeError" in res.content and "disk went away" in res.content