Skip to content

fix(website): clamp pathological markdown nesting depth before parse - #8916

Closed
javenciu wants to merge 1 commit into
kirodotdev:mainfrom
javenciu:fix/markdown-walker-depth-clamp
Closed

javenciu wants to merge 1 commit into
kirodotdev:mainfrom
javenciu:fix/markdown-walker-depth-clamp

Conversation

@javenciu

@javenciu javenciu commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

A chat message containing pathologically nested markdown — for example thousands of leading > blockquote markers, or equivalently deep nested list indentation, or a long <div><div>… raw-HTML run — parses into an mdast/hast tree whose depth equals the nesting count. MarkdownRenderer.tsx walks that tree with plain recursive functions (eight self-recursive walk helpers), and remark-rehype's own mdast→hast transform recurses too, as does rehype-raw's parse5→hast transform. Past the engine's call-stack limit this throws RangeError: Maximum call stack size exceeded while rendering a single message.

Reproduced at origin/main: a message of 50,000 nested blockquote markers crashes <Markdown> with RangeError (React error-boundary trace pointing into the render), and the affected vitest run hangs to timeout. Where that error lands is surface-dependent — see Why it matters.

Why it matters

The blast radius depends on the surface, and the honest statement is two-part. In the chat transcript, every message is wrapped in MessageErrorBoundary (src/pages/chat/AssistantMessage.tsx, src/pages/chat/ChatPageMessageContent.tsx, src/app-sdk/messageRenderers.tsx), so the pre-fix cost there is one message degraded to the boundary's raw-text fallback — plus a multi-second overflow parse repeated on every streaming frame while that message is the live tail. Outside chat, MarkdownRenderer is rendered bare: src/pages/ChannelPage.tsx (channel message bodies) and src/components/notifications/NotificationDetailPanel.tsx (notification bodies) have no per-item boundary, so the same RangeError propagates to the app-level ErrorBoundary in App.tsx and replaces the whole view. Both are input-controlled: a channel message or a notification body arrives from outside, and nothing upstream caps nesting depth, so the renderer is the layer that has to defend itself.

What changed (motivation → approach → change)

The tree's depth is decided before any walker runs — at parse time, from the raw markdown text. Two fix shapes were considered: per-walker depth caps (eight vendored walkers plus the remark/rehype pipeline's own visitors, each needing its own cap and each a future maintenance hazard) versus one input-side clamp at the choke point where a message enters parsing. The input clamp wins structurally: every downstream walker — present and future — inherits the guarantee.

New website/src/utils/clampNestingDepth.ts bounds three spellings of the same class, each a distinct way to reach a recursive layer:

  1. CommonMark container prefixes in any interleaving the spec allows (>>>>, > > > re-opens through the 0–3 space indent, > - > - quote/list mixes). Scanned as whole CONTAINER units (up to 3 spaces + a quote or list marker, sticky-iterated), not as consecutive > characters, and bounded per line by MAX_BLOCKQUOTE_DEPTH (100).
  2. Progressively indented list items, which are multi-line and invisible to any per-line marker count. Bounded by MAX_LIST_INDENT_COLS (256) indent truncation. A marker at end of line is an empty item and nests like any other, so the indent clamp accepts it exactly as the container scanner does — a run of empty items otherwise kept its full indent and built the deep tree unbounded.
  3. Raw HTML tag runs (<div><div>…). rehype-raw is wired into both rehype pipelines, so embedded HTML parses (parse5) into HAST that the recursive walkers consume before sanitization — the same stack-overflow class through an alternate grammar. A conservative model of parse5's open-element stack neutralizes opening tags past MAX_HTML_TAG_DEPTH (100) by rewriting < to &lt; (literal in both micromark and parse5 contexts). Tag names are read by the grammar of the context the line is in: micromark's inline-HTML shape (letters, digits, -) outside a block, where anything else makes the whole <…> literal text; parse5's tokenizer rule inside an HTML block (any byte until whitespace, / or >), where <x:y> is a real element and reading it with the inline grammar would leave every such open uncounted. "Whitespace" there is the HTML tokenizer's set — tab, LF, FF, CR, space — wider than CommonMark's, and it is the set used both to end the name and to accept what follows it, or a tag ended by a form feed reads as literal text; NUL is a name byte (the tokenizer substitutes U+FFFD and keeps going).

The HTML model errs over-count-only by construction: voids never push; self-closing spelling on non-voids still opens (per parse5 — honoring the slash would under-count); same-name implied-end siblings replace the stack top (<li> spam is flat); closes pop only on exact top match (bogus closers cannot drain the counter).

A close tag can also be spelled where the tokenizer will not read one, and every such place has to stop the pop — otherwise the counter drains one per open and a run of any length never clamps. Two are lexical: a quoted attribute value and an inline code span. The code-span mask pairs backtick runs by exact length across the lines of a paragraph, as CommonMark does, and resets at a paragraph break; a run of any other length inside the span is literal and leaves the mask on. And the mask is over-count-only: it may suppress a pop, never a rewrite. An open past the bound is neutralized whether or not the mask is on, because the mask is a guess that a span is open and an unpaired backtick run is literal text to micromark — honoring the guess at the bound would let one stray backtick switch the guard off for the rest of the paragraph. The cost of guessing wrong the other way is cosmetic: &lt;div> shown inside a code span that already sits past a hundred open tags. The rest are spans parse5 makes a single node of, so their whole body is skipped, latched across lines when the end is not on the opening line:

  • <!-- is a comment, ending at --> or at --!>, and abruptly on the empty spellings <!--> and <!--->.
  • <?, any other <!, and </ followed by a non-name are bogus comments, each ending at the first >. <![CDATA[ is one of those: the CDATA tokenizer state is reachable only inside foreign (SVG/MathML) content, which this model does not enter, so ending that span at ]]> would run it past the > where parse5 ends it.

Ending a span late is the dangerous direction — it skips tags the parser does nest, which under-counts and leaves the run unclamped — so each end condition is taken from the tokenizer, and the search starts two characters into the opener, which is what makes the abrupt empty-comment spellings end where the tokenizer ends them. A <! inside an inline code span is literal text that opens no node, so no latch is taken there: latching would skip the real tags after the span. And because a latched span's end line can carry no < at all (a bare -->), the two fast-path guards that skip a line with no tag character also run the scan while a latch is open — skipping such a line would leave the latch set and hide the next line's real tags.

Exemption windows are judged by the downstream parser's semantics, in both directions. A fenced code block is exempt (marker runs inside a fence are literal text), and the standard for "is this line a fence?" is micromark's CommonMark semantics: a backtick fence's info string may not contain a backtick, so such a line is a paragraph to the parser and opens no exemption window here. Conversely, a line opening an HTML block (CommonMark 4.6: type-6 known block names, condition-7 complete tags alone on a line, <pre>/<script>/<style>/<textarea>, comments, PIs, declarations, CDATA) swallows every following line as raw block content until the block's end condition — a ```-shaped line there is not a fence to micromark, so entering fence state on it would exempt an unclamped deep run behind a 3-token shield prefix. While that latch is open, fence-OPEN recognition is suppressed (backtick and tilde alike), container clamps do not apply, the inline code-span mask is inert, and the HTML tag pass keeps applying — raw block content is exactly what parse5 nests. Block-name tables are copied from micromark's own micromark-util-html-tag-name lists, and the raw-block end condition is a disjunction over all four raw closers, matching micromark's continuationRawEndTag, which accepts </script> as the end of a <pre> block. Where fence detection is unsure it fails closed (stays clampable), and the approximations over-latch only: the worst case is cosmetic clamping of fenced marker art, never an unclamped deep run reaching the parser.

Clamping stays minimal-mutation: below every bound content is byte-identical, and a clamped line drifts by one inserted escape byte (containers) or 3 bytes per neutralized tag (HTML). The API is deliberately minimal — clampNestingDepth(s) with the bounds as module constants — since the production call site uses the defaults and unused tunables are a maintenance liability.

Lint boundary. website/eslint.i18n.config.js lists the module as a named boundary, the same idiom as unifiedPatchHeaders.ts: every string in it is a grammar token handed to a parser (</pre>-class raw-block closers, the &lt; a neutralized tag becomes, tag names from micromark's tables), never user-visible copy, and the raw-block closers are derived from the names table so the two cannot drift. Verified copy-free: the module imports neither i18nT nor useTranslation.

The call site is MarkdownRenderer.tsx (MarkdownBlock): clean = clampNestingDepth(clean) immediately after the existing stray-tag strip, before any parsing. It runs in both sourcePos modes — a message that crashes the renderer has no coordinates worth preserving.

Tests

website/src/test/MarkdownRenderer.depthGuard.test.tsx (44 tests; the overflow vectors, the pseudo-fence vector and every fake-close spelling fail without the fix):

  • renders 50-deep nesting normally (below any clamp bound — byte-identical passthrough)
  • survives 5,000-deep and 50,000-deep blockquote nesting without a stack overflow
  • survives deep nested-list nesting (the non-blockquote nesting vector)
  • survives deep raw-HTML tag runs, including behind HTML-block fence-shield prefixes
  • clamp path stays roughly linear in input length (no quadratic re-scan)
  • a backtick-in-info-string pseudo-fence does not open an exemption window (a line like ```x`y is a paragraph per CommonMark; treating it as a fence would exempt a following deep run from clamping — pinned failing-without-fix with the exact RangeError)
  • every place a close tag can be spelled without being one does not pop: quoted attribute value, inline code span, HTML comment, processing instruction, declaration, and a malformed close (</ … >); a comment spanning lines keeps swallowing closes until its end; an ordinary below-bound comment stays byte-identical
  • the code-span mask cannot be turned against the guard: a mismatched-length backtick run does not close a cross-line span (two shapes, including one where every model state is clean at each line end, so only exact-length pairing catches it); an unpaired backtick before a deep run — same line, previous line, or across a blank line — does not switch neutralization off; a genuine cross-line span below the bound stays byte-identical
  • inside an HTML block a parse5-shaped tag name (<x:y>) counts toward depth and is neutralized past the bound, as does a tag ended by form feed or CR or holding NUL; outside one <x:y> is literal text and stays byte-identical
  • a marker-only (empty) list item is indent-clamped like any other item
  • every span end lands where the tokenizer puts it, asserted on the clamp's own output because a late end silently under-counts: CDATA ends at the first > rather than ]]> (both with and without a > of its own before the run), a comment also ends at --!>, and <!--> / <!---> end abruptly

Revert-verified per guard, not just in aggregate: removing the span skip turns the comment and PI/declaration cases red with RangeError: Maximum call stack size exceeded; removing the --!> alternative, the malformed-close span, the exact-length pairing, the mask-independent neutralization, the raw-context tag-name rule, the tokenizer whitespace set, or the empty-item marker each leaves its own vector entirely unclamped while the other 43 stay green.

The nested-list fixture is pinned at 600 levels rather than 1,500: it is quadratic in depth (~2.3MB at 1,500), which parses in ~3s locally but 28s on CI against the 15s per-test budget — a fixture-cost timeout, not a clamp miss. 600 levels still convicts 4.7× past the ~128 effective-level bound.

Manual verification

Rendered a 50,000-deep blockquote message through the fixed MarkdownBlock in the vitest DOM harness: renders as a clamped-depth blockquote chain instead of crashing. A 50-deep message renders exactly as before (passthrough verified byte-identical at the clamp layer).

Related Issues

None fixed by this PR. Deferred follow-up: #10571 (the mochi ChatPanel surface runs its own copy of this pipeline and needs the same clamp; see Pattern harvest). Re-checked against the current open queue (428 PRs): 11 rows touch MarkdownRenderer.tsx or the mochi panel, none of them on this seam.

Pattern harvest

The pattern is recursive tree processing whose recursion depth is input-controlled with no guard at any layer. Harvested across this seam: eight self-recursive walkers inside MarkdownRenderer.tsx plus the remark/rehype pipeline's own recursive visitors all share the same exposure, and all funnel through one input choke point (MarkdownBlock's pre-parse string). Fixing at the choke point covers every current walker and any walker added later, where per-walker caps would rot.

Four further harvests, each from review:

  • An exemption window inside a guard must judge its trigger by the downstream parser's semantics — a looser line-shape match (here, a fence regex that accepted backticks in a backtick fence's info string) turns the guard itself into the bypass.
  • An input clamp must cover every grammar the pipeline turns into tree depth, not just the one that crashed first. rehype-raw makes embedded HTML a parse path, so <div> runs were the same attack through a different grammar, and the guard was incomplete until all three spellings (container prefixes, list indent, HTML tags) hit a bound at the same choke point.
  • A guard that maintains a counter is only as good as its enumeration of the places its decrement can be spelled without being real. Attribute values and code spans were covered from the start; comments, PIs, declarations and a malformed close were not, and each let a fake close drain one pop per open so the run never clamped. The generalization: when a scanner models a parser's stack, every construct the parser treats as opaque content must be skipped wholesale, not scanned.
  • A mask that models "the parser might be inside a code span here" is a guess, and a guess may only ever be allowed to err in the safe direction. Letting it suppress pops is over-count; letting it suppress the rewrite of an open past the bound was under-count, and turned a single unpaired backtick into an off switch for the whole guard. The rule: enumerate, for each piece of uncertain state, which of the two decisions it gates, and forbid it from gating the one whose failure is silent.
  • And, one level down from that: skipping opaque content is only safe if the span's end is the parser's end, and the two error directions are not symmetric. Ending a span early over-counts, which only clamps more. Ending it late skips real tags and silently disables the guard for the rest of the input — so an end condition has to be read off the tokenizer rather than inferred from the syntax it looks like. <![CDATA[ is the trap: it looks like it ends at ]]>, and does in foreign content, but in HTML content it is a bogus comment ending at the first >. Every end condition here is now pinned by a test asserting the clamp's own output, because a late end produces no error — just an unguarded run.

And one harvest about scope rather than mechanism: a guard placed at "the" choke point is only as complete as the count of choke points. The mochi ChatPanel surface runs its own copy of this pipeline over the same untrusted content and stays crashable; it is tracked in #10571 rather than fixed here, because that file has five <Markdown> call sites and no single pre-parse point — clamping its two function inputs upstream would rewrite <mcwidget> HTML before parseWidgets extracts it (measured: a 150-deep widget body loses 51 opening tags), so a correct fix is per-segment clamping at all five sites, which is a different change from this one.

Rule candidate: when recursion depth is controlled by input, clamp the input at every entry choke point instead of capping each recursive consumer — and enumerate four things, because covering one of each leaves the guard bypassable through the next: the grammars the pipeline parses into depth, the surfaces that run that pipeline, the constructs in which a decrement can be spelled without being real, and the exact end condition of each construct you skip.

F2 (source-position drift) — human-writer override rationale

The flagged drift (data-sourcepos coordinates vs unclamped content; first-duplicate fallback may miscite a selection location) can occur only on lines the clamp rewrote — input carrying more than 100 leading container markers on a single line, which does not occur in human-authored content. For that adversarial class the alternative to approximate citation is no render at all (the stack overflow this guard exists to stop). The rewrite keeps the kept prefix byte-identical and inserts exactly one byte, so coordinates are exact for all unclamped lines and for everything before the clamp point on a clamped line. Adjudication: total=0 uphold=0 (flag not upheld); requesting human-writer override on that basis.

Checklist

  • At most two commits (one is the norm), with a Conventional Commits title (feat|fix|docs|refactor|perf|test|chore|ci|build|revert: ...)
  • Existing tests pass and new tests added for new functionality
  • Self-review completed; code follows project style guidelines
  • Documentation updated (if applicable)
  • No secrets, credentials, or internal references in the diff

Contribution License Agreement

Per the template placeholder (CLA text pending): offered under the same terms as my prior merged contributions to this repository (#8835).

Why no screenshot: no visual delta -- this change rewrites pathological input strings (>100
leading container markers per line, >256 indent columns, or >100-deep raw
HTML tag runs per message) before parsing; ordinary content is byte-identical
through the clamp and renders unchanged. UX review confirmed zero visual
delta.

@javenciu
javenciu requested review from a team and dwu96 September 6, 2026 07:26
@github-actions github-actions Bot added fork Pull request from a fork (external contributor) readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Sep 6, 2026
@github-actions

github-actions Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

UX Review (Fable 5, fork) — ✅ PASS

UX-level review of dda95c5e1bdc66fd5ce4896934176f9db0ee3c67 via the fork AI-review pipeline — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

This PR adds no user-visible control, label, or copy — it is a pre-parse depth clamp that stops pathological markdown from crashing the transcript, channel, and notification views. Below the 100-level bound content renders byte-identically; past it (attacker-grade input only), content degrades gracefully to literal text instead of a RangeError wiping the whole view. No screenshot or recording is needed for a change with no user-visible surface, and no lens raised a finding.

UX-Verdict: PASS

No user-visible surface changes: ordinary messages render byte-identically, and pathological input now degrades to visible text instead of crashing the whole view.

[UX-REVIEWED] dda95c5

@github-actions

github-actions Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

First Principles Review (Fable 5, fork) — 🟡 CONCERNS

Premise-level review of dda95c5e1bdc66fd5ce4896934176f9db0ee3c67 via the fork AI-review pipeline — why this exists and whether the shipped surface is the smallest honest version. Updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

All evidence gathered. The fix has checkable provenance (the added render tests execute the real parser and would overflow on base), no existing mechanism does this job, ChannelPage.tsx:174 confirms the bare-renderer blast radius, and my grep for from 'react-markdown' outside tests found exactly one second render pipeline the clamp does not cover.

First-Principles-Verdict: CONCERNS

"The single choke point" is one short: mochi's ChatPanel.tsx runs its own react-markdown + rehype-raw pipeline, unclamped — the crash class survives there.

What this change ships

Inventory (6 items) — 6 justified

Intent: stop input-controlled markdown with pathological nesting from stack-overflowing the renderer and taking down channel/notification views — a FIX.

  1. A message with thousands of nested quote/list markers now renders instead of crashing the view — justified
  2. List indent past 256 columns is truncated — justified
  3. Raw <div><div>… runs past 100 opens render as literal text instead of crashing — justified
  4. Content past the bounds shows as literal text at clamp depth (one escaped marker / &lt; per tag) — justified
  5. New clampNestingDepth.ts module, one consumer (MarkdownBlock) — justified
  6. i18n-lint exemption for the new module — justified

Watch

  • Point patch with 1 counted unfixed sibling: grepped from 'react-markdown' excluding tests — 2 render pipelines exist, and website/src/apps/mochi/src/renderer/ChatPanel.tsx:1731 (MD_REHYPE = [rehypeRaw, rehypeSanitize]) parses the same input-controlled markdown with no clamp, contradicting "the single choke point where message markdown enters the renderer." A general fix is genuinely a separate change — accepted-and-deferred, not a demand.
    Clears when: mochi's pipeline routes through clampNestingDepth, or a linked issue records the deferral.

[FIRST-PRINCIPLES-REVIEWED] dda95c5

@github-actions

github-actions Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Fable 5, fork) — 🟡 CONCERNS

Design-level review of dda95c5e1bdc66fd5ce4896934176f9db0ee3c67 via the fork AI-review pipeline — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

All premises verified: rehype-raw sits in both rehype pipelines, and ChannelPage.tsx:174 / NotificationDetailPanel.tsx:124 render MarkdownRenderer bare over external input, so the crash class and the choke-point placement are both real.

Design-Verdict: CONCERNS

Right fix shape at the right layer, but an 803-line hand-mirrored model of micromark + parse5 is now the sole availability defense on two boundary-less surfaces.

Watch

  • clampNestingDepth.ts re-implements CommonMark block grammar (fence rules, HTML-block conditions 1–7) and parse5 tokenizer semantics (bogus comments, implied-end tags, span masks). The over-count-only bias and the 44 end-to-end tests pin today's spellings, but a micromark/parse5/rehype-raw upgrade that admits a nesting spelling this model doesn't know produces no test failure and no error — just an unclamped run. On chat that lands in MessageErrorBoundary; on ChannelPage.tsx:174 and NotificationDetailPanel.tsx:124 (both external input, per the description's own blast-radius analysis) it still replaces the whole view via the app-level boundary, because this PR makes the clamp the only defense there instead of also adding the backstop chat already has.
    Clears when: the two bare surfaces get a per-item error boundary (or equivalent fallback) so an unmodeled future spelling degrades one item, not the view — small enough for this PR or an immediately-linked follow-up.

Suggestions

[DESIGN-REVIEWED] dda95c5

@github-actions

github-actions Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Opus 4.8 Review (fork) — ✅ no blocking findings

Reviewed dda95c5e1bdc66fd5ce4896934176f9db0ee3c67 via the fork AI-review pipeline; updated in place on each push.

Review details

The single candidate rests on an ordering seam: clampNestingDepth(clean) (line 3965) runs before fixCodeFences(clean) (line 3990), so the clamp analyzes a string the parser doesn't ultimately see. I falsified it:

  • The discovery pass itself rated this "low" and explicitly could not construct a crashing input; its (a)/(b)/(c) are all phrased as "if a rewrite ever causes" / "potential."
  • Any deep container/tag run the clamp already neutralizes (backslash escape or <→&lt;) is baked into clean before fixCodeFences sees it; those rewrites are inert to every fixCodeFences transform.
  • The only un-clamped content is what the clamp exempted as fenced. fixCodeFences's four passes (escape bare N., insert blank line before glued opening fences, split closing/opening fences from trailing text) only add or split fence markers — none removes a leading ``` opener or converts a fenced region into unfenced deep content. So a region the clamp treated as fenced stays fenced (or more) to micromark; the exemption cannot be silently revoked downstream to expose an unclamped deep run.

The concern is real as a seam but cannot be grounded to a concrete input → observable crash. It dies under Step 1. No further grounded defect surfaced in the new module or its integration point.

No findings.

[OPUS-REVIEWED] dda95c5

@github-actions

github-actions Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

GPT 5.6 Review (fork) — 🔴 changes requested (blocking)

Reviewed dda95c5e1bdc66fd5ce4896934176f9db0ee3c67 via the fork AI-review pipeline; updated in place on each push.

2 of 2 blocking finding(s) are security-class and were withheld from adjudication, so the blocking verdict stands.

BLOCKING -- website/src/components/MarkdownRenderer.tsx:3968 -- Fence repair can expose nesting exempted by the clamp
clean = clampNestingDepth(clean)
Indented fence + glued uppercase closer -> fixCodeFences creates an early closer -> unbounded blockquotes reach ReactMarkdown and overflow the stack.
Anchor: residual/crash-data-loss-corruption
Fix: Run fixCodeFences before clampNestingDepth.

BLOCKING -- website/src/utils/clampNestingDepth.ts:641 -- HTML void rules undercount foreign-content nesting
if (VOID_ELEMENTS.has(name)) {
<svg> plus thousands of <base> tags -> clamp skips SVG-namespace elements -> rehypeRaw builds a deeply nested tree and overflows the stack.
Anchor: residual/crash-data-loss-corruption
Fix: Apply void-element handling only in the HTML namespace.

[BLOCK-MERGE] dda95c5
[GPT-REVIEWED] dda95c5

Adjudication (Opus 4.8) — is blocking on each finding proportionate?

Both F1 and F2 are fenced findings — annotate-only, and I have no downgrade authority over them. My verdict set is UPHOLD-FENCED vs FLAG, and FLAG requires a complete evidence record showing the reaching conditions are so extreme a human would accept the residual risk.

F1 — The diff adds clampNestingDepth(clean) at ~line 3960, and fixCodeFences(clean) runs afterward at MarkdownRenderer.tsx:3990. The clamp's fence-exemption is computed against pre-fixCodeFences text, but the comment at 3979–3983 states fixCodeFences creates/moves fence boundaries (including "splitting a closing fence glued to trailing text"). So a region the clamp treated as fence-interior (and left unclamped) can become non-fenced content the parser actually sees, letting a deep blockquote run reach ReactMarkdown → stack overflow. Trigger is a single crafted chat message — not extreme, not self-contradicting, not a legacy-only artifact. Cannot complete a rarity argument for FLAG.

F2 — VOID_ELEMENTS.has(name) (clampHtmlLine, diff line 1188) skips depth push for base/br/etc. unconditionally. Inside <svg> (foreign content), parse5 does not treat these as void and nests them, so <svg> + thousands of <base> under-counts to depth ~1 and flows unclamped into rehype-raw → the same stack-overflow class the guard exists to stop. The module header itself only claims foreign-content self-closers are over-counted; the void-in-foreign-namespace under-count is unmodeled. Trigger is one crafted message — not extreme. Cannot complete a rarity argument for FLAG.

[ADJUDICATION] dda95c5e1bdc66fd5ce4896934176f9db0ee3c67 total=0 uphold=0 downgrade=0
[GPT-ADJUDICATED] dda95c5e1bdc66fd5ce4896934176f9db0ee3c67
[ADJUDICATION-FENCED] dda95c5e1bdc66fd5ce4896934176f9db0ee3c67 fenced=2 flagged=0
UPHOLD-FENCED F1 website/src/components/MarkdownRenderer.tsx:3968 -- fixCodeFences runs after the clamp and can move a fence boundary so clamp-exempted deep nesting reaches the parser; a single crafted message triggers it, so the unbounded crash risk stands.
UPHOLD-FENCED F2 website/src/utils/clampNestingDepth.ts:641 -- void-element skipping ignores that parse5 nests those tags inside `<svg>` foreign content, so `<svg>`+many `<base>` under-counts and overflows the stack via one crafted message.
[GPT-ADJUDICATED-FENCED] dda95c5e1bdc66fd5ce4896934176f9db0ee3c67

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Sep 6, 2026
@javenciu
javenciu force-pushed the fix/markdown-walker-depth-clamp branch from 0cf09c1 to 9f68e58 Compare September 6, 2026 10:01
@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention merge conflict Branch has merge conflicts with its base — author must resolve before merge and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Sep 6, 2026
@javenciu

javenciu commented Sep 6, 2026

Copy link
Copy Markdown
Contributor Author

Human-writer override request for the source-position-drift flag (F2), per the adjudication result on this PR:

The flagged drift (data-sourcepos coordinates vs unclamped content;
first-duplicate fallback may miscite a selection location) can occur only on
lines the clamp rewrote — input carrying more than 100 leading container
markers on a single line, which does not occur in human-authored content.
For that adversarial class the alternative to approximate citation is no
render at all (the stack overflow this guard exists to stop). Commit 2
narrows the drift further: the rewrite keeps the kept prefix byte-identical
and inserts exactly one byte, so coordinates are exact for all unclamped
lines and for everything before the clamp point on a clamped line.
Adjudication: total=0 uphold=0 (flag not upheld); requesting human-writer
override on that basis.

@javenciu
javenciu force-pushed the fix/markdown-walker-depth-clamp branch from 9f68e58 to 2a03bd2 Compare September 6, 2026 17:13
@github-actions github-actions Bot removed the merge conflict Branch has merge conflicts with its base — author must resolve before merge label Sep 6, 2026
@javenciu

javenciu commented Sep 6, 2026

Copy link
Copy Markdown
Contributor Author

Maintainer re-run request: the CI and Build workflow runs on this PR failed inside the 17:19Z rate-limit window. The Detect changed surface setup job died with API rate limit exceeded for installation (run 34047928722), and the Coverage Gate failure is the missing-inputs cascade from that setup job, not a coverage regression. The review-family checks re-ran after the window and are green at this head (2a03bd2). No code delta is needed: re-running the failed workflows should clear the board. Thanks!

@iamwhatever iamwhatever added the drive-to-green PR claimed by drive-to-green pipeline label Sep 13, 2026
@iamwhatever

Copy link
Copy Markdown
Contributor

🤖 Kiro Crew [operator: iamwhatever#241cc860]: This PR has been inactive for 7+ days with failing CI. I've assessed the blockers and they appear resolvable -- I'll push fixes directly to this branch as a co-author. Assessment: the reds are a GitHub API rate-limit flake and AI lanes that died before a verdict; plan is a rebase onto current main, a fresh CI run, and a decision on the mochi ChatPanel clamp the reviewers asked about. If you'd prefer I don't touch this PR, add the pr-no-autofix label.

@iamwhatever

Copy link
Copy Markdown
Contributor

🤖 Kiro Crew [operator: iamwhatever#241cc860]:
Intent: A chat message with pathologically deep markdown nesting (blockquote runs, list indent, raw-HTML tag runs) must not crash the transcript view with RangeError: Maximum call stack size exceeded. One pre-parse input clamp at the MarkdownBlock choke point bounds every spelling of input-controlled depth, so every recursive walker downstream — present and future — inherits the guarantee, and ordinary content stays byte-identical.
Not a goal: Per-walker depth caps; changes to any other markdown surface (mochi ChatPanel is tracked separately in #10571); any change to what below-bound content renders as.

@iamwhatever

Copy link
Copy Markdown
Contributor

🤖 Kiro Crew [operator: iamwhatever#241cc860]:

  • accepted-and-deferred — point patch with one counted unfixed sibling (mochi ChatPanel) (span=14e1b37cc90d)

Tracked in #10571 (label deferred-finding, assignee, Due: 2026-10-11). The sibling is real: apps/mochi/src/renderer/ChatPanel.tsx runs rehypeRaw over the same untrusted content at five <Markdown> sites and stays crashable.
It is deferred rather than fixed here because the "one import plus a wrap" fix is wrong at that file: both of its entry functions extract <mcwidget> payloads from the message string AFTER the point where a wrap would run, so clamping there rewrites widget HTML before parseWidgets splits it out — measured, a 150-deep widget body loses 51 opening tags and WidgetFrame renders corrupted markup. That was tried on an earlier head of this PR and reverted. A correct fix is per-segment clamping below widget extraction at all five sites, which is a different change with its own tests; the issue body carries that design.
This PR's description no longer claims a single choke point for the product; it names the sibling and the issue.

@iamwhatever

Copy link
Copy Markdown
Contributor

🤖 Kiro Crew [operator: iamwhatever#241cc860]:

  • rebutted — cosmetic escaping of past-bound marker art "rides along" (span=937c70fa7609)

This is the guard's declared fail-closed edge, not a rider: the module and the description both state that where fence or block detection is unsure the clamp stays on, and that the worst case is cosmetic rewriting of marker art that already sits past 100 units on one line. Removing that edge means adding a second parser to decide "art or attack", which is exactly the shadow-parser growth the Design lane warns against, and an under-clamp on the guess is the crash this PR exists to stop.
Below every bound content is byte-identical (pinned by tests); the rewrite exists only on lines no human-authored content produces. Findings that the clamp rewrites past-bound art in some spelling are covered by this ruling.

@iamwhatever

Copy link
Copy Markdown
Contributor

🤖 Kiro Crew [operator: iamwhatever#241cc860]:

  • accepted-and-deferred — guard depends on byte-for-byte parity with micromark / parse5 tables that can drift silently (span=364f0038bfee)

Tracked in #10607 (label deferred-finding, assignee, Due: 2026-10-11): either import HTML_BLOCK_NAMES / HTML_RAW_NAMES / VOID_ELEMENTS from micromark-util-html-tag-name and html-void-elements, or pin the copies equal to those packages' exports by test, so an upgrade that moves them fails loudly.
Deferred rather than done here because adding a direct dependency (or a test that imports a package the app does not declare) is a maintainers' scope decision on a contributor PR being driven within its original intent, and neither option changes the guard's behavior at the pinned versions. One piece is already closed in this PR: the raw-block closers are now derived from the names table rather than copied a second time, so those two cannot drift apart.

@iamwhatever

Copy link
Copy Markdown
Contributor

🤖 Kiro Crew [operator: iamwhatever#241cc860]:

  • accepted-and-deferred — add a note naming the parity invariant a maintainer must re-verify on a react-markdown / rehype-raw major bump (span=58c5e25763c6)

Folded into #10607 (label deferred-finding, assignee, Due: 2026-10-11), whose second option — a test asserting the copied tables equal the packages' exports — makes the invariant discoverable at upgrade time by turning red, which is stronger than a prose note a bump would not run. The issue body names the invariant explicitly.

@github-actions github-actions Bot added readiness: checking Automated validation is still running merge conflict Branch has merge conflicts with its base — author must resolve before merge readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Sep 13, 2026
Chat markdown is input-controlled. Deeply nested constructs parse into a
tree whose depth equals the nesting count, and every recursive layer
downstream -- remark-rehype's mdast->hast transform, rehype-raw's
parse5->hast transform, and MarkdownRenderer's own eight self-recursive
walkers -- recurses to that depth. Past the engine's call-stack limit a
single message throws `RangeError: Maximum call stack size exceeded` and
takes down the whole transcript view.

The tree's depth is decided before any walker runs, at parse time, from the
raw text. So the guard is one input-side clamp at the choke point where a
message enters parsing, rather than a cap inside each of eight vendored
walkers plus the pipeline's own visitors: every downstream walker, present
and future, inherits the guarantee.

`website/src/utils/clampNestingDepth.ts` clamps three spellings of the same
class, each a way to reach a recursive layer:

1. CommonMark container prefixes in any interleaving the spec allows
   (">>>>", ">  >  >" re-opens, "> - > -" quote/list mixes): scanned as
   whole CONTAINER units (up to 3 spaces + quote or list marker,
   sticky-iterated), not as consecutive ">" characters, and bounded per
   line by MAX_BLOCKQUOTE_DEPTH.
2. Progressively indented list items, which no per-line marker count sees:
   bounded by MAX_LIST_INDENT_COLS indent truncation. A marker at end of
   line is an EMPTY item and nests like any other, so the indent clamp
   accepts it exactly as the container scanner does; a run of empty items
   otherwise kept its full indent and built the deep tree unbounded.
3. Raw HTML tag runs (<div><div>...): rehype-raw is wired into both rehype
   pipelines, so embedded HTML parses into HAST the walkers recurse over
   BEFORE sanitization. A conservative model of parse5's open-element stack
   neutralizes opens past MAX_HTML_TAG_DEPTH by rewriting '<' to '&lt;'
   (literal in both micromark and parse5 contexts). Tag names are read by
   the grammar of the context the line is in: micromark's inline-HTML shape
   (letters, digits, '-') outside a block, where anything else makes the
   whole '<...>' literal text; parse5's tokenizer rule inside an HTML block
   (any byte until whitespace, '/' or '>'), where '<x:y>' is a real element
   and reading it with the inline grammar would leave every such open
   uncounted. "Whitespace" there
   is the HTML tokenizer's set -- tab, LF, FF, CR, space -- wider than
   CommonMark's, and it is the set used both to end the name and to accept
   what follows it, or a tag ended by a form feed reads as literal text; NUL
   is a name byte (the tokenizer substitutes U+FFFD and keeps going).

The HTML model errs over-count-only by construction: voids never push;
self-closing spelling on non-voids still opens (per parse5 -- honoring the
slash would under-count); same-name implied-end siblings replace the stack
top (<li> spam is flat); closes pop only on exact top match (bogus closers
cannot drain the counter).

A close tag can also be SPELLED where the tokenizer will not read one, and
every such place has to stop the pop -- otherwise the counter drains one per
open and a run of any length never clamps. Two are lexical: a quoted
attribute value and an inline code span. The code-span mask pairs backtick
runs by EXACT length across the lines of a paragraph, as CommonMark does,
and resets at a paragraph break; a run of any other length inside the span
is literal and leaves the mask on. The mask is over-count-only: it may
suppress a pop, never a rewrite -- an open past the bound is neutralized
whether or not the mask is on, because the mask is a guess that a span is
open and an unpaired backtick run is literal text, so honoring the guess at
the bound would let one stray backtick switch the guard off for the rest of
the paragraph. The rest are spans parse5 makes a single node of, so their
whole body is skipped, latched across lines when the end is not on the
opening one:

- `<!--` is a comment, ending at '-->' or at '--!>', and abruptly on the
  empty spellings '<!-->' and '<!--->'.
- `<?`, any other `<!`, and `</` followed by a non-name are BOGUS COMMENTS,
  each ending at the first '>'. `<![CDATA[` is one of them: the CDATA
  tokenizer state is reachable only inside foreign (SVG/MathML) content,
  which this model does not enter, so ending that span at ']]>' would run it
  PAST the '>' where parse5 ends it.

Ending a span late is the dangerous direction -- it skips tags the parser
does nest, which under-counts and leaves the run unclamped -- so each end
condition is taken from the tokenizer and the search starts two characters
into the opener, which is what makes the abrupt empty-comment spellings end
where the tokenizer ends them. A '<!' inside a code span is literal text
that opens no node, so no latch is taken there: latching would skip the real
tags after the span. And because a latched span's end line can carry no '<'
at all (a bare '-->'), the two fast-path guards that skip a line with no tag
character also run the scan while a latch is open; skipping such a line would
leave the latch set and hide the next line's real tags.

Exemption windows are judged by the downstream parser's semantics, in both
directions. A fenced code block is exempt (marker runs inside a fence are
literal text), and "is this line a fence?" follows micromark's CommonMark
semantics: a backtick fence's info string may not contain a backtick, so
such a line is a paragraph to the parser and opens no exemption window
here. A line opening an HTML BLOCK swallows following lines as raw content
until the block's end condition, so while that latch is open fence-OPEN
recognition is suppressed and container clamps do not apply, while the tag
pass keeps running -- raw block content is exactly what parse5 nests. The
raw-block end condition is a disjunction over all four raw closers, matching
micromark's own continuationRawEndTag, which accepts '</script>' as the end
of a '<pre>' block. Where fence detection is unsure it fails closed (stays
clampable): the worst case is cosmetic clamping of fenced marker art, never
an unclamped deep run reaching the parser.

Clamping stays minimal-mutation: below every bound content is
byte-identical, and a clamped line drifts by one inserted escape byte
(containers) or 3 bytes per neutralized tag (HTML). The API is deliberately
minimal -- `clampNestingDepth(s)` with the bounds as module constants -- so
there are no tunables the single production call site does not use.

The call site is `MarkdownRenderer.tsx` (`MarkdownBlock`), immediately after
the existing stray-tag strip and before any parsing. It runs in both
sourcePos modes: a message that crashes the renderer has no coordinates
worth preserving.

Tests: `MarkdownRenderer.depthGuard.test.tsx`, 44 cases. The overflow
vectors, the pseudo-fence vector and every fake-close spelling fail without
the fix, each independently: reverting the span skip turns the comment and
the PI/declaration cases red with the exact `RangeError`, and reverting
the '--!>' alternative, the malformed-close span, the exact-length span
pairing, the mask-independent neutralization, the raw-context tag-name rule,
the tokenizer whitespace set or the empty-item marker leaves its own vector
completely unclamped. The nested-list fixture is pinned at 600
levels: it is quadratic in depth (~2.3MB at 1,500) and parses well inside
the per-test budget at 600, which still convicts 4.7x past the effective
bound.

The module is listed as a named boundary in website/eslint.i18n.config.js,
alongside unifiedPatchHeaders.ts: every string in it is a grammar token
handed to a parser, never copy, and the raw-block closers are derived from
the names table so the two cannot drift apart.

Co-authored-by: Kiro Crew <noreply@kirodotdev.github.io>
@iamwhatever
iamwhatever force-pushed the fix/markdown-walker-depth-clamp branch from ad183c9 to dda95c5 Compare September 13, 2026 21:46
@iamwhatever

Copy link
Copy Markdown
Contributor

🤖 Kiro Crew [operator: iamwhatever#241cc860]:

  • fixed — parse5-valid form-feed whitespace bypasses the depth clamp (span=828e44fd0ede, clampNestingDepth.ts start-tag terminator check)

Reproduced before fixing at ad183c9: '<div>\n' + '<span\f>'.repeat(5000) and the <span\0> form both throw RangeError: Maximum call stack size exceeded through MarkdownRenderer; <span\r> was already counted; the inline forms are literal text to micromark and do not crash.

Fixed at dda95c5. Raw-context tokenization now uses the HTML tokenizer's whitespace set — tab, LF, FF, CR, space — in BOTH places it is consulted: to end the tag name (isTagNameChar) and to accept what follows it (the terminator check), via one isHtmlWhitespace helper so the two cannot disagree again. NUL is a name byte (the tokenizer substitutes U+FFFD and keeps going), so it no longer ends the name either. Micromark's inline grammar is unchanged outside HTML blocks.
Pinned by a test over the FF, CR and NUL spellings; revert-verified red with the old terminator set.
Class-level ruling: in raw HTML-block content the model's whitespace and name-byte sets are the HTML tokenizer's, applied identically wherever a tag boundary is judged; findings that a tokenizer-accepted byte is mis-classified at one of those boundaries are covered by this rule.

@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention merge conflict Branch has merge conflicts with its base — author must resolve before merge readiness: checking Automated validation is still running labels Sep 13, 2026
@iamwhatever

Copy link
Copy Markdown
Contributor

🤖 Kiro Crew [operator: iamwhatever#241cc860]:

  • accepted-and-deferred — fence repair can expose nesting exempted by the clamp (span=e072207effd8, MarkdownRenderer.tsx MarkdownBlock ordering)

Reproduced at dda95c5: ' ```\n ```X\n' + '>'.repeat(50000) throws RangeError through MarkdownRenderer (the un-indented spellings do not). The finding holds.

Tracked in #10620 (label deferred-finding, assignee, Due: 2026-10-11) with the reproducer and the fix shape you proposed — run fixCodeFences before clampNestingDepth so the clamp judges the fence structure the parser will see.
Not fixed on this PR because the review cap for it is spent: two code rounds after the first re-review, both used on reproduced crashes of this same class. A hardening guard invites an unbounded stream of new spellings, and the cap is the mechanism that ends the loop; this one lands as tracked work with a reproducer rather than as a fifth push.

@iamwhatever

Copy link
Copy Markdown
Contributor

🤖 Kiro Crew [operator: iamwhatever#241cc860]:

  • accepted-and-deferred — HTML void rules undercount foreign-content nesting (span=828e44fd0ede, VOID_ELEMENTS check in clampHtmlLine)

Reproduced at dda95c5: '<svg>\n' + '<base>'.repeat(5000) and the inline form both throw RangeError through MarkdownRenderer; <br> in the same position does not. The finding holds for HTML-only voids that are ordinary elements in SVG/MathML.

Tracked in #10620 (label deferred-finding, assignee, Due: 2026-10-11) with both reproducers and a fix shape: track foreign-content entry on the modeled stack and suspend the void and implied-end rules (honoring the self-closing slash) while svg/math is open — over-count-only, as the rest of the model.
Not fixed on this PR because its review cap is spent (see the sibling record on this head).

@iamwhatever

Copy link
Copy Markdown
Contributor

🤖 Kiro Crew [operator: iamwhatever#241cc860]:

  • accepted-and-deferred — point patch with one counted unfixed sibling (mochi ChatPanel) (span=a077bf70f2a3)

Tracked in #10571 (label deferred-finding, assignee, Due: 2026-10-11). The sibling is real and the issue carries the design: per-segment clamping below parseWidgets at all five <Markdown> sites, because a wrap upstream of widget extraction rewrites <mcwidget> HTML (measured: a 150-deep widget body loses 51 opening tags). That was tried on an earlier head of this PR and reverted. Same ruling as on the two prior heads; this record carries it forward.

@iamwhatever

Copy link
Copy Markdown
Contributor

🤖 Kiro Crew [operator: iamwhatever#241cc860]:

  • accepted-and-deferred — shadow-parser drift: the two bare surfaces need a per-item error boundary so an unmodeled future spelling degrades one item, not the view (span=e77b04f4f435)

Accepted: the guard re-implements CommonMark block grammar and parse5 tokenizer states, and this PR's own review history is the evidence — four rounds each found a spelling the model missed, and #10620 records two more found on this head. Containment is the right complement to the clamp: src/pages/ChannelPage.tsx and src/components/notifications/NotificationDetailPanel.tsx render MarkdownRenderer bare, so an unmodeled spelling there escalates to the app-level boundary.
Deferred to #10620 as its third item (label deferred-finding, assignee, Due: 2026-10-11): wrap those two call sites in MessageErrorBoundary (or the equivalent per-item fallback the chat surfaces already use). It is a separate surface change — two files this PR does not otherwise touch — and this PR's review cap is spent. The drift-pinning half of the concern is already tracked in #10607.

@iamwhatever

Copy link
Copy Markdown
Contributor

🤖 Kiro Crew [operator: iamwhatever#241cc860]:

Agreed and already tracked: #10571 carries a Due: 2026-10-11 line, an assignee and the deferred-finding label, and its body names the fix shape. Nothing further to record on this PR.

@iamwhatever

Copy link
Copy Markdown
Contributor

🤖 Kiro Crew [operator: iamwhatever#241cc860]: Maintainer decision needed — head dda95c5e1b.

This PR was driven under a two-code-round cap after its first re-review (a hardening guard invites an unbounded stream of new bypass spellings). Both rounds were spent on reproduced crashes, and every CI gate except the GPT lane is green on the current head. The GPT lane's final round found two more, both reproduced (RangeError through MarkdownRenderer), and both are now tracked with reproducers and fix shapes in #10620 rather than fixed here.

What this head fixes vs. main (all revert-verified, 44 tests): blockquote / list-indent / raw-HTML depth; fake closes inside attribute values, code spans, comments, CDATA, PIs, declarations and malformed closes; exact-length code-span pairing; mask that never suppresses neutralization; parse5 tag names, tokenizer whitespace and NUL in HTML blocks; empty list items.

What remains (#10620): (1) fixCodeFences runs after the clamp, so an indented glued closer un-exempts a fenced deep run — fix is to reorder the two calls; (2) HTML-only voids (<base>) are ordinary elements inside <svg>/<math> — fix is a foreign-content flag on the modeled stack. Plus (3) per-item error boundaries on the two bare MarkdownRenderer surfaces (ChannelPage, NotificationDetailPanel).

Options:

Design / First Principles CONCERNS on this head are all dispositioned (records above); UX and Opus are clean.

@iamwhatever

Copy link
Copy Markdown
Contributor

🤖 Kiro Crew [operator: iamwhatever#241cc860]: Closing this PR in favor of a different approach. @javenciu — thank you for this work: the problem statement is exactly right, the reproducers are real, and four review rounds here are what made the structural issue below visible. The replacement PR will credit you as co-author.

Why the input-side clamp cannot converge

The clamp rewrites the raw string before parsing, so it has to predict what two parsers (micromark, then parse5 via rehype-raw) will make of the text without running them. That is a shadow parser, and every rule it gets slightly different from the real ones is a bypass in the under-count direction. The empirical record on this PR:

  • 7 bypass spellings found across 4 rounds (comment fake-close, code-span mask, <x:y>, empty list items, \f-terminated tags, fence-repair ordering, SVG foreign-content voids)
  • 2 regressions introduced by fixes (CDATA modeled as ending at ]]>; --!> comment close) — the shadow parser is itself a bug source
  • 2 still open at head dda95c5e1b (fix(chat): two residual nesting-depth clamp bypasses (fence repair ordering, SVG foreign-content voids) #10620), each a reproduced RangeError
  • 772 lines of grammar model, plus the fixCodeFences pass that runs after the clamp and changes the text the clamp judged

What the verification showed

Measured against the pinned versions in website/node_modules:

  • micromark and mdast-util-from-markdown are iterative: remark-parse alone parses 50,000 nested blockquotes without throwing (~12s).
  • The actual crash is unist-util-visit-parents (recursive) inside mdast-util-gfm-autolink-literal's transforms hook — which runs inside parse(), before any unified transformer. That is why a plain remark plugin cannot protect it, but a fromMarkdownExtensions.transforms entry registered before remark-gfm can.
  • On the HTML side, parse5's parser is iterative; the crash is hast-util-from-parse5's recursion inside hast-util-raw, whose parser options are a hardcoded constant (no adapter injection).

The replacement design

Bound depth on the real parser's output, so there is nothing to predict:

  1. mdast bound — a fromMarkdownExtensions.transforms entry, registered ahead of remark-gfm, walks the parsed mdast with an explicit stack and folds subtrees past depth N into a text node. Exact by construction: micromark already decided the structure.
  2. raw-HTML bound — a rehype plugin ahead of rehype-raw runs parse5.parseFragment (iterative) over the tree's serialized HTML as an oracle; if the resulting DOM nests past N, the message's raw nodes are neutralized to text. hast-util-from-parse5 then never sees a deep tree.
  3. Both are pipeline plugins, so mochi's ChatPanel adopts them by adding two entries to MD_REMARK / MD_REHYPE — no text rewriting, so the <mcwidget> corruption that blocked the mochi clamp here (fix(mochi): clamp markdown nesting depth in ChatPanel's own pipeline #10571) does not arise.

Prototype results at the same bounds, ~60 lines total, no grammar modeling: every vector this PR's tests pin plus both #10620 residuals render without throwing; ordinary content is byte-identical through the bounded pipeline.

Out of scope for either PR and tracked separately: micromark's own quadratic cost on multi-megabyte deeply indented lists (~97s for a 1,500-level 2 MB message) is a size problem, not a depth problem, and wants an input-size cap; the two bare MarkdownRenderer surfaces (ChannelPage, NotificationDetailPanel) want a per-item error boundary regardless (#10620, item 3).

Follow-up PR link will be added here once it is open. Issues #10571, #10607 and #10620 will be updated to point at it.

@iamwhatever iamwhatever removed the drive-to-green PR claimed by drive-to-green pipeline label Sep 14, 2026
@github-actions github-actions Bot removed the readiness: action required A blocking check or review needs attention label Sep 14, 2026
@iamwhatever

Copy link
Copy Markdown
Contributor

🤖 Kiro Crew [operator: iamwhatever#241cc860]: Follow-up PR is open: #10753 — "bound markdown nesting depth on the parsed tree, not the text". It bounds depth on the parsed mdast (via a fromMarkdownExtensions.transforms entry ahead of remark-gfm) and on raw HTML with parse5 as an oracle ahead of rehype-raw, plus a lexical whitespace-run cap for micromark's per-line cost. Every bypass vector found here is a test there, and none needed a rule. @javenciu is credited as co-author.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

fork Pull request from a fork (external contributor)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants