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.

feat(report): add cited-source filter engine for final bibliography (#5379) (#6746)

S96a514454221
diff --git a/src/local_deep_research/utilities/search_utilities.py b/src/local_deep_research/utilities/search_utilities.py
index 7fa96b813a..0d570a3b08 100644
--- a/src/local_deep_research/utilities/search_utilities.py
+++ b/src/local_deep_research/utilities/search_utilities.py
@@ -1,5 +1,5 @@
import re
-from typing import Dict, List
+from typing import Dict, List, Optional, Set, Tuple
from loguru import logger
@@ -298,6 +298,566 @@ def source_url_field(link: Dict) -> object:
return link.get("link") or link.get("url") or ""
+# ---------------------------------------------------------------------------
+# Uncited-source filter engine (#5379).
+#
+# Heuristic parser: extracts citation signals (numeric bracket indices,
+# tagged citations, "Source N" phrases, inline URLs) from report prose so
+# the final ``## Sources`` bibliography can drop accumulated search hits
+# that were never cited. Over-inclusion is safe (extra bibliography line);
+# under-inclusion silently drops a cited source, so every ambiguous or
+# indeterminate case falls back to the full list in ``fallback`` mode.
+# ---------------------------------------------------------------------------
+
+_MAX_RANGE_SPAN = 1000
+_MAX_TOTAL_EXPANSION = 5000
+_MAX_RANGE_ENDPOINT_DIGITS = 18
+
+_FENCE_MARKERS = ("```", "~~~")
+
+# Ordinary prose tokens that must NOT force the indeterminate fallback:
+# ordinals ("1st", "2nd", "3rd"), units with g-z suffixes ("5x", "100m"),
+# multi-letter suffixes ("12px"), percentages ("50%"). Single bracket
+# tokens of digits immediately followed by such suffixes are prose, not
+# attempted citations. Only contents with list/range syntax (",", "-",
+# "–", "—", "and", "&") look like attempted citation syntax and may
+# trigger indeterminate.
+#
+# Single-letter a-f suffixes ("3a", "4b", "12c") are DELIBERATELY excluded:
+# they are regex-identical to sub-reference citations, so they stay on the
+# safe (indeterminate → fallback) side instead of being silently ignored.
+_PROSE_TOKEN_RE = re.compile(r"\d+[A-Za-z%]+")
+_SUBREF_SINGLE_LETTERS = frozenset("abcdefABCDEF")
+_LIST_SYNTAX_RE = re.compile(r",|[\-–—]|&|\band\b", re.IGNORECASE)
+
+# Single/double ASCII + CJK full-width brackets with numeric content:
+# [N], [N, M], [[N]], 【N】, [N-M], [N–M], [ 1, 2 ] (outer spaces allowed).
+# Letters excluded so [GPT-4]/[COVID-19] never match here
+# (handled/rejected as tagged).
+_BRACKET_NUMERIC_RE = re.compile(
+ r"[\[【]\[?\^?\s*([0-9][0-9\s,\-–—]*[0-9]|[0-9])\s*\]?[\]】]"
+)
+_BRACKET_CANDIDATE_RE = re.compile(r"[\[【]\[?([^\]\n]{1,256})[\]】]")
+
+# Tagged citations: [arxiv-1], [arxiv.org-2], [openai.com-2]. Tag must
+# contain a letter or dot so pure ranges ([1-3]) never match as tag "1".
+_TAGGED_CITATION_RE = re.compile(
+ r"\[(?=[^\[\]]*[A-Za-z.][^\[\]]*-\d+\])(?P<tag>[A-Za-z0-9._/\-]*"
+ r"[A-Za-z.][A-Za-z0-9._/\-]*)-(?P<idx>\d+)\]"
+)
+
+# "Source 1", "Sources 1 and 2", "sources 1, 2 & 3", "Sources 1-3"
+# (case-insensitive). Dash/en-dash/em-dash ranges are part of the capture
+# so "Sources 1-3" parses the whole range instead of just the "1" prefix
+# (which previously kept only source 1 with no fallback).
+_SOURCE_PHRASE_RE = re.compile(
+ r"(?i)\bsources?\s+(?P<nums>\d+(?:\s*[\-–—]\s*\d+)?"
+ r"(?:\s*(?:,|and|&)\s*\d+(?:\s*[\-–—]\s*\d+)?)*)"
+)
+
+# Broad capture; paren-balance + trailing-punct peeling happens per match.
+# In addition to absolute URLs and markdown-link destinations
+# (``](/library/…)``), bare library routes (``/library/document/…``,
+# ``/lib/document/…``) are in scope by design: prose commonly mentions
+# them outside link syntax, and dropping a bare-path mention is the same
+# citation-loss class as dropping a markdown destination.
+_URL_RE = re.compile(
+ r"(?P<absolute>https?://[^\s<>\[\]\"'<>]+)"
+ r"|\]\([ \t]*(?P<relative>/[^)\s]*)"
+ r"|(?P<bare_library>/(?:library|lib)/document/[^\s<>\[\]\"'<>]+)",
+ re.IGNORECASE,
+)
+
+# ``canonical_url_key`` lowercases scheme/host but keeps path case, and the
+# library-route parser matches ``/library/document/`` case-sensitively
+# (like the Flask route and ``library_resolver``). The prose regex above
+# captures ``/LIBRARY/Document/…`` case variants, so normalize just the
+# route prefix to lowercase before keying — the doc id itself keeps its
+# case. Without this the mention is captured but never matches its link.
+_BARE_LIBRARY_PREFIX_RE = re.compile(
+ r"^/(?:library|lib)/document/", re.IGNORECASE
+)
+
+
+def _normalize_bare_library_prefix(candidate: str) -> str:
+ """Lowercase only the ``/library|lib/document/`` route prefix."""
+ return _BARE_LIBRARY_PREFIX_RE.sub("/library/document/", candidate)
+
+
+# Sentence-final + CJK punctuation stripped from prose URLs. Deliberately
+# excludes closing delimiters ( ) ] } > ' " ` ) — those are balanced
+# separately so a balanced ")" before a final "." survives.
+_URL_SENTENCE_PUNCT = ".,;:!?。、,!?;:「」『』、…·—–"
+_URL_WRAPPER_PUNCT = "'\"`]}>"
+
+
+def _strip_fence_prefix(s: str) -> str:
+ """Strip Markdown quote/list prefixes from a line-start string.
+
+ Handles ``>``, ``-``/``*``/``+``, ``1.``/``1)`` nesting (e.g.
+ ``> - ```js``). Capped at 32 iterations so a hostile single line
+ of ``\"1. \"`` repetitions cannot turn the per-line slice into a
+ quadratic scan; realistic nesting is single digits.
+ """
+ for _ in range(32):
+ if s.startswith(">"):
+ s = s[1:].lstrip(" \t")
+ continue
+ if len(s) >= 2 and s[0] in "-*+" and s[1] in " \t":
+ i = 1
+ while i < len(s) and s[i] in " \t":
+ i += 1
+ s = s[i:]
+ continue
+ m = re.match(r"\d+[.)][ \t]+", s)
+ if m:
+ s = s[m.end() :]
+ continue
+ break
+ return s
+
+
+def _is_fence_line(line: str, marker: str) -> bool:
+ """True when ``line`` can *open* a ``marker`` code block.
+
+ A fence is recognized at the start of a line after optional
+ spaces/tabs indent *and* optional Markdown quote/list prefixes
+ (``>``, ``-``/``*``/``+``, ``1.``/``1)`` — e.g. ``> ```json`` or
+ ``- ```js``). Those shapes are how models quote tool output and
+ search results; ignoring the opener while counting a later plain
+ ````` closer pairs the closer with the next real opener and strips
+ real citations between them (source loss in the default mode).
+
+ A line whose stripped remainder starts with ``marker`` but contains
+ a second ``marker`` *after the initial fence run* (````` decorate
+ [8] ``` end``) is a decorative single-line run, not an opener, and
+ returns False so it never opens a block. A longer single run
+ (`` `````` ``) has no second marker after its run and still opens.
+ Closers are deliberately not vetted here — see
+ :func:`_is_fence_closer_line`.
+ """
+ content = line.rstrip("\r\n")
+ s = _strip_fence_prefix(content.lstrip(" \t"))
+ if not s.startswith(marker):
+ return False
+ # Initial fence run (3+ backticks/tildes): a longer single run is
+ # one fence, not two.
+ fence_char = marker[0]
+ run = 0
+ while run < len(s) and s[run] == fence_char:
+ run += 1
+ # Second marker after the run → decorative single-line run.
+ if marker in s[run:]:
+ return False
+ return True
+
+
+def _is_fence_closer_line(line: str, marker: str) -> bool:
+ """True when ``line`` can *close* an open ``marker`` code block.
+
+ Same prefix rule as the opener, but with no double-marker veto: a
+ closer carrying trailing text (````` done ``` ``) or a longer fence
+ (`` `````` `` closing a `` ``` `` block) must still close. Vetoing
+ it here pairs the opener with the *next* opener and strips real
+ prose between them with no indeterminate fallback.
+ """
+ content = line.rstrip("\r\n")
+ s = _strip_fence_prefix(content.lstrip(" \t"))
+ return s.startswith(marker)
+
+
+def _find_fence_positions(prose: str, marker: str) -> list[int]:
+ """Return line-start offsets of ``marker`` fence *openers*.
+
+ Recognizes line-anchored markers plus blockquoted/bulleted forms
+ (``> ```json``, ``- ```js``) via :func:`_is_fence_line`; inline
+ decorative runs and single-line double-marker runs are not openers.
+ Closers (which carry no veto) are paired statefully in
+ :func:`_strip_marker_blocks`, not by blind consecutive pairing.
+ """
+ positions: list[int] = []
+ offset = 0
+ for line in prose.splitlines(keepends=True):
+ if _is_fence_line(line, marker):
+ positions.append(offset)
+ offset += len(line)
+ return positions
+
+
+def _strip_marker_blocks(prose: str, marker: str) -> tuple[str, bool]:
+ """Strip paired ``marker`` blocks; True dangling if odd.
+
+ Stateful pairing: the double-marker veto applies only to *openers*
+ (so ````` decorate [8] ``` end`` never opens), while any
+ line-anchored ``marker`` *closes* an open block (so ````` done ```
+ `` and six-backtick `` `````` `` closers still close instead of
+ letting the opener pair across real prose). Full opener-through-
+ closer lines are excluded; an unterminated block returns the
+ original prose with dangling True so the caller falls back to the
+ full bibliography.
+ """
+ lines = prose.splitlines(keepends=True)
+ if not lines:
+ return prose, False
+ spans: list[tuple[int, int]] = []
+ in_block = False
+ block_start = 0
+ for i, line in enumerate(lines):
+ if not in_block:
+ if _is_fence_line(line, marker):
+ in_block = True
+ block_start = i
+ else:
+ if _is_fence_closer_line(line, marker):
+ in_block = False
+ spans.append((block_start, i))
+ if in_block:
+ return prose, True
+ if not spans:
+ return prose, False
+ exclude: set[int] = set()
+ for span_start, span_end in spans:
+ for i in range(span_start, span_end + 1):
+ exclude.add(i)
+ return "".join(
+ line for i, line in enumerate(lines) if i not in exclude
+ ), False
+
+
+def _strip_fenced_code(prose: str) -> tuple[str, bool]:
+ """Strip fenced code blocks (``` and ~~~); dangling either → indeterminate.
+
+ Fence lines include blockquoted/bulleted forms (``> ```json``,
+ ``- ```js``) so a quoted opener pairs with its closer instead of
+ letting a later plain marker pair across real prose. Inline
+ decorative runs (``~~~ config [2] ~~~``) and single-line
+ double-marker runs (```` ``` decorate [8] ``` end``) never *open* a
+ block, but any line-anchored marker still *closes* an open block
+ (so ````` done ``` `` and six-backtick closers close rather than
+ pairing the opener across real prose). Each marker type pairs only
+ with itself so a ``` block never swallows across a ~~~ fence. A
+ dangling (unterminated) marker of either type marks the parse
+ indeterminate instead of stripping half the report (a single stray
+ fence in quoted web content would otherwise swallow real citations
+ between it and the next block).
+ """
+ indeterminate = False
+ text = prose
+ for marker in _FENCE_MARKERS:
+ text, dangling = _strip_marker_blocks(text, marker)
+ if dangling:
+ indeterminate = True
+ return text, indeterminate
+
+
+def _is_all_uppercase_tag(tag: str) -> bool:
+ letters = [ch for ch in tag if ch.isalpha()]
+ return bool(letters) and all(ch.isupper() for ch in letters)
+
+
+def _is_ignorable_prose_singleton(content: str) -> bool:
+ """True when a digit-led singleton is ordinary prose, not a sub-ref."""
+ if "%" in content:
+ return True
+ m = re.fullmatch(r"\d+([A-Za-z]+)", content)
+ if m is None:
+ return True
+ suffix = m.group(1)
+ if len(suffix) >= 2:
+ return True
+ return suffix not in _SUBREF_SINGLE_LETTERS
+
+
+def _is_malformed_numeric_content(content: str) -> bool:
+ """True when a digit-led bracket looks like a broken citation list.
+
+ Ordinary prose singletons (ordinals ``2nd``/``1st``, ``g``-``z`` units
+ ``5x``/``100m``, multi-letter ``12px``, percentages ``50%``) are
+ explicitly NOT malformed: they are digits immediately followed by a
+ safe suffix with no list/range syntax, so they are ignored instead of
+ forcing the full-bibliography fallback (which would defeat ``strict``
+ mode's cited-only contract). Single-letter ``a``-``f`` suffixes
+ (``3a``/``4b``/``12c``) are sub-reference-shaped and stay indeterminate
+ so fallback preserves the bibliography. Only contents containing
+ list/range syntax (``,``, ``-``/``–``/``—``, ``and``/``&``) look like
+ attempted citation syntax; a bad chunk there
+ (``[1,abc,3]``, ``[1-abc]``) stays indeterminate so fallback preserves
+ the bibliography. Other singletons without list syntax (``[1 abc]``,
+ ``[1 and 2]``) also stay indeterminate — ignoring them would risk
+ silently dropping an intended citation.
+ """
+ content = content.strip()
+ if not content or not content[0].isascii() or not content[0].isdigit():
+ return False
+ if not _LIST_SYNTAX_RE.search(content):
+ # Single token, no list/range syntax. Prose shapes (digits +
+ # letters/% suffix) are ignored; anything else falls through to
+ # the chunk check below (e.g. "1 abc" has a space so it does not
+ # match _PROSE_TOKEN_RE and is still indeterminate).
+ if _PROSE_TOKEN_RE.fullmatch(content):
+ if _is_ignorable_prose_singleton(content):
+ return False
+ for chunk in content.split(","):
+ chunk = chunk.strip()
+ if not chunk:
+ return True
+ if chunk.isascii() and chunk.isdigit():
+ continue
+ if re.fullmatch(r"[0-9]+\s*[\-–—]\s*[0-9]+", chunk):
+ continue
+ return True
+ return False
+
+
+def _peel_url_candidate(raw: str) -> str:
+ """Strip emphasis wrapping, balance parens, drop trailing punctuation.
+
+ Sentence punctuation is peeled BEFORE balancing delimiters: a balanced
+ Wikipedia-style ``...(lang).`` first loses the final ``.`` leaving a
+ balanced ``...(lang)`` which is kept. The old order stripped ``.`` and
+ ``)`` together via a single ``rstrip``, turning the balanced URL into
+ the unbalanced ``...(lang`` and dropping the source.
+ """
+ url = raw.strip("'\"*_`")
+ unmatched_closing = max(0, url.count(")") - url.count("("))
+ end = len(url)
+ while end:
+ trailing = url[end - 1]
+ if trailing in _URL_SENTENCE_PUNCT or trailing in _URL_WRAPPER_PUNCT:
+ end -= 1
+ continue
+ if trailing == ")" and unmatched_closing:
+ unmatched_closing -= 1
+ end -= 1
+ continue
+ break
+ return url[:end].strip("'\"*_`")
+
+
+def _parse_bracket_content(
+ content: str, indices: Set[int], state: dict
+) -> None:
+ """Expand comma lists + dash/en-dash ranges into ``indices``.
+
+ Sets ``state["indeterminate"]`` when any range exceeds span, digit,
+ or aggregate budgets instead of keeping endpoints-only (which would
+ suppress the safety-net fallback with a partial result).
+ """
+ for chunk in content.split(","):
+ chunk = chunk.strip()
+ if not chunk:
+ continue
+ m = re.fullmatch(r"(\d+)\s*[\-–—]\s*(\d+)", chunk)
+ if m:
+ lo_s, hi_s = m.group(1), m.group(2)
+ if (
+ len(lo_s) > _MAX_RANGE_ENDPOINT_DIGITS
+ or len(hi_s) > _MAX_RANGE_ENDPOINT_DIGITS
+ ):
+ state["indeterminate"] = True
+ continue
+ try:
+ lo, hi = int(lo_s), int(hi_s)
+ except ValueError:
+ state["indeterminate"] = True
+ continue
+ if lo > hi:
+ lo, hi = hi, lo
+ if hi - lo > _MAX_RANGE_SPAN:
+ state["indeterminate"] = True
+ continue
+ if state["expanded"] + (hi - lo + 1) > _MAX_TOTAL_EXPANSION:
+ state["indeterminate"] = True
+ continue
+ for i in range(lo, hi + 1):
+ indices.add(i)
+ state["expanded"] += hi - lo + 1
+ elif chunk.isascii() and chunk.isdigit():
+ if len(chunk) > _MAX_RANGE_ENDPOINT_DIGITS:
+ state["indeterminate"] = True
+ continue
+ try:
+ indices.add(int(chunk))
+ except ValueError:
+ state["indeterminate"] = True
+ else:
+ continue
+
+
+def extract_cited_indices_and_urls(
+ prose: str,
+) -> Tuple[Set[int], Set[str], bool]:
+ """Parse citation signals from report body prose.
+
+ Returns ``(cited_indices, cited_url_keys, indeterminate)`` where
+ ``cited_url_keys`` are ``canonical_url_key`` values. ``indeterminate``
+ is True when a range, bracket, or fence is ambiguous and the result
+ must be treated as unreliable (caller falls back to the full list).
+
+ Recognized signals: numeric brackets (outer spaces allowed:
+ ``[ 1, 2 ]``), tagged citations, ``Source N`` phrases, absolute URLs,
+ markdown-link library destinations (``](/library/…)``) AND bare
+ library routes (``/library/document/…``, ``/lib/document/…``) mentioned
+ outside link syntax. Route-prefix case is normalized for both bare
+ mentions and markdown destinations, so ``/LIBRARY/Document/…``
+ retains like the lowercase form. Fenced code (``` and ~~~,
+ including blockquoted/bulleted forms like ``> ```json``) is stripped;
+ inline runs and single-line double-marker runs never swallow
+ citations; a dangling fence of either type marks the parse
+ indeterminate.
+
+ Ordinary prose singletons (ordinals ``2nd``, ``g``-``z`` units
+ ``5x``/``100m``, multi-letter ``12px``, percentages ``50%``) are
+ ignored — they never set indeterminate — so normal writing does not
+ force the full-bibliography fallback in ``strict`` mode.
+ Single-letter ``a``-``f`` suffixes (``3a``) stay indeterminate as
+ sub-reference-shaped. Only digit-led brackets with list/range syntax
+ that fail to parse (``[1,abc,3]``) are indeterminate.
+
+ Heuristic: over-includes on years/array indices; over-inclusion is
+ harmless because the fallback keeps extra lines, while
+ under-inclusion drops cited sources.
+ """
+ indices: Set[int] = set()
+ url_keys: Set[str] = set()
+ state = {"indeterminate": False, "expanded": 0}
+ if not prose or not prose.strip():
+ return indices, url_keys, False
+
+ text, fence_indeterminate = _strip_fenced_code(prose)
+ if fence_indeterminate:
+ state["indeterminate"] = True
+
+ for m in _BRACKET_NUMERIC_RE.finditer(text):
+ _parse_bracket_content(m.group(1), indices, state)
+
+ for m in _BRACKET_CANDIDATE_RE.finditer(text):
+ if _is_malformed_numeric_content(m.group(1)):
+ state["indeterminate"] = True
+
+ for m in _TAGGED_CITATION_RE.finditer(text):
+ tag, idx_s = m.group("tag"), m.group("idx")
+ if _is_all_uppercase_tag(tag):
+ continue
+ if len(idx_s) > _MAX_RANGE_ENDPOINT_DIGITS:
+ # Implausibly large tag index (no bibliography has 10^18
+ # entries): clearly prose/hostile, not a citation. Ignore
+ # instead of marking indeterminate so a single token like
+ # [a-999…] cannot force the fallback for every reader.
+ continue
+ try:
+ indices.add(int(idx_s))
+ except ValueError:
+ state["indeterminate"] = True
+
+ for m in _SOURCE_PHRASE_RE.finditer(text):
+ # Expand comma lists AND dash ranges ("Sources 1-3") with the same
+ # budget-checked helper as bracket citations, so "1-3" yields
+ # {1, 2, 3} instead of just endpoints. "and"/"&" normalize to ",".
+ nums = m.group("nums")
+ nums_norm = re.sub(r"\s*(?:and|&)\s*", ",", nums, flags=re.IGNORECASE)
+ _parse_bracket_content(nums_norm, indices, state)
+
+ for m in _URL_RE.finditer(text):
+ raw = (
+ m.group("absolute")
+ or m.group("relative")
+ or m.group("bare_library")
+ )
+ peeled = _peel_url_candidate(raw)
+ candidates = {raw, peeled} if peeled != raw else {peeled}
+ # Case-variant library routes (``/LIBRARY/Document/d2``): the regex
+ # captures them (bare mentions and markdown destinations) but the
+ # canonical key is prefix-case-sensitive, so also key the
+ # prefix-normalized spelling. Applies to both branches — a
+ # markdown destination is the stronger citation signal and must
+ # not lose while the bare mention of the same route retains.
+ for base in list(candidates):
+ if _BARE_LIBRARY_PREFIX_RE.match(base):
+ candidates.add(_normalize_bare_library_prefix(base))
+ for candidate in candidates:
+ if not candidate:
+ continue
+ try:
+ key = canonical_url_key(candidate)
+ except Exception:
+ continue
+ if key:
+ url_keys.add(key)
+
+ return indices, url_keys, state["indeterminate"]
+
+
+def filter_cited_links(
+ all_links: List[Dict],
+ prose: Optional[str],
+ mode: str = "fallback",
+) -> List[Dict]:
+ """Keep only links cited in ``prose`` (by index or URL).
+
+ Modes: ``fallback`` (default) returns ``all_links`` when extraction
+ is empty/indeterminate or nothing matches; ``strict`` returns only
+ matches (possibly empty); ``disabled`` returns ``all_links``.
+ Indeterminate input falls back to ``all_links`` in every mode.
+ """
+ if not all_links:
+ return all_links
+ if mode == "disabled" or not prose or not prose.strip():
+ return all_links
+
+ cited_indices, cited_urls, indeterminate = extract_cited_indices_and_urls(
+ prose
+ )
+ if indeterminate:
+ logger.warning(
+ "filter_cited_links: indeterminate citation parse; "
+ "falling back to all {} links",
+ len(all_links),
+ )
+ return all_links
+ if not cited_indices and not cited_urls:
+ if mode == "fallback":
+ logger.warning(
+ "filter_cited_links: no citations parsed from prose "
+ "({} links); falling back to full bibliography",
+ len(all_links),
+ )
+ return all_links
+ return []
+
+ kept: List[Dict] = []
+ for link in all_links:
+ if not isinstance(link, dict):
+ continue
+ idx = link.get("index", "")
+ try:
+ idx_int = int(str(idx).strip())
+ except (ValueError, TypeError):
+ idx_int = None
+ if idx_int is not None and idx_int in cited_indices:
+ kept.append(link)
+ continue
+ raw = source_url_field(link)
+ if isinstance(raw, str) and raw:
+ try:
+ key = canonical_url_key(raw)
+ except Exception:
+ key = ""
+ if key and key in cited_urls:
+ kept.append(link)
+
+ if not kept and mode == "fallback":
+ logger.warning(
+ "filter_cited_links: {} cited indices / {} cited urls matched "
+ "nothing in {} links; falling back to full bibliography",
+ len(cited_indices),
+ len(cited_urls),
+ len(all_links),
+ )
+ return all_links
+ return kept
+
+
def count_distinct_sources(all_links: List[Dict]) -> int:
"""How many distinct sources a report cites (document-level count).
@@ -326,8 +886,14 @@ def count_distinct_sources(all_links: List[Dict]) -> int:
return len(seen)
-def format_links_to_markdown(all_links: List[Dict]) -> str:
+def format_links_to_markdown(
+ all_links: List[Dict],
+ prose: Optional[str] = None,
+ uncited_mode: str = "fallback",
+) -> str:
parts: list[str] = []
+ if prose and uncited_mode != "disabled":
+ all_links = filter_cited_links(all_links, prose, mode=uncited_mode)
logger.info(f"Formatting {len(all_links)} links to markdown...")
if all_links:
diff --git a/tests/utilities/test_search_utilities_formatting.py b/tests/utilities/test_search_utilities_formatting.py
index 1533dda0a5..71dc882e45 100644
--- a/tests/utilities/test_search_utilities_formatting.py
+++ b/tests/utilities/test_search_utilities_formatting.py
@@ -1395,3 +1395,609 @@ class TestSourceUrlField:
assert rendered.count("URL:") == 1, rendered
assert "[1, 2]" in rendered
assert "elsewhere.test" not in rendered
+
+
+class TestFilterCitedLinks:
+ """Uncited-source filter engine (#5379, PR1)."""
+
+ @staticmethod
+ def _filter(links, prose, mode="fallback"):
+ from local_deep_research.utilities.search_utilities import (
+ filter_cited_links,
+ )
+
+ return filter_cited_links(links, prose, mode=mode)
+
+ @staticmethod
+ def _format(links, prose=None, uncited_mode="fallback"):
+ from local_deep_research.utilities.search_utilities import (
+ format_links_to_markdown,
+ )
+
+ return format_links_to_markdown(
+ links, prose=prose, uncited_mode=uncited_mode
+ )
+
+ @staticmethod
+ def _extract(prose):
+ from local_deep_research.utilities.search_utilities import (
+ extract_cited_indices_and_urls,
+ )
+
+ return extract_cited_indices_and_urls(prose)
+
+ def _links(self):
+ return [
+ {"title": "A", "url": "https://a.test/x", "index": "1"},
+ {"title": "B", "url": "https://b.test/y", "index": "2"},
+ {"title": "C", "url": "https://c.test/z", "index": "3"},
+ ]
+
+ def test_bracket_and_comma_list(self):
+ prose = "Claims [1] and more [1, 3]."
+ kept = self._filter(self._links(), prose)
+ assert [link["index"] for link in kept] == ["1", "3"]
+
+ def test_range_expansion(self):
+ prose = "Summary [1-3]."
+ kept = self._filter(self._links(), prose)
+ assert [link["index"] for link in kept] == ["1", "2", "3"]
+
+ def test_en_dash_range(self):
+ prose = "Summary [1–3]."
+ kept = self._filter(self._links(), prose)
+ assert len(kept) == 3
+
+ def test_double_and_fullwidth_brackets(self):
+ prose = "See [[1]] and 【2】."
+ kept = self._filter(self._links(), prose)
+ assert [link["index"] for link in kept] == ["1", "2"]
+
+ def test_tagged_citation_accepted(self):
+ prose = "Per [arxiv.org-2] the result holds."
+ kept = self._filter(self._links(), prose)
+ assert [link["index"] for link in kept] == ["2"]
+
+ def test_footnote_citation_accepted(self):
+ prose = "See [^1] and [3]."
+ kept = self._filter(self._links(), prose)
+ assert [link["index"] for link in kept] == ["1", "3"]
+
+ def test_uppercase_tag_rejected_with_fallback(self):
+ # Bare [GPT-4] must not mark index 4 as cited; nothing else
+ # cited either, so fallback keeps everything (never wipe out).
+ links = self._links()
+ kept = self._filter(links, "Model [GPT-4] is great.")
+ assert kept == links
+
+ def test_uppercase_tag_ignored_alongside_real_citation(self):
+ prose = "Model [GPT-4] is great, see [1]."
+ kept = self._filter(self._links(), prose)
+ assert [link["index"] for link in kept] == ["1"]
+
+ def test_source_phrase(self):
+ prose = "Sources 1 and 2 agree."
+ kept = self._filter(self._links(), prose)
+ assert [link["index"] for link in kept] == ["1", "2"]
+
+ def test_fenced_code_ignored(self):
+ prose = "```\ndata[3]\n```\nSee [1]."
+ kept = self._filter(self._links(), prose)
+ assert [link["index"] for link in kept] == ["1"]
+
+ def test_dangling_fence_marks_parse_indeterminate(self):
+ prose = "See [1].\n```\nstray [2] between\n```\nblock\n```\nafter [3]."
+ _, _, indeterminate = self._extract(prose)
+ assert indeterminate is True
+ assert self._filter(self._links(), prose) == self._links()
+
+ def test_wikipedia_paren_url(self):
+ links = [
+ {
+ "title": "Python",
+ "url": "https://en.wikipedia.org/wiki/Python_(programming_language)",
+ "index": "5",
+ },
+ {"title": "Other", "url": "https://o.test/q", "index": "6"},
+ ]
+ prose = (
+ "See https://en.wikipedia.org/wiki/Python_(programming_language)"
+ " for details."
+ )
+ kept = self._filter(links, prose)
+ assert [link["index"] for link in kept] == ["5"]
+
+ def test_external_paren_peeling(self):
+ links = [
+ {"title": "P", "url": "https://ex.test/page", "index": "1"},
+ {"title": "Q", "url": "https://o.test/q", "index": "2"},
+ ]
+ kept = self._filter(links, "(https://ex.test/page).")
+ assert [link["index"] for link in kept] == ["1"]
+
+ def test_markdown_relative_library_url_with_mixed_citations(self):
+ links = [
+ {
+ "title": "One",
+ "url": "/library/document/d1",
+ "index": "1",
+ },
+ {
+ "title": "Two",
+ "url": "/library/document/d2",
+ "index": "2",
+ },
+ {"title": "Three", "url": "https://c.test/z", "index": "3"},
+ ]
+ prose = "See [[doc-two-1]](/library/document/d2) and [3]."
+ kept = self._filter(links, prose)
+ assert [link["index"] for link in kept] == ["1", "2", "3"]
+
+ def test_url_peeling_handles_many_trailing_parentheses(self):
+ import time
+
+ from local_deep_research.utilities.search_utilities import (
+ _peel_url_candidate,
+ )
+
+ raw = "https://e.test/" + ")" * 100_000
+ started = time.process_time()
+ peeled = _peel_url_candidate(raw)
+ elapsed = time.process_time() - started
+ assert peeled == "https://e.test/"
+ assert elapsed < 1.0, f"peeling took {elapsed:.3f}s CPU"
+
+ def test_balanced_paren_url_with_sentence_period_mixed_citations(self):
+ """Balanced ")" before sentence "." must survive when another index matches.
+
+ Reproduced from review: prose citing ``[1]`` plus
+ ``https://en.wikipedia.org/wiki/Python_(programming_language).``
+ dropped source 2 (only ``[1]`` kept); the same URL without the
+ final period retained it. Sentence punctuation is peeled before
+ balancing so the balanced paren is preserved.
+ """
+ links = [
+ {"title": "A", "url": "https://a.test/x", "index": "1"},
+ {
+ "title": "Python",
+ "url": "https://en.wikipedia.org/wiki/Python_(programming_language)",
+ "index": "2",
+ },
+ ]
+ prose = (
+ "See [1] and "
+ "https://en.wikipedia.org/wiki/Python_(programming_language)."
+ " for details."
+ )
+ kept = self._filter(links, prose)
+ assert [link["index"] for link in kept] == ["1", "2"]
+ # Control: without the sentence-final period both were already kept.
+ prose_no_period = (
+ "See [1] and "
+ "https://en.wikipedia.org/wiki/Python_(programming_language)"
+ " for details."
+ )
+ kept_no_period = self._filter(links, prose_no_period)
+ assert [link["index"] for link in kept_no_period] == ["1", "2"]
+
+ def test_source_phrase_range_matches_comma_list(self):
+ """``Sources 1-3`` must retain 1, 2 and 3 like ``Sources 1, 2 and 3``.
+
+ The old phrase regex captured only the ``1`` prefix of ``1-3``,
+ so with indices 1-3 available the filter kept just source 1 and
+ — having matched something — never fell back to restore 2 and 3.
+ """
+ range_kept = self._filter(self._links(), "Sources 1-3 agree.")
+ list_kept = self._filter(self._links(), "Sources 1, 2 and 3 agree.")
+ assert [link["index"] for link in range_kept] == ["1", "2", "3"]
+ assert [link["index"] for link in list_kept] == ["1", "2", "3"]
+
+ def test_uppercase_scheme(self):
+ links = [{"title": "P", "url": "https://ex.test/page", "index": "1"}]
+ kept = self._filter(links, "See HTTPS://ex.test/page.")
+ assert [link["index"] for link in kept] == ["1"]
+
+ def test_cjk_trailing_punct(self):
+ links = [{"title": "P", "url": "https://ex.test/page", "index": "1"}]
+ kept = self._filter(links, "See https://ex.test/page。")
+ assert [link["index"] for link in kept] == ["1"]
+
+ def test_empty_parse_falls_back(self):
+ links = self._links()
+ assert self._filter(links, "No citations here.") == links
+ assert self._filter(links, "") == links
+ assert self._filter(links, None) == links
+
+ def test_no_match_falls_back(self):
+ links = self._links()
+ assert self._filter(links, "See [99].") == links
+
+ def test_strict_mode_drops_uncited(self):
+ kept = self._filter(self._links(), "See [99].", mode="strict")
+ assert kept == []
+ kept = self._filter(self._links(), "See [1].", mode="strict")
+ assert [link["index"] for link in kept] == ["1"]
+
+ def test_strict_mode_falls_back_on_indeterminate_parse(self):
+ links = self._links()
+ prose = "See [1-1002] and [2]."
+ _, _, indeterminate = self._extract(prose)
+ assert indeterminate is True
+ assert self._filter(links, prose, mode="strict") == links
+
+ def test_disabled_mode_keeps_all(self):
+ links = self._links()
+ assert self._filter(links, "See [1].", mode="disabled") == links
+
+ def test_overcap_range_falls_back(self):
+ links = self._links()
+ assert self._filter(links, "See [1-1002].") == links
+
+ def test_malformed_numeric_bracket_marks_parse_indeterminate(self):
+ links = self._links()
+ prose = "[1,abc,3] and [3]."
+ _, _, indeterminate = self._extract(prose)
+ assert indeterminate is True
+ assert self._filter(links, prose) == links
+
+ def test_huge_endpoint_digits_falls_back(self):
+ links = self._links()
+ assert self._filter(links, "See [1-99999999999999999999].") == links
+
+ def test_format_links_prose_filters(self):
+ rendered = self._format(self._links(), prose="See [1].")
+ assert "https://a.test/x" in rendered
+ assert "https://b.test/y" not in rendered
+ assert "https://c.test/z" not in rendered
+
+ def test_format_links_no_prose_keeps_all(self):
+ rendered = self._format(self._links())
+ assert rendered.count("URL:") == 3
+
+ def test_extract_indeterminate_flag(self):
+ _, _, indeterminate = self._extract("See [1-1002].")
+ assert indeterminate is True
+ _, _, indeterminate = self._extract("See [1].")
+ assert indeterminate is False
+
+ def test_prose_singletons_do_not_force_fallback(self):
+ """Ordinary prose ([2nd]/[1st]/[5x]/[100m]/[50%]) is ignored.
+
+ Regression for review: each shape flipped the parser to
+ indeterminate and returned the full bibliography even in strict
+ mode, defeating the cited-only contract. Mixed with a real [1],
+ only source 1 is kept in both modes.
+ """
+ for token in ["[2nd]", "[1st]", "[5x]", "[100m]", "[50%]"]:
+ _, _, indeterminate = self._extract(token)
+ assert indeterminate is False, token
+ for prose in (
+ "See [1] and [2nd].",
+ "The 2nd trial [2nd] results, see [1].",
+ "[50%] off, see [1].",
+ ):
+ _, _, indeterminate = self._extract(prose)
+ assert indeterminate is False, prose
+ assert [
+ link["index"] for link in self._filter(self._links(), prose)
+ ] == ["1"]
+ assert [
+ link["index"]
+ for link in self._filter(self._links(), prose, mode="strict")
+ ] == ["1"]
+
+ def test_malformed_list_still_marks_indeterminate(self):
+ """Genuinely ambiguous lists keep the safety-net fallback."""
+ for prose in ["[1,abc,3]", "[1-abc]", "[1 and 2]"]:
+ _, _, indeterminate = self._extract(prose)
+ assert indeterminate is True, prose
+ assert self._filter(self._links(), prose) == self._links()
+
+ def test_hostile_tagged_huge_index_does_not_force_fallback(self):
+ """A single [a-999…] token must not wipe strict-mode filtering."""
+ _, _, indeterminate = self._extract("[a-9999999999999999999]")
+ assert indeterminate is False
+ prose = "[a-9999999999999999999] and [1]."
+ _, _, indeterminate = self._extract(prose)
+ assert indeterminate is False
+ assert [
+ link["index"]
+ for link in self._filter(self._links(), prose, mode="strict")
+ ] == ["1"]
+
+ def test_bare_library_path_retained_like_markdown_destination(self):
+ """Bare /library/document/… mentions retain their source."""
+ links = [
+ {"title": "One", "url": "/library/document/d1", "index": "1"},
+ {"title": "Two", "url": "/library/document/d2", "index": "2"},
+ {"title": "Three", "url": "https://c.test/z", "index": "3"},
+ ]
+ for prose in (
+ "See /library/document/d2 and [3].",
+ "See /library/document/d2. and [3].",
+ "See (/library/document/d2) and [3].",
+ "See /lib/document/d2 and [3].",
+ ):
+ for mode in ("fallback", "strict"):
+ kept = self._filter(links, prose, mode=mode)
+ assert [link["index"] for link in kept] == ["2", "3"], (
+ prose,
+ mode,
+ )
+
+ def test_spaced_brackets_parse(self):
+ """[ 1, 2 ] keeps both indices instead of dropping silently."""
+ _, _, indeterminate = self._extract("[ 1, 2 ]")
+ assert indeterminate is False
+ kept = self._filter(self._links(), "[ 1, 2 ]")
+ assert [link["index"] for link in kept] == ["1", "2"]
+ kept = self._filter(self._links(), "[ 1, 2 ]", mode="strict")
+ assert [link["index"] for link in kept] == ["1", "2"]
+ kept = self._filter(self._links(), "See [ 1, 2 ] and [3].")
+ assert [link["index"] for link in kept] == ["1", "2", "3"]
+
+ def test_tilde_fences_stripped_like_backtick_fences(self):
+ """~~~ blocks are stripped; dangling ~~~ marks indeterminate."""
+ kept = self._filter(self._links(), "~~~\ncode [1] here\n~~~\nSee [2].")
+ assert [link["index"] for link in kept] == ["2"]
+ _, _, indeterminate = self._extract("~~~\ndangling [1]\nSee [2].")
+ assert indeterminate is True
+ assert (
+ self._filter(self._links(), "~~~\ndangling [1]\nSee [2].")
+ == self._links()
+ )
+
+ def test_subref_single_letter_marks_indeterminate(self):
+ """``[3a]``/``[4b]``/``[12c]`` stay on the safe side of the gate.
+
+ They are regex-identical to sub-reference citations, so mixing one
+ with a real citation falls back to the full bibliography in every
+ mode instead of silently keeping only the numeric index.
+ Controls: ordinals/units/percentages (``2nd``, ``5x``, ``50%``)
+ are still ignored prose.
+ """
+ for token in ["[3a]", "[4b]", "[12c]", "[3A]", "[5d]"]:
+ _, _, indeterminate = self._extract(token)
+ assert indeterminate is True, token
+ for prose in ("See [3a] and [2].", "See [12c] and [1]."):
+ _, _, indeterminate = self._extract(prose)
+ assert indeterminate is True, prose
+ assert self._filter(self._links(), prose) == self._links()
+ assert (
+ self._filter(self._links(), prose, mode="strict")
+ == self._links()
+ )
+ # Controls: safe prose shapes never set indeterminate.
+ for token in ["[2nd]", "[1st]", "[5x]", "[100m]", "[50%]", "[12px]"]:
+ _, _, indeterminate = self._extract(token)
+ assert indeterminate is False, token
+
+ def test_inline_decorative_fences_do_not_swallow_citations(self):
+ """Mid-line ``~~~``/``` runs are decorative, not code blocks."""
+ for prose in (
+ "Config ~~~ config [2] ~~~ end and [1].",
+ "Use ``` code [2] ``` here and [1].",
+ ):
+ _, _, indeterminate = self._extract(prose)
+ assert indeterminate is False, prose
+ assert [
+ link["index"] for link in self._filter(self._links(), prose)
+ ] == ["1", "2"]
+ assert [
+ link["index"]
+ for link in self._filter(self._links(), prose, mode="strict")
+ ] == ["1", "2"]
+
+ def test_indented_fence_block_still_stripped(self):
+ """Leading spaces do not stop a line-anchored fence from working."""
+ kept = self._filter(
+ self._links(), " ```\ncode [1] here\n ```\nSee [2]."
+ )
+ assert [link["index"] for link in kept] == ["2"]
+
+ def test_bare_library_prefix_case_variants_retained(self):
+ """``/LIBRARY/Document/d2`` retains like the lowercase form."""
+ links = [
+ {"title": "One", "url": "/library/document/d1", "index": "1"},
+ {"title": "Two", "url": "/library/document/d2", "index": "2"},
+ {"title": "Three", "url": "https://c.test/z", "index": "3"},
+ ]
+ for prose in (
+ "See /LIBRARY/Document/d2 and [3].",
+ "See /Library/Document/d2 and [3].",
+ "See /LIB/document/d2 and [3].",
+ ):
+ for mode in ("fallback", "strict"):
+ kept = self._filter(links, prose, mode=mode)
+ assert [link["index"] for link in kept] == ["2", "3"], (
+ prose,
+ mode,
+ )
+
+ def test_markdown_link_case_variant_retained_like_bare(self):
+ """``[x](/LIBRARY/Document/d2)`` retains like the bare mention.
+
+ Regression: the prefix normalization applied only to the
+ ``bare_library`` branch, so a markdown destination (the stronger
+ citation signal) dropped its source in strict mode while the
+ bare mention of the same route retained it.
+ """
+ links = [
+ {"title": "One", "url": "/library/document/d1", "index": "1"},
+ {"title": "Two", "url": "/library/document/d2", "index": "2"},
+ {"title": "Three", "url": "https://c.test/z", "index": "3"},
+ ]
+ for prose in (
+ "See [x](/LIBRARY/Document/d2) and [3].",
+ "See [x](/Library/Document/d2) and [3].",
+ "See [x](/LIB/document/d2) and [3].",
+ "See [x](/LIBRARY/Document/d2/pdf) and [3].",
+ ):
+ for mode in ("fallback", "strict"):
+ kept = self._filter(links, prose, mode=mode)
+ assert [link["index"] for link in kept] == ["2", "3"], (
+ prose,
+ mode,
+ )
+
+ def test_blockquoted_fence_does_not_swallow_citations(self):
+ """Non-anchored opener + anchored closer with even count.
+
+ A blockquoted opener (``> ```json``) is a real fence: ignoring
+ it while counting its plain ````` closer pairs that closer
+ with the next real opener, stripping ``[2]`` (and ``[3]`` with
+ a trailing quoted block) with no indeterminate fallback.
+ """
+ prose = (
+ "Intro cites [1].\n"
+ "> ```json\n"
+ '> {"key": "value"}\n'
+ "```\n"
+ "Real analysis cites [2].\n"
+ "```python\n"
+ "code [4]\n"
+ "```\n"
+ "Outro cites [3].\n"
+ "> ```\n"
+ "> quoted\n"
+ "```\n"
+ )
+ _, _, indeterminate = self._extract(prose)
+ assert indeterminate is False
+ for mode in ("fallback", "strict"):
+ kept = self._filter(self._links(), prose, mode=mode)
+ assert [link["index"] for link in kept] == ["1", "2", "3"], mode
+
+ def test_bulleted_fence_with_unterminated_block_falls_back(self):
+ """Bulleted opener (``- ```js``) pairs; unterminated → fallback.
+
+ The bulleted opener is a fence, so the first plain ````` is
+ its closer (not an opener for the real prose). The final lone
+ ````` is unterminated: odd count → indeterminate → full
+ bibliography instead of keeping only ``['1']`` while counting
+ the unterminated block's ``[9]``.
+ """
+ prose = (
+ "Intro cites [1].\n"
+ "- ```js\n"
+ "code [9]\n"
+ "```\n"
+ "Analysis cites [2] and [3].\n"
+ "```\n"
+ "code [9]\n"
+ )
+ _, _, indeterminate = self._extract(prose)
+ assert indeterminate is True
+ assert self._filter(self._links(), prose) == self._links()
+ assert (
+ self._filter(self._links(), prose, mode="strict") == self._links()
+ )
+
+ def test_crlf_blockquoted_fence_variants_retained(self):
+ """CRLF line endings use the same fence pairing as LF."""
+ prose = (
+ "Intro cites [1].\r\n"
+ "> ```json\r\n"
+ '> {"key": "value"}\r\n'
+ "```\r\n"
+ "Real analysis cites [2].\r\n"
+ "```python\r\n"
+ "code [4]\r\n"
+ "```\r\n"
+ "Outro cites [3].\r\n"
+ "> ```\r\n"
+ "> quoted\r\n"
+ "```\r\n"
+ )
+ _, _, indeterminate = self._extract(prose)
+ assert indeterminate is False
+ for mode in ("fallback", "strict"):
+ kept = self._filter(self._links(), prose, mode=mode)
+ assert [link["index"] for link in kept] == ["1", "2", "3"], mode
+
+ def test_line_start_decorative_runs_do_not_swallow_citations(self):
+ """````` decorate [8] ``` end`` is decorative, not a fence.
+
+ A single line carrying two markers must not open a block:
+ pairing it with the next real opener stripped ``[1]``/``[2]``
+ (keeping only ``['3']`` in the two-decorative + one-block
+ shape). The decorative ``[8]`` itself is over-included (safe)
+ while real citations survive.
+ """
+ prose = (
+ "``` decorate [8] ``` end\n"
+ "Real cites [1].\n"
+ "```python\n"
+ "code [4]\n"
+ "```\n"
+ "Outro cites [2].\n"
+ "``` decorate [8] ``` end\n"
+ "Final [3].\n"
+ )
+ kept = self._filter(self._links(), prose)
+ assert [link["index"] for link in kept] == ["1", "2", "3"]
+ kept = self._filter(self._links(), prose, mode="strict")
+ assert [link["index"] for link in kept] == ["1", "2", "3"]
+
+ def test_junk_text_closers_close_both_blocks(self):
+ """````` done ``` `` closers must close, not vanish.
+
+ Regression vs the opener-only veto: vetoing a closer carrying
+ trailing text paired its opener with the *next* opener, stripping
+ ``[2]`` while retaining in-block ``[9]`` (``['1','3','9']``)
+ with no fallback. The veto stops openers only; closers close.
+ """
+ prose = (
+ "Intro cites [1].\n"
+ "```python\n"
+ "x [9]\n"
+ "``` done ```\n"
+ "Real analysis cites [2].\n"
+ "```js\n"
+ "y [9]\n"
+ "``` fin ```\n"
+ "Outro cites [3].\n"
+ )
+ _, _, indeterminate = self._extract(prose)
+ assert indeterminate is False
+ for mode in ("fallback", "strict"):
+ kept = self._filter(self._links(), prose, mode=mode)
+ assert [link["index"] for link in kept] == ["1", "2", "3"], mode
+
+ def test_six_backtick_closers_close_both_blocks(self):
+ """Six-backtick `` `````` `` lines close `` ``` `` blocks.
+
+ A longer single run is one fence, not two: the opener veto
+ looks past the initial run, and closers carry no veto at all.
+ """
+ prose = (
+ "Intro cites [1].\n"
+ "```python\n"
+ "x [9]\n"
+ "``````\n"
+ "Real analysis cites [2].\n"
+ "```js\n"
+ "y [9]\n"
+ "``````\n"
+ "Outro cites [3].\n"
+ )
+ _, _, indeterminate = self._extract(prose)
+ assert indeterminate is False
+ for mode in ("fallback", "strict"):
+ kept = self._filter(self._links(), prose, mode=mode)
+ assert [link["index"] for link in kept] == ["1", "2", "3"], mode
+
+ def test_single_junk_closer_stays_safe(self):
+ """Single junk closer control: no loss on either head."""
+ prose = (
+ "Intro cites [1].\n"
+ "```python\n"
+ "x [9]\n"
+ "``` done ```\n"
+ "Real analysis cites [2].\n"
+ )
+ _, _, indeterminate = self._extract(prose)
+ assert indeterminate is False
+ for mode in ("fallback", "strict"):
+ kept = self._filter(self._links(), prose, mode=mode)
+ assert [link["index"] for link in kept] == ["1", "2"], mode