Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions docs/adr/0105-mathematical-script-semantic-normalization.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# ADR 0105: Preserve explicit metric scripts in semantic text

**Status:** Accepted on this PR; not protected-main truth
**Date:** 2026-08-21
**Owners:** LineageWeave ingestion and buyer-surface maintainers

## Context

Source posts commonly encode a unit such as `m<sup>3</sup>` or an indexed
quantity such as `m<sub>3</sub>` with HTML text-level markup. Dropping the
markup changes the searchable meaning to `m3`, while treating every numeric
`sup` element as mathematics would break the existing numeric-footnote
contract. Full MathML parsing is not yet justified by the current product
surface, but the loss of explicit unit scripts is a buyer-visible defect.

MathML 4 defines `msup`, `msub`, and `msubsup` as structural script elements;
HTML `sup`/`sub` are a permitted lighter-weight notation when detailed
mathematical markup is not required. This decision therefore adds a bounded
normalization boundary and keeps the source representation unchanged.

## Decision

1. Preserve the immutable source body exactly as imported.
2. In derived semantic text only, normalize an explicitly bounded metric base
(`m`, `cm`, `mm`, `km`, or `kg`, optionally preceded by a number) followed
by numeric `sup` or `sub` markup into Unicode superscript/subscript digits.
For example, `5m<sup>3</sup>` becomes `5m³` and `m<sub>3</sub>` becomes
`m₃`.
3. Keep ordinary numeric superscripts on prose under the existing footnote
role contract. Do not infer a mathematical formula from an arbitrary word.
4. Apply the same bounded normalization in backend semantic chunks and the
React buyer display so search text and visible text agree.
5. Defer full MathML/LaTeX parsing, expression trees, and ontology term
creation until an authorized fixture demonstrates a need beyond metric
scripts. Any such change requires a new ADR and parser contract.

## Consequences

- Search and the buyer popup retain the visible distinction between `m³` and
`m3` without exposing source HTML to the embedding model.
- Existing numeric-footnote tests remain unchanged because the bounded metric
pattern is the only new conversion.
- The current implementation does not claim to understand arbitrary equations;
unsupported script markup remains ordinary source text and must not be
presented as a parsed ontology expression.

## References (APA 7th)

World Wide Web Consortium. (2026). *Mathematical Markup Language (MathML)
Version 4.0* (W3C Recommendation). https://www.w3.org/TR/mathml4/
6 changes: 6 additions & 0 deletions frontend/src/postBodyDisplay.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,12 @@ describe("splitPostBody", () => {
]);
});

it("preserves explicit metric superscripts and subscripts", () => {
expect(splitPostBody("<p>Volume: 5m<sup>3</sup>, index m<sub>3</sub>.</p>")).toEqual([
{ kind: "text", text: "Volume: 5m³, index m₃." },
]);
});

it("limits numeric superscript footnote roles to their source paragraph", () => {
expect(
splitPostBody(
Expand Down
13 changes: 12 additions & 1 deletion frontend/src/postBodyDisplay.ts

@devin-ai-integration devin-ai-integration Bot Aug 21, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📝 Info: Non-metric tags remain handled inconsistently (pre-existing)

In the frontend, stripHtmlTags explicitly strips <sup> tags to empty string but not <sub> (postBodyDisplay.ts), so a non-metric subscript like x<sub>i</sub> is replaced with spaces (x i) rather than joined (xi). This asymmetry is pre-existing and not introduced by this PR — metric subs are converted to Unicode before stripping, so they are unaffected — but it is an inconsistency in how residual sup vs sub markup is collapsed that could matter for non-metric subscripts.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,17 @@ const INDENT_MARKER_END = "\u0002";
const INDENT_MARKER_PATTERN = /lw-indent:(\d+)/g;
const NUMERIC_FOOTNOTE_MARKER = "\u0003lw-numeric-footnote\u0004";
const NUMERIC_SUPERSCRIPT = /<sup\b[^>]*>\s*(\d{1,3})\s*<\/sup>/gi;
const SUPERSCRIPT_DIGITS = "⁰¹²³⁴⁵⁶⁷⁸⁹";
const SUBSCRIPT_DIGITS = "₀₁₂₃₄₅₆₇₈₉";
const METRIC_MARKUP =
/((?<![A-Za-z])(?:\d+(?:\.\d+)?\s*)?(?:km|cm|mm|kg|m))\s*<(sup|sub)\b[^>]*>\s*(\d{1,3})\s*<\/\2>/gi;
Comment on lines +37 to +38

@devin-ai-integration devin-ai-integration Bot Aug 21, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📝 Info: Lookbehind prevents footnote regression on words ending in a metric unit

The (?<![A-Za-z]) lookbehind at the start of the metric base in METRIC_MARKUP (postBodyDisplay.ts and chunking.py) is what keeps ordinary footnote superscripts working. For example Body claim<sup>1</sup> — "claim" ends in "m", but that "m" is preceded by "i" so the lookbehind fails and no metric conversion occurs, preserving the numeric-footnote role. However, note a subtle edge: for an input like x5m<sup>2</sup>, the engine can still match with base=m because the char before "m" is the digit "5" (not a letter), yielding x5m². This is a benign edge but worth being aware of if identifier-like tokens (e.g. abc5m) ever appear before scripts.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.


function normalizeMetricMarkup(raw: string): string {
return raw.replace(METRIC_MARKUP, (_match, base: string, kind: string, digits: string) => {
const table = kind.toLowerCase() === "sup" ? SUPERSCRIPT_DIGITS : SUBSCRIPT_DIGITS;
return `${base}${[...digits].map((digit) => table[Number(digit)]).join("")}`;
});

@devin-ai-integration devin-ai-integration Bot Aug 21, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📝 Info: Metric base requires the unit immediately adjacent to the script tag

The metric pattern requires the unit and <sup>/<sub> to be separated only by optional whitespace ((?:km|cm|mm|kg|m)\s*<(sup|sub)...). Cases where markup intervenes, e.g. <b>m</b><sup>3</sup>, or where the base is a letter-prefixed unit like Nm<sup>2</sup> (blocked by (?<![A-Za-z])), are left unconverted. This is consistent between frontend and backend and matches the bounded scope in ADR 0105, so search and display still agree; noted as a coverage limitation rather than a defect.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

}
Comment on lines +42 to +55

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📝 Info: Opposite normalization order backend vs frontend is safe

normalize_semantic_text runs plain-script then markup at chunking.py; normalizeMetricMarkup runs markup then plain-script at postBodyDisplay.ts. Neither replacement produces output the other can then match, so the orders are equivalent and search and display text agree.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.


function stripIndentMarkers(value: string): string {
return value
Expand Down Expand Up @@ -219,7 +230,7 @@ function isDecodableBase64(raw: string): boolean {

function pushText(segments: PostBodySegment[], raw: string, indentUnit: number): void {
const text = stripHtmlTags(
raw.replace(NUMERIC_SUPERSCRIPT, `${NUMERIC_FOOTNOTE_MARKER}$1`),
normalizeMetricMarkup(raw).replace(NUMERIC_SUPERSCRIPT, `${NUMERIC_FOOTNOTE_MARKER}$1`),
);
Comment on lines 246 to 251

@devin-ai-integration devin-ai-integration Bot Aug 21, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📝 Info: Frontend normalizes plain scripts over raw HTML, backend over extracted text

pushText runs normalizeMetricMarkup (markup plus plain-script) over the raw HTML slice including attributes, while the backend runs only _normalize_metric_markup on raw HTML and defers plain-script conversion to normalize_semantic_text on extracted text (chunking.py,137). An attribute like class="cm_2" gets rewritten inside the tag on the frontend, but stripHtmlTags removes the tag, so output text stays consistent.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

for (const paragraph of splitSemanticParagraphs(text)) {
const hasNumericSuperscriptMarker = paragraph.includes(NUMERIC_FOOTNOTE_MARKER);
Expand Down
21 changes: 18 additions & 3 deletions lineageweave/chunking.py

@devin-ai-integration devin-ai-integration Bot Aug 21, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📝 Info: Metric normalization applied before footnote detection keeps the two contracts disjoint

In both paths, metric normalization runs strictly before superscript-footnote handling: normalizeMetricMarkup(raw).replace(NUMERIC_SUPERSCRIPT, ...) in postBodyDisplay.ts, and parser.feed(_normalize_metric_markup(html)) in chunking.py. This means a metric <sup>/<sub> is consumed into Unicode digits before the parser's numeric-superscript footnote detector (chunking.py) ever sees it, so a metric like 5m<sup>3</sup> never gets a footnote role while <sup>1</sup> still does. The ordering is essential to the design and is correct here.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,22 @@ def chunk_by_paragraph(text: str) -> list[Chunk]:


_SENTENCE_BOUNDARY = re.compile(r"(?<=[.!?])\s+(?=[A-Z0-9가-힣])")
_SUPERSCRIPT_DIGITS = str.maketrans("0123456789", "⁰¹²³⁴⁵⁶⁷⁸⁹")
_SUBSCRIPT_DIGITS = str.maketrans("0123456789", "₀₁₂₃₄₅₆₇₈₉")
_METRIC_MARKUP = re.compile(
r"(?P<base>(?<![A-Za-z])(?:\d+(?:\.\d+)?\s*)?(?:km|cm|mm|kg|m))\s*"
r"<(?P<kind>sup|sub)\b[^>]*>\s*(?P<digits>\d{1,3})\s*</(?P=kind)>",
re.IGNORECASE,
)


def _normalize_metric_markup(html: str) -> str:
"""Keep explicit metric superscript/subscript digits in semantic text."""
def replace(match: re.Match[str]) -> str:
table = _SUPERSCRIPT_DIGITS if match.group("kind").lower() == "sup" else _SUBSCRIPT_DIGITS
return f"{match.group('base')}{match.group('digits').translate(table)}"

return _METRIC_MARKUP.sub(replace, html)


def chunk_by_sentence(text: str) -> list[Chunk]:
Expand Down Expand Up @@ -554,8 +570,7 @@ def _markdown_cells(line: str) -> list[str] | None:
if "|" not in line:
return None
value = line.strip()
if value.startswith("|"):
value = value[1:]
value = value.removeprefix("|")
if value.endswith("|") and not value.endswith("\\|"):
value = value[:-1]
cells = [cell.strip().replace(r"\|", "|") for cell in re.split(r"(?<!\\)\|", value)]
Expand Down Expand Up @@ -695,7 +710,7 @@ def chunk_by_dom(html: str) -> list[Chunk]:
]

parser = _BlockTextExtractor()
parser.feed(html)
parser.feed(_normalize_metric_markup(html))
entries = parser.finished()
chunks: list[Chunk] = []
for index, (
Expand Down
18 changes: 18 additions & 0 deletions tests/test_chunking.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,24 @@ def test_chunk_by_dom_does_not_treat_non_numeric_superscript_as_footnote() -> No
]


def test_chunk_by_dom_preserves_explicit_metric_superscripts() -> None:
"""A unit exponent remains searchable mathematical evidence."""
chunks = chunk_by_dom("<p>Volume: 5m<sup>3</sup>.</p>")

assert [(chunk.label, chunk.text) for chunk in chunks] == [
("p", "Volume: 5m³."),
]


def test_chunk_by_dom_preserves_explicit_metric_subscripts() -> None:
"""A unit subscript is retained without changing ordinary footnotes."""
chunks = chunk_by_dom("<p>Index m<sub>3</sub> is measured.</p>")

assert [(chunk.label, chunk.text) for chunk in chunks] == [
("p", "Index m₃ is measured."),
]


def test_chunk_by_dom_preserves_nested_list_order_and_depth() -> None:
"""Nested list items retain source order and increasing depth."""
chunks = chunk_by_dom(
Expand Down
Loading