Skip to content

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

fix(obsidian): resolve qualified backlink targets

dajiaohuangdc2b50355acd
diff --git a/deeptutor/capabilities/obsidian/vault.py b/deeptutor/capabilities/obsidian/vault.py
index d18f401f0..546493b39 100644
--- a/deeptutor/capabilities/obsidian/vault.py
+++ b/deeptutor/capabilities/obsidian/vault.py
@@ -214,20 +214,37 @@ def outgoing_links(root: Path, ref: str) -> list[str]:
def backlinks(root: Path, ref: str, limit: int = 50) -> list[dict[str, str]]:
- """Notes that link to ``ref`` via ``[[name]]`` (matched by basename)."""
+ """Notes whose wikilinks resolve to the same destination as ``ref``."""
target = resolve_note(root, ref)
if target is None:
raise VaultError(f"Note {ref!r} not found in the vault.")
- stem = target.stem.lower()
+ notes = list(_iter_markdown(root))
+ exact_names: dict[str, Path] = {}
+ folded_names: dict[str, Path] = {}
+ for note in notes:
+ exact_names.setdefault(note.stem, note)
+ folded_names.setdefault(note.stem.lower(), note)
+
+ def points_to_target(link: str) -> bool:
+ link = link.strip()
+ if "/" in link or link.lower().endswith(".md"):
+ try:
+ destination = resolve_note(root, link)
+ except VaultError:
+ return False
+ else:
+ destination = exact_names.get(link) or folded_names.get(link.lower())
+ return destination is not None and destination.resolve() == target.resolve()
+
out: list[dict[str, str]] = []
- for path in _iter_markdown(root):
+ for path in notes:
if path == target:
continue
try:
text = _read_text(path)
except OSError:
continue
- if any(t.strip().lower() == stem for t in _WIKILINK_RE.findall(text)):
+ if any(points_to_target(link) for link in _WIKILINK_RE.findall(text)):
out.append({"path": _rel(root, path), "snippet": _snippet(text, target.stem)})
if len(out) >= limit:
break
diff --git a/tests/capabilities/test_obsidian_backlink_paths.py b/tests/capabilities/test_obsidian_backlink_paths.py
new file mode 100644
index 000000000..d1aa11148
--- /dev/null
+++ b/tests/capabilities/test_obsidian_backlink_paths.py
@@ -0,0 +1,55 @@
+"""Resolve Obsidian backlink destinations using real vault notes."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from deeptutor.capabilities.obsidian.tools import ObsidianBacklinksTool
+
+
+ "link",
+ [
+ "[[concepts/Photosynthesis]]",
+ "[[concepts/Photosynthesis.md#Light|Overview]]",
+ "![[concepts/Photosynthesis#^block]]",
+ ],
+)
+async def test_backlinks_include_folder_qualified_targets(tmp_path: Path, link: str) -> None:
+ """Folder paths, headings, aliases and embeds retain their destination."""
+ target = tmp_path / "concepts" / "Photosynthesis.md"
+ target.parent.mkdir()
+ target.write_text("Plant energy.\n", encoding="utf-8")
+ (tmp_path / "Index.md").write_text(link + "\n", encoding="utf-8")
+
+ result = await ObsidianBacklinksTool().execute(
+ _vault_path=str(tmp_path), note="concepts/Photosynthesis.md"
+ )
+
+ assert result.success
+ assert [item["path"] for item in json.loads(result.content)["backlinks"]] == ["Index.md"]
+
+
+async def test_backlinks_do_not_attribute_same_stem_to_another_note(tmp_path: Path) -> None:
+ """The link resolver chooses one note when basenames are duplicated."""
+ for folder in ("concepts", "other"):
+ target = tmp_path / folder / "Photosynthesis.md"
+ target.parent.mkdir()
+ target.write_text(folder + "\n", encoding="utf-8")
+ (tmp_path / "Index.md").write_text("[[Photosynthesis]]\n", encoding="utf-8")
+
+ chosen = await ObsidianBacklinksTool().execute(
+ _vault_path=str(tmp_path), note="concepts/Photosynthesis.md"
+ )
+ other = await ObsidianBacklinksTool().execute(
+ _vault_path=str(tmp_path), note="other/Photosynthesis.md"
+ )
+
+ assert chosen.success and other.success
+ assert [item["path"] for item in json.loads(chosen.content)["backlinks"]] == ["Index.md"]
+ assert json.loads(other.content)["backlinks"] == []