Skip to content

Fix GitHub GFM inline math rendering across READMEs & docs and harden CI guard - #30

Merged
ShaneLogic merged 1 commit into
mainfrom
devel
Nov 23, 2026
Merged

ShaneLogic merged 1 commit into
mainfrom
devel

Conversation

@ShaneLogic

@ShaneLogic ShaneLogic commented Nov 23, 2026 •

Copy link
Copy Markdown
Owner

Summary

Resolves all remaining GitHub cmark-gfm + MathJax v3 inline/block math parsing issues across all 45 tracked Markdown files (verified 412 / 412 <math-renderer> blocks with 0 issues via GitHub's live /markdown API) and upgrades tests/ci/test_markdown_contracts.py to prevent regressions (src/ production code untouched).

Root Causes Fixed

  1. Adjacent - / [ before opening $ (Suns-$V_{\mathrm{oc}}$, pseudo-$J\text{–}V$, pseudo-$\mathrm{FF}$, [$\text{m}^{-1}$], negative-$p$) — converted to clean math-contained forms ($\text{Suns-}V_{\mathrm{oc}}$, $\text{pseudo-}J\text{-}V$, $\text{pseudo-FF}$, parenthesized units).
  2. Double-parenthesis )$) boundary breaks (2D ($(y, x)$), ($...)$)) — simplified to avoid adjacent )$).
  3. GFM *...* / }_..._ emphasis collisions across $...$ ($\tilde{A}^* = \min(A^*_L, A^*_R)$, ($\mathbf{F}_\alpha \cdot \mathbf{n} = 0$) + $\theta = (P_+ + P_-)/P_{\mathrm{lim}}$) — rewritten using \ast, ($F_{\alpha,n} = 0$), and $\theta = (P^{+} + P^{-})/P_{\mathrm{lim}}$.
  4. CommonMark backslash-unescaping inside single $...$ (0.031\% / 0.009\% turned into unescaped TeX % comments; G\,\mathrm{d}x turned into literal commas ,) — moved literal percentages outside $ (0.031%, 0.009%) and standardized thin spaces to \ .
  5. Non-ASCII \text{–} inside MathJax & nested-list indented $$ blocks — normalized to pure ASCII \text{-} and top-level/inline equations; hardened tests/ci/test_markdown_contracts.py to guard all rules above.

Verification

  • Live GitHub /markdown GFM render audit across all 45 .md files (412 <math-renderer> blocks, 86 / 86 in root README.md): 0 unparsed $, 0 HTML tag collisions, 0 % comment truncations, 0 non-ASCII math tokens.
  • GitHub Actions Refactor checks on devel (2e4e783): 9 / 9 jobs passed (https://github.com/ShaneLogic/SolarLab/actions/runs/45156129751).

Summary by Sourcery

Make project documentation render consistently on GitHub by correcting incompatible Markdown math patterns and strengthening CI regression guards.

Bug Fixes:

  • Fix GitHub GFM and MathJax parsing issues across the tracked README and documentation files so inline and display equations render correctly.

Enhancements:

  • Expand Markdown CI contracts to validate inline math delimiters, emphasis collisions, unsafe boundaries, escaping, Unicode, table content, display-math fences, and code-span handling.

CI:

  • Harden Markdown contract checks and broaden their coverage to the relevant documentation files while preserving link validation.

Documentation:

  • Normalize math notation and formatting throughout project documentation, examples, and README content for reliable GitHub rendering.

@sourcery-ai

sourcery-ai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Documentation

Update the root README’s inline-math delimiters, escaping, and notation to render reliably in GitHub GFM.

  • README.md L144-155, L195-198 (+6 small edits)

Revise the Beer–Lambert reference protocol’s equations and units to avoid GFM inline-math parsing and escaping pitfalls.

  • docs/BeerLambertReferenceProtocolV1.md L47-50 (+5 small edits)

Reformat inline mathematics throughout the physics-corrections scope document to prevent delimiter, emphasis, and escape conflicts.

  • docs/PhysicsCorrectionsScopeV1.md L47-53, L104-112, L150-159 (+9 small edits)

Correct inline math in the retired-models, contracts, and research-example READMEs so the examples and references render consistently on GitHub.

  • docs/RetiredModelsV1.md L51, L86
  • docs/contracts/README.md L51
  • examples/research_1d/README.md L43, L96
  • examples/research_2d/README.md L15-17, L28

Tests

Extend the Markdown CI contract to check GFM inline-math delimiter and escaping rules across the expanded set of tracked documentation files.

  • tests/ci/test_markdown_contracts.py L70-133, L145-156, L166-169 (+5 small edits)

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-23T10:57:49.481549Z 2e4e783 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2e4e783811

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

violations.append(
f"{rel}:{lineno}: unescaped '|' inside table math {span.group(0)!r}"
)
if "$$" in line:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Ignore inline code before classifying $$ fences

When a Markdown paragraph documents the literal $$ token inside inline code, this check still sees it and reports a fence violation, even though it is valid code-span content rather than a display-math delimiter. Scrub inline code before classifying $$ so the new CI guard accepts valid documentation.

Useful? React with 👍 / 👎.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 8 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="tests/ci/test_markdown_contracts.py" line_range="30" />
<code_context>
 MACRO_PATTERN = re.compile(
     r"\\(?:" + "|".join(DISALLOWED_MATHJAX_MACROS) + r")\b"
 )
+INLINE_CODE_PATTERN = re.compile(r"(`+)([^`]*?)\1")
 MD_LINK_PATTERN = re.compile(r"!?\[[^\]]*\]\(([^)]+)\)")
 IMG_SRC_PATTERN = re.compile(r'<img\s+[^>]*src="([^"]+)"')
</code_context>
<issue_to_address>
**Code spans trigger false math and link errors**

When a Markdown code span contains backticks or crosses a line and includes dollar- or link-like text, `INLINE_CODE_PATTERN` does not recognize the span, so `_check_inline_gfm_math_line` or the link check scans its literal content and fails CI for valid Markdown.

Use CommonMark-aware code-span masking across lines before the math and link checks.

Also at `tests/ci/test_markdown_contracts.py:73`, `tests/ci/test_markdown_contracts.py:166`.
</issue_to_address>

### Comment 2
<location path="tests/ci/test_markdown_contracts.py" line_range="78" />
<code_context>
+        return errors
+
+    dollar_positions = [
+        m.start() for m in re.finditer(r"(?<!\\)\$", scrubbed)
+    ]
+    if len(dollar_positions) % 2 != 0:
</code_context>
<issue_to_address>
**Backslash runs misclassify math delimiters**

When a dollar, percent, comma, or table pipe follows an even-length run of backslashes, the one-character lookbehind treats the character as escaped, so the math scan misses or mispairs active delimiters and the table check accepts an unescaped separator; valid TeX is also reported as invalid.

Determine whether each character is escaped by counting its immediately preceding backslash run, and use that rule in the math and table checks.

Also at `tests/ci/test_markdown_contracts.py:79`, `tests/ci/test_markdown_contracts.py:107`, `tests/ci/test_markdown_contracts.py:122`.
</issue_to_address>

### Comment 3
<location path="tests/ci/test_markdown_contracts.py" line_range="145-152" />
<code_context>
-                        violations.append(
-                            f"{rel}:{lineno}: unescaped '|' inside table math {span.group(0)!r}"
-                        )
+            if "$$" in line:
+                if line != "$$":
+                    violations.append(
+                        f"{rel}:{lineno}: '$$' fence must stand alone at column 0"
+                    )
+                else:
+                    in_display_math = not in_display_math
+                continue
+            if not in_display_math:
+                violations.extend(_check_inline_gfm_math_line(rel, lineno, line))
</code_context>
<issue_to_address>
**Code examples trigger display-fence errors**

When a Markdown line contains `$$` inside inline code, the display-fence check examines the raw line, so it treats literal code as a math fence and fails CI for valid documentation.

Exclude inline code before checking lines for display-math fences.

Also at `tests/ci/test_markdown_contracts.py:30`.
</issue_to_address>

### Comment 4
<location path="tests/ci/test_markdown_contracts.py" line_range="73" />
<code_context>
+def _check_inline_gfm_math_line(rel: str, lineno: int, line: str) -> list[str]:
+    """Validate cmark-gfm inline $...$ delimiter and backslash-escape invariants."""
+    errors: list[str] = []
+    scrubbed = INLINE_CODE_PATTERN.sub("CODE", line)
+    if "$" not in scrubbed:
+        return errors
</code_context>
<issue_to_address>
**Code spans create false Markdown syntax**

When inline code is adjacent to a math delimiter or separates `]` from `(`, the code-span scrubber substitutes `CODE` or deletes the span, changing the surrounding characters; the math or link check then rejects valid Markdown.

Mask code-span contents while preserving the original boundary characters.

Also at `tests/ci/test_markdown_contracts.py:166-169`.
</issue_to_address>

### Comment 5
<location path="tests/ci/test_markdown_contracts.py" line_range="24-25" />
<code_context>
     "si",
     "pu",
     "ce",
+    "colorbox",
+    "fcolorbox",
 )
 MACRO_PATTERN = re.compile(
</code_context>
<issue_to_address>
**Inline examples trip macro guard**

When a tracked Markdown file uses one of the newly disallowed commands in an inline code example, the macro scan searches each raw Markdown line, including inline code spans, so a valid code example that documents `\colorbox` or `\fcolorbox` is reported as a disallowed MathJax macro and fails CI.

Scrub inline code spans before searching for disallowed macros, while continuing to check actual math content.
</issue_to_address>

### Comment 6
<location path="tests/ci/test_markdown_contracts.py" line_range="154" />
<code_context>
+                    in_display_math = not in_display_math
+                continue
+            if not in_display_math:
+                violations.extend(_check_inline_gfm_math_line(rel, lineno, line))
+        if in_display_math:
+            violations.append(f"{rel}: unclosed '$$' display math block")
</code_context>
<issue_to_address>
**Indented code is checked as math**

When a Markdown document uses an indented code block containing a dollar sign, `_iter_non_code_lines` excludes fenced code but not Markdown's indented code blocks, so this call sends their contents to the inline-math validator. A literal dollar in an indented example, such as a shell prompt, is reported as unbalanced math and fails CI.

Exclude indented code blocks from math validation, including their list-container equivalents.
</issue_to_address>

### Comment 7
<location path="tests/ci/test_markdown_contracts.py" line_range="153" />
<code_context>
+                else:
+                    in_display_math = not in_display_math
+                continue
+            if not in_display_math:
+                violations.extend(_check_inline_gfm_math_line(rel, lineno, line))
+        if in_display_math:
</code_context>
<issue_to_address>
**Display math bypasses checks**

When a display-math body contains a non-ASCII token or a backslash-escaped `%` or `,` that GFM strips, the loop skips `_check_inline_gfm_math_line` throughout display blocks, so Unicode and backslash-escape errors in a block pass CI and render incorrectly on GitHub.

Validate display-math bodies with the applicable GFM checks while excluding their `$$` delimiters.
</issue_to_address>

### Comment 8
<location path="tests/ci/test_markdown_contracts.py" line_range="122" />
<code_context>
+            )
+        if re.search(r"\}_(?=[{\\])", span):
+            brace_underscore_spans += 1
+        if line.lstrip().startswith("|") and re.search(r"(?<!\\)\|", span):
+            errors.append(
+                f"{rel}:{lineno}: unescaped '|' inside table math ${span}$"
</code_context>
<issue_to_address>
**Some table math escapes checks**

When a GFM table row omits its optional leading pipe and contains an unescaped `|` inside inline math, the pipe check runs only when a row starts with `|`, so an unescaped pipe in math in a valid table row without an optional leading pipe passes CI and breaks the table rendering.

Check math pipes in table rows regardless of whether the row has a leading pipe.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

MACRO_PATTERN = re.compile(
r"\\(?:" + "|".join(DISALLOWED_MATHJAX_MACROS) + r")\b"
)
INLINE_CODE_PATTERN = re.compile(r"(`+)([^`]*?)\1")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Code spans trigger false math and link errors

When a Markdown code span contains backticks or crosses a line and includes dollar- or link-like text, INLINE_CODE_PATTERN does not recognize the span, so _check_inline_gfm_math_line or the link check scans its literal content and fails CI for valid Markdown.

Use CommonMark-aware code-span masking across lines before the math and link checks.

Also at tests/ci/test_markdown_contracts.py:73, tests/ci/test_markdown_contracts.py:166.

Prompt for AI agents
In `tests/ci/test_markdown_contracts.py` at line 30:

**Code spans trigger false math and link errors**

When a Markdown code span contains backticks or crosses a line and includes dollar- or link-like text, `INLINE_CODE_PATTERN` does not recognize the span, so `_check_inline_gfm_math_line` or the link check scans its literal content and fails CI for valid Markdown.

Use CommonMark-aware code-span masking across lines before the math and link checks.

Also at `tests/ci/test_markdown_contracts.py:73`, `tests/ci/test_markdown_contracts.py:166`.

return errors

dollar_positions = [
m.start() for m in re.finditer(r"(?<!\\)\$", scrubbed)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Backslash runs misclassify math delimiters

When a dollar, percent, comma, or table pipe follows an even-length run of backslashes, the one-character lookbehind treats the character as escaped, so the math scan misses or mispairs active delimiters and the table check accepts an unescaped separator; valid TeX is also reported as invalid.

Determine whether each character is escaped by counting its immediately preceding backslash run, and use that rule in the math and table checks.

Also at tests/ci/test_markdown_contracts.py:79, tests/ci/test_markdown_contracts.py:107, tests/ci/test_markdown_contracts.py:122.

Prompt for AI agents
In `tests/ci/test_markdown_contracts.py` at line 78:

**Backslash runs misclassify math delimiters**

When a dollar, percent, comma, or table pipe follows an even-length run of backslashes, the one-character lookbehind treats the character as escaped, so the math scan misses or mispairs active delimiters and the table check accepts an unescaped separator; valid TeX is also reported as invalid.

Determine whether each character is escaped by counting its immediately preceding backslash run, and use that rule in the math and table checks.

Also at `tests/ci/test_markdown_contracts.py:79`, `tests/ci/test_markdown_contracts.py:107`, `tests/ci/test_markdown_contracts.py:122`.

Comment on lines +145 to +152
if "$$" in line:
if line != "$$":
violations.append(
f"{rel}:{lineno}: '$$' fence must stand alone at column 0"
)
else:
in_display_math = not in_display_math
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Code examples trigger display-fence errors

When a Markdown line contains $$ inside inline code, the display-fence check examines the raw line, so it treats literal code as a math fence and fails CI for valid documentation.

Exclude inline code before checking lines for display-math fences.

Also at tests/ci/test_markdown_contracts.py:30.

Prompt for AI agents
In `tests/ci/test_markdown_contracts.py` at lines 145-152:

**Code examples trigger display-fence errors**

When a Markdown line contains `$$` inside inline code, the display-fence check examines the raw line, so it treats literal code as a math fence and fails CI for valid documentation.

Exclude inline code before checking lines for display-math fences.

Also at `tests/ci/test_markdown_contracts.py:30`.

def _check_inline_gfm_math_line(rel: str, lineno: int, line: str) -> list[str]:
"""Validate cmark-gfm inline $...$ delimiter and backslash-escape invariants."""
errors: list[str] = []
scrubbed = INLINE_CODE_PATTERN.sub("CODE", line)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Code spans create false Markdown syntax

When inline code is adjacent to a math delimiter or separates ] from (, the code-span scrubber substitutes CODE or deletes the span, changing the surrounding characters; the math or link check then rejects valid Markdown.

Mask code-span contents while preserving the original boundary characters.

Also at tests/ci/test_markdown_contracts.py:166-169.

Prompt for AI agents
In `tests/ci/test_markdown_contracts.py` at line 73:

**Code spans create false Markdown syntax**

When inline code is adjacent to a math delimiter or separates `]` from `(`, the code-span scrubber substitutes `CODE` or deletes the span, changing the surrounding characters; the math or link check then rejects valid Markdown.

Mask code-span contents while preserving the original boundary characters.

Also at `tests/ci/test_markdown_contracts.py:166-169`.

Comment on lines +24 to +25
"colorbox",
"fcolorbox",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Inline examples trip macro guard

When a tracked Markdown file uses one of the newly disallowed commands in an inline code example, the macro scan searches each raw Markdown line, including inline code spans, so a valid code example that documents \colorbox or \fcolorbox is reported as a disallowed MathJax macro and fails CI.

Scrub inline code spans before searching for disallowed macros, while continuing to check actual math content.

Prompt for AI agents
In `tests/ci/test_markdown_contracts.py` at lines 24-25:

**Inline examples trip macro guard**

When a tracked Markdown file uses one of the newly disallowed commands in an inline code example, the macro scan searches each raw Markdown line, including inline code spans, so a valid code example that documents `\colorbox` or `\fcolorbox` is reported as a disallowed MathJax macro and fails CI.

Scrub inline code spans before searching for disallowed macros, while continuing to check actual math content.

in_display_math = not in_display_math
continue
if not in_display_math:
violations.extend(_check_inline_gfm_math_line(rel, lineno, line))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Indented code is checked as math

When a Markdown document uses an indented code block containing a dollar sign, _iter_non_code_lines excludes fenced code but not Markdown's indented code blocks, so this call sends their contents to the inline-math validator. A literal dollar in an indented example, such as a shell prompt, is reported as unbalanced math and fails CI.

Exclude indented code blocks from math validation, including their list-container equivalents.

Prompt for AI agents
In `tests/ci/test_markdown_contracts.py` at line 154:

**Indented code is checked as math**

When a Markdown document uses an indented code block containing a dollar sign, `_iter_non_code_lines` excludes fenced code but not Markdown's indented code blocks, so this call sends their contents to the inline-math validator. A literal dollar in an indented example, such as a shell prompt, is reported as unbalanced math and fails CI.

Exclude indented code blocks from math validation, including their list-container equivalents.

else:
in_display_math = not in_display_math
continue
if not in_display_math:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Display math bypasses checks

When a display-math body contains a non-ASCII token or a backslash-escaped % or , that GFM strips, the loop skips _check_inline_gfm_math_line throughout display blocks, so Unicode and backslash-escape errors in a block pass CI and render incorrectly on GitHub.

Validate display-math bodies with the applicable GFM checks while excluding their $$ delimiters.

Prompt for AI agents
In `tests/ci/test_markdown_contracts.py` at line 153:

**Display math bypasses checks**

When a display-math body contains a non-ASCII token or a backslash-escaped `%` or `,` that GFM strips, the loop skips `_check_inline_gfm_math_line` throughout display blocks, so Unicode and backslash-escape errors in a block pass CI and render incorrectly on GitHub.

Validate display-math bodies with the applicable GFM checks while excluding their `$$` delimiters.

)
if re.search(r"\}_(?=[{\\])", span):
brace_underscore_spans += 1
if line.lstrip().startswith("|") and re.search(r"(?<!\\)\|", span):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Some table math escapes checks

When a GFM table row omits its optional leading pipe and contains an unescaped | inside inline math, the pipe check runs only when a row starts with |, so an unescaped pipe in math in a valid table row without an optional leading pipe passes CI and breaks the table rendering.

Check math pipes in table rows regardless of whether the row has a leading pipe.

Prompt for AI agents
In `tests/ci/test_markdown_contracts.py` at line 122:

**Some table math escapes checks**

When a GFM table row omits its optional leading pipe and contains an unescaped `|` inside inline math, the pipe check runs only when a row starts with `|`, so an unescaped pipe in math in a valid table row without an optional leading pipe passes CI and breaks the table rendering.

Check math pipes in table rows regardless of whether the row has a leading pipe.

@ShaneLogic
ShaneLogic merged commit 37a5383 into main Nov 23, 2026
25 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant