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.

69.1 KB
Raw Blame
"""Tests for format-aware citation stripping in chat follow-up context.

Prior-turn answers carry citations in whatever shape `report.citation_format`
produced (markdown hyperlinks `[[1]](url)` / `[[arxiv.org-1]](url)`, the plain
source-tagged form `[arxiv-1]` / `[local-1]`, plain `[1]`, lenticular `【1】`).
Those index the prior turn's sources, so they must be stripped from the
context carried into a follow-up — but ONLY from assistant-authored text;
anything the user typed themselves must survive untouched.
"""

import time

import pytest
from markdown import markdown

from local_deep_research.chat.context import ChatContextManager


def _manager(messages=None, mode=None):
    snapshot = {"chat.followup_context_mode": mode} if mode else None
    return ChatContextManager(
        session_id="s1",
        messages=messages or [],
        accumulated_context={},
        settings_snapshot=snapshot,
    )


class TestStripCitationMarkers:
    @pytest.mark.parametrize(
        "text,expected",
        [
            # number_hyperlinks (default report.citation_format)
            (
                "Light is used [[1]](http://a) in cells.",
                "Light is used in cells.",
            ),
            ("Both [[1, 2]](http://a) agree.", "Both agree."),
            # domain / domain-id hyperlinks
            # single-bracket domain forms count only when the label names
            # the link's own host, as CitationFormatter would label it
            ("Per [arxiv.org-1](https://arxiv.org/abs/1).", "Per."),
            ("Per [arxiv.org](https://www.arxiv.org/abs/1).", "Per."),
            # no_hyperlinks plain markers
            ("Plain [1] cite.", "Plain cite."),
            ("A group [1, 2] of cites.", "A group of cites."),
            # lenticular brackets some models emit
            ("Lenticular 【1】 marker.", "Lenticular marker."),
            ("Lenticular 【1, 2】 marker.", "Lenticular marker."),
            # mixed old + new in one string
            ("Old [1] new [[2]](http://x) mix.", "Old new mix."),
            # nothing to strip
            ("No citations at all.", "No citations at all."),
            ("", ""),
        ],
    )
    def test_strips_all_citation_formats(self, text, expected):
        assert _manager()._strip_citation_markers(text) == expected

    def test_none_input_passthrough(self):
        assert _manager()._strip_citation_markers(None) is None


class TestBuildResearchContextStripsCitations:
    """End-to-end: a raw-mode follow-up's past_findings has no leaked markers."""

    def test_raw_mode_strips_hyperlinked_citations(self, mocker):
        # raw mode makes no LLM call; guard get_llm anyway.
        mocker.patch("local_deep_research.config.llm_config.get_llm")
        messages = [
            {
                "role": "user",
                "content": "How do plants make energy?",
                "message_type": "query",
            },
            {
                "role": "assistant",
                "content": (
                    "Plants convert light [[1]](http://a) into energy in "
                    "chloroplasts [arxiv.org-2](https://arxiv.org/abs/2)."
                ),
                "message_type": "response",
                "research_id": "r1",
            },
        ]
        result = _manager(messages, mode="raw").build_research_context(
            current_query="explain more"
        )
        past = result["past_findings"]
        assert "](http" not in past  # no markdown link residue
        assert "[1]" not in past and "[arxiv.org-2]" not in past
        assert "Plants convert light" in past and "chloroplasts" in past


class TestStripScopeAndRobustness:
    """Adversarial coverage: scope, over/under-strip edges, long input."""

    def test_only_prior_findings_stripped_not_original_query(self, mocker):
        """Stripping targets carried-over findings, never the user's query.

        ``original_query`` is the session's first user message verbatim; a
        bracketed token the user themselves typed must survive untouched.
        """
        mocker.patch("local_deep_research.config.llm_config.get_llm")
        messages = [
            {
                "role": "user",
                "content": "What does array[1] mean?",
                "message_type": "query",
            },
            {
                "role": "assistant",
                "content": "It indexes [[1]](http://a) the element.",
                "message_type": "response",
                "research_id": "r1",
            },
        ]
        result = _manager(messages, mode="raw").build_research_context(
            current_query="tell me more"
        )
        # User's own query preserved verbatim (not routed through the strip).
        assert result["original_query"] == "What does array[1] mean?"
        # Prior findings had their carried-over marker removed.
        assert "](http" not in result["past_findings"]

    def test_long_input_with_many_markers_is_linear(self, monkeypatch):
        """Many markers plus a glued bracket flood cost O(1) lookups each.

        Work is counted, not timed: every citation-token and verbatim-link
        lookup is tallied. Each marker needs one lookup, and the whole
        ``a[[[[...`` flood one, because a failed match advances past the
        entire opener run; retrying from every ``[`` of the run would make
        the flood alone cost one lookup (and one run scan) per bracket.
        """
        from local_deep_research.chat import citation_stripping as cs

        calls = {"n": 0}

        def counted(real):
            def wrapper(*args):
                calls["n"] += 1
                return real(*args)

            return wrapper

        monkeypatch.setattr(
            cs, "_match_citation_token", counted(cs._match_citation_token)
        )
        monkeypatch.setattr(
            cs, "_match_verbatim_link", counted(cs._match_verbatim_link)
        )
        k = 4000
        text = (
            ("word [[1]](http://a) " * k)
            + ("[1, 2] " * k)
            + "a"
            + ("[" * k)
            + " tail"
        )
        out = _manager()._strip_citation_markers(text)
        assert "](http" not in out
        assert "[1]" not in out and "[1, 2]" not in out
        assert out.count("word") == k
        # 2k markers -> 2k lookups, plus a constant for the flood.
        assert calls["n"] <= 2 * k + 16

    def test_escaped_bracket_runs_are_not_rescanned(self, monkeypatch):
        """A label full of escaped ``]`` is skipped once per link lookup.

        The verbatim-link matcher used to re-find and re-check every
        escaped ``]`` after each nested ``[``, about 6,000 escape checks
        per input character on this shape (over 1 ms per character).
        """
        from local_deep_research.chat import citation_stripping as cs

        calls = {"n": 0}
        real = cs._is_escaped

        def counted(text, pos):
            calls["n"] += 1
            return real(text, pos)

        monkeypatch.setattr(cs, "_is_escaped", counted)
        text = ("[\\]" * 330 + "](x)") * 3
        assert _manager()._strip_citation_markers(text) == text
        assert calls["n"] <= len(text)

    def test_adversarial_unclosed_brackets_terminate(self):
        """Pathological unclosed-bracket run must not hang and must be inert."""
        out = _manager()._strip_citation_markers("[" * 20000 + "1")
        # Nothing forms a complete citation, so content is returned unharmed.
        assert out.endswith("1")


class TestSourceTaggedCitations:
    """SOURCE_TAGGED_HYPERLINKS' plain (non-hyperlinked) marker shape.

    CitationFormatter._format_source_tagged_hyperlinks emits ``[tag-N]``
    (no trailing ``(url)``) for any cited source whose URL is not http(s)
    — local files and RAG/library hits. This used to survive into
    follow-up context unstripped (the exact dangling-citation problem this
    module exists to prevent); the tag shape is covered in
    ``chat.citation_stripping`` (see ``_is_tag_id``).
    """

    @pytest.mark.parametrize(
        "text,expected",
        [
            # CitationFormatter._extract_source_label's known-tag vocabulary
            ("From the paper [arxiv-1].", "From the paper."),
            ("See the docs [local-1] here.", "See the docs here."),
            ("Per [pubmed-3] and [pmc-4].", "Per and."),
            ("Study [biorxiv-2] found this.", "Study found this."),
            ("As in [medrxiv-7] trial.", "As in trial."),
            ("Per [semantic_scholar-12] study.", "Per study."),
            ("Ref [doi-9] confirms it.", "Ref confirms it."),
            # domain-derived tags (_extract_domain always yields a dotted
            # string) also covered
            ("See [nytimes.com-9] report.", "See report."),
            ("Per [arxiv.org-1] source.", "Per source."),
            # dotless collection slugs — _slugify_collection keeps only
            # [a-z0-9-], so RAG collection tags never carry the dot the
            # old pattern required
            ("Finding [personal-notes-3].", "Finding."),
            ("From [my-papers-2] here.", "From here."),
            # digit-leading slug (collection named "2024 notes") still
            # has letters, so it is a tag — unlike a numeric range
            ("Cites [2024-notes-3] store.", "Cites store."),
            # hyperlinked slug label (linkable collection source)
            ("See [[personal-notes-3]](http://a) cited.", "See cited."),
            # mixed with the hyperlinked form in one string
            (
                "Mix [local-1] and [[arxiv-2]](http://a) both.",
                "Mix and both.",
            ),
        ],
    )
    def test_strips_plain_source_tagged_markers(self, text, expected):
        assert _manager()._strip_citation_markers(text) == expected

    @pytest.mark.parametrize(
        "text",
        [
            # Common code-indexing prose this (developer-facing) tool's
            # chat regularly carries. The tag charset is lowercase-only
            # with at least one letter and the (?<![\w.\]]) lookbehind
            # rejects markers glued to an identifier — so these are NOT
            # treated as citations (an open `[label-N]` pattern would
            # catch them — the class of over-widening #5903 fixed for the
            # sub-index pattern).
            "x = arr[i-1]",
            "data[idx-2] = 5",
            "See [RFC-2119] for definitions.",
            "Range [1 - 2] applies.",
        ],
    )
    def test_does_not_strip_code_like_or_uppercase_brackets(self, text):
        assert _manager()._strip_citation_markers(text) == text

    def test_end_to_end_raw_mode_strips_source_tagged_marker(self, mocker):
        mocker.patch("local_deep_research.config.llm_config.get_llm")
        messages = [
            {
                "role": "user",
                "content": "What's in my notes?",
                "message_type": "query",
            },
            {
                "role": "assistant",
                "content": "Your notes say the deadline is Friday [local-1].",
                "message_type": "response",
                "research_id": "r1",
            },
        ]
        result = _manager(messages, mode="raw").build_research_context(
            current_query="tell me more"
        )
        assert "[local-1]" not in result["past_findings"]
        assert "deadline is Friday" in result["past_findings"]


class TestFullModeScopedToAssistantTurns:
    """`full` mode must strip citations from assistant turns only.

    Regression for the bug where ``build_research_context`` ran the WHOLE
    joined transcript (both roles) through the citation stripper, deleting
    any markdown link a USER typed in an earlier turn.
    """

    def test_user_typed_markdown_link_survives_full_mode(self, mocker):
        mocker.patch("local_deep_research.config.llm_config.get_llm")
        link = "[arxiv.org](https://arxiv.org/abs/2401.00001)"
        user_text = f"See {link} for context."
        # The label is citation-shaped (it names its own host), so only the
        # role scoping can keep it: a role-blind pass would delete it.
        assert link not in _manager()._strip_citation_markers(user_text)
        messages = [
            {
                "role": "user",
                "content": user_text,
                "message_type": "query",
            },
            {
                "role": "assistant",
                "content": "Noted. Light is used [[1]](http://a) in cells.",
                "message_type": "response",
                "research_id": "r1",
            },
        ]
        result = _manager(messages, mode="full").build_research_context(
            current_query="tell me more"
        )
        past = result["past_findings"]
        # The user's own link is preserved verbatim.
        assert link in past
        # The assistant's carried-over citation marker is still stripped.
        assert "[[1]](http://a)" not in past
        assert "Light is used in cells." in past

    def test_user_typed_source_tagged_shape_survives_full_mode(self, mocker):
        """A user typing something citation-shaped (e.g. quoting a prior
        answer) must not be treated as a citation either — scope is by
        role, not by pattern."""
        mocker.patch("local_deep_research.config.llm_config.get_llm")
        messages = [
            {
                "role": "user",
                "content": "You mentioned [arxiv-1] earlier, what did it say?",
                "message_type": "query",
            },
            {
                "role": "assistant",
                "content": "It found X [arxiv-1].",
                "message_type": "response",
                "research_id": "r1",
            },
        ]
        result = _manager(messages, mode="full").build_research_context(
            current_query="more"
        )
        past = result["past_findings"]
        assert "You mentioned [arxiv-1] earlier" in past
        assert "It found X." in past


class TestWhitespacePreservedOnStrip:
    """Stripping must not corrupt unrelated indentation/whitespace.

    Regression for the bug where a blanket ``[ \\t]{2,}`` collapse ran over
    the ENTIRE findings string on every follow-up turn, flattening code
    indentation, nested list indentation and table column alignment that
    never had a citation marker anywhere near them.
    """

    def test_code_block_indentation_survives(self):
        text = "def f():\n    if x:\n        return data  [[1]](http://a)"
        out = _manager()._strip_citation_markers(text)
        assert out == "def f():\n    if x:\n        return data"

    def test_nested_list_indentation_survives(self):
        text = (
            "- item one\n  - nested [[1]](http://a) item\n    - deeper item [2]"
        )
        out = _manager()._strip_citation_markers(text)
        assert out == ("- item one\n  - nested item\n    - deeper item")

    def test_table_column_alignment_survives(self):
        text = (
            "| Col A | Col B [[1]](http://a) |\n"
            "|-------|-------|\n"
            "| val1  | val2  |"
        )
        out = _manager()._strip_citation_markers(text)
        assert out == (
            "| Col A | Col B |\n|-------|-------|\n| val1  | val2  |"
        )


class TestStripHardening:
    """Adversarial-gate cases: non-citation content survives, citations
    are removed whole.

    These were xfail'd known gaps before the strip gained code-span
    protection, a balanced-parenthesis URL matcher, and citation-shaped
    link labels.
    """

    def test_parenthesized_url_leaves_no_residue(self):
        # The URL matcher tolerates one level of balanced parentheses, so
        # a Wikipedia "(disambiguation)" URL is consumed whole instead of
        # stopping at the first ')' and leaving a stray one behind.
        out = _manager()._strip_citation_markers(
            "See [[1]](https://en.wikipedia.org/wiki/Foo_(bar)) now."
        )
        assert ")" not in out

    def test_code_block_index_not_stripped(self):
        # Fenced code is not a citation site.
        out = _manager()._strip_citation_markers("```\nx = arr[1]\n```")
        assert "arr[1]" in out

    def test_inline_code_index_not_stripped(self):
        # Neither is inline code.
        out = _manager()._strip_citation_markers("Use `results[1]` here.")
        assert "results[1]" in out

    def test_ordinary_markdown_link_survives(self):
        # A link whose label is not citation-shaped (here: it contains a
        # space, which no CitationFormatter label ever does) is verbatim
        # content, not a citation — it must keep label AND destination.
        text = (
            "Download [the dataset](https://example.com/data) before analysis."
        )
        assert _manager()._strip_citation_markers(text) == text

    def test_citation_starting_a_line_does_not_join_lines(self):
        # Whitespace consumption is horizontal-only, so a marker at the
        # start of the next line can never eat the newline(s); the
        # indentation before it is kept and the separator after it goes.
        text = "First line\n  [[1]](https://example.com) second line"
        assert (
            _manager()._strip_citation_markers(text)
            == "First line\n  second line"
        )


class TestRawModeStripsBeforeTruncating:
    """Raw mode must strip citations BEFORE the 500-char truncation.

    A citation crossing the truncation cutoff is cut into a shape no
    pattern can match ("[](htt..."), so stripping AFTER truncating can
    never clean it up — extraction strips each assistant message first.
    """

    def test_citation_crossing_cutoff_leaves_no_residue(self, mocker):
        mocker.patch("local_deep_research.config.llm_config.get_llm")
        long_answer = "a" * 490 + " [[1]](https://example.com/reference) final"
        messages = [
            {
                "role": "user",
                "content": "summarize",
                "message_type": "query",
            },
            {
                "role": "assistant",
                "content": long_answer,
                "message_type": "response",
                "research_id": "r1",
            },
        ]
        result = _manager(messages, mode="raw").build_research_context(
            current_query="more"
        )
        past = result["past_findings"]
        assert "[[" not in past
        assert "[]" not in past
        assert "](http" not in past
        assert past.endswith("final")


class TestAdjacentCitationRuns:
    """Formatter-produced ADJACENT markers must strip as one run.

    ``CitationFormatter._replace_comma_citations`` joins the formatted
    parts of a comma group with no separator, so
    ``[1, 2]`` in source-tagged mode renders as
    ``[local-1][personal-notes-2]`` (both non-linkable) or
    ``[[web-1]](url)[local-2]`` (mixed). Round 2 of the adversarial gate
    showed the round-1 ``]``-lookbehind rejecting the second tag, gluing
    debris to the preceding word; the run consumer in
    ``chat.citation_stripping`` removes the whole run. Footnote-style
    period-glued tags (``holds.[local-1]``) strip too — a period is not
    an identifier character.
    """

    @pytest.mark.parametrize(
        "text,expected",
        [
            (
                "Cites [local-1][personal-notes-2] here.",
                "Cites here.",
            ),
            (
                "Source [[web-1]](https://example.com)[local-2] says.",
                "Source says.",
            ),
            ("This holds.[local-1]", "This holds."),
            ("Group [1][2][3] chain.", "Group chain."),
            (
                "Mix [[a-1]](http://x)[[b-2]](http://y) done.",
                "Mix done.",
            ),
        ],
    )
    def test_adjacent_run_fully_stripped(self, text, expected):
        assert _manager()._strip_citation_markers(text) == expected


class TestSingleWordOrdinaryLinksSurvive:
    """A one-word ordinary Markdown link is not a citation.

    Grounded in CitationFormatter's actual emissions: every hyperlinked
    citation is ``[[label]](url)``. The only single-bracket links stripped
    are domain labels naming the link's own host
    (``[arxiv.org](https://arxiv.org/x)``) — never a bare dotless word.
    Round 2 of the gate showed the round-1 charset label deleting
    ``[dataset](...)`` and ``[release-notes](...)`` from assistant prose.
    """

    @pytest.mark.parametrize(
        "text",
        [
            "Download [dataset](https://example.com/data) before analysis.",
            "Read [release-notes](https://example.com/releases) now.",
            "See [Dataset](https://example.com/data) too.",
        ],
    )
    def test_single_word_link_survives(self, text):
        assert _manager()._strip_citation_markers(text) == text

    @pytest.mark.parametrize(
        "text",
        [
            "Edit [config.yaml](https://github.com/o/r/blob/main/config.yaml) first.",
            "the [README.md](README.md) file",
            "Upgrade to [v1.2](https://github.com/o/r/releases/v1.2) now.",
            "Open [example.com](https://other.org/) x",
            "Docs at [docs.python.org](https://docs.python.org/3/) here.",
        ],
    )
    def test_dotted_link_text_survives_unless_it_names_its_host(self, text):
        """A dot in the label is not enough: ``[config.yaml](url)`` is link
        text. The formatter never emits a single-bracket hyperlink, so a
        dotted single-bracket label strips only when it is the link's own
        host as ``CitationFormatter`` labels it."""
        assert _manager()._strip_citation_markers(text) == text

    @pytest.mark.parametrize(
        "text,expected",
        [
            ("Per [arxiv.org](https://arxiv.org/abs/1) x", "Per x"),
            ("Per [arxiv.org-2](https://www.arxiv.org/abs/1) x", "Per x"),
            ("Per [github.com](https://github.com/o/r) x", "Per x"),
        ],
    )
    def test_dotted_link_naming_its_own_host_strips(self, text, expected):
        assert _manager()._strip_citation_markers(text) == expected


class TestCodeProtectionCommonMark:
    """Fence/span protection must cover CommonMark variants, and a bare
    ``identifier[...]`` index in prose is not a citation marker.

    Round 2 of the gate showed tilde fences and double-backtick spans
    losing their brackets, and plain prose ``results[1]`` being stripped.
    """

    @pytest.mark.parametrize(
        "text",
        [
            "~~~python\nx = results[1]\n~~~",
            "````\ny = data[2]\n````",
            "``code `x[1]` here``",
            "The second item is results[1].",
        ],
    )
    def test_code_shapes_and_prose_index_survive(self, text):
        assert _manager()._strip_citation_markers(text) == text


class TestNestedParenthesisUrl:
    """URLs with nested balanced parentheses strip whole (round-2 gate).

    The URL matcher balances parens up to ``_URL_MAX_DEPTH`` (well past
    any real Wikipedia-style URL), so ``Foo_(bar_(baz))`` leaves no
    ``[](...)`` residue. Past the bound the text is simply not treated as
    a URL — nothing is mangled.
    """

    def test_nested_parens_stripped_whole(self):
        out = _manager()._strip_citation_markers(
            "See [[1]](https://example.com/Foo_(bar_(baz))) now."
        )
        assert out == "See now."

    def test_depth_beyond_bound_is_inert(self):
        from local_deep_research.chat.citation_stripping import _URL_MAX_DEPTH

        depth = _URL_MAX_DEPTH + 1
        deep = "(" * depth + "x" + ")" * depth
        text = f"See [[1]]({deep}) now."
        assert _manager()._strip_citation_markers(text) == text


class TestBracketRunIsLinear:
    """An unclosed bracket run must not backtrack quadratically.

    The round-1 ``\\[+``-prefixed link regex took ~10s at 20k brackets and
    ~90s at 60k; the scanner in ``chat.citation_stripping`` skips the
    whole bracket run in one pass (measured in milliseconds). 60k is far
    past any linear cost yet impossible for a quadratic matcher, so a
    generous bound separates the regimes without wall-clock flake.
    """

    @pytest.mark.parametrize("suffix", ["1", "`code`", "<span>value</span>"])
    def test_bracket_run_strips_linearly(self, suffix):
        """Protected spans must not cause failed prefixes to be parsed repeatedly."""
        text = "[" * 60_000 + suffix
        start = time.monotonic()
        out = _manager()._strip_citation_markers(text)
        elapsed = time.monotonic() - start
        assert out == text  # inert: nothing forms a complete citation
        assert elapsed < 10.0


class TestRoundFiveFormatterAuthorities:
    @pytest.mark.parametrize(
        "text",
        [
            "See [[LOCALHOST]](http://LOCALHOST/a) now.",
            "See [[LOCALHOST-1]](http://LOCALHOST/a) now.",
        ],
    )
    def test_uppercase_dotless_authority_citations_strip(self, text):
        out = _manager()._strip_citation_markers(text)

        assert out == "See now."
        assert markdown(out) == "<p>See now.</p>"


class TestRoundFiveMarkdownStructures:
    @pytest.mark.parametrize(
        "text,rendered_fragment",
        [
            (
                "[dataset](/page/[1]/details)",
                'href="/page/[1]/details"',
            ),
            (
                "[1]: /page/[2]/details\n\n[x][1]",
                'href="/page/[2]/details"',
            ),
            (
                "> [1]: https://example.com\n\n> [x][1]",
                '<blockquote>\n<p><a href="https://example.com">x</a></p>',
            ),
            (
                "[see [1]](https://example.com)",
                ">see [1]</a>",
            ),
            (
                "![alt\n[1]](pic.jpg)",
                'alt="alt\n[1]" src="pic.jpg"',
            ),
        ],
    )
    def test_valid_markdown_structures_survive(self, text, rendered_fragment):
        out = _manager()._strip_citation_markers(text)

        assert out == text
        assert rendered_fragment in markdown(out)


class TestRoundFiveRenderedSeparation:
    def test_link_before_removed_citation_keeps_word_boundary(self):
        text = "[left](x)[[1]](u)right"

        out = _manager()._strip_citation_markers(text)

        assert out == "[left](x) right"
        assert markdown(out) == '<p><a href="x">left</a> right</p>'


class TestRoundFiveCodeProtection:
    @pytest.mark.parametrize(
        "text,rendered_fragment",
        [
            (
                "Use `first\n[1] second` now.",
                "<code>first\n[1] second</code>",
            ),
            ("```\n[1]", "[1]"),
            ("<pre>[1]</pre>", "<pre>[1]</pre>"),
        ],
    )
    def test_multiline_and_block_code_survive(self, text, rendered_fragment):
        out = _manager()._strip_citation_markers(text)

        assert out == text
        assert rendered_fragment in markdown(out, extensions=["fenced_code"])


class TestRoundSixMarkdownCodeComposition:
    @pytest.mark.parametrize(
        "text",
        [
            "Click [see `code` [1]](https://example.com).",
            "![alt `x` [1]](pic.jpg)",
        ],
    )
    def test_link_or_image_with_inline_code_survives(self, text):
        assert _manager()._strip_citation_markers(text) == text


class TestRoundSixHtmlLookingInlineCode:
    @pytest.mark.parametrize(
        "text,expected",
        [
            (
                "Run `<code>foo` then see [1].\n\nNext paragraph [2] more.",
                "Run `<code>foo` then see.\n\nNext paragraph more.",
            ),
            (
                "Run `first\n<code>[1]</code>\nlast` then see [2].",
                "Run `first\n<code>[1]</code>\nlast` then see.",
            ),
        ],
    )
    def test_html_looking_tag_in_code_cannot_disable_later_stripping(
        self, text, expected
    ):
        assert _manager()._strip_citation_markers(text) == expected


class TestRoundSixRemainingMarkdownBlocks:
    @pytest.mark.parametrize(
        "text",
        [
            "[ref]:\n  /page/[1]/details\n\n[x][ref]",
            "> [ref]:\n>   /page/[1]/details\n>\n> [x][ref]",
            "- [ref]:\n    /page/[1]/details\n\n  [x][ref]",
            "- [ref]:\n\t/page/[1]/details\n\n  [x][ref]",
        ],
    )
    def test_multiline_relative_reference_destination_survives(self, text):
        out = _manager()._strip_citation_markers(text)

        assert out == text
        assert 'href="/page/[1]/details"' in markdown(out)

    @pytest.mark.parametrize("indent", ["    ", "\t"])
    def test_indented_code_after_fence_survives(self, indent):
        text = f"```\nx\n```\n{indent}[1]"

        out = _manager()._strip_citation_markers(text)

        assert out == text
        assert markdown(out, extensions=["fenced_code"]).count("<code>") == 2


class TestRoundSixMirroredBacktickScaling:
    def test_mirrored_run_lengths_scale_linearly(self):
        elapsed = []
        for size in (800, 1600):
            half = "x".join("`" * length for length in range(1, size + 1))
            text = f"{half}\n\n{half}"
            start = time.monotonic()

            out = _manager()._strip_citation_markers(text)

            elapsed.append(time.monotonic() - start)
            assert out == text

        assert elapsed[1] < elapsed[0] * 6


class TestRoundSevenFormatterTagsAndLinks:
    @pytest.mark.parametrize(
        "text,expected",
        [
            ("See [123-1] now.", "See [123-1] now."),
            ("See [[123-1]](https://example.com) now.", "See now."),
        ],
    )
    def test_numeric_collection_tags_strip(self, text, expected):
        """Bare numeric tags also represent factual ranges; only links disambiguate."""
        assert _manager()._strip_citation_markers(text) == expected

    @pytest.mark.parametrize(
        "text",
        [
            "x = arr[123-1]",
            "[label \\] [1]](u)",
            "![alt \\] [1]](pic.jpg)",
        ],
    )
    def test_array_and_escaped_label_structures_survive(self, text):
        out = _manager()._strip_citation_markers(text)

        assert out == text
        assert markdown(out) == markdown(text)


class TestRoundSevenCodeAndReferenceBlocks:
    def test_crlf_blank_paragraph_ends_inline_code_pairing(self):
        text = "`before\r\n\r\n[1]` after [2]"

        out = _manager()._strip_citation_markers(text)

        assert out == "`before\r\n\r\n` after"

    @pytest.mark.parametrize(
        "text",
        [
            '[ref]: /page\n  "title [1]"\n\n[x][ref]',
            '> [ref]: /page\n>   "title [1]"\n>\n> [x][ref]',
            '- [ref]: /page\n    "title [1]"\n\n  [x][ref]',
            '[ref]:\n  /page\n  "title [1]"\n\n[x][ref]',
        ],
    )
    def test_multiline_reference_titles_survive(self, text):
        out = _manager()._strip_citation_markers(text)

        assert out == text
        assert 'title="title [1]"' in markdown(out)

    @pytest.mark.parametrize(
        "text",
        [
            "# heading\n    [1]",
            "---\n    [1]",
            "heading\n---\n    [1]",
            "<div>block</div>\n    [1]",
            "<div>\nblock\n</div>\n    [1]",
        ],
    )
    def test_indented_code_after_completed_block_survives(self, text):
        out = _manager()._strip_citation_markers(text)

        assert out == text
        assert "<code>[1]" in markdown(out)


class TestRoundSevenHtmlContexts:
    def test_code_tag_text_inside_html_comment_does_not_open_code(self):
        text = "<!-- mentions <code> only -->\nProse [1] continues."

        assert _manager()._strip_citation_markers(text) == (
            "<!-- mentions <code> only -->\nProse continues."
        )

    def test_backtick_in_fence_cannot_mask_later_html_code(self):
        text = "~~~\n`\n~~~\n<code>[1]</code> `x`"

        out = _manager()._strip_citation_markers(text)

        assert out == text
        assert "<code>[1]</code>" in markdown(out, extensions=["fenced_code"])

    def test_html_comment_contents_survive_while_following_prose_strips(self):
        text = "<!-- hidden [1] -->\nProse [2] continues."

        assert _manager()._strip_citation_markers(text) == (
            "<!-- hidden [1] -->\nProse continues."
        )

    def test_backtick_in_comment_cannot_mask_later_html_code(self):
        text = "<!-- ` -->\n<code>[1]</code> `x`"

        assert _manager()._strip_citation_markers(text) == text

    def test_backtick_inside_comment_cannot_mask_later_html_code(self):
        text = "<!-- ` -->\n<code>[1]</code> `x`"

        out = _manager()._strip_citation_markers(text)

        assert out == text

    def test_backtick_inside_comment_cannot_mask_later_prose(self):
        text = "<!-- ` -->\nProse [1] `x`"

        assert (
            _manager()._strip_citation_markers(text) == "<!-- ` -->\nProse `x`"
        )


class TestRoundEightParserContexts:
    @pytest.mark.parametrize(
        "text,expected",
        [
            ("See [1-1] now.", "See [1-1] now."),
            ("See [[1-1]](https://example.com) now.", "See now."),
            ("See [7-42] now.", "See [7-42] now."),
        ],
    )
    def test_single_digit_numeric_collection_tags_strip(self, text, expected):
        """Without provenance, preserving numeric ranges takes precedence."""
        assert _manager()._strip_citation_markers(text) == expected

    @pytest.mark.parametrize(
        "text",
        [
            'Read [see [1]](/page "a title") now.',
            "Read [see [1]](/page 'a title') now.",
            'Read [see [1]](<page target> "a title") now.',
            "Read [see [1]][ref] now.\n\n[ref]: /page",
            "Read [see [1]][] now.",
        ],
    )
    def test_titled_and_reference_markdown_links_survive(self, text):
        out = _manager()._strip_citation_markers(text)

        assert out == text
        assert markdown(out) == markdown(text)

    @pytest.mark.parametrize(
        "text",
        [
            '<a href="/page/[1]/details">dataset</a>',
            '<a data-x="[1]">x</a>',
            '<a data-x="> [1]">x</a>',
            '<img alt="[1]" src="x">',
        ],
    )
    def test_citation_shapes_inside_html_attributes_survive(self, text):
        assert _manager()._strip_citation_markers(text) == text

    @pytest.mark.parametrize(
        "text",
        [
            ">     [1]",
            "> ~~~\n> [1]\n> ~~~",
            "> ```python\n> [1]\n> ```",
        ],
    )
    def test_blockquote_code_blocks_survive(self, text):
        out = _manager()._strip_citation_markers(text)

        assert out == text
        assert "[1]" in markdown(out, extensions=["fenced_code"])


@pytest.mark.parametrize("mode", ["raw", "full"])
def test_factual_ranges_survive_context_assembly(mode):
    """Removing bare numeric collection tags also erased unambiguous year facts."""
    messages = [
        {"role": "user", "content": "Which years were observed?"},
        {
            "role": "assistant",
            "research_id": "synthetic",
            "content": "The window is [2020-2024]. Evidence [[1]](https://example.com/a).",
        },
    ]
    past = _manager(messages, mode=mode).build_research_context()[
        "past_findings"
    ]
    assert "The window is [2020-2024]." in past
    assert "[[1]]" not in past


def test_summary_citation_cleanup_precedes_output_cap(mocker):
    """A citation straddling the summary cap must not become an incomplete URL."""
    from types import SimpleNamespace

    answer = "x" * 1990 + " [[1]](https://example.org/source) final"
    model = SimpleNamespace(
        invoke=lambda prompt: SimpleNamespace(content=answer)
    )
    mocker.patch(
        "local_deep_research.config.llm_config.get_llm", return_value=model
    )
    manager = _manager(
        [
            {
                "role": "assistant",
                "research_id": "r",
                "content": "Prior fact [1].",
            }
        ],
        mode="summary",
    )
    result = manager.build_research_context("Tell me more")["past_findings"]
    assert result == "x" * 1990 + " final"


def test_summary_truncation_does_not_rescan_partial_code(mocker):
    """Cleanup after truncation would mistake the now-unclosed code for prose."""
    from types import SimpleNamespace

    answer = "`literal [1] " + "x" * 2100 + "`"
    model = SimpleNamespace(
        invoke=lambda prompt: SimpleNamespace(content=answer)
    )
    mocker.patch(
        "local_deep_research.config.llm_config.get_llm", return_value=model
    )
    manager = _manager(
        [
            {
                "role": "assistant",
                "research_id": "r",
                "content": "Prior fact [1].",
            }
        ],
        mode="summary",
    )
    result = manager.build_research_context("Tell me more")["past_findings"]
    assert result.startswith("`literal [1] ")
    assert len(result) <= manager.CONTEXT_SUMMARY_MAX_CHARS + 3


class TestAdversarialGateBoundaryFixes:
    """Revert-catching tests for the adversarial-gate round of fixes.

    Each test pins one defect the gate reproduced at the PR head: a
    multiline HTML code opening tag, a non-1 ordered marker splitting a
    code-span paragraph, outer trims running before citation cleanup,
    an unclosed fence inside a code element, and word-joins after a
    protected span.
    """

    def test_multiline_code_opening_tag_protects_element_contents(self):
        """The ``>`` of the opening tag sits on the next line.

        Per-line tag scanning never recognized the element, so the code
        contents were scanned as prose and ``[1, 2]`` was deleted.
        """
        text = 'See <code\nclass="py">values = [1, 2]\n</code> end'

        out = _manager()._strip_citation_markers(text)

        assert out == text
        assert markdown(out) == markdown(text)

    def test_ordered_marker_other_than_one_is_lazy_continuation(self):
        """CommonMark: only ``1.`` (or a bullet) can interrupt a paragraph.

        ``2.`` used to split the backtick paragraph, leaving both values
        deleted and stray unpaired backticks behind.
        """
        text = "Set `x = [1]\n2. y = [2]` done"

        out = _manager()._strip_citation_markers(text)

        assert out == text

    def test_context_modes_strip_markers_before_outer_trim(self, mocker):
        """Full mode trimmed indentation before cleanup.

        The trim dedented a leading indented-code line into prose, so its
        bracket literals were deleted as citations (raw mode never
        trimmed, so the modes diverged). Summary mode cannot keep a
        LEADING indented line: ``ProcessingLLMWrapper`` trims every
        response before the summarizer sees it. The model below returns
        what that wrapper delivers, and code later in the summary must
        still be protected while its markers strip.
        """
        content = "    data = [1, 2, 3]\n    keep = [4]\nDone."
        messages = [
            {"role": "user", "content": "show the data"},
            {
                "role": "assistant",
                "research_id": "r",
                "content": content,
            },
        ]
        full = _manager(messages, mode="full").build_research_context("more")[
            "past_findings"
        ]
        assert "data = [1, 2, 3]" in full
        assert "keep = [4]" in full

        from types import SimpleNamespace

        # Already trimmed, as ProcessingLLMWrapper._normalize_response
        # (remove_think_tags + strip) delivers it in production.
        delivered = (
            "Summary:\n\n    data = [1, 2, 3]\n    keep = [4]\n\nDone [1]."
        )
        model = SimpleNamespace(
            invoke=lambda prompt: SimpleNamespace(content=delivered)
        )
        mocker.patch(
            "local_deep_research.config.llm_config.get_llm", return_value=model
        )
        summary = _manager(messages, mode="summary").build_research_context(
            "more"
        )["past_findings"]
        assert summary == (
            "Summary:\n\n    data = [1, 2, 3]\n    keep = [4]\n\nDone."
        )

    def test_unclosed_fence_inside_code_element_still_strips_afterwards(self):
        """A fence glyph inside ``<code>`` is element content, not a fence.

        Recognizing it as an unclosed fence used to protect the rest of
        the document, so the dangling ``[2]`` after the element survived
        — the exact residue this stripper exists to remove.
        """
        text = "<code>\n```\nfmt = [1]\n</code>\nSee [2] here"

        out = _manager()._strip_citation_markers(text)

        assert out == "<code>\n```\nfmt = [1]\n</code>\nSee here"

    @pytest.mark.parametrize(
        "text,expected",
        [
            ("Run <code>x</code>[1]now", "Run <code>x</code> now"),
            ("q <b>z</b>[7]w tail", "q <b>z</b> w tail"),
            (
                "a <code>1</code>[2]b <code>3</code>",
                "a <code>1</code> b <code>3</code>",
            ),
        ],
    )
    def test_citation_after_protected_span_retains_separator(
        self, text, expected
    ):
        """One separator survives when a run directly follows a span.

        The tail and per-segment strip calls had no left context, so
        removing the citation joined the neighbouring rendered words.
        """
        out = _manager()._strip_citation_markers(text)

        assert out == expected
        assert markdown(out) == markdown(expected)


class TestAdversarialGateOverlapAndBlockEnds:
    """Revert-catching tests for the second adversarial-gate round.

    Each test pins one defect the gate reproduced at the PR head: a
    ``<!--``/backtick inside an HTML tag's quoted attribute (or inside a
    Markdown link) starting a phantom span that duplicated text and
    shielded citations, a thematic break line never ending a backtick
    paragraph, and a setext underline never ending one either.
    """

    @pytest.mark.parametrize(
        "text,expected",
        [
            ('<a title="<!--">x [1]', '<a title="<!--">x'),
            ("[x](y<!--z)q [1]", "[x](y<!--z)q"),
        ],
    )
    def test_overlapping_phantom_span_does_not_duplicate_or_shield(
        self, text, expected
    ):
        """A ``<!--`` inside a tag attribute or link destination is inert.

        The phantom comment span started inside the already-emitted
        verbatim tag/link and ran past it, so the stitcher re-emitted
        text[start:end] — duplicating the overlap — and protected the
        ``[1]`` after it.
        """
        out = _manager()._strip_citation_markers(text)

        assert out == expected
        assert markdown(out) == markdown(expected)

    def test_thematic_break_line_ends_backtick_paragraph(self):
        """``_backtick_runs`` feeds keepends lines; ``---\\n`` never
        fullmatched the thematic-break regex, so the code span paired
        across it and kept both markers verbatim.
        """
        text = "`a [1]\n***\nb [2]` tail"

        out = _manager()._strip_citation_markers(text)

        assert out == "`a\n***\nb ` tail"
        assert markdown(out) == markdown("`a\n***\nb ` tail")

    def test_setext_underline_ends_backtick_paragraph(self):
        """An ``=====`` underline closes the paragraph above it.

        CommonMark never lets a code span pair across a setext heading;
        the module kept the span, shielding both markers inside it.
        """
        text = "`a [1]\n=====\nb [2]` tail"

        out = _manager()._strip_citation_markers(text)

        assert out == "`a\n=====\nb ` tail"
        assert markdown(out) == markdown("`a\n=====\nb ` tail")


class TestAdversarialGateLazyReentryDefinitionsTagFloor:
    """Revert-catching tests for the third adversarial-gate round.

    Each test pins one defect the gate reproduced at the PR head: a
    ``>`` re-entry after a lazy continuation line splitting the
    blockquoted paragraph (deleting a marker inside a real code span),
    pseudo reference definitions protecting their whole line, and
    single-letter slug tags (array indexing) deleted from prose.
    """

    def test_lazy_quote_reentry_keeps_code_span_paragraph(self):
        """One blockquoted paragraph spans the lazy line and the re-entry.

        CommonMark keeps ``> one `code``, ``lazy [1]`` and ``> end` tail``
        in a single blockquoted paragraph, so the code span pairs across
        all three lines and ``[1]`` renders inside it. The old
        ``depth > previous_depth`` split ended the run at the re-entry,
        leaving both backticks unpaired and ``[1]`` deleted.
        """
        text = "> one `code\nlazy [1]\n> end` tail"

        out = _manager()._strip_citation_markers(text)

        assert out == text
        assert "<code>code\nlazy [1]\nend</code>" in markdown(out)

    @pytest.mark.parametrize(
        "text,expected",
        [
            ("[Note]: See [1] for details.", "[Note]: See for details."),
            (
                "[TL;DR]: summary [1] of the answer [2] follows.",
                "[TL;DR]: summary of the answer follows.",
            ),
        ],
    )
    def test_pseudo_reference_definition_strips_markers(self, text, expected):
        """A space-bearing destination with no valid title is prose.

        ``[Note]: See [1] for details.`` is not a CommonMark reference
        definition, so it must not protect its whole line verbatim —
        only genuine definitions (validated destination, optional
        well-formed title) pass through untouched.
        """
        assert _manager()._strip_citation_markers(text) == expected

    def test_glued_short_slug_indexing_survives(self):
        """``dp[i-1]`` is indexing: the word-glue guard, not a slug-length
        floor, protects it (a one-letter collection slug is a real tag;
        see ``TestShortCollectionSlugTags``)."""
        text = "compare dp[i-1] with dp[i] and x[1][2]"

        out = _manager()._strip_citation_markers(text)

        assert out == text
        assert markdown(out) == markdown(text)


class TestAdversarialGateIndentColumnsSetextSpans:
    """Revert-catching tests for the fourth adversarial-gate round.

    Each test pins one defect the gate reproduced at the PR head:
    indented code decided from column zero of the quote-stripped line
    instead of the containing block's content column, a setext
    underline missing from the main block-boundary rule, and comment
    masking computing inline code spans per line so a multi-line
    span's comment opener latched the comment state.
    """

    @pytest.mark.parametrize(
        "text,expected",
        [
            # five spaces past the marker: the item's content is code
            ("-     [1]", "-     [1]"),
            ("1.     [1]", "1.     [1]"),
            # tabs advance to column 8, six past the content column
            ("- \t\t[1]", "- \t\t[1]"),
            # a tab reaching column 4 is top-level indented code
            ("   \t[1]", "   \t[1]"),
            (">   \t[1]", ">   \t[1]"),
            # controls: four spaces after a marker (or a single tab,
            # which only reaches two past the content column) stay a
            # paragraph continuation and strip
            ("-    [1]", "-"),
            ("- [1]", "-"),
            ("-\t[1]", "-"),
            ("   [1]", ""),
        ],
    )
    def test_indent_measured_from_content_column(self, text, expected):
        """Indented code is decided against the containing block's column.

        The old check inspected the quote-stripped body from column
        zero, so a citation CommonMark renders as indented code inside a
        list item (or after tab indentation) was deleted — leaving only
        the list marker, or an empty line.
        """
        assert _manager()._strip_citation_markers(text) == expected

    @pytest.mark.parametrize(
        "text",
        [
            "Values\n=====\n    [1] xs[2]",
            "Values\n-----\n    [1] xs[2]",
        ],
    )
    def test_setext_underline_ends_block_for_indented_code(self, text):
        """A setext heading underline completes the paragraph's block.

        The line after ``=====`` is genuinely indented code (the
        heading ends the paragraph), but the main block-boundary rule
        had no setext clause — only the backtick-run helper did — so
        the bracketed index expressions below the underline were
        stripped. The dashes variant already ended the block via the
        thematic-break rule.
        """
        out = _manager()._strip_citation_markers(text)

        assert out == text
        assert "<code>[1] xs[2]" in markdown(out)

    @pytest.mark.parametrize(
        "text",
        [
            "`span <!-- continues\ncrossing` text\n~~~\n[1]\n~~~",
            "`same <!-- line` text\n~~~\n[1]\n~~~",
        ],
    )
    def test_multiline_code_span_comment_cannot_mask_fence(self, text):
        """Comment masking must compute code spans over the whole text.

        The per-line computation missed a span continuing onto the next
        line, so a ``<!--`` inside it latched the comment state and
        masked the fence further down; the fenced ``[1]`` was then
        stripped as prose. A span opened and closed on one line already
        masked correctly.
        """
        out = _manager()._strip_citation_markers(text)

        assert out == text
        assert "<code>[1]" in markdown(out, extensions=["fenced_code"])


class TestAdversarialGateType7CodeAndSpecIndents:
    """Revert-catching tests for the fifth adversarial-gate round.

    ``<code>`` is a CommonMark HTML block type 7: it cannot interrupt a
    paragraph, its block ends at the first blank line, and a mid-line or
    trailing-content occurrence is inline HTML inside the paragraph.
    The stripper previously latched element state from any ``<code>``
    mention, disabling stripping (and fence recognition) for the rest
    of the answer. ``<pre>`` is type 1 and keeps its blank-spanning
    behaviour. Separately, reference-definition continuation lines may
    carry indent 0 (the old "at least one column" floor rejected the
    spec-legal indent-0 destination line, deleting the rendered link
    and mangling list-item definitions).
    """

    @pytest.mark.parametrize(
        "text,expected",
        [
            # prose mentioning the literal tag, then a fence, then prose
            (
                "Use the <code> tag\n```\nx[1]\n```\nmore [2] text",
                "Use the <code> tag\n```\nx[1]\n```\nmore text",
            ),
            # an unclosed type-7 element ends at the blank line
            ("<code>\n\nsome [1] text", "<code>\n\nsome text"),
            # balanced inline pair: the following indented line is a
            # lazy paragraph continuation, not indented code
            ("<code>x</code>\n    [1]", "<code>x</code>\n"),
        ],
    )
    def test_type7_code_element_cannot_latch_block_state(self, text, expected):
        """A ``<code>`` mention no longer freezes the rest of the answer.

        Before the fix, any line containing the tag entered element
        state that survived blank lines, so a later fence was never
        recognized and trailing citations leaked verbatim.
        """
        assert _manager()._strip_citation_markers(text) == expected

    def test_pre_element_still_spans_blank_lines(self):
        """``<pre>`` is type 1: a blank line does not end its block."""
        text = "<pre>\n\nsome [1] text"

        assert _manager()._strip_citation_markers(text) == text

    @pytest.mark.parametrize(
        "text",
        [
            # indent-0 destination line (spec-legal continuation)
            "[1]:\n/url\nlater [1] ref",
            # lazy destination line inside a list item
            "- [1]:\n /url\nlater [1] x",
        ],
    )
    def test_multiline_reference_definitions_at_spec_indents(self, text):
        """Multi-line definitions keep their rendered reference links.

        The old continuation floor rejected these lines, so the label
        never registered: the later ``[1]`` was stripped (deleting the
        rendered link) and the list-item definition line was mangled to
        its marker and colon.
        """
        out = _manager()._strip_citation_markers(text)

        assert out == text


class TestReferenceContinuationIndentsAndBlockOpeners:
    """Revert-catching tests for reference-definition continuation lines.

    A definition's destination or title line continues the definition's
    paragraph, and indented code cannot interrupt a paragraph, so
    CommonMark sets no indentation limit on that line; a lazy line with
    fewer ``>`` markers continues it too. The previous three-column cap
    was measured from column 0, so a list item's content column
    (``- [ref]:`` then four spaces or a tab), any deeper indent and lazy
    quote lines were rejected, and the literal ``[1]`` in the rendered
    destination or title was stripped. Conversely a line that opens a
    fence or ``<pre>`` element interrupts the paragraph: consuming it as
    the destination exposed the block's code to stripping.
    """

    @pytest.mark.parametrize(
        "text",
        [
            "[ref]:\n    /page/[1]/details\n\n[x][ref]",
            "[ref]:\n        /page/[1]/details\n\n[x][ref]",
            "[ref]:\n\t/page/[1]/details\n\n[x][ref]",
            "- a\n  - [ref]:\n      /page/[1]/details\n\n    [x][ref]",
            "> [ref]:\n>     /page/[1]/details\n>\n> [x][ref]",
            # lazy continuation line without the ``>`` prefix
            "> [ref]:\n    /page/[1]/details\n\n> [x][ref]",
        ],
    )
    def test_destination_line_at_any_indent_survives(self, text):
        out = _manager()._strip_citation_markers(text)

        assert out == text
        assert 'href="/page/[1]/details"' in markdown(out)

    def test_lazy_title_line_survives(self):
        text = "> [ref]: /url\n'ti [1] tle'\n\n> [x][ref]"

        out = _manager()._strip_citation_markers(text)

        assert out == text
        assert 'title="ti [1] tle"' in markdown(out)

    def test_deeper_quote_line_does_not_continue_a_definition(self):
        """A nested ``>`` interrupts the paragraph, so its text is prose."""
        text = "> [ref]:\n> > /page/[1]/details\n\n> [x][ref]"

        out = _manager()._strip_citation_markers(text)

        assert out == "> [ref]:\n> > /page//details\n\n> [x][ref]"

    @pytest.mark.parametrize(
        "text",
        [
            "[ref]:\n```\ncode [1]\n```",
            "[ref]:\n~~~\ncode [1]\n~~~",
            "[ref]:\n<pre>\ncode [1]\n</pre>",
            "- [ref]:\n  ```\n  code [1]\n  ```",
            # opener two columns past the list content column: still a
            # fence or <pre> block whose content sits at that column
            "- [ref]:\n    ```\n  code [1]\n  ```",
            "- [ref]:\n    <pre>\n  code [1]\n  </pre>",
        ],
    )
    def test_fence_or_pre_opener_never_continues_a_definition(self, text):
        out = _manager()._strip_citation_markers(text)

        assert out == text

    def test_code_element_line_still_continues_a_definition(self):
        """``<code>`` (HTML block type 7) cannot interrupt a paragraph.

        The line is the definition's destination, so the next line is
        prose and its marker strips.
        """
        text = "[ref]:\n<code>\nx [1]\n</code>"

        out = _manager()._strip_citation_markers(text)

        assert out == "[ref]:\n<code>\nx\n</code>"


class TestWhitespaceAroundLineLeadingAndTrailingRuns:
    """Only one separator flanking a stripped run is removed."""

    @pytest.mark.parametrize(
        "text,expected",
        [
            # Indentation of a list item's continuation paragraph is kept;
            # the separator after the run goes instead.
            (
                "1. First item.\n\n   [1] Second paragraph.\n2. Next",
                "1. First item.\n\n   Second paragraph.\n2. Next",
            ),
            ("a\n\t[1] b", "a\n\tb"),
            # A run at the start of a line drops the space after it rather
            # than leaving the next word indented.
            ("Line one\n[1] Line two", "Line one\nLine two"),
            ("[1] Opening line", "Opening line"),
        ],
    )
    def test_line_leading_run_keeps_indentation(self, text, expected):
        assert _manager()._strip_citation_markers(text) == expected

    @pytest.mark.parametrize(
        "text,expected",
        [
            # Keeping the two spaces would create a Markdown hard break.
            ("Text  [1]\nnext", "Text\nnext"),
            ("Text  [[1]](https://a.b/c)\nnext", "Text\nnext"),
            ("Text [1]\r\nnext", "Text\r\nnext"),
            ("x\n  [1]\ny", "x\n\ny"),
        ],
    )
    def test_line_ending_run_leaves_no_trailing_whitespace(
        self, text, expected
    ):
        out = _manager()._strip_citation_markers(text)
        assert out == expected
        assert markdown(out) == markdown(expected)


class TestStrippingFailsSafe:
    """An unexpected stripping error must not fail every later follow-up."""

    @pytest.mark.parametrize("mode", ["raw", "full"])
    def test_error_carries_text_unstripped(self, mocker, mode):
        mocker.patch(
            "local_deep_research.chat.context.strip_prior_turn_citations",
            side_effect=RuntimeError("boom"),
        )
        messages = [
            {"role": "user", "content": "q"},
            {
                "role": "assistant",
                "research_id": "r",
                "content": "Fact [1].",
            },
        ]
        past = _manager(messages, mode=mode).build_research_context("more")[
            "past_findings"
        ]
        assert "Fact [1]." in past

    def test_error_in_summary_cleanup_keeps_the_summary(self, mocker):
        from types import SimpleNamespace

        model = SimpleNamespace(
            invoke=lambda prompt: SimpleNamespace(content="Summary [1].")
        )
        mocker.patch(
            "local_deep_research.config.llm_config.get_llm", return_value=model
        )
        mocker.patch(
            "local_deep_research.chat.context.strip_prior_turn_citations",
            side_effect=RuntimeError("boom"),
        )
        messages = [
            {"role": "user", "content": "q"},
            {
                "role": "assistant",
                "research_id": "r",
                "content": "Fact [1].",
            },
        ]
        past = _manager(messages, mode="summary").build_research_context(
            "more"
        )["past_findings"]
        assert past == "Summary [1]."


class TestBareUrlGuard:
    """Only a citation INSIDE a bare URL is kept; a ``)`` closing a Markdown
    link destination, or a line break, ends the URL."""

    @pytest.mark.parametrize(
        "text,expected",
        [
            (
                "Read [the paper](https://x.org)[1].",
                "Read [the paper](https://x.org).",
            ),
            (
                "[link](http://a.com)[[1]](http://b.com) next",
                "[link](http://a.com) next",
            ),
            ("(https://a.com)[1] now", "(https://a.com) now"),
            ("Claim https://x.org/a\n[1] more", "Claim https://x.org/a\nmore"),
            ("a [[1]](https://x.org/a)\n[[2]](https://x.org/b)", "a\n"),
        ],
    )
    def test_citation_after_a_url_strips(self, text, expected):
        assert _manager()._strip_citation_markers(text) == expected

    @pytest.mark.parametrize(
        "text",
        [
            "see https://x.org/a[1] here",
            "see https://en.wikipedia.org/wiki/F_(b)[1] here",
        ],
    )
    def test_brackets_inside_a_bare_url_survive(self, text):
        assert _manager()._strip_citation_markers(text) == text

    def test_url_guard_scans_each_chunk_once(self, monkeypatch):
        """The guard used to run a ``$``-anchored search over a 4096-char
        window per candidate (quadratic per token: 16 KB took ~5 s). Bare
        URLs are now found in one pass per prose chunk, counted here in
        characters scanned."""
        from local_deep_research.chat import citation_stripping as cs

        scanned = {"chars": 0}
        real = cs._bare_url_spans

        def counted(text):
            scanned["chars"] += len(text)
            return real(text)

        monkeypatch.setattr(cs, "_bare_url_spans", counted)
        text = ("http://" * 500 + " " + "[1]," * 150 + "\n") * 4
        text += "see https://a.org/x[1] and (https://b.org)[2] `c` [3]\n" * 300
        out = _manager()._strip_citation_markers(text)
        assert "[2]" not in out and "[3]" not in out
        assert out.count("https://a.org/x[1]") == 300
        assert scanned["chars"] <= 3 * len(text)


class TestShortCollectionSlugTags:
    """``_slugify_collection`` maps "AI" -> "ai" and "X" -> "x", and the
    formatter emits ``[{slug}-{n}]`` for non-http sources, so a 1- or
    2-character slug is a real tag."""

    @pytest.mark.parametrize(
        "text,expected",
        [
            ("Alpha [ai-1] beta.", "Alpha beta."),
            ("Alpha [x-1] beta.", "Alpha beta."),
            (
                "Alpha [ai-1][[arxiv-2]](https://arxiv.org/abs/9) beta",
                "Alpha beta",
            ),
            ("Alpha [[ml-3]](https://a.org/x) beta", "Alpha beta"),
        ],
    )
    def test_short_slug_tags_strip(self, text, expected):
        assert _manager()._strip_citation_markers(text) == expected


class TestSingleBracketNumericLinksSurvive:
    """The formatter never emits a single-bracket numeric link, and the
    summarizer reads a transcript whose assistant citations are already
    stripped; ``[1998](url)`` is a year, ``[1](#step-1)`` an anchor."""

    @pytest.mark.parametrize(
        "text",
        [
            "Founded in [1998](https://en.wikipedia.org/wiki/1998).",
            "Step [1](#step-1) then",
            "Top [10](https://x.org/top10) list",
            "See [1, 2](https://x.org/a) too",
        ],
    )
    def test_numeric_label_link_survives(self, text):
        assert _manager()._strip_citation_markers(text) == text


class TestLineLeadingBibliographyEntries:
    """``[1]: ...`` at the start of a line's content is a bibliography
    entry, judged per line through container and heading markers, not by
    the marker's offset in the prose chunk."""

    @pytest.mark.parametrize(
        "text",
        [
            "Text\n[1]: x",
            "Sources\n- [1]: Smith 2020",
            "## [1]: Intro",
            "> 1. [2]: quoted entry",
            "Intro\n  * [3]: indented entry",
        ],
    )
    def test_line_leading_entry_survives(self, text):
        assert _manager()._strip_citation_markers(text) == text

    def test_mid_line_colon_marker_still_strips(self):
        out = _manager()._strip_citation_markers("Note [1]: mid-line")
        assert out == "Note: mid-line"


class TestUnspacedScripts:
    """CJK text is written without spaces, so a glued marker is a
    citation, and removing it must not insert a space."""

    @pytest.mark.parametrize(
        "text,expected",
        [
            ("東京は首都です[1]。次", "東京は首都です。次"),
            ("東京は首都です [1]。次", "東京は首都です。次"),
            ("東京[1]次", "東京次"),
            ("東京[[1]](https://a.org/x)次", "東京次"),
        ],
    )
    def test_cjk_glued_citation_strips(self, text, expected):
        assert _manager()._strip_citation_markers(text) == expected


class TestReferenceLabelsHoldNoBrackets:
    def test_citation_after_bracketed_text_strips(self):
        """``[Table 2][[1]](url)`` is not a full reference link (a reference
        label cannot contain ``[``), so the citation strips."""
        out = _manager()._strip_citation_markers(
            "Shown in [Table 2][[1]](https://a.org/x) here."
        )
        assert out == "Shown in [Table 2] here."

    def test_real_full_reference_link_survives(self):
        text = "See [text][1] ok\n\n[1]: https://a.org/x"
        assert _manager()._strip_citation_markers(text) == text


class TestSeparatorBetweenWords:
    @pytest.mark.parametrize(
        "text,expected",
        [
            ("Claim.[[1]](https://a.com)Next", "Claim. Next"),
            ("word[[1]](https://a.com)next", "word next"),
            ("x</b>[[1]](https://a.com)y", "x</b> y"),
            # Path-like and punctuation joins stay joined.
            ("/page/[[1]](https://a.com)/x", "/page//x"),
            ("Founded [[1]](https://a.com).", "Founded."),
            ("(see[[1]](https://a.com))", "(see)"),
        ],
    )
    def test_space_only_between_words(self, text, expected):
        assert _manager()._strip_citation_markers(text) == expected


class TestDoubleBracketLabelsTheFormatterEmits:
    """Every label shape ``CitationFormatter`` can put inside ``[[...]]``.

    ``_slugify_title``/``_slugify_collection`` turn "2024-01-15", "1.2.3"
    and "2023/2024" into all-digit hyphenated slugs, and the id modes
    append "-N"; destinations keep Unicode spaces (only ASCII ones are
    escaped), may be long, and may nest balanced parentheses.
    """

    @pytest.mark.parametrize(
        "text,expected",
        [
            ("Claim [[2024-01-15]](/library/document/abc).", "Claim."),
            ("Claim [[1-2-3]](/library/document/abd).", "Claim."),
            ("Claim [[2024-01-15-1]](/library/document/abc).", "Claim."),
            (
                "Text [[2023-2024-26]](https://shop.example.com/a) more",
                "Text more",
            ),
            (
                "Claim [[arxiv-1]](https://arxiv.org/abs/1)[local-12]"
                "[[2023-2024-26]](https://shop.example.com/a)[local-27].",
                "Claim.",
            ),
            ("Claim [[20]](https://example.com/a\xa0b).", "Claim."),
            ("Claim [[21]](https://example.jp/a\u3000b).", "Claim."),
            (
                "Claim [[22]](https://example.com/?q=" + "a" * 4100 + ").",
                "Claim.",
            ),
            (
                "Claim [[23]](https://example.com/((((((((((x))))))))))).",
                "Claim.",
            ),
        ],
    )
    def test_formatter_label_strips(self, text, expected):
        assert _manager()._strip_citation_markers(text) == expected

    def test_bare_numeric_range_still_survives(self):
        """Only the hyperlinked form widened: a bare ``[2020-2024]`` has no
        provenance and stays prose."""
        text = "The window is [2020-2024] and [1-2-3]."
        assert _manager()._strip_citation_markers(text) == text


class TestLenticularMarkersIgnoreWordGlue:
    """Nobody indexes with ``x【1】``, so the word-glue guard is skipped."""

    @pytest.mark.parametrize(
        "text,expected",
        [
            ("Founded in 2020【1】.", "Founded in 2020."),
            ("Paris【1, 2】 is", "Paris is"),
            ("capital【1】【2】.", "capital."),
        ],
    )
    def test_glued_lenticular_strips(self, text, expected):
        assert _manager()._strip_citation_markers(text) == expected


class TestIndexingGlueAndTradeOffs:
    def test_latex_subscript_survives(self):
        text = "$x_{[i-1]}$ and $y_{[1]}$"
        assert _manager()._strip_citation_markers(text) == text

    def test_spaced_short_slug_is_stripped_documented_trade_off(self):
        """A one-letter collection slug is a real tag (``X`` -> ``[x-1]``),
        so an UNGLUED ``[i-1]`` cannot be told apart from one and strips;
        only the glued ``dp[i-1]`` form is protected."""
        out = _manager()._strip_citation_markers(
            "compare dp [i-1] with dp[i-1]"
        )
        assert out == "compare dp with dp[i-1]"


class TestSeparatorClosingPunctuation:
    """A space replaces a glued run only between a word (or punctuation
    that ends one) and a following word."""

    @pytest.mark.parametrize(
        "text,expected",
        [
            # ``*`` / quotes count only when they close a span.
            ("**[[1]](https://a.com)Smith et al.**", "**Smith et al.**"),
            ("**bold**[[1]](https://a.com)Next", "**bold** Next"),
            (
                'He said "yes"[[1]](https://a.com)and left',
                'He said "yes" and left',
            ),
            ('"[[1]](https://a.com)Quote"', '"Quote"'),
            # ``.`` between digits is a decimal point.
            ("3.[[1]](https://a.com)5", "3.5"),
            ("Claim.[[1]](https://a.com)Next", "Claim. Next"),
            # A non-word, non-closing character before: stays joined.
            ("/page/[[1]](https://a.com)x", "/page/x"),
            # ``_`` after the run: an emphasis closer, not a word.
            ("_word[[1]](https://a.com)_ end", "_word_ end"),
            # A script written without spaces after the run: no space.
            ("Claim.[[1]](https://a.com)東京", "Claim.東京"),
            ("word[[1]](https://a.com)東京", "word東京"),
        ],
    )
    def test_separator(self, text, expected):
        assert _manager()._strip_citation_markers(text) == expected


class TestSeparatorBeforeLinkOrTag:
    """A following ``[`` (link label) or ``<`` (inline tag) renders as the
    next word, so it gets a space after a word or a closing tag."""

    @pytest.mark.parametrize(
        "text,expected",
        [
            ("word[[1]](u)[dataset](v)", "word [dataset](v)"),
            ("<b>x</b>[[1]](u)[y](z)", "<b>x</b> [y](z)"),
            (
                "<span>word</span>[[1]](u)<span>next</span>",
                "<span>word</span> <span>next</span>",
            ),
            ("word[[1]](u)<b>next</b>", "word <b>next</b>"),
            # Paths, an opening tag and unspaced scripts stay joined.
            ("/a/[[1]](u)[b](c)", "/a/[b](c)"),
            ("<span>[[1]](u)<b>x</b>", "<span><b>x</b>"),
            ("東京[[1]](u)[x](y)", "東京[x](y)"),
        ],
    )
    def test_separator_before_link_or_tag(self, text, expected):
        assert _manager()._strip_citation_markers(text) == expected


class TestParenthesesHoldingOnlyACitation:
    @pytest.mark.parametrize(
        "text,expected",
        [
            ("Claim ([[1]](https://a.com)).", "Claim."),
            ("Claim ([1][2]) next", "Claim next"),
            ("Claim ([1]) next", "Claim next"),
            # Glued to a word, the parentheses may be a call: kept.
            ("f([[1]](https://a.com)) x", "f() x"),
        ],
    )
    def test_empty_parentheses_are_removed(self, text, expected):
        assert _manager()._strip_citation_markers(text) == expected