Skip to content

feat: add math core for formatting AI answers 🧮 - #915

Closed
Wisesofthemall wants to merge 1 commit into
colorstackorg:mainfrom
Wisesofthemall:ask-ai-formatting/1-math-core
Closed

Wisesofthemall wants to merge 1 commit into
colorstackorg:mainfrom
Wisesofthemall:ask-ai-formatting/1-math-core

Conversation

@Wisesofthemall

@Wisesofthemall Wisesofthemall commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Description ✏️

Part 1 of 3 for #914 (Ask AI formatting is off). Next: #916 (KaTeX and parsers), then #917 (switches it on). Nothing uses this code yet.

The Ask AI answer is shown as raw text today, so the model's markdown (**bold**, 1. lists, backticks) appears as-is. The fix renders the answer as markdown with math. This PR adds the hardest part: deciding which $...$ spans are math and which are prices.

What's added: packages/utils/src/ai-formatting/math.ts, exported as @oyster/utils/ai-formatting. It has no KaTeX import, so it runs on the server and in tests.

  • findInlineMathDollarSpans is a scanner, not a regex. When it rejects a span, it moves forward one character from that span's opening $, so the rejected span's closing $ can still open the next span. That's how Costs $5, $10 and $x$. still finds $x$. A lone $ skips to the end of its line, so one price doesn't stop later math from rendering.
  • isInlineMathSpan and looksLikeLatex decide whether a span is math, using the same spacing rules as pandoc:
    • $5 and $10 and $5-$10 are currency.
    • $ E = mc^2 $ is math.
    • $x-axis$ is prose.
  • protectCodeRegions masks code fences and inline code so that later passes never touch them.
  • normalizeLatex and balanceLatexBraces fix common model mistakes before KaTeX runs:
    • Unicode math letters such as 𝑥
    • x 2 written instead of x^2
    • the Unicode minus sign
    • a stray }
  • packages/utils/tsconfig.json now sets "target": "ESNext", like apps/member-profile. The regexes need the u flag and lookbehind, which the old ES5 default target doesn't allow.

Screenshots 📸

These were taken locally on the /ask-ai page with the full stack (#917) applied. A sample answer was stored in Redis so the page renders it without calling the AI. The sample's markdown source is in the collapsed section below the image.

The math-vs-currency logic in this PR. Prices, ranges, 5 * 3 * 2, hyphenated words and $ inside code all stay as plain text. Only $x$ and $E = mc^2$ become math:

Tricky cases: prices stay as text, only real math renders

Sample answer source (4-tricky.md)
These should all stay as plain text (no math, no italics):

- Prices: LeetCode Premium is $35 a month or $159 a year.
- Ranges: internships pay $40-$60 an hour, and $100,000 is twice $50,000.
- Multiplication: 5 * 3 * 2 = 30.
- Hyphens: the x-axis, a p-value, low-level code.
- Comparisons in prose: 2 < 3 and 5 > 4.
- Code with dollars: `echo "$HOME"` and `price = $5`.

But this IS math, right after prices: costs $5, $10 and $x$.

Unicode stars: **this is bold** but a ∗ b stays as is.

A lone price on this line: $20
Math on the next line still works: $E = mc^2$.

```js
// Code blocks are never touched: $x$, **bold**, *italic*, <b>tags</b>
const total = price * qty;
```

Here's the answer to your question: this line should NOT be stripped because it is not the first line.

Test cases 🧪

Run with cd packages/utils && bun test (no database needed). 60 pass, 0 fail.

Input Result
Costs $5, $10, $20 and $x$. only x is math
$5 and $10, $5-$10, $100,000 is twice $50,000 no math (currency)
$3x$, $f(x)$, $f''(t)$, $|x - 3|$, $A'$, $O(n \log n)$ math
$2x < 4$, $x >= 0$, $a != b$ math
$x-axis$, $p-value$, $low-level$ prose
$ E = mc^2 $ math (a strong math signal such as ^ beats the spacing rule)
$ x $ literal (same as pandoc)
It costs $5. then Solve $x^2 = 4$. on the next line the equation is still found
`price = $5` and a fence containing $x$ masked and restored unchanged
w = abba \in \Sigma^*} stray } dropped
𝑥 + 𝐀, x 2 + y 2 = 1 x + A, x^2 + y^2 = 1
Full test output
(pass) findInlineMathDollarSpans > Should only find math between prices, not the prices themselves.
(pass) findInlineMathDollarSpans > Should treat "$5 and $10" as currency.
(pass) findInlineMathDollarSpans > Should treat "$5-$10" as currency.
(pass) findInlineMathDollarSpans > Should treat "$100,000 is twice $50,000" as currency.
(pass) findInlineMathDollarSpans > Should treat "It costs $5 or $10 per month." as currency.
(pass) findInlineMathDollarSpans > Should treat "$3x$" as math.
(pass) findInlineMathDollarSpans > Should treat "$f(x)$" as math.
(pass) findInlineMathDollarSpans > Should treat "$f''(t)$" as math.
(pass) findInlineMathDollarSpans > Should treat "$|x - 3|$" as math.
(pass) findInlineMathDollarSpans > Should treat "$A'$" as math.
(pass) findInlineMathDollarSpans > Should treat "$2x < 4$" as math.
(pass) findInlineMathDollarSpans > Should treat "$x >= 0$" as math.
(pass) findInlineMathDollarSpans > Should treat "$a != b$" as math.
(pass) findInlineMathDollarSpans > Should treat "$O(n \log n)$" as math.
(pass) findInlineMathDollarSpans > Should treat "$x-axis$" as prose.
(pass) findInlineMathDollarSpans > Should treat "$p-value$" as prose.
(pass) findInlineMathDollarSpans > Should treat "$low-level$" as prose.
(pass) findInlineMathDollarSpans > A hard math signal should win over the spacing rule.
(pass) findInlineMathDollarSpans > A padded simple span should stay literal (same as pandoc).
(pass) findInlineMathDollarSpans > A lone price on one line should not stop math on later lines.
(pass) findInlineMathDollarSpans > Should skip escaped dollar signs and display math.
(pass) replaceInlineMathDollarSpans > Should replace only the math and keep the currency as is.
(pass) isInlineMathSpan > A span containing an HTML tag is never math.
(pass) isInlineMathSpan > A digit right after the closer means it is currency.
(pass) looksLikeLatex > A sentence is not LaTeX.
(pass) looksLikeLatex > A bare number is only math when allowed.
(pass) looksLikeLatex > An interval is LaTeX.
(pass) isPlainNumericMathContent > "7.23" is a number.
(pass) isPlainNumericMathContent > "1,234.56" is a number.
(pass) isPlainNumericMathContent > " 10 " is a number.
(pass) isPlainNumericMathContent > "" is not a number.
(pass) isPlainNumericMathContent > "3x" is not a number.
(pass) isPlainNumericMathContent > "1/2" is not a number.
(pass) normalizeLatex > Should map Unicode math letters to ASCII.
(pass) normalizeLatex > Should fix "x 2" written instead of "x^2".
(pass) normalizeLatex > Should replace the Unicode minus and collapse "++".
(pass) normalizeLatex > Should drop a duplicated equation tail.
(pass) normalizeLatex > Should keep primes.
(pass) balanceLatexBraces > Should drop a stray closing brace.
(pass) balanceLatexBraces > Should close an unclosed group.
(pass) balanceLatexBraces > Should ignore escaped braces.
(pass) wrapBareLatexSetBraces > Should wrap bare set braces in $.
(pass) wrapBareLatexSetBraces > Should leave wrapped set braces alone.
(pass) protectCodeRegions > Should mask code so math passes cannot touch it.
(pass) protectCodeRegions > Should only mask fences when asked to.
(pass) escapeHtml > Should escape HTML and decode back to the same text.
(pass) isKaTeXErrorOutput > Should detect KaTeX error markup.

 60 pass
 0 fail
Ran 60 tests across 2 files.

(The 13 tests not listed are the existing ones in src/index.test.ts.)

Type of Change 🐞

  • Feature - A non-breaking change which adds functionality.
  • Fix - A non-breaking change which fixes an issue.
  • Refactor - A change that neither fixes a bug nor adds a feature.
  • Documentation - A change only to in-code or markdown documentation.
  • Tests - A change that adds missing unit/integration tests.
  • Chore - A change that is likely none of the above.

Checklist ✅

  • I have done a self-review of my code.
  • I have manually tested my code (if applicable).
  • I have added/updated any relevant documentation (if applicable).

🤖 Generated with Claude Code

Adds the pure math helpers that decide which `$...$` spans are math and
which are prices, plus code masking and LaTeX cleanup. Nothing uses them
yet; they are the first piece of the fix for colorstackorg#914.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Wisesofthemall

Copy link
Copy Markdown
Contributor Author

Closing in favor of #918, which uses react-markdown instead of our own parsing logic, per the review feedback. Thanks!

@Wisesofthemall
Wisesofthemall deleted the ask-ai-formatting/1-math-core branch November 7, 2026 04:00
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