Skip to content
14 changes: 12 additions & 2 deletions docs-agent-mcp/pipelines/utils/canonical_rag_ingest.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,13 @@
CHARS_PER_TOKEN = 4

HEADING_RE = re.compile(r"^(#{1,6})\s+(.+?)\s*$")
FENCE_START_RE = re.compile(r"^(`{3,}|~{3,})(\w*)\s*$")
# CommonMark fence opener: 3+ backticks or tildes, optional spaces, then an
# info string. The first word of the info string is the language; the rest
# (e.g. Hugo attributes like {linenos=true}) is ignored. Backtick info strings
# may not contain backticks, so inline ```code``` lines are not fences. A `|`
# right after the fence marks a table cell (fences inside converted HTML
# tables), not an opener; pipes later in the info string are allowed.
FENCE_START_RE = re.compile(r"^(?!`+[^`]+`)(`{3,}|~{3,})(?![ \t]*\|)[ \t]*([^\s{]*).*$")
GFM_TABLE_ROW_RE = re.compile(r"^\s*\|")
ALERT_RE = re.compile(
r"\{\{%\s*alert\b[^%]*%\}\}(.*?)\{\{%\s*/alert\s*%\}\}",
Expand Down Expand Up @@ -318,7 +324,11 @@ def parse_canonical_document(content: str) -> CanonicalDocument:
closed = False
while idx < len(lines):
block_lines.append(lines[idx])
if lines[idx].strip().startswith(fence_char * fence_len):
# CommonMark closer: only the opening fence character, at least
# as many as the opener (so a ```lang line inside a block, or a
# ~~~ line inside a ``` block, does not end it).
closing = lines[idx].strip()
if len(closing) >= fence_len and set(closing) == {fence_char}:
closed = True
idx += 1
break
Expand Down
105 changes: 105 additions & 0 deletions tests/test_canonical_fences.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
"""Tests for fenced code block detection in the canonical ingest parser (#322)."""

import sys
from pathlib import Path

import pytest

ROOT = Path(__file__).resolve().parents[1] / "docs-agent-mcp"
for path in (ROOT / "pipelines", ROOT / "pipelines" / "utils"):
if str(path) not in sys.path:
sys.path.insert(0, str(path))

import canonical_rag_ingest # noqa: E402


def blocks(text):
"""Parse text and return (block_type, content) pairs in document order."""
doc = canonical_rag_ingest.parse_canonical_document(text)
return [(b.block_type, b.content) for s in doc.sections for b in s.blocks]


@pytest.mark.parametrize(
"opening_fence",
[
"```python", # baseline: already recognised
"``` python", # space before the language
"```shell-session", # hyphen in the language
"```c++", # non-word characters in the language
"```yaml {linenos=true}", # Hugo-style fence attributes
],
)
def test_opening_fence_variants_are_parsed_as_code(opening_fence):
text = f"Intro:\n\n{opening_fence}\ndef f():\n return 1\n```\n\nAfter.\n"

result = blocks(text)

assert [kind for kind, _ in result] == ["prose", "code_fence", "prose"]
assert " return 1" in result[1][1] # indentation preserved
assert result[2][1] == "After."


def test_unrecognised_fence_does_not_invert_the_rest_of_the_page():
text = "Intro:\n\n``` python\ndef f():\n return 1\n```\n\nAfter.\n\n```bash\nls\n```\n"

result = blocks(text)

assert [kind for kind, _ in result] == ["prose", "code_fence", "prose", "code_fence"]
assert result[2][1] == "After."
assert "ls" in result[3][1]


def test_comment_lines_inside_code_are_not_headings():
text = "# Title\n\n``` python\n# a comment, not a heading\nx = 1\n```\n"

doc = canonical_rag_ingest.parse_canonical_document(text)

headings = [s.heading for s in doc.sections]
assert "a comment, not a heading" not in headings


@pytest.mark.parametrize(
("line", "language"),
[
("~~~sh title=a|b", "sh"),
("```js title=a|b", "js"),
],
)
def test_pipes_later_in_the_info_string_are_allowed(line, language):
match = canonical_rag_ingest.FENCE_START_RE.match(line)
assert match is not None
assert match.group(2) == language


def test_tilde_fence_info_string_may_contain_backticks():
match = canonical_rag_ingest.FENCE_START_RE.match("~~~sh title=`example`")
assert match is not None
assert match.group(2) == "sh"


@pytest.mark.parametrize(
"line",
[
"```inline code```", # backtick info strings cannot contain backticks
"``` |", # closing fence inside a converted HTML table row
"~~~ |",
],
)
def test_non_fence_lines_are_not_openers(line):
assert canonical_rag_ingest.FENCE_START_RE.match(line) is None


@pytest.mark.parametrize(
"text",
[
"````markdown\n```bash\nls\n```\n````\n\nAfter.\n", # shorter fence inside a longer one
"```python\nx = 1\n```bash\ny = 2\n```\n\nAfter.\n", # info string on a would-be closer
"```text\n~~~\nstill code\n```\n\nAfter.\n", # other fence character does not close
"```text\ncode\n``` \n\nAfter.\n", # trailing spaces after the closer are allowed
],
)
def test_closing_fence_contains_only_fence_characters(text):
result = blocks(text)

assert [kind for kind, _ in result] == ["code_fence", "prose"]
assert result[1][1] == "After."