Skip to content

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.

fix(wiki): stop code-quoted and template scaffolding from polluting the memory map

Ruben Lütke98e67d86fef4
diff --git a/jarvis/memory/wiki/wikilink.py b/jarvis/memory/wiki/wikilink.py
index f2b0fadd97..3025f80d65 100644
--- a/jarvis/memory/wiki/wikilink.py
+++ b/jarvis/memory/wiki/wikilink.py
@@ -36,6 +36,43 @@ SEARCHABLE_DIRS: tuple[str, ...] = ("entities", "concepts", "projects", "session
# A leading ``+`` (one-or-more) prevents matching ``[[]]``.
_WIKILINK_RE = re.compile(r"(?<!\\)\[\[([^\]\n]+)\]\]")
+# Code is documentation, not linkage: Obsidian renders neither inline code
+# spans nor fenced blocks as live links, and the vault's own ``schema.md``
+# quotes example links (`` `[[wikilinks]]` ``) in code throughout. Matching
+# inside code once produced phantom graph nodes for every quoted example —
+# including one whose "target" was half a sentence, because a lone ``[[``
+# inside an inline span absorbed all prose up to the next real ``]]``.
+_INLINE_CODE_RE = re.compile(r"(`+)([^`\n]+?)\1")
+_FENCE_OPEN_RE = re.compile(r"^[ \t]{0,3}(`{3,}|~{3,})")
+
+
+def _blank_code_regions(body: str) -> str:
+ """Replace fenced code blocks and inline code spans with spaces.
+
+ Offsets and newlines are preserved so callers that search the original
+ body for context (snippets, backlinks) stay aligned.
+ """
+ lines: list[str] = []
+ fence_char = ""
+ for line in body.splitlines(keepends=True):
+ match = _FENCE_OPEN_RE.match(line)
+ if fence_char:
+ lines.append(_blank_keep_newline(line))
+ if match and match.group(1)[0] == fence_char:
+ fence_char = ""
+ continue
+ if match:
+ fence_char = match.group(1)[0]
+ lines.append(_blank_keep_newline(line))
+ continue
+ lines.append(_INLINE_CODE_RE.sub(lambda m: " " * len(m.group(0)), line))
+ return "".join(lines)
+
+
+def _blank_keep_newline(line: str) -> str:
+ stripped = line.rstrip("\r\n")
+ return " " * len(stripped) + line[len(stripped):]
+
def extract_wikilinks(body: str) -> tuple[str, ...]:
"""Return all wikilink targets in ``body`` in source order.
@@ -43,11 +80,12 @@ def extract_wikilinks(body: str) -> tuple[str, ...]:
The returned strings are in *canonical form*: the alias (the part
after ``|``) is stripped, but any directory prefix is preserved.
Duplicates are kept — a page that references ``[[ruben]]`` twice
- yields a 2-tuple. Escaped links (``\\[[ignored]]``) and empty links
- (``[[]]``) are not returned.
+ yields a 2-tuple. Escaped links (``\\[[ignored]]``), empty links
+ (``[[]]``), and links inside inline code or fenced code blocks are
+ not returned.
"""
out: list[str] = []
- for match in _WIKILINK_RE.finditer(body):
+ for match in _WIKILINK_RE.finditer(_blank_code_regions(body)):
target = _canonicalise(match.group(1))
if target:
out.append(target)
diff --git a/jarvis/ui/web/wiki_routes.py b/jarvis/ui/web/wiki_routes.py
index 280f0973a3..f5bf614101 100644
--- a/jarvis/ui/web/wiki_routes.py
+++ b/jarvis/ui/web/wiki_routes.py
@@ -78,6 +78,12 @@ _PAGE_DIRS: tuple[tuple[str, str], ...] = (
_EXCLUDED_PAGE_DIRS: frozenset[str] = frozenset(
{"_archive", "attachments", "90-attachments"}
)
+# Template scaffolding stays browsable in the tree but never enters the
+# graph: its bodies are unrendered placeholders (``{{title}}``, ``[[…]]``),
+# so every "link" would materialise as a phantom node.
+_TEMPLATE_DIRS: frozenset[str] = frozenset(
+ {"templates", "_templates", "99-templates"}
+)
_ROOT_FOLDER_NAME = "root"
# Snippet window (chars) for backlink context extraction around the wikilink.
@@ -158,6 +164,21 @@ def _title_of(page: WikiPage) -> str:
return page.slug.replace("-", " ").replace("_", " ").title()
+def _display_title(page: WikiPage) -> str:
+ """Frontmatter title, else H1, else humanised slug — never a placeholder.
+
+ Template pages carry unrendered Obsidian placeholders (``{{title}}``,
+ ``{{date:dddd, MMMM Do YYYY}}``) as their H1; showing those verbatim in
+ the tree or graph reads as junk, so any candidate containing ``{{``
+ falls through to the next source.
+ """
+ for candidate in (str(page.frontmatter.get("title") or ""), _title_of(page)):
+ candidate = candidate.strip()
+ if candidate and "{{" not in candidate:
+ return candidate
+ return _human_title_from_slug(page.slug)
+
+
def _kind_of(page: WikiPage) -> str:
"""Schema kind (entity/concept/project/session/meta) of a page."""
return page.page_type or "meta"
@@ -289,7 +310,7 @@ def _tree_from_visible_pages(
files = [
{
"slug": item.page.slug,
- "title": item.page.frontmatter.get("title") or _title_of(item.page),
+ "title": _display_title(item.page),
"mtime": item.mtime,
"size": item.size,
}
@@ -393,7 +414,7 @@ async def get_page(slug: str, request: Request) -> dict[str, Any]:
size_bytes = len(page.body.encode("utf-8"))
rel_path = _relative_to_vault(page_path, vault_root)
- title = page.frontmatter.get("title") or _title_of(page)
+ title = _display_title(page)
body_md = page.body
words = len(body_md.split())
@@ -432,7 +453,14 @@ async def get_graph(request: Request) -> dict[str, Any]:
log.warning("wiki_route_failed route=/graph error=%s", exc)
return {"ok": False, "error": "graph build failed"}
- pages = [item.page for item in visible]
+ pages = [
+ item.page
+ for item in visible
+ if not (
+ len(item.relative_path.parts) > 1
+ and item.relative_path.parts[0].casefold() in _TEMPLATE_DIRS
+ )
+ ]
nodes: list[dict[str, Any]] = []
known_slugs: set[str] = set()
@@ -445,7 +473,7 @@ async def get_graph(request: Request) -> dict[str, Any]:
{
"id": slug,
"kind": _kind_of(page),
- "title": page.frontmatter.get("title") or _title_of(page),
+ "title": _display_title(page),
}
)
@@ -507,7 +535,7 @@ async def get_backlinks(slug: str, request: Request) -> dict[str, Any]:
out.append(
{
"slug": src.slug,
- "title": src.frontmatter.get("title") or _title_of(src),
+ "title": _display_title(src),
"snippet": snippet,
}
)
diff --git a/tests/unit/memory/wiki/test_wikilink.py b/tests/unit/memory/wiki/test_wikilink.py
index 3824b557de..a860376c25 100644
--- a/tests/unit/memory/wiki/test_wikilink.py
+++ b/tests/unit/memory/wiki/test_wikilink.py
@@ -76,6 +76,43 @@ def test_extract_adjacent_links() -> None:
assert extract_wikilinks("[[a]][[b]]") == ("a", "b")
+def test_extract_ignores_inline_code_spans() -> None:
+ # Quoted example links in docs (schema.md style) are not live links.
+ body = "Use `[[wikilinks]]` or the short form `[[ruben]]` in prose."
+ assert extract_wikilinks(body) == ()
+
+
+def test_extract_ignores_fenced_code_blocks() -> None:
+ body = (
+ "Log format:\n"
+ "```\n"
+ "- pages touched: [[entities/x]], [[concepts/y]]\n"
+ "```\n"
+ "Real link: [[alice]].\n"
+ )
+ assert extract_wikilinks(body) == ("alice",)
+
+
+def test_extract_lone_open_bracket_in_code_span_does_not_swallow_prose() -> None:
+ # Regression: a bare ``[[`` inside inline code once absorbed the whole
+ # sentence up to the next real closing ``]]``, creating a phantom link
+ # target that was half a paragraph long.
+ body = (
+ "typing `[[` should surface candidates instantly, and all sit on "
+ "top of [[Markdown as Foundation]]. The [[Graph View Visualisation]] "
+ "becomes a diagnostic."
+ )
+ assert extract_wikilinks(body) == (
+ "Markdown as Foundation",
+ "Graph View Visualisation",
+ )
+
+
+def test_extract_tilde_fence_and_unclosed_fence_ignored() -> None:
+ body = "~~~\n[[inside]]\n~~~\n[[real]]\n```\n[[dangling]]"
+ assert extract_wikilinks(body) == ("real",)
+
+
def test_extract_link_with_internal_whitespace_preserved() -> None:
# Internal whitespace inside the slug is preserved (no normalisation).
# The schema discourages it but the parser tolerates anything that is
diff --git a/tests/unit/ui/web/test_wiki_routes.py b/tests/unit/ui/web/test_wiki_routes.py
index ca19cacf53..6821d092c0 100644
--- a/tests/unit/ui/web/test_wiki_routes.py
+++ b/tests/unit/ui/web/test_wiki_routes.py
@@ -406,9 +406,11 @@ def test_starter_vault_pages_are_readable_and_connected_in_graph(
).json()
assert graph["ok"] is True
- assert len(graph["nodes"]) == 12
+ # Template scaffolding stays out of the graph (10 of the 12 tree pages).
+ assert len(graph["nodes"]) == 10
node_ids = {node["id"] for node in graph["nodes"]}
assert {"README", "Home", "Personal Knowledge Management"} <= node_ids
+ assert node_ids.isdisjoint({"Daily Note", "Note Template"})
edge_pairs = {(edge["source"], edge["target"]) for edge in graph["edges"]}
assert ("Home", "Personal Knowledge Management") in edge_pairs
assert ("Home", "README") in edge_pairs
@@ -421,6 +423,51 @@ def test_starter_vault_pages_are_readable_and_connected_in_graph(
assert {item["slug"] for item in backlinks["backlinks"]} == {"Home"}
+def test_template_placeholder_titles_fall_back_to_filename(tmp_path: Path) -> None:
+ """Obsidian template files carry unrendered ``{{...}}`` placeholders as
+ their H1. The tree must show the filename instead of the placeholder,
+ and the templates folder must not leak nodes or phantom link targets
+ into the graph."""
+ vault = tmp_path / "vault"
+ templates = vault / "99-templates"
+ templates.mkdir(parents=True)
+ (templates / "Daily Note.md").write_text(
+ "---\ntags: [daily]\ncreated: {{date:YYYY-MM-DD}}\n---\n\n"
+ "# {{date:dddd, MMMM Do YYYY}}\n\n## Plan\n\n-\n",
+ encoding="utf-8",
+ )
+ (templates / "Note Template.md").write_text(
+ "---\ntags: []\n---\n\n# {{title}}\n\n## See Also\n\n- [[…]]\n- [[…]]\n",
+ encoding="utf-8",
+ )
+ _write_page(
+ vault,
+ "entities",
+ "alice",
+ page_type="entity",
+ body="# Alice\n\n## Summary\nA person.\n",
+ )
+
+ app = _make_app(vault)
+ with TestClient(app) as client:
+ tree = client.get("/api/wiki/tree").json()
+ graph = client.get("/api/wiki/graph").json()
+
+ folders_by_name = {folder["name"]: folder for folder in tree["folders"]}
+ template_titles = {
+ f["slug"]: f["title"] for f in folders_by_name["99-templates"]["files"]
+ }
+ assert template_titles == {
+ "Daily Note": "Daily Note",
+ "Note Template": "Note Template",
+ }
+
+ assert graph["ok"] is True
+ assert {node["id"] for node in graph["nodes"]} == {"alice"}
+ assert graph["edges"] == []
+ assert graph["broken"] == [] # no phantom "…" targets from template bodies
+
+
# ----------------------------------------------------------------------
# /backlinks/{slug}
# ----------------------------------------------------------------------