~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(export): land bounded citations and Quarto safeguards on main (#7139)
LearningCircuitffb1107af01e
diff --git a/changelog.d/+bounded-citation-exports.bugfix.md b/changelog.d/+bounded-citation-exports.bugfix.mdnew file mode 100644index 0000000000..d0c9b56579--- /dev/null+++ b/changelog.d/+bounded-citation-exports.bugfix.md@@ -0,0 +1 @@+Keep Quarto references within the report's Sources section, emit each RIS reference ID once, and avoid excessive parsing time on long whitespace in RIS titles and authors, collection metadata, or Quarto code-cell fences, and on long runs of indented Quarto code cells.diff --git a/changelog.d/6471.security.md b/changelog.d/6471.security.mdindex 8d0105936b..c3f39bd911 100644--- a/changelog.d/6471.security.md+++ b/changelog.d/6471.security.md@@ -4,10 +4,23 @@ report and a cell that `quarto render` runs in a `.qmd`, and report bodiescarry web-influenced content, so the braces are now dropped and the code isexported as the display fence it was (#6470).-The rule follows Quarto's own splitter rather than CommonMark, because that is-what decides which fences run: a cell may be indented arbitrarily while a-display fence may not be indented at all, whitespace is allowed between the-fence and the brace, cell options are unrestricted text (backticks and `}`-included), a block closes only on an exact tick-count match, and `~~~` is not-a fence to Quarto. A plain ```` ```python ```` fence, Pandoc's `{.python}`-attribute form, and a cell tag quoted inside an open fence are all left alone.+Quarto export also no longer lets report text pull in another file or print the renderer's environment variables when the exported `.qmd` is rendered on its own (see the residual risks below), and it now turns every code-cell header in a report into a plain code fence wherever it appears: inside another code block, in a blockquote, with any whitespace or byte-order mark around the fence, or split across a line break.++The exported `.qmd` now sets `from: markdown-raw_html-raw_tex-raw_attribute-native_divs-native_spans-fenced_divs-bracketed_spans-header_attributes-link_attributes-inline_code_attributes-fenced_code_attributes-yaml_metadata_block-pandoc_title_block` in its front matter. Quarto hands this reader format to its own `.qmd` reader, which it also uses to read attribute text such as a callout title again as a document, so report text can no longer produce an attribute, a raw HTML or LaTeX block or inline, a raw `{=format}` block, a Div or Span, or Pandoc metadata. That switches off the routes by which Quarto (v1.10.18) decodes text into further shortcodes: attribute values (including a callout title or a caption read again as a document), `qmd` and `qmd-base64` attributes, the `pandoc-native`, `pandoc-json` and `pandoc-reader-*` raw formats, `\QuartoMarkdownBase64{}` in raw LaTeX, and raw HTML. This has a rendering cost. Raw HTML in a report (such as `<br>` or `<sup>`) and raw LaTeX are shown as text instead of being rendered. Attribute blocks are shown as written: `{#id .class}` after a heading, link, image or inline code, `[text]{...}` spans and `:::` divs. A code fence with an attribute block, such as ```` ```{.python} ````, is no longer a code block; Pandoc reads it as inline code in a paragraph. The bibliography note is now a bold paragraph instead of a callout, because callouts are fenced divs.++The title is not read with that reader format: Quarto passes the front matter to Pandoc as a separate metadata file, and Pandoc parses it with all of its default markdown extensions because Quarto's reader is a Lua custom reader. The exporter therefore writes the title with a backslash before every ASCII punctuation character and with runs of spaces, tabs and line breaks collapsed to one space, so Pandoc reads it as plain text: raw HTML, a raw `{=pandoc-native}` inline, a `[...]{qmd-base64=...}` span or any other markup in the title is shown as written. The rendered title shows the same characters; Markdown formatting, entities and typographic quotes or dashes in it are no longer applied.++What still decodes report text is a fixed chain: Quarto's whole-file shortcode pass, Pandoc's single decoding of entities and backslash escapes, and Quarto's internal shortcode encodings. The exporter breaks every shortcode along that chain by inserting an invisible zero-width space, in the report, its title and its bibliography note:+- the literal `{{<` and `{{%` openers, escaped forms included (such as `{{< include >}}`, `{{< env >}}` and `{{< meta >}}`), and two braces (with any backslashes between them) followed, after any whitespace or backslashes, by `<`, `%` or `&`;+- an HTML entity that Pandoc would decode to `{`, `-`, `_` or an ASCII letter or digit, and any `&#` reference other than a plain decimal or hex one of up to 8 digits;+- Quarto's two internal shortcode encodings, which a sweep of quarto-cli v1.10.18 finds to be the only ones (the `b58fc729-690b-4000-b19f-365a4093b2ff` hex marker and the `cf5733e5-0370-4aae-8689-61bad1dd9ec0` unicode escape), and the `quarto-shortcode__` class.++Any other `&` is left alone. `&`, `<` and ` ` still render, and URLs with query strings (`?q=a&hl=en`), `AT&T` and `&x` in C code come through unchanged, so Sources links keep working. Math such as `\frac{{\partial f}}` is left alone. Every HTML comment opener in report text is broken the same way. The `<!-- LDR_APPENDED_SOURCES_START -->` marker that the report generator puts before its appended Sources section is removed from the exported body instead, so it does not show as text; a copy quoted elsewhere in the report is broken like any other comment. A fourth dash is added wherever three dashes end a line after nothing but whitespace, `>`, `:`, `~` or `|` prefix characters and footnote labels such as `[^1]:`, so Quarto finds no YAML block in the body; any other text before them leaves them alone, so prose ending in ` ---` keeps its em dash and a URL ending in `---` keeps its dashes. Pandoc reads no YAML block from the body at all, including one inside a grid-table cell: Quarto removes the front matter before Pandoc reads the file and passes the metadata separately, so the reader format switches Pandoc's YAML metadata blocks off, and its `%` title blocks too. So a report can no longer pull in another file, print the renderer's environment variables, or add YAML metadata such as an engine, filters or PDF engine options. Quarto therefore picks its markdown engine for the exported file, which runs no code cells and no inline `r` or `{python}` expressions.++Residual risks:+- The protection holds for the file rendered as exported, against Quarto v1.10.18's readers as traced from source; no Quarto binary was run in testing. A future Quarto version that adds another decoder would need another look.+- The exported file is meant to be rendered on its own. Quarto appends its own markup to the page before reading it with the same reader format: in a website, blog or book project, for a revealjs presentation, or with `math:` or `keep-source` set. That markup uses fenced divs, spans and code-block attributes, so it shows as text at the end of the page, and the page and site titles and descriptions it renders are lost. No reader format can keep Quarto's markup while dropping the same syntax from the report, because both are read in one pass.+- An engine forced from outside the file, such as `-M engine:knitr`, would still evaluate inline expressions. A reader format set from outside that overrides the file's `from` would turn the switched-off readers back on.+- A few Quarto filters read text with Pandoc's own reader, all extensions on, instead of the `.qmd` reader: a `{...}` ending a table caption, `{#eq-...}` after display math, and a ```` ```quarto-title-block ```` code fence (read as title-block metadata after shortcodes have run; without a template the render fails). In v1.10.18 none of these reaches a shortcode parser, but a table caption can still put attributes on the rendered table. A code fence's language also becomes a class, which some other Quarto filters act on when rendering; none of those found expands a shortcode.++A report that quotes the cell syntax as an example now shows it without its braces but keeps the rest of the line. A quoted shortcode, HTML comment or decodable entity keeps a zero-width space inside it.diff --git a/src/local_deep_research/text_optimization/citation_formatter.py b/src/local_deep_research/text_optimization/citation_formatter.pyindex a71865cc1d..2903559b25 100644--- a/src/local_deep_research/text_optimization/citation_formatter.py+++ b/src/local_deep_research/text_optimization/citation_formatter.py@@ -4,6 +4,7 @@ import htmlimport refrom array import arrayfrom enum import Enum+from html.entities import html5from typing import Any, Dict, List, Optional, Tuplefrom urllib.parse import urlparse, urlsplit@@ -906,15 +907,9 @@ class CitationFormatter:# Sources section may carry a "Collection: <name>" line for RAG /# library hits (emitted by ``utilities/search_utilities.format_links_to_markdown``).- # The line sits between this ``[N]`` entry's ``URL:`` line and the- # next ``[N+1]`` entry. We anchor the match on a non-greedy span up- # to the next citation header (or end of string) to scope correctly.- _collection_line_pattern = re.compile(- r"^\[(\d+(?:,\s*\d+)*)\][^\n]*\n" # the [N] header line- r"(?:[^\n\[]*\n)*?" # any non-[ lines (typically URL: ...)- r"\s*Collection:\s*(.+?)\s*$",- re.MULTILINE,- )+ # Read one line at a time: overlapping multiline whitespace patterns+ # can repeatedly rescan an entire run of blank lines.+ _collection_header_pattern = re.compile(r"^\[(\d+(?:,\s*\d+)*)\]")def _parse_collections(self, sources_content: str) -> Dict[str, str]:"""Extract ``{citation_num: collection_name}`` from a sources@@ -922,13 +917,21 @@ class CitationFormatter:— the absence of collection info is the common case (web URLs)and must never raise."""collections: Dict[str, str] = {}- for match in self._collection_line_pattern.finditer(sources_content):- citation_nums_str = match.group(1)- collection = match.group(2).strip()- if not collection:+ citation_nums = ()+ for line in sources_content.split("\n"):+ if line.startswith("["):+ match = self._collection_header_pattern.match(line)+ citation_nums = (+ tuple(_iter_citation_group(match.group(1))) if match else ()+ )continue- for num in (n.strip() for n in citation_nums_str.split(",")):- collections[num] = collection+ field = line.strip()+ if citation_nums and field.startswith("Collection:"):+ collection = field[len("Collection:") :].strip()+ if collection:+ for num in citation_nums:+ collections[num] = collection+ citation_nums = ()return collectionsdef _format_source_tagged_hyperlinks(@@ -1175,69 +1178,49 @@ class CitationFormatter:return "source"-# What counts as an executable cell is decided by Quarto's own splitter, so-# this mirrors that grammar rather than CommonMark's. From quarto-cli-# ``src/core/lib/break-quarto-md.ts``:+# Whether a ``.qmd`` runs code is decided by more than one reader, and they+# disagree with each other. From quarto-cli and knitr:#-# startCodeCellRegEx ^\s*(```+)\s*\{([=A-Za-z][=A-Za-z0-9._]*)( *[ ,].*)?\}\s*$-# startCodeRegEx ^```-# endCodeRegEx ^\s*(```+)\s*$ closing on an EXACT tick match+# languagesWithClasses (src/core/pandoc/pandoc-partition.ts), which picks+# the engine, run over the WHOLE file with the /gm flags:+# /^[\t >]*```+\s*\{([a-zA-Z][a-zA-Z0-9_.]*)([^}]*)?\}\s*$/gm+# breakQuartoMd (src/core/lib/break-quarto-md.ts):+# ^\s*(```+)\s*\{([=A-Za-z][=A-Za-z0-9._]*)( *[ ,].*)?\}\s*$+# quartoMdToJupyter (src/core/jupyter/jupyter.ts), the Jupyter engine:+# "^(\\s*)(```+)\\s*\\{" + kernelspec.language.toLowerCase() ++# "( *[ ,].*)?\\}\\s*$"+# knitr's md chunk.begin (R/pattern.R):+# '^[\t >]*```+\\s*\\{([a-zA-Z0-9_]+( *[ ,].*)?)\\}\\s*$'#-# Every difference from CommonMark is one a fence can be written to exploit: a-# cell may be indented arbitrarily while a display fence may not be indented at-# all, whitespace is allowed between the fence and the brace, cell options are-# unrestricted text (backticks and ``}`` included), the closer must match the-# opener's tick count exactly, and ``~~~`` is not a fence to Quarto at all.+# They differ in fence tracking (none for languagesWithClasses and knitr,+# none that shields a cell for quartoMdToJupyter), in the prefix they allow+# (``>`` for blockquotes), in line splitting (/m treats \r, U+2028 and U+2029+# as line ends) and in the meaning of ``\s``. Modelling any one of them left+# a cell another one runs. So nothing is modelled: every one of them needs a+# run of three or more backticks, optional whitespace, ``{`` and a language+# character, and that shape is broken wherever it occurs.#-# Pandoc's attribute form carries a leading marker — ``{.python}`` (class),-# ``{#id}`` — and is excluded by the ``[=A-Za-z]`` first character, which is-# also why ``{=html}`` raw blocks are in scope: Quarto reads them as cells.-_QUARTO_CELL_FENCE = re.compile(- r"^(?P<indent>\s*)(?P<fence>`{3,})\s*"- r"\{(?P<lang>[=A-Za-z][=A-Za-z0-9._]*)(?P<rest> *[ ,].*)?\}\s*$"+# The whitespace class is the union of Python's ``\s`` (which adds+# \x1c-\x1f and \x85), JavaScript's (which adds U+FEFF) and U+180E (a space+# before Unicode 6.3). It includes every line break, so a header split+# across lines is caught too. A language character is ``=`` or anything+# Python's Unicode ``\w`` matches, a superset of the ASCII classes above and+# of a locale-dependent ``[a-zA-Z]``. ``{.class}`` and ``{#id}`` (Pandoc+# attributes, which no reader runs) are left alone.+_ANY_SPACE = r"[\s]"+_QUARTO_CELL_HEADER = re.compile(+ rf"^(?P<indent>(?:{_ANY_SPACE}|>)*)(?P<fence>`{{3,}}){_ANY_SPACE}*"+ r"\{(?P<lang>[=\w][=\w.]*)"+ rf"(?P<rest>[^=\w.}}\n\r][^}}\n\r]*)?\}}{_ANY_SPACE}*$")-_QUARTO_DISPLAY_FENCE = re.compile(r"^`{3,}")-_QUARTO_FENCE_CLOSE = re.compile(r"^\s*(?P<fence>`{3,})\s*$")---def _quarto_tick_count(line: str) -> int:- """Backticks in the first space-separated token, as Quarto counts them."""- return line.split(" ")[0].count("`")---def _defuse_quarto_cells_once(body: str) -> tuple[str, bool]:- """One pass of the cell demotion. Returns the body and whether it changed."""- out: list[str] = []- changed = False- open_ticks = 0-- for line in body.split("\n"):- if open_ticks:- # Only an exact tick match closes: a longer fence inside a shorter- # block is content to Quarto, and treating it as a closer would- # hand the rest of the block back to plain text.- closing = _QUARTO_FENCE_CLOSE.match(line)- if closing and len(closing.group("fence")) == open_ticks:- open_ticks = 0- out.append(line)- continue-- cell = _QUARTO_CELL_FENCE.match(line)- if cell:- open_ticks = len(cell.group("fence"))- out.append(- f"{cell.group('indent')}{cell.group('fence')}{cell.group('lang')}"- )- changed = True- continue-- if _QUARTO_DISPLAY_FENCE.match(line):- # Column 0 only. An indented ``` is prose to Quarto, so treating it- # as an open fence would shield a cell further down.- open_ticks = _quarto_tick_count(line)- out.append(line)-- return "\n".join(out), changed+# The backstop: an opening brace of the same shape anywhere in the text. The+# lookbehind starts a match only at the first backtick of a run, which keeps+# the scan linear on a long run of backticks.+_QUARTO_CELL_BRACE = re.compile(+ rf"(?<!`)(?P<head>`{{3,}}{_ANY_SPACE}*)\{{(?=[=\w])"+)+# Quarto's own line splitting (``lines()`` in src/core/lib/text.ts).+_QUARTO_LINE_BREAK = re.compile(r"(\r\n?|\n)")def _defuse_quarto_cells(body: str) -> str:@@ -1250,30 +1233,341 @@ def _defuse_quarto_cells(body: str) -> str:that arrives need not have been written by the user reading it.Dropping the braces keeps the code visible and stops it being a cell. A- plain ```` ```python ```` fence is display-only already and is untouched,- and so is anything inside an open fence: a cell tag quoted inside a code- block is content, not syntax.-- The pass repeats to a fixed point. Demoting an *indented* cell leaves a- line Quarto does not read as a fence at all, which returns the lines after- it to plain text — where a tag that was content a moment ago becomes a cell- in its own right. Each pass only ever removes braces, so the set of- cell-shaped lines shrinks and the loop settles; it is bounded by that count- so an unforeseen shape cannot spin.-- Front matter is deliberately not modelled. Quarto reads a ``---`` block as- raw YAML, and a mid-document ``---`` surrounded by blank lines as a- horizontal rule, so tracking it here would only ever *stop* a defusion.+ plain ```` ```python ```` fence is display-only already and is untouched.++ This fails closed. Every line shaped like a cell header is demoted, with+ any indent or ``>`` prefix, wherever it is: inside another fence, in a+ blockquote or in plain prose alike. The demotion removes only the two+ braces and the whitespace around them; the language and any options stay,+ so ```` ```{python, echo=false} ```` becomes ```` ```python, echo=false+ ````. A report that quotes the syntax as an example therefore shows it+ without its braces; that is the accepted cost. Any other occurrence of a+ fence followed by ``{`` and a language character — inside a line of+ prose, split across a line break, or with a ``}`` in its options — loses+ only that opening brace, so no text after it is dropped. Neither step+ adds or removes a backtick or a line break, so no line changes whether+ it opens a Markdown code fence.++ One regex test per line and one scan of the whole text: linear."""- passes = (- sum(1 for line in body.split("\n") if _QUARTO_CELL_FENCE.match(line))- + 1+ parts = _QUARTO_LINE_BREAK.split(body)+ for index in range(0, len(parts), 2):+ cell = _QUARTO_CELL_HEADER.match(parts[index])+ if cell:+ parts[index] = (+ f"{cell.group('indent')}{cell.group('fence')}"+ f"{cell.group('lang')}{cell.group('rest') or ''}"+ )+ return _QUARTO_CELL_BRACE.sub(r"\g<head>", "".join(parts))+++# Quarto and Pandoc read more than cells out of the text before and while+# rendering it. Two features are reachable from a report body:+#+# * Shortcodes. ``{{< env NAME >}}`` or ``{{< meta key >}}`` prints the+# renderer's environment or metadata into the output, and+# ``{{< include path >}}`` pulls in a file, cells included, before the+# engine is chosen.+# * YAML metadata blocks. src/core/yaml.ts collects every block in the file+# with /gm, after removing HTML comments (/<!--[\W\w]*?-->/gm) and fenced+# code, and merges them into the render metadata (engine, filters,+# pdf-engine-opt, ...):+# /(^)(---[ \t]*[\r\n]+(?![ \t]*[\r\n]+)[\W\w]*?[\r\n]+(?:---|\.\.\.))+# ([ \t]*)$/gm+# Pandoc's own yaml_metadata_block opens at a ``---`` line in any block+# context: after a ``>`` or list prefix, and inside a grid-table cell+# (``| --- |``), where the dashes do not end the line. Quarto removes the+# front matter before Pandoc reads the file and passes the metadata with+# ``--metadata-file`` (src/command/render/pandoc.ts in v1.10.18: the+# ``partitionYamlFrontMatter`` call at line 1146 and the push at 1351), so+# the reader format below switches that extension off and Pandoc reads no+# metadata block from the body at all.+#+# Shortcodes are the hard part, because Quarto decodes text in many places+# before it looks for them (quarto-cli v1.10.18): Pandoc entities and+# backslash escapes in attribute values, a callout title or a caption+# attribute read again as a whole document (``string_to_quarto_ast_*``),+# ``qmd``/``qmd-base64`` attributes on a Span or Div, raw blocks in the+# ``pandoc-native``, ``pandoc-json`` or ``pandoc-reader-<any reader>``+# formats, ``\QuartoMarkdownBase64{}`` in raw LaTeX, and raw HTML whose+# attributes and tables Pandoc's HTML reader parses. Breaking each+# spelling in turn has failed repeatedly, so the exported file switches+# those readers off instead. Its front matter sets+# ``from: _QUARTO_READER_FORMAT``: Pandoc's markdown without raw HTML, raw+# TeX, raw attributes, fenced or native divs and spans, attribute blocks+# on headers, links, images, code and fences, YAML metadata blocks or a+# ``%`` title block.+# Quarto passes ``from`` to its reader (``user-defined-from`` in+# src/command/render/pandoc.ts, used by readqmd.lua for the document and+# for every string read again through ``string_to_quarto_ast_*``), so the+# body yields no attribute, no raw block or inline, no Div or Span and no+# metadata, and every decoder above is unreachable. The front matter itself+# is not read with that format: Quarto passes it to Pandoc with+# ``--metadata-file`` (pandoc.ts:1351), and Pandoc parses a metadata file+# with all of its default markdown extensions whenever the reader is not+# literally ``markdown`` or ``commonmark`` (``readerOptsMeta`` in Pandoc's+# App.hs). Quarto's reader is a Lua custom reader+# (filters/qmd-reader.lua), so raw HTML, a raw ``{=pandoc-native}`` inline+# or a ``[...]{qmd-base64=...}`` span in the title would reach the+# decoders above. ``_quarto_title_markdown`` therefore escapes the title+# so that Pandoc reads it as plain text, whatever the extensions.+# The same reader format applies to the markup Quarto itself+# appends to the body before Pandoc reads it (pandoc.ts:1275-1283): the+# ``:::{#quarto-meta-markdown .hidden}`` envelope of ``[...]{.hidden ...}``+# spans in a website, blog or book project (website.ts:328-330,+# website-meta.ts:588, markdown-pipeline.ts:99-121), and the same kind of+# envelope for revealjs (format-reveal.ts:304) or a document that sets+# ``math:`` (pandoc.ts:627-659), as well as the ``keep-source`` block+# (codetools.ts:72-89). The exported file sets none of these and is meant+# to be rendered on its own. Rendered inside such a project or with those+# options, that markup shows as text at the end of the page and what it+# feeds (the rendered page and site titles and descriptions) is lost. No+# reader format can keep Quarto's markup and drop the report's: both are+# read in one pass, and the Divs and Spans that markup needs are what the+# report would use to reach the decoders above.+# What still decodes body text is one fixed chain:+#+# 1. the raw file. lpegshortcode.lua opens a shortcode at a literal+# ``{{<`` (escaped ``{{{<`` and ``{{</*``), and parse-shortcode.ts,+# which expands includes, at a literal ``{{< ``. ``wrap_lpeg_match``+# then restores ``cf5733e5-0370-4aae-8689-61bad1dd9ec0&#x<hex>;`` to+# the character it encodes, after matching but before Pandoc reads+# the text.+# 2. Pandoc, once: an entity (``&`` and non-space characters up to the+# first ``;``, looked up as ``&name;``, ``{`` or ``{``) or a+# backslash escape becomes its character, in text, link targets and+# image sources. Code, code blocks and math are not decoded.+# 3. readqmd.lua hex-decodes+# ``b58fc729-690b-4000-b19f-365a4093b2ff;<hex>;`` in text, code, math,+# code blocks, link targets and image sources and reads the result as+# a shortcode, and customnodes/shortcodes.lua runs the ``{{<`` parser+# again on code, code blocks, math, link targets and image sources.+#+# Those two UUIDs are the only shortcode encodings in quarto-cli's filters+# (a sweep of every UUID in src/resources finds the others naming ids,+# data URIs, LaTeX placeholders, the AST vault or a Confluence macro).+# A few Quarto filters still read text with Pandoc's own reader, every+# extension on: a ``{...}`` ending a table caption (common/tables.lua),+# ``{#eq-...}`` after display math (crossref/equations.lua) and a+# ```` ```quarto-title-block ```` fence (quarto-post/book.lua, after+# shortcodes have run). In v1.10.18 none of them reaches a shortcode+# parser or the ``.qmd`` reader.+# Each step is broken by+# inserting a zero-width space (U+200B), which no reader treats as+# whitespace and no decoding removes:+#+# A. ``b58fc729...`` and ``cf5733e5...`` are broken after their first+# letter, and so is ``quarto-shortcode__``, the class ast/parse.lua+# turns into a shortcode (no Span can carry it any more; this is kept+# as a second line). A letter can be spelled only as itself or as an+# entity (rule B); ``-`` and ``_`` also with backslashes before them.+# B. An ``&`` gets the space after it if Pandoc would decode it (step 2)+# to ``{``, ``-``, ``_`` or an ASCII letter or digit (the characters+# of an opener or a sentinel), or if it starts ``&#`` and anything but+# a plain decimal or hex reference of at most 8 digits up to the+# ``;``. Pandoc decodes only once, so ``&``, ``<`` or `` ``+# stay as they are, and so does every ``&`` that starts no entity: one+# that no ``;`` closes before a space, as in a URL query+# (``?q=a&hl=en``) or C code (``&x``), or one whose name is not an+# HTML5 entity.+# C. Two ``{``, with any backslashes before the second, followed after any+# whitespace or backslashes by ``<``, ``%`` or ``&`` (which may decode+# to either or to whitespace) get the space after the first. No step+# can then put ``{{`` before a ``<`` or ``%``. ``{{\partial`` in math+# is left alone.+# HTML comment openers ``<!--`` get the zero-width space between the+# dashes, so yaml.ts cannot remove a comment to join text into a new line+# start. Three dashes ending a line become four when everything before+# them on the line is whitespace and block-prefix characters (``>``,+# ``:``, ``~``, ``|``) or footnote labels (``[^1]:``): ``----`` is the+# same thematic break or setext underline to Markdown but opens no YAML+# block for Quarto's yaml.ts, which needs the dashes at the very start of+# a line. Any other text before them on the line leaves them alone, so+# prose ending in `` ---`` keeps its em dash and a URL ending in ``---``+# keeps its dashes. Pandoc reads no body metadata block with the reader+# format below, wherever the dashes are; the block prefixes are a second+# line against that. Nor does it read a ``%`` title block: Quarto starts the+# body it hands to Pandoc with a line break (``partitionYamlFrontMatter``+# in src/core/yaml.ts), which already keeps one from opening, and the+# reader format switches the extension off as well.+_QUARTO_READER_FORMAT = "markdown" + "".join(+ f"-{extension}"+ for extension in (+ "raw_html",+ "raw_tex",+ "raw_attribute",+ "native_divs",+ "native_spans",+ "fenced_divs",+ "bracketed_spans",+ "header_attributes",+ "link_attributes",+ "inline_code_attributes",+ "fenced_code_attributes",+ "yaml_metadata_block",+ "pandoc_title_block",)- for _ in range(passes):- body, changed = _defuse_quarto_cells_once(body)- if not changed:+)+_ZERO_WIDTH_SPACE = "\u200b"+_HTML_COMMENT_OPEN = re.compile(r"<!-(?=-)")+# Matched against one line at a time; group 1 is the whole prefix. Linear:+# anchored, and each prefix unit starts with a character no other unit+# starts with.+_YAML_BLOCK_DELIMITER = re.compile(+ rf"\A((?:[\s\ufeff\u180e>:~|]|\[\^[^\]]+\]:)*)---(?={_ANY_SPACE}*\Z)"+)+# Every line break any reader uses: Python's ``str.splitlines`` set, which+# includes JavaScript's /m line terminators (\n, \r, U+2028, U+2029).+_ANY_LINE_BREAK = re.compile(r"(\r\n|[\n\r\v\f\x1c-\x1e\x85\u2028\u2029])")++# Pandoc's ``characterReference``: ``&``, then ``many1Till nonspaceChar+# (char ';')`` where a space is one of these four characters.+_PANDOC_SPACE = re.compile(r"[ \t\n\r]")+_SHORTCODE_CHARACTERS = frozenset(+ "{-_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"+)+_NUMERIC_REFERENCE = re.compile(r"#(?:([0-9]{1,8})|[xX]([0-9a-fA-F]{1,8}))")+# Longer than any HTML5 entity name (31 characters) or plain numeric+# reference (``#x`` and 8 digits), so never sliced out of the text.+_LONGEST_REFERENCE = 40+_QUARTO_SHORTCODE_BRACES = re.compile(+ rf"\{{(?=\\*\{{(?:{_ANY_SPACE}|\\)*[<%&])"+)+_QUARTO_SHORTCODE_TOKENS = re.compile(+ r"(?<=b)(?=58fc729\\*-690b\\*-4000\\*-b19f\\*-365a4093b2ff)"+ r"|(?<=c)(?=f5733e5\\*-0370\\*-4aae\\*-8689\\*-61bad1dd9ec0)"+ r"|(?<=q)(?=uarto\\*-shortcode\\*_\\*_)",+ re.IGNORECASE,+)+++def _reference_is_hazardous(reference: str) -> bool:+ """True if Pandoc decodes ``&<reference>;`` to a character rule B breaks.++ *reference* is what Pandoc reads between the ``&`` and the ``;``. A+ numeric one is hazardous unless it is a plain decimal or hex number of+ a harmless character; a name is hazardous if it is an HTML5 entity for+ a character that can spell a shortcode or a sentinel. Any other name+ is no entity, so Pandoc keeps it as text.+ """+ if reference.startswith("#"):+ number = _NUMERIC_REFERENCE.fullmatch(reference)+ if number is None:+ return True+ decimal, hexadecimal = number.groups()+ code = int(decimal, 10) if decimal else int(hexadecimal, 16)+ if not 0 < code <= 0x10FFFF:+ return True+ return chr(code) in _SHORTCODE_CHARACTERS+ value = html5.get(reference + ";")+ return value is not None and bool(_SHORTCODE_CHARACTERS.intersection(value))+++def _break_entities(text: str) -> str:+ """Rule B: no entity Pandoc decodes can spell a shortcode or sentinel.++ The ``;`` and the space after each ``&`` are found by searches that+ only move forward, so the scan is linear.+ """+ pieces = []+ position = 0+ semicolon = space = -1+ start = text.find("&")+ while start != -1:+ if semicolon < start + 2:+ semicolon = text.find(";", start + 2)+ if semicolon == -1:break- return body+ if space <= start:+ found = _PANDOC_SPACE.search(text, start + 1)+ space = found.start() if found else len(text)+ if space > semicolon and (+ text[start + 1] == "#"+ if semicolon - start > _LONGEST_REFERENCE+ else _reference_is_hazardous(text[start + 1 : semicolon])+ ):+ pieces.append(text[position : start + 1])+ pieces.append(_ZERO_WIDTH_SPACE)+ position = start + 1+ start = text.find("&", start + 1)+ pieces.append(text[position:])+ return "".join(pieces)+++def _defuse_quarto_text(text: str) -> str:+ """Break every shortcode and HTML-comment opener in *text*.++ Rules A-C above, for body text read with ``_QUARTO_READER_FORMAT``.+ Used on the report title too, before ``_quarto_title_markdown``+ escapes it (the title is not read with that format): Quarto expands+ shortcodes in metadata, and a comment opened in the title could be+ closed in the body. Only zero-width spaces are inserted; removing them+ gives back *text*. Linear: a constant number of scans.+ """+ text = _break_entities(text)+ text = _HTML_COMMENT_OPEN.sub("<!-" + _ZERO_WIDTH_SPACE, text)+ text = _QUARTO_SHORTCODE_BRACES.sub("{" + _ZERO_WIDTH_SPACE, text)+ return _QUARTO_SHORTCODE_TOKENS.sub(_ZERO_WIDTH_SPACE, text)+++def _defuse_quarto_body(body: str) -> str:+ """Neutralise the cells, shortcodes and metadata blocks in a report body.++ Cells are demoted (``_defuse_quarto_cells``), shortcodes and HTML+ comments are broken (``_defuse_quarto_text``) and no line can open a+ YAML metadata block for Quarto (three dashes ending a line after+ nothing but whitespace, ``>``, ``:``, ``~``, ``|`` and footnote labels+ gain a fourth; prose ending in `` ---`` is left alone; Pandoc's own+ metadata blocks, which also open inside a grid-table cell, are+ switched off by ``_QUARTO_READER_FORMAT``). The exported file's+ metadata is then only the exporter's own front matter, which names no+ engine; no cell header is left and no file can be included, so+ Quarto's engine detection finds no language and picks its markdown+ engine, which runs no code, inline `` `r ...` `` and+ `` `{python} ...` `` expressions included. That holds for the file+ rendered on its own: an engine forced from outside it (a project+ ``_quarto.yml``, ``quarto render -M engine:knitr`` or ``knitr::knit``)+ would still evaluate those inline expressions, and a reader format+ that overrides the file's ``from`` from outside would turn the readers+ listed above back on.++ The steps only insert characters, or remove a cell's opening brace or a+ cell header's braces and the whitespace around them. None of that can+ create an opener another step breaks, so the result is a fixed point.+ Linear: a constant number of scans.+ """+ body = _defuse_quarto_cells(_defuse_quarto_text(body))+ parts = _ANY_LINE_BREAK.split(body)+ for index in range(0, len(parts), 2):+ parts[index] = _YAML_BLOCK_DELIMITER.sub(r"\1----", parts[index])+ return "".join(parts)+++# Every ASCII punctuation character. Pandoc's markdown reads a backslash+# before any of them as that character (``all_symbols_escapable``).+_ASCII_PUNCTUATION = re.compile(r"([!-/:-@\[-`{-~])")+# Runs of what Pandoc's markdown reader treats as spaces and line endings.+_PANDOC_SPACE_RUN = re.compile(r"[ \t\n\r]+")+++def _quarto_title_markdown(title: str) -> str:+ """The Markdown source for *title* in the exported front matter.++ Pandoc reads the front matter with all of its default markdown+ extensions, not with ``_QUARTO_READER_FORMAT`` (see the comment above+ it), so the title gets its own treatment. Runs of spaces, tabs and+ line breaks become one space and the ends are trimmed, so no line can+ start a block such as an indented code block; shortcodes and comment+ openers are broken (``_defuse_quarto_text``); and a backslash goes+ before every ASCII punctuation character. Pandoc then reads the title+ as ``Str`` and ``Space`` nodes only: no raw HTML or raw ``{=format}``+ inline, no span or attribute, no markup, entity, math or citation.+ The title renders as the same characters, with its whitespace+ collapsed; Markdown formatting, entities and typographic quotes or+ dashes in it are shown as written. Linear.+ """+ title = _PANDOC_SPACE_RUN.sub(" ", title).strip(" ")+ return _ASCII_PUNCTUATION.sub(r"\\\1", _defuse_quarto_text(title))# Characters that must be escaped inside a YAML double-quoted scalar: the@@ -1345,9 +1639,10 @@ class QuartoExporter:current_date = datetime.now(UTC).strftime("%Y-%m-%d")yaml_header = f"""----title: {_yaml_double_quote(title)}+title: {_yaml_double_quote(_quarto_title_markdown(title))}author: "Local Deep Research"date: "{current_date}"+from: {_QUARTO_READER_FORMAT}format:html:toc: true@@ -1387,27 +1682,56 @@ csl: apa.cslreplace_citation, processed_content)- # Generate bibliography file content- bib_content = self._generate_bibliography(content)+ # The report generator's sources sentinel is an HTML comment, which+ # the reader format would show as text (raw HTML is off) and+ # _defuse_quarto_body would break. Drop the one the bibliography is+ # scoped by (the last one on its own line); a quoted one elsewhere+ # is report text and is defused like any other comment.+ sentinel_start, on_sentinel = find_sources_section(processed_content)+ if on_sentinel:+ processed_content = (+ processed_content[:sentinel_start]+ + processed_content[+ sentinel_start + len(LDR_APPENDED_SOURCES_SENTINEL) :+ ]+ )++ # Generate bibliography file content. It is shown in a code block,+ # which Pandoc does not decode, but readqmd.lua hex-decodes the+ # internal shortcode encodings in CodeBlock text too and+ # shortcodes.lua then expands the result, so a source title or URL+ # carrying one is broken as in the body. Its braces are already+ # escaped (``_escape_bibtex``) or rejected (``_safe_bibtex_url``).+ bib_content = _QUARTO_SHORTCODE_TOKENS.sub(+ _ZERO_WIDTH_SPACE, self._generate_bibliography(content)+ )- # Add note about bibliography file+ # Add note about bibliography file. It is a plain paragraph: the+ # reader format turns fenced divs off, so a callout would show as+ # text.bibliography_note = (- "\n\n::: {.callout-note}\n## Bibliography File Required\n\nThis document requires a `references.bib` file in the same directory with the following content:\n\n```bibtex\n"+ "\n\n**Bibliography File Required**\n\nThis document requires a `references.bib` file in the same directory with the following content:\n\n```bibtex\n"+ bib_content- + "\n```\n:::\n"+ + "\n```\n")- # The callout and its bibtex fence below are the exporter's own- # markup, so only the report body is defused.+ # The note and its bibtex fence are the exporter's own markup, so+ # of the note only the bibliography entries are defused (above).return (yaml_header- + _defuse_quarto_cells(processed_content)+ + _defuse_quarto_body(processed_content)+ bibliography_note)def _generate_bibliography(self, content: str) -> str:"""Generate BibTeX bibliography from sources."""- entries = _collect_bibliography_entries(content)+ sources_start, _on_sentinel = find_sources_section(content)+ # Keep accepting bare source lists for programmatic callers. A full+ # report's explicit Sources boundary takes precedence over its body.+ sources_content = (+ content[sources_start:] if sources_start != -1 else content+ )+ entries = _collect_bibliography_entries(sources_content)bibliography = ""for citation_num in sorted(entries, key=_sort_key):@@ -1428,6 +1752,37 @@ csl: apa.cslreturn bibliography.strip()+# Metadata clauses cut from a RIS title, applied in this order. Each one+# starts at its keyword: a leading ``\s*`` would retry from every position+# of a whitespace run before failing, which is quadratic in the run length.+# ``_cut_title_clause`` removes the whitespace before the keyword instead.+_RIS_TITLE_CLAUSES = (+ re.compile(r"DOI:\s*[^\s]+", re.IGNORECASE),+ re.compile(r"Published in.*", re.IGNORECASE),+ re.compile(r"Volume.*", re.IGNORECASE),+ re.compile(r"Pages.*", re.IGNORECASE),+)+++def _cut_title_clause(clause: re.Pattern, text: str) -> str:+ r"""Remove every *clause* match together with the whitespace before it.++ Gives the same result as ``re.sub(r"\s*" + clause.pattern, "", text)``+ in linear time. ``rstrip()`` and ``\s`` treat the same characters as+ whitespace. The strip stops at the end of the previous match, which is+ where the leading ``\s*`` of the next match could start at the earliest.+ """+ pieces = []+ position = 0+ for match in clause.finditer(text):+ pieces.append(text[position : match.start()].rstrip())+ position = match.end()+ if not pieces:+ return text+ pieces.append(text[position:])+ return "".join(pieces)++class RISExporter:"""Export references to RIS format for reference managers like Zotero."""@@ -1477,8 +1832,7 @@ class RISExporter:sources_content = sources_content[:sources_end]# Parse sources and generate RIS entries- ris_entries = []- seen_refs = set() # Track which references we've already processed+ ris_entries = {}# Split sources into individual entriesimport re@@ -1526,9 +1880,7 @@ class RISExporter:citation_group = match.group(1)entry_text = match.group(2).strip()- # Extract the title (first line)lines = entry_text.split("\n")- title = lines[0].strip()# Extract URL, DOI, and other metadata from subsequent linesurl = ""@@ -1557,19 +1909,15 @@ class RISExporter:# the group text: a report repeats its Sources block, and the same# source may be written ``[1]`` in one block and ``[1, 3]`` in# another, so keying on the raw group would let ``ref1`` be emitted- # twice. ``metadata`` is shared across the indices of one line;- # ``_create_ris_entry`` only reads it.+ # twice. Later definitions replace earlier ones, as they do in+ # the inline citation map. ``metadata`` is shared across the+ # indices of one line; ``_create_ris_entry`` only reads it.for citation_num in _iter_citation_group(citation_group):- ref_key = (citation_num, title, url)- if ref_key not in seen_refs:- seen_refs.add(ref_key)- # Create RIS entry with full text for metadata extraction- ris_entry = self._create_ris_entry(- citation_num, full_text, url, metadata- )- ris_entries.append(ris_entry)+ ris_entries[citation_num] = self._create_ris_entry(+ citation_num, full_text, url, metadata+ )- return "\n".join(ris_entries)+ return "\n".join(ris_entries.values())def _create_ris_entry(self,@@ -1606,8 +1954,10 @@ class RISExporter:authors = []if authors_match:authors_text = authors_match.group(1)- # Split by 'and' or ','- author_parts = re.split(r"\s*(?:,|\sand\s|&)\s*", authors_text)+ # Split at delimiters only, then trim each author. Consuming+ # optional whitespace before a delimiter makes a long run with+ # no delimiter quadratic; lookarounds keep "and" word-scoped.+ author_parts = re.split(r",|(?<=\s)and(?=\s)|&", authors_text)authors = [a.strip() for a in author_parts if a.strip()]# Extract DOI from metadata or text@@ -1626,18 +1976,8 @@ class RISExporter:if authors_match.end() < len(title)else title[: authors_match.start()])- clean_title = re.sub(- r"\s*DOI:\s*[^\s]+", "", clean_title, flags=re.IGNORECASE- )- clean_title = re.sub(- r"\s*Published in.*", "", clean_title, flags=re.IGNORECASE- )- clean_title = re.sub(- r"\s*Volume.*", "", clean_title, flags=re.IGNORECASE- )- clean_title = re.sub(- r"\s*Pages.*", "", clean_title, flags=re.IGNORECASE- )+ for clause in _RIS_TITLE_CLAUSES:+ clean_title = _cut_title_clause(clause, clean_title)clean_title = clean_title.strip()# TY - Type of reference (ELEC for electronic source/website)diff --git a/tests/text_optimization/test_citation_formatter_contracts.py b/tests/text_optimization/test_citation_formatter_contracts.pyindex cc9345fe86..85865f40b3 100644--- a/tests/text_optimization/test_citation_formatter_contracts.py+++ b/tests/text_optimization/test_citation_formatter_contracts.py@@ -23,7 +23,11 @@ defect in its ``reason``."""import html+import html.entities+import json+import randomimport re+import subprocessimport timeimport pytest@@ -34,6 +38,8 @@ from local_deep_research.text_optimization.citation_formatter import (LaTeXExporter,QuartoExporter,RISExporter,+ _defuse_quarto_body,+ _defuse_quarto_cells,)ALL_MODES = list(CitationMode)@@ -85,7 +91,7 @@ def bibliography_of_latex(latex: str) -> str:def bibtex_of_quarto(quarto: str) -> str:start = quarto.index("```bibtex")- return quarto[start : quarto.index("\n```\n:::")]+ return quarto[start : quarto.rindex("\n```\n")]class TestCitationIdentity:@@ -873,36 +879,11 @@ class TestBibliographySelection:assert "\\bibitem[1]{1} Real Local Document." in bibassert "evil.example" not in bib- @pytest.mark.xfail(- strict=True,- reason=(- "SECURITY/CORRECTNESS DEFECT: QuartoExporter._generate_"- "bibliography runs _collect_bibliography_entries over the "- "WHOLE document instead of the Sources section (LaTeX slices "- "first, Quarto does not). Combined with that helper's "- "'a URL-bearing entry never loses to a URL-less one' rule, a "- "Sources-shaped line in the answer body takes citation key "- "ref1 away from the real, URL-less source. The exported .bib "- "then points ref1 at a different source than the report body "- "does - a citation naming the wrong source."- ),- )def test_quarto_bibliography_is_not_poisoned_by_body_prose(self):bib = bibtex_of_quarto(QuartoExporter().export_to_quarto(self.POISONED))assert "evil.example" not in bibassert "Real Local Document" in bib- @pytest.mark.xfail(- strict=True,- reason=(- "DEFECT: RISExporter.seen_refs is keyed on "- "(index, title, url), so a Sources block that lists index [1] "- "twice with different titles emits two records both carrying "- "'ID - ref1'. A reference manager importing the file gets "- "two entries claiming the same citation key and resolves [1] "- "to whichever it kept."- ),- )def test_ris_emits_at_most_one_record_per_reference_id(self):document = make_doc("See [1].",@@ -911,15 +892,95 @@ class TestBibliographySelection:)ris = RISExporter().export_to_ris(document)assert ris.count("ID - ref1") == 1+ assert "TI - Second Title\n" in ris+ assert "UR - https://second.example\n" in ris+ assert "first.example" not in ris++ def test_quarto_uses_the_appended_sources_boundary(self):+ from local_deep_research.text_optimization.citation_formatter import (+ LDR_APPENDED_SOURCES_SENTINEL,+ )++ content = (+ "## Sources\n[1] Earlier prose\nURL: https://wrong.example\n\n"+ f"{LDR_APPENDED_SOURCES_SENTINEL}\n"+ "## Sources\n[1] Real Local Document\n"+ )+ bib = QuartoExporter()._generate_bibliography(content)+ assert "Real Local Document" in bib+ assert "wrong.example" not in bib++ @staticmethod+ def _full_report():+ """A report as ``_format_final_report`` assembles it, with the+ marker also quoted inline in the LLM's prose."""+ from local_deep_research.text_optimization.citation_formatter import (+ LDR_APPENDED_SOURCES_SENTINEL,+ )++ prose = (+ "# Research Report\n\n"+ "Body text citing [1]. The tool marks sources with "+ f"{LDR_APPENDED_SOURCES_SENTINEL} internally.\n\n"+ "[1] Attacker Controlled Entry\n"+ "URL: https://evil.example/poison"+ )+ return (+ prose+ + f"\n\n{LDR_APPENDED_SOURCES_SENTINEL}\n\n"+ + "## Sources\n\n[1] Real Local Document\n"+ + "URL: https://real.example/doc\n"+ )++ @staticmethod+ def _quarto_body(qmd):+ front_end = qmd.index("\n---\n\n", 3) + len("\n---\n\n")+ note = qmd.rindex("\n\n**Bibliography File Required**")+ return qmd[:front_end], qmd[front_end:note]++ def test_quarto_drops_the_appended_sources_sentinel(self):+ """The trusted sentinel line is the generator's markup, not report+ text: it is removed rather than defused into visible text, while+ the bibliography is still scoped by it and a copy quoted in the+ prose is still broken like any other comment."""+ qmd = QuartoExporter().export_to_quarto(self._full_report())+ _front, body = self._quarto_body(qmd)+ assert body.count("LDR_APPENDED_SOURCES_START") == 1, body+ assert "internally" in body.split("LDR_APPENDED_SOURCES_START")[1]+ assert "<!--" not in body+ assert "\n\n## Sources\n\n[@ref1] Real Local Document" in body+ bib = bibtex_of_quarto(qmd)+ assert "Real Local Document" in bib+ assert "evil.example" not in bib++ def test_pandoc_shows_no_sentinel_text_in_the_quarto_body(self):+ """Read the exported body with the file's own ``from`` (raw HTML+ off), as Quarto does: no paragraph is left holding the sentinel."""+ pypandoc = pytest.importorskip("pypandoc")+ front, body = self._quarto_body(+ QuartoExporter().export_to_quarto(self._full_report())+ )+ line = next(x for x in front.splitlines() if x.startswith("from:"))+ reader = line[len("from:") :].strip()+ document = json.loads(+ pypandoc.convert_text(body, "json", format=reader)+ )+ holding = [+ block+ for block in document["blocks"]+ if "LDR_APPENDED_SOURCES_START" in json.dumps(block)+ ]+ # Only the copy quoted in the prose, inside its own sentence.+ assert len(holding) == 1, holding+ assert "internally" in json.dumps(holding[0])class TestRegexBounds:"""Hostile input must not drive a pattern super-linear.- Inputs are deliberately small (10-25 KB) and every measurement is- bounded by construction: the patterns below are quadratic, not- exponential, so the worst case at these sizes is a couple of seconds- even on a slow machine. Nothing here can hang the suite.+ Inputs are deliberately small (10-40 KB). The formerly quadratic+ parsers take seconds at these sizes, while a linear implementation+ stays comfortably within the bounds below."""def test_pathological_bracket_input_stays_fast(self):@@ -941,19 +1002,6 @@ class TestRegexBounds:elapsed = time.perf_counter() - startedassert elapsed < 2.0, f"input {chunk[:24]!r}... took {elapsed:.2f}s"- @pytest.mark.xfail(- strict=True,- reason=(- "DoS DEFECT: RISExporter._create_ris_entry splits authors on "- r"r'\s*(?:,|\sand\s|&)\s*'. The leading \s* and the \sand\s "- "alternative overlap, so on a whitespace run the split is "- "quadratic: measured 108ms at 2.5k spaces, 390ms at 5k, "- "1.6s at 10k, and the curve keeps going (~64s at 64k). The "- "run reaches the pattern through any source title of the "- "form 'X by A<spaces>B.', and titles come from untrusted "- "search-result metadata."- ),- )def test_ris_author_split_is_not_quadratic_in_whitespace(self):run = " " * 10000sources_block = (@@ -969,18 +1017,1104 @@ class TestRegexBounds:f"author split took {elapsed:.2f}s on a 10KB whitespace run")- @pytest.mark.xfail(- strict=True,- reason=(- "DoS DEFECT: CitationFormatter._collection_line_pattern pairs "- r"a lazy '(?:[^\n\[]*\n)*?' loop with a following '\s*' that "- "also matches newlines. On a Sources block padded with blank "- "lines the two overlap and the scan is quadratic: measured "- "47ms at 6k blank lines, 188ms at 12k, 715ms at 24k. Only "- "reached in SOURCE_TAGGED_HYPERLINKS mode, which calls "- "_parse_collections on the Sources section."- ),+ @pytest.mark.parametrize(+ "title",+ [+ # The run sits outside any "by ..." span, so the author cut+ # does not remove it before the title-clause cleanup runs.+ "A{run}B",+ "A{run}B by C.",+ "A.{run}B",+ "A{run}\t{run}B",+ "A{run}DOI",+ "A{run}Published i",+ "A{run}Volum",+ "A{run}Page",+ "A{run}Volume 3",+ "A{run}Pages 4",+ ],+ ids=[+ "plain",+ "before-by",+ "after-period",+ "tabs",+ "near-doi",+ "near-published",+ "near-volume",+ "near-pages",+ "volume",+ "pages",+ ],+ )+ def test_ris_title_cleanup_is_not_quadratic_in_whitespace(self, title):+ run = " " * 20000+ sources_block = (+ "## Sources\n\n[1] "+ + title.format(run=run)+ + "\nURL: https://x.example/p\n"+ )+ started = time.process_time()+ RISExporter().export_to_ris(sources_block)+ elapsed = time.process_time() - started+ # Linear cleanup takes a few milliseconds here. Each of the four+ # former ``\s*``-led substitutions took about 2s at 20k.+ assert elapsed < 0.25, (+ f"title cleanup took {elapsed:.2f}s on a 20KB whitespace run"+ )++ @pytest.mark.parametrize(+ ("title", "expected"),+ [+ ("Deep Learning DOI: 10.1/x Tail", "Deep Learning Tail"),+ ("Deep Learning Published in Nature", "Deep Learning"),+ ("Audio \t Volume 3 Pages 1-9", "Audio"),+ ("Title doi:10.1/a DOI:10.2/b end", "Title end"),+ ("Mixed DOI:10.1/a", "Mixed"),+ ("Plain Title", "Plain Title"),+ ],+ )+ def test_ris_title_cleanup_output(self, title, expected):+ """Control: the linear cleanup cuts what the old regexes cut."""+ entry = RISExporter()._create_ris_entry("1", title)+ assert f"TI - {expected}" in entry.splitlines()++ @pytest.mark.parametrize(+ "line",+ ["```{rRUN", "```{rRUNx", " ````{pythonRUN, echo"],+ ids=["run-to-end", "run-then-text", "indented-options"],+ )+ def test_quarto_cell_fence_scan_is_not_quadratic_in_spaces(self, line):+ body = "# Report\n\n" + line.replace("RUN", " " * 10000) + "\n\nText.\n"+ started = time.process_time()+ QuartoExporter().export_to_quarto(body, "Report")+ elapsed = time.process_time() - started+ # The former `` *[ ,].*`` options group took 2.5-3.5s here.+ assert elapsed < 0.25, (+ f"cell-fence scan took {elapsed:.2f}s on a 10KB run of spaces"+ )++ def test_quarto_cell_fence_with_spaced_options_is_still_defused(self):+ """Control: an options group led by several spaces still matches."""+ body = "# Report\n\n```{python , echo=false}\nprint(1)\n```\n"+ output = QuartoExporter().export_to_quarto(body, "Report")+ assert "```{python" not in output+ assert "```python" in output++ @pytest.mark.parametrize(+ "unit",+ [" ```{a}\n", "\t````{r, echo=false}\n", " ```{python}\ncode\n"],+ ids=["indented-cells", "tab-indented-options", "indented-with-code"],+ )+ def test_quarto_cell_defusion_is_not_quadratic_in_indented_cells(+ self, unit+ ):+ # Each demoted indented cell stops shielding the line after it, so+ # the former re-read-until-stable loop needed one full pass per+ # cell: 8000 cells took 20-50s.+ body = "# Report\n\n" + unit * 8000 + "\nText.\n"+ started = time.process_time()+ output = QuartoExporter().export_to_quarto(body, "Report")+ elapsed = time.process_time() - started+ assert "{a}" not in output+ assert "{r" not in output+ assert "{python" not in output+ assert elapsed < 1.0, (+ f"cell defusion took {elapsed:.2f}s on 8000 indented cells"+ )++ @pytest.mark.parametrize(+ ("body", "expected"),+ [+ # A demoted indented cell is prose, so the next tag is live.+ (" ```{r}\n```{python}\nx\n```", " ```r\n```python\nx\n```"),+ # Fence state is not modelled: a cell inside a cell is demoted.+ ("```{r}\n```{python}\n```", "```r\n```python\n```"),+ (+ " ```{r}\n````\n```\n```{python}\n````\n```",+ " ```r\n````\n```\n```python\n````\n```",+ ),+ # Quoted as an example inside a longer fence: demoted as well.+ # Quarto's engine detection and knitr do not track display+ # fences, and the Jupyter engine's reader lets a cell open+ # inside one, so a quoted header is live to them.+ ("````\n```{r}\n````\n", "````\n```r\n````\n"),+ (+ "````markdown\n```{r}\nsummary(cars)\n```\n````",+ "````markdown\n```r\nsummary(cars)\n```\n````",+ ),+ (+ "```\n```{python}\nimport os; os.system('id')\n```\n```",+ "```\n```python\nimport os; os.system('id')\n```\n```",+ ),+ (+ "```\n ```{python}\nprint(1)\n ```\n```",+ "```\n ```python\nprint(1)\n ```\n```",+ ),+ # knitr and engine detection accept a ``>`` blockquote prefix.+ (+ "> ```{r}\n> system('id')\n> ```",+ "> ```r\n> system('id')\n> ```",+ ),+ (">> \t```{r, echo=FALSE}\n", ">> \t```r, echo=FALSE\n"),+ # A bare \r ending a prose line is a break to Quarto but not+ # one every reader shares; demoting regardless covers both.+ (+ "Some prose.\r```\n```{python}\nimport os\n```\n",+ "Some prose.\r```\n```python\nimport os\n```\n",+ ),+ # Engine detection's ``\s*`` and ``[^}]*`` span line breaks, so+ # a header split across lines is broken at its brace.+ ("```\r{python}\nimport os\n```", "```\rpython}\nimport os\n```"),+ (+ "```\n{r}\n```\n`r system('id')`",+ "```\nr}\n```\n`r system('id')`",+ ),+ ("x ```{r} y", "x ```r} y"),+ # Inside prose, too.+ ("use ```{r}``` here", "use ```r}``` here"),+ ],+ ids=[+ "unshielded",+ "cell-in-cell",+ "demoted-once-stays",+ "quoted-in-four-ticks",+ "verbatim-rmd",+ "python-in-display-fence",+ "indented-in-display-fence",+ "blockquote",+ "nested-blockquote",+ "lone-cr-prose",+ "lone-cr-split-header",+ "newline-split-header",+ "u2028-split-header",+ "mid-line",+ ],+ )+ def test_quarto_cell_defusion_ignores_fence_state(self, body, expected):+ assert _defuse_quarto_cells(body) == expected++ @pytest.mark.parametrize(+ ("body", "expected"),+ [+ ("```{python}\nx\n```", "```python\nx\n```"),+ ("```{python}\nx\n```", "```python\nx\n```"),+ ("```{python}\nx\n```", "```python\nx\n```"),+ (+ "```\n\x1c```\n```\n```{r}\nx\n```",+ "```\n\x1c```\n```\n```r\nx\n```",+ ),+ (+ "```\n```\x85\n```\n```{r}\nx\n```",+ "```\n```\x85\n```\n```r\nx\n```",+ ),+ ("x\r```{python}\nx\n```", "x\r```python\nx\n```"),+ ("```\r```\r```{r}\r\nx\r\n```", "```\r```\r```r\r\nx\r\n```"),+ ],+ ids=[+ "bom-before-brace",+ "bom-indent",+ "bom-trailing",+ "x1c-line",+ "x85-line",+ "lone-cr-line",+ "lone-cr-closer",+ ],+ )+ def test_quarto_cell_defusion_reads_any_whitespace_and_line_break(+ self, body, expected+ ):+ assert _defuse_quarto_cells(body) == expected++ @pytest.mark.parametrize(+ "body",+ ["```{.python}\nx\n```", "```{#id}\nx\n```", "```{{python}}\nx\n```"],+ ids=["pandoc-class", "pandoc-id", "escaped-cell"],)+ def test_quarto_defusion_leaves_non_cells_alone(self, body):+ """Control: no reader runs these, so they stay as written."""+ assert _defuse_quarto_cells(body) == body++ def test_quarto_cell_whitespace_is_every_readers(self):+ """The whitespace class is Python's ``\\s`` plus JavaScript's.++ JavaScript's ``\\s`` (ECMAScript WhiteSpace and LineTerminator) adds+ U+FEFF to Python's, Python's adds \\x1c-\\x1f and \\x85, and U+180E+ was a space before Unicode 6.3. A character either reader skips must+ not shield a header in any of the three positions.+ """+ spaces = {+ *(chr(c) for c in range(0x10000) if chr(c).isspace()),+ "",+ "",+ }+ for char in sorted(spaces):+ for body in (+ f"{char}```{char}{{r}}{char}\nx\n```",+ f"```{char}{{r}}\nx\n```",+ f"{char}```{{r, echo=FALSE}}{char}",+ ):+ assert "{r" not in _defuse_quarto_cells(body), hex(ord(char))++ def test_quarto_defusion_output_matches_no_reader(self):+ """Fuzz: no reader that decides execution sees a cell header.++ The regexes are the upstream ones, transcribed with ``\\s`` widened+ to the union above and every line splitting a reader could use:++ * quarto-cli ``languagesWithClasses`` (pandoc-partition.ts), /gm over+ the whole text: ``^[\\t >]*```+\\s*\\{([a-zA-Z][a-zA-Z0-9_.]*)``+ ``([^}]*)?\\}\\s*$``+ * quarto-cli ``breakQuartoMd`` (break-quarto-md.ts):+ ``^\\s*(```+)\\s*\\{([=A-Za-z][=A-Za-z0-9._]*)( *[ ,].*)?\\}\\s*$``+ * quarto-cli ``quartoMdToJupyter`` (jupyter.ts):+ ``^(\\s*)(```+)\\s*\\{<language>( *[ ,].*)?\\}\\s*$``+ * knitr md ``chunk.begin`` (R/pattern.R):+ ``^[\\t >]*```+\\s*\\{([a-zA-Z0-9_]+( *[ ,].*)?)\\}\\s*$``+ """+ space = r"[\s]"+ ends = "\n\r "+ engine_detection = re.compile(+ rf"(?:^|(?<=[{ends}]))[\t >]*`{{3,}}{space}*"+ rf"\{{[a-zA-Z][a-zA-Z0-9_.]*[^}}]*\}}{space}*(?=$|[{ends}])"+ )+ line_readers = [+ re.compile(+ rf"^{space}*`{{3,}}{space}*\{{[=A-Za-z][=A-Za-z0-9._]*"+ rf"( *[ ,].*)?\}}{space}*$"+ ),+ re.compile(+ rf"^{space}*`{{3,}}{space}*\{{[a-z0-9_]+( *[ ,].*)?\}}{space}*$",+ re.IGNORECASE,+ ),+ re.compile(+ rf"^[\t >]*`{{3,}}{space}*\{{[a-zA-Z0-9_]+( *[ ,].*)?\}}"+ rf"{space}*$"+ ),+ ]+ splits = [r"\r\n?|\n", r"\r?\n", r"\n", "\r\n|[\n\r \x85]"]++ def live(text):+ if engine_detection.search(text):+ return True+ return any(+ reader.match(line)+ for split in splits+ for line in re.split(split, text)+ for reader in line_readers+ )++ rng = random.Random(6982)+ spacing = ["", " ", "\t", "", "\x1c", "\x85", " "]+ spacing += ["\xa0", "", "> ", "\r", "\n"]+ langs = ["r", "python", "=html", ".r", "R", "r-x", "1r", "é", "ojs"]+ rests = ["", " echo=FALSE", ', x="`}`"', "}", " ", "x"]+ lines = ["```", "````", " ```", "```python", "~~~", "---", "text"]+ lines += ["", "`r x`", "```{{python}}", "```{.python}", "{r}"]+ breaks = ["\n", "\n", "\r\n", "\r", " "]+ for _ in range(3000):+ body = ""+ for _ in range(rng.randint(0, 20)):+ if rng.random() < 0.55:+ line = (+ f"{rng.choice(spacing)}{'`' * rng.choice([3, 4])}"+ f"{rng.choice(spacing)}{{{rng.choice(langs)}"+ f"{rng.choice(rests)}}}{rng.choice(spacing)}"+ )+ else:+ line = rng.choice(lines)+ body += line + rng.choice(breaks)+ output = _defuse_quarto_cells(body)+ assert not live(output), repr(body)+ assert _defuse_quarto_cells(output) == output, repr(body)++ @pytest.mark.parametrize(+ ("body", "expected"),+ [+ # Prose that starts with a fence and ends in ``}`` is no header+ # to any reader. Only the opening brace goes; the text stays.+ (+ "```{r}``` chunks run R, see {Figure 1}",+ "```r}``` chunks run R, see {Figure 1}",+ ),+ (+ "```{python}: Quarto cell syntax {docs}",+ "```python}: Quarto cell syntax {docs}",+ ),+ # A real header keeps its options; only the braces go.+ (+ "```{python, echo=false}\nx\n```",+ "```python, echo=false\nx\n```",+ ),+ ("```{r, x='}'}\nx\n```", "```r, x='}'}\nx\n```"),+ ],+ ids=["prose-code-span", "prose-colon", "options", "brace-in-options"],+ )+ def test_quarto_cell_demotion_drops_no_text(self, body, expected):+ assert _defuse_quarto_cells(body) == expected++ @staticmethod+ def _qmd_body(body, title="Report"):+ qmd = QuartoExporter().export_to_quarto(body, title)+ front_end = qmd.index("\n---\n\n", 3) + len("\n---\n\n")+ note = qmd.rindex("\n\n**Bibliography File Required**")+ return qmd[:front_end], qmd[front_end:note]++ @pytest.mark.parametrize(+ "body",+ [+ "{{< include ../../../usr/lib/R/x/skeleton.Rmd >}}\n`r system('id')`",+ "Key: {{< env OPENAI_API_KEY >}}",+ "{{< meta title >}} and {{<meta x>}}",+ "{{% env OPENAI_API_KEY %}}",+ "{{ < env OPENAI_API_KEY >}}",+ "{{{< env OPENAI_API_KEY >}}}",+ "{{</* include x.qmd */>}}",+ "```\n{{< include x.qmd >}}\n```",+ ],+ ids=[+ "include",+ "env",+ "meta",+ "percent",+ "spaced",+ "escaped",+ "comment-escaped",+ "in-code-block",+ ],+ )+ def test_quarto_shortcodes_in_the_body_are_broken(self, body):+ """quarto-cli opens a shortcode at ``{{<`` (lpegshortcode.lua) and+ expands includes before it picks the engine, so an include can bring+ in a file with cells and ``env`` prints the renderer's secrets."""+ _front, rendered = self._qmd_body(body)+ assert re.search(r"\{\s*\{\s*[<%]", rendered) is None, rendered+ # The text stays readable: only a zero-width space was inserted.+ assert rendered.replace("", "") == body++ def test_quarto_shortcode_in_the_title_is_broken(self):+ """Quarto expands shortcodes in metadata, the title included."""+ front, _body = self._qmd_body(+ "Body.", title="{{< env OPENAI_API_KEY >}}"+ )+ assert "{{<" not in front+ line = next(x for x in front.splitlines() if x.startswith("title"))+ value = line[len('title: "') : -1].replace("\\\\", "\\")+ assert self._pandoc_decode(value) == "{{< env OPENAI_API_KEY >}}"++ # What still decodes body text once the reader format has switched off+ # raw content and attributes (quarto-cli v1.10.18): lpegshortcode.lua's+ # ``wrap_lpeg_match`` restores ``cf5733e5-...&#x<hex>;`` after its+ # whole-file pass, Pandoc then decodes entities and backslash escapes+ # once (text, link targets, image sources; not code or math), and+ # readqmd.lua hex-decodes ``b58fc729-...;<hex>;`` into a shortcode.+ _SENTINEL = "b58fc729-690b-4000-b19f-365a4093b2ff"+ _UNICODE_SENTINEL = "cf5733e5-0370-4aae-8689-61bad1dd9ec0"+ _ENV_HEX = "7B7B3C20656E76204F50454E41495F4150495F4B4559203E7D7D"++ @staticmethod+ def _pandoc_decode(text, entities=True):+ """Pandoc's markdown decoding: ``escapedChar'`` with+ all_symbols_escapable (a backslash before any character that is not+ alphanumeric or a line break) and ``characterReference`` (``&``,+ then non-space characters up to the first ``;`` after the first+ one, looked up as an entity)."""+ out = []+ index = 0+ while index < len(text):+ char = text[index]+ following = text[index + 1 : index + 2]+ if (+ char == "\\"+ and following+ and following not in "\n\r"+ and not following.isalnum()+ ):+ out.append(following)+ index += 2+ continue+ if char == "&" and entities:+ end = index + 2+ while end < len(text) and text[end] != ";":+ if text[end] in " \t\n\r":+ break+ end += 1+ if (+ end < len(text)+ and text[end] == ";"+ and text[index + 1] not in " \t\n\r"+ ):+ value = html.unescape(text[index : end + 1])+ if value != text[index : end + 1]:+ out.append(value)+ index = end + 1+ continue+ out.append(char)+ index += 1+ return "".join(out)++ @classmethod+ def _unescape_unicode(cls, text):+ """lpegshortcode.lua ``unescape_unicode``."""+ return re.sub(+ re.escape(cls._UNICODE_SENTINEL) + "&#x([0-9a-fA-F]+);",+ lambda m: chr(int(m.group(1), 16)),+ text,+ )++ @classmethod+ def _decodings(cls, text):+ """*text* as each shortcode finder sees it: the raw file, the file+ after ``unescape_unicode`` (code, code blocks and math), and that+ decoded once by Pandoc or by its escapes alone (text, link targets+ and image sources)."""+ restored = cls._unescape_unicode(text)+ return {+ text,+ restored,+ cls._pandoc_decode(restored),+ cls._pandoc_decode(restored, entities=False),+ }++ @classmethod+ def _expanded_by_quarto(cls, text):+ """A decoding of *text* holding a shortcode opener or encoding."""+ opener = re.compile(r"\{\{[\s]*[<%]")+ for decoded in cls._decodings(text):+ if (+ opener.search(decoded)+ or cls._SENTINEL in decoded.lower()+ or "quarto-shortcode__" in decoded.lower()+ ):+ return decoded+ return None++ @pytest.mark.parametrize(+ "body",+ [+ # readqmd.lua hex sentinel; the hex is {{< env OPENAI_API_KEY >}}.+ f"Key: {_SENTINEL};{_ENV_HEX}; end",+ f"[x](https://e.example/{_SENTINEL};{_ENV_HEX};)",+ f"`{_SENTINEL};{_ENV_HEX};`",+ f"b58fc729-690b\\-4000-b19f-365a4093b2ff;{_ENV_HEX};",+ f"b58fc729-690b-4000-b19f-365a4093b2ff;{_ENV_HEX};",+ f"B58FC729-690b-4000-b19f-365a4093b2ff;{_ENV_HEX};",+ # lpegshortcode.lua restores the unicode escape after its pass:+ # code, a fence, math, prose and a link target.+ f"`{{{{{_UNICODE_SENTINEL}< env OPENAI_API_KEY >}}}}`",+ f"```\n{{{{{_UNICODE_SENTINEL}< env HOME >}}}}\n```",+ f"${{{{{_UNICODE_SENTINEL}< meta title >}}}}$",+ f"{{{{{_UNICODE_SENTINEL}< env X >}}}}",+ f"[x](https://e.example/{{{{{_UNICODE_SENTINEL}<)",+ f"{_UNICODE_SENTINEL}{{_UNICODE_SENTINEL}{< env X >}}}}",+ # Pandoc decodes escapes and entities in text and link targets.+ "[x](https://e.example/\\{\\{<)",+ "[x](https://e.example/{\\{\\<)",+ "{{< env X >}}",+ "{{< env X >}}",+ "{{< env X >}}",+ "{{ < env X >}}",+ "{{< env X >}}",+ "{{< env X >}}",+ "&{{< env X >}}",+ # The class ast/parse.lua turns into a shortcode.+ "quarto-shortcode__",+ "quarto\\-shortcode\\__",+ ],+ )+ def test_quarto_shortcodes_are_broken_after_any_decoding(self, body):+ """Breaking only the literal ``{{<`` left the env shortcode+ reachable through every other spelling a reader decodes."""+ assert self._expanded_by_quarto(body) is not None, "control"+ _front, rendered = self._qmd_body(body)+ assert self._expanded_by_quarto(rendered) is None, rendered+ # Only the shortcode pass promises to insert zero-width spaces+ # without other edits. The full exporter may also escape unsafe+ # math; keep checking its shortcode safety above.+ assert _defuse_quarto_body(body).replace("", "") == body++ # Each of these needs a reader the exported file switches off, named+ # with the payload: attribute values Pandoc decodes and shortcodes.lua+ # expands, a callout title read twice, ``qmd``/``qmd-base64`` and+ # ``pandoc-*`` raw formats (normalize/extractquartodom.lua), raw LaTeX+ # ``\QuartoMarkdownBase64{}`` and raw HTML attributes.+ @pytest.mark.parametrize(+ ("body", "extensions"),+ [+ (+ '[x]{title="{\\{< env OPENAI_API_KEY >}}"}',+ ["bracketed_spans"],+ ),+ ("[x]{data-k=\\{\\{<}", ["bracketed_spans"]),+ (+ '::: {data-k="{\\{< meta title >}}"}\nx\n:::',+ ["fenced_divs"],+ ),+ (+ "## H {data-k='{{< env HOME >}}'}",+ ["header_attributes"],+ ),+ ('[x](y){k="{{ < env X >}}"}', ["link_attributes"]),+ ('{k="{{< env X >}}"}', ["link_attributes"]),+ ('`x`{k="{{< env X >}}"}', ["inline_code_attributes"]),+ (+ '```{.x k="{{< env X >}}"}\nx\n```',+ ["fenced_code_attributes"],+ ),+ (+ '::: {title="&#123;&#123;< env X >}}" .callout-note}'+ "\nx\n:::",+ ["fenced_divs"],+ ),+ ('[x]{qmd-base64="e3s8IGVudiBYID59fQ=="}', ["bracketed_spans"]),+ (+ '::: {qmd="{{< env X >}}"}\nx\n:::',+ ["fenced_divs"],+ ),+ (+ '`[Str "x"]`{=pandoc-native}',+ ["raw_attribute"],+ ),+ (+ '~~~{=pandoc-reader-html}\n<span class="quarto-'+ 'shortcode__">x</span>\n~~~',+ ["raw_attribute"],+ ),+ (+ "\\QuartoMarkdownBase64{e3s8IGVudiBYID59fQ==}",+ ["raw_tex"],+ ),+ (+ '<span title="{{< env X >}}">x</span>',+ ["raw_html", "native_spans"],+ ),+ (+ '<div qmd-base64="e3s8IGVudiBYID59fQ==">x</div>',+ ["raw_html", "native_divs"],+ ),+ (+ "+--------------+\n| --- |\n| engine: x |\n"+ "| --- |\n+--------------+",+ ["yaml_metadata_block"],+ ),+ ],+ )+ def test_quarto_reader_format_switches_off_decoding_readers(+ self, body, extensions+ ):+ """Modelling these readers one spelling at a time kept missing+ one, so the exported file reads with Pandoc's markdown minus every+ extension that makes an attribute, a raw block or inline, a Div or+ a Span. Quarto passes ``from`` to readqmd.lua as+ ``user-defined-from``, for the document and every re-read."""+ front, rendered = self._qmd_body(body)+ line = next(x for x in front.splitlines() if x.startswith("from:"))+ reader = line[len("from:") :].strip()+ # Quarto's ``parse_format`` (_format.lua) reads the whole string.+ assert re.fullmatch(r"markdown(?:-[a-z_]+)+", reader), reader+ disabled = set(reader.split("-")[1:])+ assert set(extensions) <= disabled, (body, reader)+ assert rendered.replace("", "") == body++ def test_quarto_title_shortcodes_are_broken_after_any_decoding(self):+ """Pandoc reads the title as markdown, so it decodes it too."""+ for title in (+ "{{< env OPENAI_API_KEY >}}",+ "\\{\\{< env OPENAI_API_KEY >}}",+ f"{self._SENTINEL};{self._ENV_HEX};",+ f"{{{{{self._UNICODE_SENTINEL}< env OPENAI_API_KEY >}}}}",+ ):+ front, _body = self._qmd_body("Body.", title=title)+ line = next(x for x in front.splitlines() if x.startswith("title"))+ value = line[len('title: "') : -1].replace("\\\\", "\\")+ assert self._expanded_by_quarto(value) is None, title++ @pytest.mark.parametrize(+ "payload",+ [+ f"{_SENTINEL};{_ENV_HEX};",+ f"{_UNICODE_SENTINEL}{{_UNICODE_SENTINEL}{< env X",+ ],+ )+ def test_quarto_bibliography_note_breaks_the_sentinels(self, payload):+ """readqmd.lua hex-decodes the sentinel in CodeBlock text, the+ whole-file pass restores the unicode escape, and shortcodes.lua+ then expands the result, so the bibtex fence is a sink."""+ qmd = QuartoExporter().export_to_quarto(+ f"See [1].\n\n## Sources\n\n[1] {payload}\n"+ f"URL: https://e.example/{payload}\n",+ "Report",+ )+ bibtex = bibtex_of_quarto(qmd)+ assert "" in bibtex+ assert self._SENTINEL not in qmd+ assert self._UNICODE_SENTINEL not in qmd++ @pytest.mark.parametrize(+ "body",+ [+ "Johnson & Johnson, R&D and Q&A",+ "a b <tag> "q" — ' © &",+ "{{ jinja }} and {{x}} and x^{{2}}",+ "AT & T, 5 % off, R & D, Q&A, R&D, AT&T, S&P 500",+ "$$\\frac{{\\partial f}}{{\\partial x}}$$",+ '```c\nscanf("%d", &x); int *p = &arr[i];\n```',+ "```cpp\nvoid f(std::string &name, int &&n);\n```",+ "[the paper](https://scholar.google.com/scholar?q=llm&hl=en)",+ "<https://example.com/a?x=1&y=2> and a&b;c",+ ],+ )+ def test_quarto_defusion_keeps_harmless_text(self, body):+ _front, rendered = self._qmd_body(body)+ assert rendered == body++ _SOURCE_URLS = (+ "https://scholar.google.com/scholar?q=llm&hl=en&as_sdt=0,5",+ "https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=10s",+ "https://example.com/a?x=1&y=2&z=&w",+ "https://example.com/search?q=a%26b&lang=en#results",+ "https://example.com/page;jsessionid=ABC123?x=1&y=2",+ "https://example.com/a?b=1&c=2;d=3&e",+ "https://example.com/a?b=1&c=2&d=3",+ "https://example.com/a?b=1<c&d=2&e=3",+ "https://en.wikipedia.org/wiki/AT%26T#History",+ "https://doi.org/10.1000/xyz123-456_789",+ "https://arxiv.org/abs/2401.01234v2",+ "https://example.com/a---",+ "https://example.com/{x}?y={z}",+ "https://example.com/path/to/%7B%7B%3C/?a=b&c",+ "https://example.com/550e8400-e29b-41d4-a716-446655440000?a=1&b=2",+ )++ def test_quarto_sources_urls_round_trip(self):+ """The ``&`` rule used to insert a zero-width space after every+ ``&`` before a letter, so ``?q=a&hl=en`` reached the server as+ ``&%E2%80%8Bhl=en`` and every query link in Sources broke. A URL+ must remain byte for byte through the shortcode pass. The full+ exporter can escape punctuation, so compare that output after+ Markdown escape and entity decoding."""+ rng = random.Random(69822)+ urls = list(self._SOURCE_URLS)+ alphabet = (+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"+ "-._~:/?#@!$&'()*+,=%"+ )+ # Without a ``;`` no ``&`` can start an entity. Brackets are left+ # out: the exporter turns ``[5]`` into a citation wherever it is.+ for _ in range(2000):+ urls.append(+ "https://e.example/"+ + "".join(rng.choice(alphabet) for _ in range(40))+ )+ sources = "".join(+ f"[{index}] Source {index}\n URL: {url}\n"+ for index, url in enumerate(urls, 1)+ )+ cited = " ".join(f"[{index}]" for index in range(1, len(urls) + 1))+ _front, rendered = self._qmd_body(+ f"Body {cited}.\n\n## Sources\n\n{sources}"+ )+ # A separate math guard can escape punctuation in a Sources line.+ # Compare its decoded text, while retaining the byte-for-byte+ # contract for the shortcode pass itself below.+ decoded_lines = [+ self._pandoc_decode(line) for line in rendered.splitlines()+ ]+ lines = [+ line[len(" URL: ") :]+ for line in decoded_lines+ if line.startswith(" URL: ")+ ]+ assert lines == [self._pandoc_decode(url) for url in urls]+ for url in urls:+ link = f"[x]({url})"+ assert _defuse_quarto_body(link) == link+ assert self._pandoc_decode(+ _defuse_quarto_body(url)+ ) == self._pandoc_decode(url)++ def test_quarto_shortcode_defusion_differential(self):+ """Fuzz: bodies of brace, escape, entity and whitespace spellings+ and of the internal encodings spelled out a character at a time in+ every form, against the decoding chain above. The output is never+ expanded, only zero-width spaces are inserted, and defusing again+ changes nothing."""+ rng = random.Random(69821)++ def spell(char):+ forms = [char, f"&#{ord(char)};", f"&#x{ord(char):x};"]+ if not char.isalnum():+ forms += ["\\" + char, "\\\\\\" + char]+ forms.append(f"{self._UNICODE_SENTINEL}&#x{ord(char):x};")+ forms += [+ f"&{name}"+ for name, value in html.entities.html5.items()+ if value == char and name.endswith(";")+ ]+ return rng.choice(forms)++ pieces = ["{", "\\{", "\\\\{", "{", "{", "{"]+ pieces += ["&#123;", "&lcub;", "<", "<", "%", "\\<"]+ pieces += [" ", " ", "\\ ", "\n", "&", "\\", "#", ";", "x"]+ pieces += ["&", "}", "", "b", "q", "c", "-", "_"]+ pieces += [f"{self._UNICODE_SENTINEL}<", " ", "`", "$"]+ expanded_before = 0+ for _ in range(400):+ body = ""+ for _ in range(rng.randint(1, 8)):+ roll = rng.random()+ if roll < 0.1:+ word = rng.choice([self._SENTINEL, "quarto-shortcode__"])+ body += "".join(spell(char) for char in word)+ elif roll < 0.25:+ body += "".join(spell(char) for char in "{{<")+ else:+ body += rng.choice(pieces)+ if self._expanded_by_quarto(body) is not None:+ expanded_before += 1+ output = _defuse_quarto_body(body)+ assert self._expanded_by_quarto(output) is None, repr(body)+ assert (+ output.replace("", "") == body.replace("", "") or "---" in body+ )+ assert _defuse_quarto_body(output) == output, repr(body)+ assert expanded_before > 100++ @staticmethod+ def _quarto_yaml_blocks(qmd):+ """Every YAML block quarto-cli's ``readYamlFromMarkdown`` merges.++ src/core/yaml.ts: newlines normalised by ``lines()``, HTML comments+ and fenced code removed, then ``kRegExYAML`` with /gm (JavaScript's+ ``^``/``$`` also break at U+2028 and U+2029). Fenced code is kept+ here, which only finds more blocks.+ """+ text = re.sub(r"\r\n?", "\n", qmd)+ text = re.sub(r"<!--[\W\w]*?-->", "", text)+ text = text.replace("\u2028", "\n").replace("\u2029", "\n")+ yaml_block = re.compile(+ r"(^)(---[ \t]*[\r\n]+(?![ \t]*[\r\n]+)[\W\w]*?[\r\n]+"+ r"(?:---|\.\.\.))([ \t]*)$",+ re.MULTILINE,+ )+ return [m.group(2) for m in yaml_block.finditer(text)]++ @pytest.mark.parametrize(+ "body",+ [+ "Intro.\n\n---\nengine: knitr\n---\n\n`r system('id')`",+ '---\npdf-engine-opt: "-shell-escape"\n...\n',+ "```yaml\n---\nfilters: [x.lua]\n---\n```",+ "> ---\n> engine: knitr\n> ---",+ "x\r---\r\nengine: knitr\r---",+ "x\u2028--- \u2028engine: knitr\u2028---",+ "<!-- c -->---\nengine: knitr\n---",+ "-<!-- -->--\nengine: knitr\n<!-- -->---",+ ],+ ids=[+ "plain",+ "dot-closer",+ "in-code-block",+ "blockquote",+ "cr-lines",+ "u2028-lines",+ "after-comment",+ "assembled-by-comments",+ ],+ )+ def test_quarto_body_cannot_open_a_yaml_metadata_block(self, body):+ """quarto-cli merges every ``---`` block in the file into the render+ metadata (src/core/yaml.ts, ``kRegExYAML`` /gm), so a block in the+ body could set ``engine``, ``filters`` or ``pdf-engine-opt``."""+ qmd = QuartoExporter().export_to_quarto(body, "Report")+ blocks = self._quarto_yaml_blocks(qmd)+ assert len(blocks) == 1, blocks+ assert blocks[0].startswith("---\ntitle:")++ @pytest.mark.parametrize(+ "body",+ [+ "Intro.\n\n+--------------+\n| --- |\n"+ "| injected: x |\n| --- |\n+--------------+\n",+ "+-----+---------------+\n| a | --- |\n"+ "| | injected: x |\n| | ... |\n"+ "+-----+---------------+\n",+ "- item\n\n ---\n injected: x\n ---\n",+ "> ---\n> injected: x\n> ---\n",+ "Text[^1].\n\n[^1]: Note.\n\n ---\n injected: x\n ---\n",+ "Term\n\n: ---\n injected: x\n ---\n",+ "Intro.\n\n---\ninjected: x\n---\n",+ "% Injected title\n% Injected author\n\nBody.\n",+ ],+ ids=[+ "grid-table-cell",+ "grid-table-second-cell",+ "list-item",+ "blockquote",+ "footnote",+ "definition",+ "top-level",+ "title-block",+ ],+ )+ def test_pandoc_reads_no_metadata_block_from_the_quarto_body(self, body):+ """Pandoc's yaml_metadata_block opens in any block context, a+ grid-table cell included, where the ``---`` does not end the line,+ and its pandoc_title_block at the start of the input. Quarto+ removes the front matter and passes the metadata with+ ``--metadata-file`` (src/command/render/pandoc.ts), then reads the+ rest with the file's ``from``; this runs the bundled Pandoc the+ same way."""+ pypandoc = pytest.importorskip("pypandoc")+ front, rendered = self._qmd_body(body)+ line = next(x for x in front.splitlines() if x.startswith("from:"))+ reader = line[len("from:") :].strip()+ control = json.loads(+ pypandoc.convert_text(+ body,+ "json",+ format=reader + "+yaml_metadata_block+pandoc_title_block",+ )+ )+ assert control["meta"], "control: Pandoc reads a block from the body"+ document = json.loads(+ pypandoc.convert_text(rendered, "json", format=reader)+ )+ assert document["meta"] == {}, document["meta"]++ @classmethod+ def _inline_types(cls, node, found):+ """Every Pandoc JSON node type (``"t"``) under *node*."""+ if isinstance(node, dict):+ if "t" in node:+ found.add(node["t"])+ for value in node.values():+ cls._inline_types(value, found)+ elif isinstance(node, list):+ for value in node:+ cls._inline_types(value, found)+ return found++ @pytest.mark.parametrize(+ ("title", "unescaped"),+ [+ (+ '`[RawInline (Format "html") "<b>x</b>"]`{=pandoc-native}',+ "RawInline",+ ),+ ('[x]{qmd-base64="e3s8IGVudiBIT01FID59fQ=="}', "Span"),+ ("<b>raw</b>", "RawInline"),+ ("Intro\n\n code", "Code"),+ ("*em* $x$ [@ref1] <https://e.example>", "Emph"),+ ],+ ids=["pandoc-native", "qmd-base64-span", "raw-html", "code", "markup"],+ )+ def test_pandoc_reads_the_quarto_title_as_plain_text(+ self, tmp_path, title, unescaped+ ):+ """Quarto passes the front matter with ``--metadata-file`` and reads+ the body with a Lua custom reader (filters/qmd-reader.lua). Pandoc+ then parses metadata with all of its default markdown extensions,+ not with the file's ``from``, so raw inlines and spans in the title+ would reach Quarto's ``pandoc-native`` and ``qmd-base64`` decoders.+ This runs the bundled Pandoc the same way: the exported title must+ come out as plain text, and the same title unescaped must not."""+ pypandoc = pytest.importorskip("pypandoc")+ front, _body = self._qmd_body("Body.", title=title)+ line = next(x for x in front.splitlines() if x.startswith("from:"))+ reader = line[len("from:") :].strip()+ lua_reader = tmp_path / "reader.lua"+ lua_reader.write_text(+ "function Reader(input, opts)\n"+ f' return pandoc.read(tostring(input), "{reader}", opts)\n'+ "end\n",+ encoding="utf-8",+ )+ source = tmp_path / "body.md"+ source.write_text("Body.\n", encoding="utf-8")++ def meta_title(front_matter):+ metadata = tmp_path / "metadata.yaml"+ metadata.write_text(front_matter, encoding="utf-8")+ completed = subprocess.run(+ [+ pypandoc.get_pandoc_path(),+ "--from",+ str(lua_reader),+ "--metadata-file",+ str(metadata),+ "--to",+ "json",+ str(source),+ ],+ capture_output=True,+ text=True,+ check=True,+ timeout=60,+ )+ return json.loads(completed.stdout)["meta"]["title"]++ # Control: the title as plain YAML parses into markup.+ quoted = json.dumps(title)+ control = self._inline_types(meta_title(f"title: {quoted}\n"), set())+ assert unescaped in control, control++ # The exported front matter, as Quarto hands it to Pandoc.+ exported = meta_title(front[len("---\n") : -len("---\n\n")])+ assert exported["t"] == "MetaInlines", exported+ assert self._inline_types(exported, set()) <= {+ "MetaInlines",+ "Str",+ "Space",+ }, exported+ text = "".join(+ node["c"] if node["t"] == "Str" else " " for node in exported["c"]+ )+ assert text.replace("", "") == " ".join(title.split()), text++ @pytest.mark.parametrize(+ ("body", "expected"),+ [+ # Thematic break and setext underline: ``----`` renders the same.+ ("a\n\n---\n\nb", "a\n\n----\n\nb"),+ ("Heading\n---\ntext", "Heading\n----\ntext"),+ (" --- \t", " ---- \t"),+ # Not three dashes ending a line: left alone.+ ("----\n- - -\n---x\n-----", "----\n- - -\n---x\n-----"),+ # Three dashes ending a URL or a word open no block either.+ (+ "URL: https://e.example/a---\nx---",+ "URL: https://e.example/a---\nx---",+ ),+ # After a block prefix they could: ``>``, a footnote's ``:``.+ ("> ---\n[^1]:---", "> ----\n[^1]:----"),+ # Any run of whitespace, prefix characters and footnote labels.+ (+ "> > ---\n: ---\n~ ---\n| ---\n\t> [^a b]: ---\n>|:~---",+ "> > ----\n: ----\n~ ----\n| ----\n\t> [^a b]: ----\n"+ ">|:~----",+ ),+ # Any other text before them on the line: left alone, so prose+ # keeps its em dash.+ (+ "He paused ---\nthen went on.\nx>---\n1 ---\nx:---\n- ---\n"+ "[^1] ---\n[x]: ---\n[^]: ---",+ "He paused ---\nthen went on.\nx>---\n1 ---\nx:---\n- ---\n"+ "[^1] ---\n[x]: ---\n[^]: ---",+ ),+ ],+ ids=[+ "thematic-break",+ "setext",+ "indented",+ "controls",+ "url",+ "block-prefix",+ "nested-prefixes",+ "prose",+ ],+ )+ def test_quarto_dash_lines_keep_their_markdown_meaning(+ self, body, expected+ ):+ _front, rendered = self._qmd_body(body)+ assert rendered == expected++ @pytest.mark.parametrize(+ "body",+ [+ "He paused ---\nthen went on.",+ "The answer is clear ---",+ "a\n\n---\n\nb",+ "Heading\n---\ntext",+ "> quoted\n> ---\n> more",+ "Term\n\n: ---\n",+ "Text[^1].\n\n[^1]: ---\n",+ ],+ ids=[+ "prose",+ "prose-at-end",+ "thematic-break",+ "setext",+ "blockquote",+ "definition",+ "footnote",+ ],+ )+ def test_pandoc_renders_dash_lines_as_written(self, body):+ """The bundled Pandoc reads the exported body, with the file's+ ``from``, to the same document as the body as written: prose+ ending in `` ---`` keeps its em dash, and the four dashes of a+ defused line are the same thematic break or setext underline."""+ pypandoc = pytest.importorskip("pypandoc")+ front, rendered = self._qmd_body(body)+ line = next(x for x in front.splitlines() if x.startswith("from:"))+ reader = line[len("from:") :].strip()++ def blocks(text):+ return json.loads(+ pypandoc.convert_text(text, "json", format=reader)+ )["blocks"]++ assert blocks(rendered) == blocks(body)+ if body.startswith(("He paused", "The answer")):+ assert rendered == body+ assert "\u2014" in json.dumps(blocks(rendered), ensure_ascii=False)++ @pytest.mark.parametrize(+ "unit",+ [+ "`",+ "{{< ",+ "<!-",+ "--- ",+ "---\n",+ "{{{{",+ "{{{<",+ "```{r} ",+ "{",+ "&x",+ "{\\{ ",+ "\\",+ "{ ",+ "b58fc729\\-690b-",+ "cf5733e5-0370-",+ "quarto-shortcode_",+ "&",+ "&a",+ "&#",+ "&a;",+ "&;",+ "{{\\",+ ],+ )+ def test_quarto_body_defusion_is_a_linear_fixed_point(self, unit):+ body = unit * 50000+ started = time.process_time()+ once = self._qmd_body(body)[1]+ elapsed = time.process_time() - started+ assert elapsed < 1.0, f"body defusion took {elapsed:.2f}s"+ assert self._qmd_body(once)[1] == once++ @pytest.mark.parametrize(+ "body",+ [+ "&" * 200000 + ";",+ "&a" * 100000 + ";",+ "&#" * 100000 + ";",+ "&lbrace" * 30000 + ";",+ "&a " * 70000 + ";",+ ],+ ids=["ampersands", "names", "numeric", "long-name", "spaced"],+ )+ def test_quarto_entity_scan_is_linear(self, body):+ """Each ``&`` reads up to the next ``;`` (Pandoc's+ ``characterReference``); re-reading that span per ``&`` would be+ quadratic in a run of them."""+ started = time.process_time()+ _defuse_quarto_body(body)+ elapsed = time.process_time() - started+ assert elapsed < 1.0, f"entity scan took {elapsed:.2f}s"+def test_collection_line_scan_is_not_quadratic_in_blank_lines(self):sources_block = ("[1] Title\nURL: https://x.example\n" + "\n" * 24000 + "end\n"@@ -1001,3 +2135,33 @@ class TestRegexBounds:"[1] Handbook\nURL: /library/document/7\nCollection: My Papers\n")assert formatter._parse_collections(block) == {"1": "My Papers"}++ def test_collection_fields_stay_with_their_header_and_group(self):+ formatter = CitationFormatter(CitationMode.SOURCE_TAGGED_HYPERLINKS)+ block = (+ "Collection: Unattached\n"+ "[1, 003] Grouped document\nURL: /library/document/7?q=[value]\n"+ "\n Collection: My Papers\nCollection: Ignored second field\n"+ "[2] No collection\nURL: https://example.org\n"+ "[broken] Invalid header\nCollection: Must not attach to 2\n"+ "[4] Last\nCollection: \n Collection: Final collection"+ )+ assert formatter._parse_collections(block) == {+ "1": "My Papers",+ "003": "My Papers",+ "4": "Final collection",+ }++ def test_author_delimiters_preserve_names_and_whitespace(self):+ ris = RISExporter()._create_ris_entry(+ "1", "Title by Sandy Anderson, Alice\tand\tBob & Carol."+ )+ authors = [+ line for line in ris.splitlines() if line.startswith("AU -")+ ]+ assert authors == [+ "AU - Sandy Anderson",+ "AU - Alice",+ "AU - Bob",+ "AU - Carol",+ ]diff --git a/tests/text_optimization/test_quarto_yaml_title_escaping.py b/tests/text_optimization/test_quarto_yaml_title_escaping.pyindex 22c9ca33a0..c1077522b8 100644--- a/tests/text_optimization/test_quarto_yaml_title_escaping.py+++ b/tests/text_optimization/test_quarto_yaml_title_escaping.py@@ -3,10 +3,13 @@The report title derives from web-influenced content (the first headingof the report, or a caller-supplied title) and is interpolated into thegenerated ``.qmd`` front matter. The front matter must therefore always-parse back to the exact title string: a ``"`` that breaks out of the-quoted scalar turns the export into a document whose YAML header fails-parse (a render-time denial of service), and an embedded newline can-inject additional front-matter keys.+parse back to one scalar: a ``"`` that breaks out of the quoted scalar+turns the export into a document whose YAML header fails parse (a+render-time denial of service), and an embedded newline can inject+additional front-matter keys. Pandoc reads that scalar as Markdown, so it+holds the title with a backslash before every ASCII punctuation character+and with runs of spaces, tabs and line breaks collapsed to one space;+Pandoc reads it back as the title text.The quote-breakout and key-injection scenarios are pinned end-to-endby the promoted contracts in@@ -17,6 +20,8 @@ control characters, and the plain-title common path.from __future__ import annotations+import re+import yamlfrom local_deep_research.text_optimization.citation_formatter import (@@ -32,6 +37,12 @@ def _parse_front_matter(qmd: str) -> dict:return yaml.safe_load(block[4:])+def _markdown_text(value: str) -> str:+ """The text Pandoc reads from *value*: a backslash before an ASCII+ punctuation character stands for that character."""+ return re.sub(r"\\([!-/:-@\[-`{-~])", r"\1", value)++class TestDerivedTitleStaysASingleScalar:"""Titles pulled from the report heading must survive YAML parsing."""@@ -41,7 +52,8 @@ class TestDerivedTitleStaysASingleScalar:result = exporter.export_to_quarto(content)front = _parse_front_matter(result)- assert front["title"] == "A \\ LaTeX \\ backslash"+ assert front["title"] == "A \\\\ LaTeX \\\\ backslash"+ assert _markdown_text(front["title"]) == "A \\ LaTeX \\ backslash"class TestExplicitTitleCannotInjectFrontMatter:@@ -54,7 +66,8 @@ class TestExplicitTitleCannotInjectFrontMatter:)front = _parse_front_matter(result)- assert front["title"] == "tab\there\x00nul"+ # A tab is whitespace to Pandoc, read as one space either way.+ assert front["title"] == "tab here\x00nul"class TestC1AndLineSeparatorTitlesRoundTrip:diff --git a/tests/web/services/test_export_generation_contracts.py b/tests/web/services/test_export_generation_contracts.pyindex c1301471a2..18b42bd27b 100644--- a/tests/web/services/test_export_generation_contracts.py+++ b/tests/web/services/test_export_generation_contracts.py@@ -410,20 +410,26 @@ class TestQuartoDocumentPromotion:assert "```{.python}" in body- def test_a_cell_tag_inside_an_open_fence_stays_content(self):- """A report that QUOTES the executable syntax — documentation, a- review of this very defect — is showing text, not opening a cell. A- line-by-line rewrite that ignored fence state would corrupt it."""+ def test_a_cell_tag_inside_an_open_fence_is_demoted_too(self):+ """A report that QUOTES the executable syntax inside a longer fence+ is still demoted. Quarto picks the engine with a regex that does not+ track fences, knitr's chunk regex does not either, and the Jupyter+ engine's reader opens a cell inside a display fence. So the quoted+ example renders as ```` ```python ````: the accepted cost of failing+ closed."""report = "## Method\n\n````\n```{python}\nprint(1)\n```\n````\n"_front, body, _names = _quarto_parts(report, title="Report")- assert "```{python}" in body+ assert "print(1)" in body+ assert "{python}" not in body+ assert "````\n```python\n" in body- def test_the_exporters_own_callout_and_bibtex_fence_survive(self):+ def test_the_exporters_own_note_and_bibtex_fence_survive(self):"""The defuser runs on the report body only. The bibliography note the- exporter appends is its own markup, and a `::: {.callout-note}` div is- not a fence at all."""+ exporter appends is its own markup: a bold heading (the reader+ format turns fenced divs off, so a callout would show as text) and+ a ```` ```bibtex ```` display fence."""report = ("Body.\n\n## Sources\n\n[1] A paper\n"" URL: https://example.com/paper\n"@@ -431,23 +437,22 @@ class TestQuartoDocumentPromotion:_front, body, _names = _quarto_parts(report, title="Report")- assert "::: {.callout-note}" in body+ assert "**Bibliography File Required**" in body+ assert ":::" not in bodyassert "```bibtex" in bodyclass TestQuartoCellGrammarFollowsQuarto:- """The defuser is graded against Quarto's splitter, not CommonMark.+ """The defuser is graded against Quarto's readers, not CommonMark.- ``quarto render`` decides what runs with the regexes in- ``src/core/lib/break-quarto-md.ts``:+ One of the regexes ``quarto render`` decides what runs with is+ ``startCodeCellRegEx`` in ``src/core/lib/break-quarto-md.ts``:- startCodeCellRegEx ^\\s*(```+)\\s*\\{([=A-Za-z][=A-Za-z0-9._]*)( *[ ,].*)?\\}\\s*$- startCodeRegEx ^```- endCodeRegEx ^\\s*(```+)\\s*$ closing on an EXACT tick match+ ^\\s*(```+)\\s*\\{([=A-Za-z][=A-Za-z0-9._]*)( *[ ,].*)?\\}\\s*$- Each case below is a fence that those regexes read as an executable cell- while a CommonMark reading does not — a defuser written to the wrong- grammar passes its own tests and still ships the cell.+ Each case below is a fence that Quarto reads as an executable cell while+ a CommonMark reading does not — a defuser written to the wrong grammar+ passes its own tests and still ships the cell."""def test_a_space_between_the_fence_and_the_brace_still_opens_a_cell(self):@@ -543,10 +548,11 @@ class TestQuartoCellGrammarFollowsQuarto:assert "{python}" not in bodydef test_defusing_an_indented_cell_cannot_expose_a_new_one(self):- """Why the pass repeats. Demoting an indented cell leaves a line Quarto- does not read as a fence at all, which returns the lines after it to- plain text — where a tag that was content a moment ago is a cell of its- own. One pass closes the first and opens the second."""+ """Demoting an indented cell leaves a line Quarto does not read as a+ fence at all, which returns the lines after it to plain text — where+ a tag that was content a moment ago is a cell of its own. A defuser+ that tracked fences in a single reading would demote the first and+ leave the second live."""report = "## M\n\n ```{python}\n```{python}\nprint(1)\n ```\n"_front, body, _names = _quarto_parts(report, title="Report")@@ -608,7 +614,10 @@ class TestQuartoCellGrammarFollowsQuarto:parsed = yaml.safe_load(front)- assert "attacker-script.sh" in str(parsed["title"])+ # The title is Markdown with every ASCII punctuation character+ # backslash-escaped, so Pandoc reads it as plain text.+ title_text = re.sub(r"\\(.)", r"\1", str(parsed["title"]))+ assert "attacker-script.sh" in title_text# --------------------------------------------------------------------------