Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(citations): fall back to title slug when citation URL has no domain (#4880)

Se748381452be
diff --git a/changelog.d/+empty-domain-citation-label.bugfix.md b/changelog.d/+empty-domain-citation-label.bugfix.md
new file mode 100644
index 0000000000..11d57f66dd
--- /dev/null
+++ b/changelog.d/+empty-domain-citation-label.bugfix.md
@@ -0,0 +1 @@
+Fix citation labels rendering as empty `[]` for library/RAG sources. The `DOMAIN_HYPERLINKS`, `DOMAIN_ID_HYPERLINKS`, and `DOMAIN_ID_ALWAYS_HYPERLINKS` modes previously fed `urlparse(url).netloc` straight into the citation label, so any relative URL (most notably RAG / library hits that look like `/library/document/<uuid>`) produced an empty string. With a single relative-URL citation the label collapsed to `[[]](url)` and rendered as a `[]` link with no anchor text; with multiple relative-URL citations the suffix leaked out as `[[-1]](url)`, `[[-2]](url)`. The formatter now falls back to a slugified (lowercased, alphanumeric-only) version of the document title, and as a final fallback to the citation number itself, so the label is always non-empty and the link carries the document name. Real web URLs (arxiv.org, github.com, etc.) are unchanged — the domain still wins when `netloc` is non-empty.
diff --git a/pdm.lock b/pdm.lock
index 69077ae141..27bb67b6ba 100644
--- a/pdm.lock
+++ b/pdm.lock
@@ -5,7 +5,7 @@
groups = ["default", "dev", "mcp"]
strategy = ["inherit_metadata"]
lock_version = "4.5.0"
-content_hash = "sha256:110f80a608527e2e3de67e96340f48caf21d5c8e8b491b200a2ac63b77d90f71"
+content_hash = "sha256:0a9c456c49fa3fff5ab43f42433e01231d9a739e3fee8f7fe1d908c7bba709bc"
[[metadata.targets]]
requires_python = ">=3.12,<3.15"
@@ -5051,7 +5051,7 @@ name = "python-slugify"
version = "8.0.4"
requires_python = ">=3.7"
summary = "A Python slugify application that also handles Unicode"
-groups = ["dev"]
+groups = ["default", "dev"]
dependencies = [
"text-unidecode>=1.3",
]
@@ -6087,7 +6087,7 @@ files = [
name = "text-unidecode"
version = "1.3"
summary = "The most basic Text::Unidecode port"
-groups = ["dev"]
+groups = ["default", "dev"]
files = [
{file = "text-unidecode-1.3.tar.gz", hash = "sha256:bad6603bb14d279193107714b288be206cac565dfa49aa5b105294dd5c4aab93"},
{file = "text_unidecode-1.3-py2.py3-none-any.whl", hash = "sha256:1311f10e8b895935241623731c2ba64f4c455287888b18189350b67134a822e8"},
@@ -6520,7 +6520,7 @@ version = "2026.2"
requires_python = ">=2"
summary = "Provider of IANA time zone data"
groups = ["default", "dev"]
-marker = "platform_system == \"Windows\" or sys_platform == \"win32\" or sys_platform == \"emscripten\" or python_version >= \"3.9\""
+marker = "platform_system == \"Windows\" or sys_platform == \"emscripten\" or sys_platform == \"win32\" or python_version >= \"3.9\""
files = [
{file = "tzdata-2026.2-py2.py3-none-any.whl", hash = "sha256:bbe9af844f658da81a5f95019480da3a89415801f6cc966806612cc7169bffe7"},
{file = "tzdata-2026.2.tar.gz", hash = "sha256:9173fde7d80d9018e02a662e168e5a2d04f87c41ea174b139fbef642eda62d10"},
diff --git a/pyproject.toml b/pyproject.toml
index ce93d4f863..f03139a555 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -72,6 +72,7 @@ dependencies = [
# with `ModuleNotFoundError: No module named 'docx'` (see issue #4414).
"python-docx~=1.2", # .doc, .docx, .odt (odt parser imports python-docx)
"python-pptx~=1.0", # .ppt, .pptx
+ "python-slugify~=8.0", # citation_formatter._slugify_title
"openpyxl~=3.1", # .xlsx (unstructured Excel partition)
"msoffcrypto-tool~=6.0", # imported at module load by unstructured.partition.xlsx
"xlrd~=2.0", # legacy .xls reading (pandas engine)
diff --git a/src/local_deep_research/text_optimization/citation_formatter.py b/src/local_deep_research/text_optimization/citation_formatter.py
index 1c939ae69a..234435cac4 100644
--- a/src/local_deep_research/text_optimization/citation_formatter.py
+++ b/src/local_deep_research/text_optimization/citation_formatter.py
@@ -2,9 +2,12 @@
import re
from enum import Enum
-from typing import Any, Dict, List, Tuple
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import urlparse
+from slugify import slugify
+
_SOURCES_SECTION_PATTERNS = [
re.compile(
r"^#{1,3}\s*(?:Sources|References|Bibliography|Citations)",
@@ -346,11 +349,22 @@ class CitationFormatter:
num: (title, url) for num, (title, url) in sources.items() if url
}
+ # Pre-compute labels so [1, 2, 3] lists and standalone [N] refs
+ # use the same string for a given citation. Previously this
+ # closure called _extract_domain on every match, so a relative
+ # URL (``/library/document/...``) produced ``[[]]`` for every
+ # occurrence. _citation_label falls back to a slugified title
+ # for relative URLs, keeping the label non-empty and readable.
+ label_cache: Dict[str, str] = {
+ num: self._citation_label(num, title, url)
+ for num, (title, url) in url_sources.items()
+ }
+
# Create formatter for citations with domain hyperlinks
def format_domain_link(citation_num, data):
_, url = data
- domain = self._extract_domain(url)
- return f"[[{domain}]]({url})"
+ label = label_cache[citation_num]
+ return f"[[{label}]]({url})"
# Handle comma-separated citations like [1, 2, 3]
content = self._replace_comma_citations(
@@ -380,12 +394,18 @@ class CitationFormatter:
self, content: str, sources: Dict[str, Tuple[str, str]]
) -> str:
"""Replace [1] with [domain.com-1] hyperlinked version with hyphen-separated IDs."""
- # First, create a mapping of domains to their citation numbers
+ # First, create a mapping of domains to their citation numbers.
+ # _citation_label (vs raw _extract_domain) means relative URLs
+ # like ``/library/document/...`` get a slugified title as the
+ # "domain" instead of an empty string. Without this, a RAG
+ # result with one citation rendered as ``[[]](url)`` (the
+ # label disappeared), and a multi-citation set rendered as
+ # ``[[-1]](url)`` (the orphaned ``-N`` suffix leaked through).
domain_citations: dict[str, list[Any]] = {}
for citation_num, (title, url) in sources.items():
if url:
- domain = self._extract_domain(url)
+ domain = self._citation_label(citation_num, title, url)
if domain not in domain_citations:
domain_citations[domain] = []
domain_citations[domain].append((citation_num, url))
@@ -438,12 +458,16 @@ class CitationFormatter:
self, content: str, sources: Dict[str, Tuple[str, str]]
) -> str:
"""Replace [1] with [domain.com-1] hyperlinked version, always with IDs."""
- # First, create a mapping of domains to their citation numbers
+ # Use _citation_label so relative URLs (e.g. RAG /library/document/...
+ # results) produce a slugified-title prefix instead of an empty
+ # string. Without this, every label here collapses to ``-N``
+ # (e.g. ``[[-1]](url)``) and the user has no idea what the link
+ # references. See _format_domain_id_hyperlinks for the same fix.
domain_citations: dict[str, list[Any]] = {}
for citation_num, (title, url) in sources.items():
if url:
- domain = self._extract_domain(url)
+ domain = self._citation_label(citation_num, title, url)
if domain not in domain_citations:
domain_citations[domain] = []
domain_citations[domain].append((citation_num, url))
@@ -536,10 +560,26 @@ class CitationFormatter:
over URL-derived tags when present for a given citation.
"""
+ # Pre-compute tags so comma-separated [1, 2, 3] and standalone
+ # [N] refs resolve to the same string for a given citation.
+ # Without this, _extract_source_label's lazy URLClassifier import
+ # can succeed on the 2nd+ call but fail on the 1st, producing
+ # inconsistent labels (e.g. "arxiv.org-1" vs "arxiv-1").
+ tag_cache: Dict[str, str] = {
+ num: self._extract_source_label(
+ url, collection=collections.get(num)
+ )
+ for num, (_, url) in sources.items()
+ if url
+ }
+
def format_link(citation_num, data):
_, url = data
- label = self._extract_source_label(
- url, collection=collections.get(citation_num)
+ label = tag_cache.get(
+ citation_num,
+ self._extract_source_label(
+ url, collection=collections.get(citation_num)
+ ),
)
tag = f"{label}-{citation_num}"
# Only emit a hyperlink for http(s) URLs — local/file URLs are
@@ -586,6 +626,44 @@ class CitationFormatter:
slug = re.sub(r"[^a-z0-9]+", "-", name.strip().lower()).strip("-")
return slug or "local"
+ @staticmethod
+ def _slugify_title(title: str, max_length: int = 32) -> Optional[str]:
+ """Generate a slug from a document title using python-slugify.
+
+ Returns ``None`` when ``title`` is empty / whitespace / pure
+ punctuation, or when ``slugify`` produces an empty result. The
+ ``None`` sentinel lets callers distinguish "no meaningful slug"
+ from "slug happens to be a real word" (e.g. a document literally
+ titled ``"Doc"`` must yield ``"doc"`` as its label, not fall
+ through to the citation-number fallback).
+ """
+ if not title:
+ return None
+ slug = slugify(title, max_length=max_length, separator="-")
+ return slug if slug else None
+
+ def _citation_label(self, citation_num: str, title: str, url: str) -> str:
+ """Return the inline-citation label for a source.
+
+ Order of preference:
+ 1. The URL's domain (``arxiv.org``, ``example.com``) — used by
+ web citations. Falls through when the URL is relative or
+ empty, as is common for RAG / library documents.
+ 2. A slugified version of the document title (truncated to
+ keep labels compact) — gives users a readable label for
+ local-library hits.
+ 3. The citation number itself — last-resort guarantee the
+ label is never empty (an empty label produces ``[[]]``
+ which renders as an uninformative ``[]`` link).
+ """
+ domain = self._extract_domain(url) if url else ""
+ if domain:
+ return domain
+ slug = self._slugify_title(title)
+ if slug:
+ return slug
+ return str(citation_num)
+
@staticmethod
def _is_linkable_url(url: str) -> bool:
"""Return True iff ``url`` is a http(s) URL safe to wrap in a
@@ -634,9 +712,38 @@ class CitationFormatter:
# Lazy import to keep the formatter usable when the content_fetcher
# package isn't importable (e.g. minimal test setups).
+ #
+ # We must avoid going through ``content_fetcher/__init__.py``
+ # because it eagerly imports ``ContentFetcher`` and its heavy
+ # transitive dependency tree (requests, playwright, sqlalchemy, …).
+ # Instead, load ``url_classifier.py`` directly from disk using
+ # ``importlib.util`` so the package chain is never entered.
+ # Tracked as follow-up tech debt — once ``content_fetcher`` is
+ # refactored to lazy-import its heavy deps (see #4992), this
+ # loader can be replaced with a normal ``from
+ # ..content_fetcher.url_classifier import URLClassifier, URLType``.
try:
- from ..content_fetcher.url_classifier import URLClassifier, URLType
- except ImportError:
+ import importlib.util
+
+ _uc_path = (
+ Path(__file__).resolve().parent
+ / ".."
+ / "content_fetcher"
+ / "url_classifier.py"
+ )
+ _uc_spec = importlib.util.spec_from_file_location(
+ "_url_classifier",
+ _uc_path,
+ )
+ if _uc_spec is not None and _uc_spec.loader is not None:
+ _uc_mod = importlib.util.module_from_spec(_uc_spec)
+ _uc_spec.loader.exec_module(_uc_mod)
+ URLClassifier = _uc_mod.URLClassifier
+ URLType = _uc_mod.URLType
+ else:
+ return self._extract_domain(url)
+ except Exception:
+ # Full import failed — fall back to domain-based label.
return self._extract_domain(url)
url_type = URLClassifier.classify(url)
@@ -644,7 +751,7 @@ class CitationFormatter:
# is a known academic source whose enum value is the short tag.
if url_type in (URLType.HTML, URLType.PDF, URLType.INVALID):
return self._extract_domain(url)
- return url_type.value
+ return str(url_type.value)
def _extract_domain(self, url: str) -> str:
"""Extract domain name from URL."""
@@ -707,7 +814,7 @@ class QuartoExporter:
title = title_match.group(1) if title_match else "Research Report"
# Create Quarto YAML header
- from datetime import datetime, UTC
+ from datetime import UTC, datetime
current_date = datetime.now(UTC).strftime("%Y-%m-%d")
yaml_header = f"""---
@@ -1028,7 +1135,7 @@ class RISExporter:
pass
# Y1 - Year accessed (current year)
- from datetime import datetime, UTC
+ from datetime import UTC, datetime
current_year = datetime.now(UTC).year
lines.append(f"Y1 - {current_year}")
diff --git a/tests/text_optimization/test_citation_formatter.py b/tests/text_optimization/test_citation_formatter.py
index fc7c5d9f8b..c5264d42b4 100644
--- a/tests/text_optimization/test_citation_formatter.py
+++ b/tests/text_optimization/test_citation_formatter.py
@@ -1,6 +1,7 @@
"""Tests for citation formatter functionality."""
import pytest
+
from local_deep_research.text_optimization import (
CitationFormatter,
CitationMode,
@@ -1881,3 +1882,516 @@ class TestReplaceCommaCitations:
assert "[1]" in result
assert "[2]" in result
assert "[3]" in result
+
+
+# ---------------------------------------------------------------------------
+# Regression tests for the empty-citation-label bug.
+#
+# Bug: _extract_domain() returns "" for relative URLs (e.g.
+# /library/document/<uuid> from RAG / library sources). The three
+# domain-hyperlink formatters used to embed that empty string directly,
+# producing "[[]](url)" (rendered as a bare "[]" link) and "[[-1]](url)"
+# for multi-citation results. _citation_label / _slugify_title close the
+# gap. These tests guard against regression.
+# ---------------------------------------------------------------------------
+
+
+def _library_url(suffix: str = "abc") -> str:
+ """Return a relative /library/document/<suffix> URL like RAG emits."""
+ return f"/library/document/{suffix}"
+
+
+class TestRelativeUrlCitationLabels:
+ """Empty-domain bug regression. All three fixed modes must produce
+ a non-empty label for relative URLs (e.g. /library/document/... from
+ RAG / library sources) by falling back to a slugified title."""
+
+ # ---- DOMAIN_HYPERLINKS -----------------------------------------------
+
+ def test_domain_hyperlinks_single_relative_url_uses_title_slug(self):
+ """Before fix: [[]](url). After: [[<title-slug>]](url)."""
+ content = """# Report
+
+See [1] for details.
+
+## Sources
+
+[1] Sumerian King List
+ URL: /library/document/abc-123
+"""
+ formatter = CitationFormatter(CitationMode.DOMAIN_HYPERLINKS)
+ result = formatter.format_document(content)
+
+ assert "[[sumerian-king-list]](/library/document/abc-123)" in result
+ assert "[[]]" not in result
+ assert "[[-1]]" not in result
+
+ def test_domain_hyperlinks_multi_relative_urls_use_distinct_slugs(self):
+ """Before fix: [[-1]](url1)[[-2]](url2) (orphans).
+ After: distinct title-based slugs."""
+ content = """# Report
+
+Findings [1] and [2].
+
+## Sources
+
+[1] Sumerian King List
+ URL: /library/document/a
+
+[2] Ancient Mesopotamia
+ URL: /library/document/b
+"""
+ formatter = CitationFormatter(CitationMode.DOMAIN_HYPERLINKS)
+ result = formatter.format_document(content)
+
+ assert "[[sumerian-king-list]](/library/document/a)" in result
+ assert "[[ancient-mesopotamia]](/library/document/b)" in result
+ assert "[[]]" not in result
+ assert "[[-1]]" not in result
+ assert "[[-2]]" not in result
+
+ def test_domain_hyperlinks_empty_title_falls_back_to_citation_number(
+ self,
+ ):
+ """Last-resort: when both domain and title slug are empty,
+ fall back to the citation number so the label is never empty.
+ Tested via the helper directly because the sources-block parser
+ requires a non-empty title line (e.g. ``[1] Title\n URL: ...``)."""
+ formatter = CitationFormatter(CitationMode.DOMAIN_HYPERLINKS)
+ result = formatter._format_domain_hyperlinks(
+ "see [1]", {"1": ("", "/library/document/abc")}
+ )
+ assert "[[1]](/library/document/abc)" in result
+ assert "[[]]" not in result
+
+ def test_domain_hyperlinks_comma_separated_relative_urls(self):
+ """Comma-separated citations with relative URLs must produce
+ non-empty labels. Before fix every label collapsed to ""."""
+ content = """# Report
+
+Sources [1, 2, 3] confirm this.
+
+## Sources
+
+[1] Doc A
+ URL: /library/document/a
+
+[2] Doc B
+ URL: /library/document/b
+
+[3] Doc C
+ URL: /library/document/c
+"""
+ formatter = CitationFormatter(CitationMode.DOMAIN_HYPERLINKS)
+ result = formatter.format_document(content)
+
+ assert (
+ "[[doc-a]](/library/document/a)"
+ "[[doc-b]](/library/document/b)"
+ "[[doc-c]](/library/document/c)"
+ ) in result
+ assert "[[]]" not in result
+
+ # ---- DOMAIN_ID_HYPERLINKS (default) ----------------------------------
+
+ def test_domain_id_hyperlinks_single_relative_url_uses_title_slug(self):
+ """The default mode. Before fix: [[]](url). After: [[slug]](url)."""
+ content = """# Report
+
+See [1].
+
+## Sources
+
+[1] Sumerian King List
+ URL: /library/document/abc-123
+"""
+ formatter = CitationFormatter(CitationMode.DOMAIN_ID_HYPERLINKS)
+ result = formatter.format_document(content)
+
+ assert "[[sumerian-king-list]](/library/document/abc-123)" in result
+ assert "[[]]" not in result
+ assert "[[-1]]" not in result
+
+ def test_domain_id_hyperlinks_multi_relative_urls_use_distinct_slugs(
+ self,
+ ):
+ content = """# Report
+
+Findings [1] and [2].
+
+## Sources
+
+[1] Sumerian King List
+ URL: /library/document/a
+
+[2] Ancient Mesopotamia
+ URL: /library/document/b
+"""
+ formatter = CitationFormatter(CitationMode.DOMAIN_ID_HYPERLINKS)
+ result = formatter.format_document(content)
+
+ assert "[[sumerian-king-list]](/library/document/a)" in result
+ assert "[[ancient-mesopotamia]](/library/document/b)" in result
+ assert "[[]]" not in result
+ assert "[[-1]]" not in result
+ assert "[[-2]]" not in result
+
+ def test_domain_id_hyperlinks_same_title_relative_urls_group_with_id(
+ self,
+ ):
+ """Multiple relative-URL citations of the SAME title group under
+ one slug and append -N suffixes. Before fix this produced
+ indistinguishable [[-1]](url1)[[-2]](url2) orphans."""
+ content = """# Report
+
+Findings [1] and [2].
+
+## Sources
+
+[1] Same Doc
+ URL: /library/document/a
+
+[2] Same Doc
+ URL: /library/document/b
+"""
+ formatter = CitationFormatter(CitationMode.DOMAIN_ID_HYPERLINKS)
+ result = formatter.format_document(content)
+
+ assert "[[same-doc-1]](/library/document/a)" in result
+ assert "[[same-doc-2]](/library/document/b)" in result
+ assert "[[same-doc]/" not in result # not the no-suffix form
+ assert "[[]]" not in result
+
+ def test_domain_id_hyperlinks_empty_title_falls_back_to_citation_number(
+ self,
+ ):
+ """Same last-resort guarantee for DOMAIN_ID_HYPERLINKS. Tested
+ via the helper directly (parser requires non-empty title line)."""
+ formatter = CitationFormatter(CitationMode.DOMAIN_ID_HYPERLINKS)
+ result = formatter._format_domain_id_hyperlinks(
+ "see [1]", {"1": ("", "/library/document/abc")}
+ )
+ assert "[[1]](/library/document/abc)" in result
+ assert "[[]]" not in result
+
+ def test_domain_id_hyperlinks_comma_separated_relative_urls(self):
+ content = """# Report
+
+Sources [1, 2, 3] confirm this.
+
+## Sources
+
+[1] Doc A
+ URL: /library/document/a
+
+[2] Doc B
+ URL: /library/document/b
+
+[3] Doc C
+ URL: /library/document/c
+"""
+ formatter = CitationFormatter(CitationMode.DOMAIN_ID_HYPERLINKS)
+ result = formatter.format_document(content)
+
+ # "Doc A" / "Doc B" / "Doc C" slugify to "doc-a" / "doc-b" /
+ # "doc-c" -- single docs in DOMAIN_ID mode keep no -N suffix.
+ assert (
+ "[[doc-a]](/library/document/a)"
+ "[[doc-b]](/library/document/b)"
+ "[[doc-c]](/library/document/c)"
+ ) in result
+ assert "[[]]" not in result
+
+ def test_domain_id_hyperlinks_mixed_real_and_relative(self):
+ """Real URLs keep their domain labels; relative URLs use title
+ slugs. No regression on the real-URL side."""
+ content = """# Report
+
+Web source [1] and library source [2].
+
+## Sources
+
+[1] Web Doc
+ URL: https://example.com/x
+
+[2] Local Doc
+ URL: /library/document/a
+"""
+ formatter = CitationFormatter(CitationMode.DOMAIN_ID_HYPERLINKS)
+ result = formatter.format_document(content)
+
+ assert "[[example.com]](https://example.com/x)" in result
+ assert "[[local-doc]](/library/document/a)" in result
+ assert "[[]]" not in result
+
+ # ---- DOMAIN_ID_ALWAYS_HYPERLINKS -------------------------------------
+
+ def test_domain_id_always_hyperlinks_single_relative_url_uses_title_slug(
+ self,
+ ):
+ """Before fix: [[-1]](url). After: [[slug-1]](url)."""
+ content = """# Report
+
+See [1].
+
+## Sources
+
+[1] Sumerian King List
+ URL: /library/document/abc-123
+"""
+ formatter = CitationFormatter(CitationMode.DOMAIN_ID_ALWAYS_HYPERLINKS)
+ result = formatter.format_document(content)
+
+ assert "[[sumerian-king-list-1]](/library/document/abc-123)" in result
+ assert "[[-1]]" not in result
+ assert "[[]]" not in result
+
+ def test_domain_id_always_hyperlinks_multi_relative_urls_use_distinct_slugs(
+ self,
+ ):
+ content = """# Report
+
+Findings [1] and [2].
+
+## Sources
+
+[1] Sumerian King List
+ URL: /library/document/a
+
+[2] Ancient Mesopotamia
+ URL: /library/document/b
+"""
+ formatter = CitationFormatter(CitationMode.DOMAIN_ID_ALWAYS_HYPERLINKS)
+ result = formatter.format_document(content)
+
+ assert "[[sumerian-king-list-1]](/library/document/a)" in result
+ assert "[[ancient-mesopotamia-1]](/library/document/b)" in result
+ assert "[[-1]]" not in result
+ assert "[[-2]]" not in result
+
+ def test_domain_id_always_hyperlinks_same_title_relative_urls_group(
+ self,
+ ):
+ content = """# Report
+
+Findings [1] and [2].
+
+## Sources
+
+[1] Same Doc
+ URL: /library/document/a
+
+[2] Same Doc
+ URL: /library/document/b
+"""
+ formatter = CitationFormatter(CitationMode.DOMAIN_ID_ALWAYS_HYPERLINKS)
+ result = formatter.format_document(content)
+
+ assert "[[same-doc-1]](/library/document/a)" in result
+ assert "[[same-doc-2]](/library/document/b)" in result
+ assert "[[-1]]" not in result
+ assert "[[]]" not in result
+
+ # ---- Real-URL regression (no behavior change) ------------------------
+
+ def test_domain_hyperlinks_real_url_unchanged(self):
+ """Guard against accidentally breaking the real-URL path."""
+ formatter = CitationFormatter(CitationMode.DOMAIN_HYPERLINKS)
+ result = formatter._format_domain_hyperlinks(
+ "see [1]", {"1": ("Paper", "https://arxiv.org/abs/1234")}
+ )
+ assert "[[arxiv.org]](https://arxiv.org/abs/1234)" in result
+
+ def test_domain_id_hyperlinks_real_url_unchanged(self):
+ formatter = CitationFormatter(CitationMode.DOMAIN_ID_HYPERLINKS)
+ result = formatter._format_domain_id_hyperlinks(
+ "see [1] and [2]",
+ {
+ "1": ("A", "https://arxiv.org/abs/1"),
+ "2": ("B", "https://arxiv.org/abs/2"),
+ },
+ )
+ assert "[[arxiv.org-1]](https://arxiv.org/abs/1)" in result
+ assert "[[arxiv.org-2]](https://arxiv.org/abs/2)" in result
+
+ def test_domain_id_always_hyperlinks_real_url_unchanged(self):
+ formatter = CitationFormatter(CitationMode.DOMAIN_ID_ALWAYS_HYPERLINKS)
+ result = formatter._format_domain_id_always_hyperlinks(
+ "see [1]",
+ {"1": ("Paper", "https://example.com/x")},
+ )
+ assert "[[example.com-1]](https://example.com/x)" in result
+
+
+class TestApplyInlineHyperlinks:
+ """Streaming-path coverage. apply_inline_hyperlinks is the only
+ formatter that takes structured dicts of sources (not markdown
+ sources blocks); it shares _format_domain_id_hyperlinks so it picks
+ up the relative-URL fix transitively."""
+
+ def test_real_url(self):
+ fmt = CitationFormatter(CitationMode.DOMAIN_ID_HYPERLINKS)
+ result = fmt.apply_inline_hyperlinks(
+ "see [1]",
+ [{"index": "1", "title": "T", "url": "https://example.com/x"}],
+ )
+ assert "[[example.com]](https://example.com/x)" in result
+
+ def test_single_relative_url_uses_title_slug(self):
+ """Before fix: [[]](url). After: [[slug]](url)."""
+ fmt = CitationFormatter(CitationMode.DOMAIN_ID_HYPERLINKS)
+ result = fmt.apply_inline_hyperlinks(
+ "see [1]",
+ [
+ {
+ "index": "1",
+ "title": "Sumerian King List",
+ "url": "/library/document/abc",
+ }
+ ],
+ )
+ assert "[[sumerian-king-list]](/library/document/abc)" in result
+ assert "[[]]" not in result
+ assert "[[-1]]" not in result
+
+ def test_multi_relative_urls_use_distinct_slugs(self):
+ fmt = CitationFormatter(CitationMode.DOMAIN_ID_HYPERLINKS)
+ result = fmt.apply_inline_hyperlinks(
+ "see [1] and [2]",
+ [
+ {
+ "index": "1",
+ "title": "Sumerian King List",
+ "url": "/library/document/a",
+ },
+ {
+ "index": "2",
+ "title": "Ancient Mesopotamia",
+ "url": "/library/document/b",
+ },
+ ],
+ )
+ assert "[[sumerian-king-list]]" in result
+ assert "[[ancient-mesopotamia]]" in result
+ assert "[[]]" not in result
+ assert "[[-1]]" not in result
+ assert "[[-2]]" not in result
+
+ def test_no_url_emits_no_link(self):
+ """Sources with no URL must not produce empty [[]] links."""
+ fmt = CitationFormatter(CitationMode.DOMAIN_ID_HYPERLINKS)
+ result = fmt.apply_inline_hyperlinks(
+ "see [1]", [{"index": "1", "title": "T", "url": ""}]
+ )
+ assert "[1]" in result
+ assert "[[]]" not in result
+ assert "[[1]]" not in result
+
+
+class TestCitationLabel:
+ """Direct unit tests for the _citation_label helper."""
+
+ def test_prefers_domain_when_present(self):
+ fmt = CitationFormatter(CitationMode.DOMAIN_HYPERLINKS)
+ assert (
+ fmt._citation_label("1", "Some Title", "https://example.com/x")
+ == "example.com"
+ )
+
+ def test_prefers_domain_for_arxiv(self):
+ fmt = CitationFormatter(CitationMode.DOMAIN_HYPERLINKS)
+ assert (
+ fmt._citation_label("1", "Some Title", "https://arxiv.org/abs/1")
+ == "arxiv.org"
+ )
+
+ def test_falls_back_to_title_slug_for_relative_url(self):
+ fmt = CitationFormatter(CitationMode.DOMAIN_HYPERLINKS)
+ assert (
+ fmt._citation_label(
+ "1", "Sumerian King List", "/library/document/abc"
+ )
+ == "sumerian-king-list"
+ )
+
+ def test_falls_back_to_citation_number_when_title_empty(self):
+ fmt = CitationFormatter(CitationMode.DOMAIN_HYPERLINKS)
+ assert fmt._citation_label("1", "", "/library/document/abc") == "1"
+
+ def test_falls_back_to_citation_number_when_title_whitespace(self):
+ fmt = CitationFormatter(CitationMode.DOMAIN_HYPERLINKS)
+ assert fmt._citation_label("1", " ", "/library/document/abc") == "1"
+
+ def test_falls_back_to_title_slug_when_url_empty(self):
+ """URL empty but title present -> use slug."""
+ fmt = CitationFormatter(CitationMode.DOMAIN_HYPERLINKS)
+ assert fmt._citation_label("1", "Title", "") == "title"
+
+ def test_falls_back_to_citation_number_when_both_empty(self):
+ fmt = CitationFormatter(CitationMode.DOMAIN_HYPERLINKS)
+ assert fmt._citation_label("1", "", "") == "1"
+
+ def test_sanitizes_special_chars_in_title(self):
+ fmt = CitationFormatter(CitationMode.DOMAIN_HYPERLINKS)
+ assert (
+ fmt._citation_label(
+ "1", "Title with: weird! chars", "/library/document/a"
+ )
+ == "title-with-weird-chars"
+ )
+
+ def test_legitimate_title_doc_keeps_doc_label(self):
+ """A document literally titled ``"Doc"`` slugifies to ``"doc"``;
+ the label must keep that slug rather than fall through to the
+ citation-number fallback. Regression guard for the case where
+ ``_slugify_title`` returned ``"doc"`` as a sentinel."""
+ fmt = CitationFormatter(CitationMode.DOMAIN_HYPERLINKS)
+ assert fmt._citation_label("1", "Doc", "/library/document/a") == "doc"
+ assert fmt._citation_label("1", "DOC", "/library/document/a") == "doc"
+
+
+class TestSlugifyTitle:
+ """Direct unit tests for the _slugify_title helper."""
+
+ def test_empty_returns_none(self):
+ assert CitationFormatter._slugify_title("") is None
+
+ def test_whitespace_only_returns_none(self):
+ assert CitationFormatter._slugify_title(" ") is None
+
+ def test_punctuation_only_returns_none(self):
+ assert CitationFormatter._slugify_title("!!!") is None
+
+ def test_basic_slugification(self):
+ assert CitationFormatter._slugify_title("Hello World") == "hello-world"
+
+ def test_special_chars_replaced_with_single_hyphen(self):
+ assert (
+ CitationFormatter._slugify_title("Some/Weird: Name (with stuff)")
+ == "some-weird-name-with-stuff"
+ )
+
+ def test_truncates_long_titles(self):
+ long = "x" * 100
+ slug = CitationFormatter._slugify_title(long)
+ assert len(slug) == 32
+ assert slug == "x" * 32
+
+ def test_truncation_strips_trailing_hyphen(self):
+ """If max_len lands on a hyphen, strip it so callers can append
+ -N without producing a malformed --N label."""
+ slug = CitationFormatter._slugify_title("x" * 32 + "-tail")
+ assert len(slug) == 32
+ assert not slug.endswith("-")
+ assert slug == "x" * 32
+
+ def test_strips_leading_and_trailing_whitespace(self):
+ assert (
+ CitationFormatter._slugify_title(" Hello World ") == "hello-world"
+ )
+
+ def test_legitimate_title_doc_is_not_treated_as_missing(self):
+ """A document literally titled ``"Doc"`` slugifies to ``"doc"``;
+ that is a real label, not a sentinel for "no meaningful slug"."""
+ assert CitationFormatter._slugify_title("Doc") == "doc"
+ assert CitationFormatter._slugify_title("DOC") == "doc"