Skip to content

Commit 43bd2e2

Browse files
Kasper JungeRalphify
authored andcommitted
fix: resolve inline backticks in code fences breaking HTML comment stripping
The fence-matching regex treated inline ``` characters on a content line as the closing fence delimiter, causing HTML comments after the inline backticks (but still inside the real fence) to be incorrectly stripped from the prompt. The fix requires the closing fence backreference to be preceded by a newline, matching CommonMark's rule that closing code fences must start on their own line. Co-authored-by: Ralphify <noreply@ralphify.co>
1 parent b01bf81 commit 43bd2e2

2 files changed

Lines changed: 22 additions & 1 deletion

File tree

src/ralphify/_frontmatter.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,12 @@
5555
# Backreferences (\2 / \3) ensure the closing fence has the same number
5656
# of characters as the opening, so a ```` fence is not broken by an
5757
# inner ``` — the inner ``` is treated as content, not a fence boundary.
58+
# The ``\n`` before each backreference requires the closing fence to
59+
# start on a new line, preventing inline backticks/tildes from being
60+
# mistaken for a closing fence (matching CommonMark's rule that closing
61+
# code fences must be on their own line).
5862
_FENCE_OR_COMMENT_RE = re.compile(
59-
r"((`{3,}).*?\2|(~{3,}).*?\3)|<!--.*?-->",
63+
r"((`{3,}).*?\n[ \t]*\2|(~{3,}).*?\n[ \t]*\3)|<!--.*?-->",
6064
re.DOTALL,
6165
)
6266

tests/test_frontmatter.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,23 @@ def test_html_comment_inside_four_backtick_fence_preserved(self):
151151
assert "<!-- keep this comment -->" in body
152152
assert "<!-- strip this comment -->" not in body
153153

154+
def test_html_comment_after_inline_backticks_inside_fence_preserved(self):
155+
"""When a ``` fence contains inline ``` characters on a content
156+
line, the inline backticks must NOT be treated as the closing
157+
fence. HTML comments that follow the inline backticks but are
158+
still inside the real fence must be preserved."""
159+
text = (
160+
"---\nagent: claude\n---\n"
161+
"```\n"
162+
"code with ``` inline\n"
163+
"<!-- keep this -->\n"
164+
"```\n"
165+
"<!-- strip this -->"
166+
)
167+
_, body = parse_frontmatter(text)
168+
assert "<!-- keep this -->" in body
169+
assert "<!-- strip this -->" not in body
170+
154171
def test_invalid_yaml_raises_value_error(self):
155172
text = "---\n: invalid: yaml: [unclosed\n---\nBody"
156173
with pytest.raises(ValueError, match="Invalid YAML"):

0 commit comments

Comments
 (0)