diff --git a/.github/scripts/check-production-line-limit.sh b/.github/scripts/check-production-line-limit.sh index a7131b89aa..08729acf1c 100755 --- a/.github/scripts/check-production-line-limit.sh +++ b/.github/scripts/check-production-line-limit.sh @@ -21,6 +21,9 @@ # file drops under the limit, delete its entry in the same PR. # # Usage: check-production-line-limit.sh [ROOT] (default: repo root) +# The pkgs/id flake runs this same script inside its fast lane, with +# ROOT defaulting to the pkgs/id source root, so PR coverage does not +# depend on the separate line-guard workflow's path filters. set -euo pipefail LIMIT=2500 @@ -28,9 +31,6 @@ ROOT="${1:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)}" # path -> removal issue declare -A GRANDFATHERED=( - # 5,325 production lines when the guard landed; split tracked by - # https://github.com/developing-today/code/issues/4704 - ["pkgs/id/src/web/markdown.rs"]="https://github.com/developing-today/code/issues/4704" # 2,504 production lines; the F11.10 file itself, regrown. Split: # https://github.com/developing-today/code/issues/4715 ["pkgs/id/src/cli.rs"]="https://github.com/developing-today/code/issues/4715" diff --git a/.github/scripts/check-production-line-limit.test.sh b/.github/scripts/check-production-line-limit.test.sh index 2f72f585b5..a8a4b5fcd4 100755 --- a/.github/scripts/check-production-line-limit.test.sh +++ b/.github/scripts/check-production-line-limit.test.sh @@ -27,10 +27,10 @@ gen() { # gen [test-lines] mkdir -p "$TMP/ok/pkgs/id/src/web" gen "$TMP/ok/pkgs/id/src/small.rs" 100 gen "$TMP/ok/pkgs/id/src/long_with_tests.rs" 100 5000 -# The real grandfathered path, over the limit: warning, not failure. -gen "$TMP/ok/pkgs/id/src/web/markdown.rs" 3000 +# A remaining grandfathered path, over the limit: warning, not failure. +gen "$TMP/ok/pkgs/id/src/cli.rs" 3000 bash "$SCRIPT" "$TMP/ok" >"$TMP/ok.out" -grep -q "GRANDFATHERED pkgs/id/src/web/markdown.rs" "$TMP/ok.out" +grep -q "GRANDFATHERED pkgs/id/src/cli.rs" "$TMP/ok.out" grep -q "production-line-guard: OK" "$TMP/ok.out" echo "pass: compliant tree passes, grandfather reported" diff --git a/.github/scripts/id-pr-checks.txt b/.github/scripts/id-pr-checks.txt index 856883def8..0dbfd73438 100644 --- a/.github/scripts/id-pr-checks.txt +++ b/.github/scripts/id-pr-checks.txt @@ -29,6 +29,7 @@ taplo-check clippy-lint web-lint cargo-check +production-line-limit test-unit test-shard-0 test-shard-1 diff --git a/.opencode/plans/2026-10-20_phase-11-status.md b/.opencode/plans/2026-10-20_phase-11-status.md index c885ae7a23..451631ec72 100644 --- a/.opencode/plans/2026-10-20_phase-11-status.md +++ b/.opencode/plans/2026-10-20_phase-11-status.md @@ -17,7 +17,7 @@ This document audits the completion status of all eighteen Phase 11 tasks (F11.1 | **F11.7** | Host metrics & tracing | **Planned** | Tracked in roadmap | Actor queue depth, command latency, and Prometheus metrics endpoint. | | **F11.8** | Benchmarks | **Planned** | Tracked in roadmap | Replay, append/fsync, and fan-out benchmarks with committed baselines. | | **F11.9** | Bytes per frame | **Planned** | Tracked in roadmap | Measure full-screen frame sizes at 80x24 and 200x60 across examples. | -| **F11.10** | Split large modules | **Done** | [PR #808](https://github.com/developing-today/code/pull/808) | `world.rs` → `world/{mod,types,core,actor,handle,util,tests}.rs`; `world_session.rs` → `world_session/{mod,types,tests}.rs`. No file over 2,500 production lines. | +| **F11.10** | Split large modules | **In Progress** | [PR #808](https://github.com/developing-today/code/pull/808), [Issue #1438](https://github.com/developing-today/code/issues/1438) | The ID fast lane now includes the `production-line-limit` flake check (shared guard + synthetic contract tests); #1438 splits the regrown `markdown.rs` and removes its grandfather entry. Other corrected-count overages remain tracked in #4715, #4716, and #4717. | | **F11.11** | One client projection | **Done** | [PR #250](https://github.com/developing-today/code/pull/250), [PR #256](https://github.com/developing-today/code/pull/256), [PR #808](https://github.com/developing-today/code/pull/808) | Seed redacted in snapshot/history (#250); single `project_event_for` projection with `history` scope (#256); structural guard pinning the two session serialization sites (#543, PR #808). Host events (#242) open. | | **F11.12** | Journal format management | **Planned** | [Issue #227](https://github.com/developing-today/code/issues/227) | Pre-fix fail-loud rollback check landed in #244. Version header and `check`/`backup` CLI planned. | | **F11.13** | Error taxonomy | **Done** | [PR #808](https://github.com/developing-today/code/pull/808) | `CapError` now carries a stable `CapErrorCode` plus an advisory reason on the wire; `schedule.at` returns the `check_schedule` reason. Codes documented in `world_caps`. | diff --git a/pkgs/id/flake.nix b/pkgs/id/flake.nix index c8c1c6a43a..40bb66e333 100644 --- a/pkgs/id/flake.nix +++ b/pkgs/id/flake.nix @@ -371,6 +371,31 @@ }; doc = mkCheck "doc" "doc"; cargo-check = mkCheck "cargo-check" "cargo-check"; + # F11.10 production module-size guard (#1438): runs the same + # repo-level guard and its synthetic-failure contract tests + # from the ID fast lane. The script is copied from the flake + # root's parent so the check does not depend on the separate + # production-line-guard workflow's path filters. No cargo or + # web build: this is a seconds-long bash/awk scan. + production-line-limit = + pkgs.runCommand "id-production-line-limit" + { + nativeBuildInputs = with pkgs; [ + gawk + findutils + gnugrep + ]; + } + '' + root="$(mktemp -d)" + mkdir -p "$root/pkgs" + cp -r ${./.} "$root/pkgs/id" + cp -r ${../../.github} "$root/.github" + bash "$root/.github/scripts/check-production-line-limit.sh" "$root" + bash "$root/.github/scripts/check-production-line-limit.test.sh" + mkdir -p $out + echo "production-line-limit passed at $(date)" > $out/result.txt + ''; crash-gate = mkCheck "crash-gate" "crash-gate"; # PR-gate splits of crash-gate (#551): the aggregate above runs # every heavy full sweep serially (~15 min, the slowest PR diff --git a/pkgs/id/src/web/markdown.rs b/pkgs/id/src/web/markdown.rs index 25d65aaff2..d00dce412e 100644 --- a/pkgs/id/src/web/markdown.rs +++ b/pkgs/id/src/web/markdown.rs @@ -31,10 +31,21 @@ //! - `link`: Hyperlink with `href` and `title` attributes //! - `strikethrough`: Strikethrough text (GFM `~~text~~`) -use comrak::nodes::{AstNode, ListDelimType, ListType, NodeValue}; -use comrak::{Arena, Options, format_commonmark, parse_document}; +use comrak::{Arena, Options, parse_document}; use serde_json::{Value, json}; +mod markdown_scan; +mod markdown_serialization; +mod parse_helpers; +mod prosemirror_json; + +use self::markdown_scan::*; +#[cfg(test)] +use self::markdown_serialization::json_to_ast; +pub use self::markdown_serialization::prosemirror_to_markdown; +use self::parse_helpers::*; +use self::prosemirror_json::*; + /// Error type for markdown conversion. #[derive(Debug)] pub enum ConversionError { @@ -166,5116 +177,6 @@ fn markdown_to_prosemirror_inner(markdown: &str, recover_orphans: bool) -> Value doc } -/// Fence tracking for the source scans below: a fence opens with a -/// run of >= 3 backticks or tildes and closes only with a run of the -/// SAME character at least as long (CommonMark) -- a three-backtick -/// line inside a four-backtick block is content, not a close (Codex -/// P2 on the first #1565 cut, which toggled on any fence-shaped line). -#[derive(Default)] -struct FenceTracker { - open: Option<(char, usize)>, -} - -/// The line to feed the FenceTracker: a fence delimiter may sit -/// up to three columns in from its container's content edge -/// (CommonMark), but strip_container_prefixes leaves those columns -/// in place (`> ```` arrives as two leading spaces), and -/// FenceTracker::feed anchors the run at the first character -- so -/// an indented opening fence inside a blockquote was missed and -/// the "code" interior was scanned as live text (Codex P2 on -/// #1565's twenty-fourth cut). Removing up to three leading spaces -/// here keeps the four-column distinction: a line still indented -/// after this (or tab-led, which is four columns at column 0) -/// reaches the tracker space-led and opens no fence, exactly like -/// indented code. -fn fence_feed_line(line: &str) -> &str { - let spaces = line.chars().take_while(|&c| c == ' ').count().min(3); - &line[spaces..] -} - -impl FenceTracker { - /// Feed one line (already stripped of up to three leading - /// spaces). Returns true when the line is a fence delimiter. - fn feed(&mut self, stripped: &str) -> bool { - let ch = match stripped.chars().next() { - Some(c @ ('`' | '~')) => c, - _ => return false, - }; - let run = stripped.chars().take_while(|&c| c == ch).count(); - if run < 3 { - return false; - } - if self.open.is_none() && ch == '`' && stripped[run..].contains('`') { - // A backtick fence's info string cannot contain a - // backtick (CommonMark), so a line like ```a`b opens - // no fence at all (Codex P2 on #1565's eighth cut). - return false; - } - match self.open { - None => { - self.open = Some((ch, run)); - true - } - Some((open_ch, open_run)) => { - if ch == open_ch && run >= open_run && stripped[run..].trim().is_empty() { - self.open = None; - true - } else { - false - } - } - } - } - - fn in_fence(&self) -> bool { - self.open.is_some() - } - - /// Forget any open fence: a fence opened inside a container - /// ends implicitly when the container ends, with no closing - /// delimiter line (Codex P2 on #1565's tenth cut). - fn reset(&mut self) { - self.open = None; - } -} - -/// HTML-block tracking for the source scans below (Codex P2 on -/// #1565's second cut): comrak parses a raw HTML block -- a comment, -/// a script/pre/style/textarea element, a block-level tag, or a lone -/// complete tag -- as literal content until its CommonMark end -/// condition (the closing marker for comments/CDATA/PIs/tag-bodies, -/// a blank line for plain block tags). A definition-shaped line in -/// that interior is literal text, exactly as in a fence; without this -/// tracking the pre-scan synthesized a live footnote out of a -/// comment's interior and a save then moved it outside the comment. -#[derive(Default)] -struct HtmlBlockTracker { - /// What ends the open block: a literal closing marker, or a - /// blank line for block-tag (type 6/7) blocks. - end: Option, -} - -#[derive(Clone, Copy, PartialEq)] -enum HtmlBlockEnd { - Marker(&'static str), - BlankLine, -} - -/// The CommonMark type-6 block-level tag names. -const HTML_BLOCK_TAGS: &[&str] = &[ - "address", "article", "aside", "base", "basefont", "blockquote", "body", "caption", "center", - "col", "colgroup", "dd", "details", "dialog", "dir", "div", "dl", "dt", "fieldset", - "figcaption", "figure", "footer", "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", - "h6", "head", "header", "hr", "html", "iframe", "legend", "li", "link", "main", "menu", - "menuitem", "nav", "noframes", "ol", "optgroup", "option", "p", "param", "search", "section", - "summary", "table", "tbody", "td", "tfoot", "th", "thead", "title", "tr", "track", "ul", -]; - -/// Whether `trimmed` (a whole line, both ends trimmed) is exactly -/// one complete HTML open or closing tag -- CommonMark type 7: a -/// tag name (a letter, then letters/digits/`-`), then for an open -/// tag any number of whitespace-separated attributes (a name, with -/// an optional `=` and an unquoted, single-quoted, or -/// double-quoted value), optional whitespace, an optional `/`, -/// and the final `>`. A closing tag is ``. Anything else angle-delimited is NOT a tag: -/// an autolink like `` (the `:` after the -/// name is not whitespace, `/`, or `>`), or a tag-shaped line with -/// junk where an attribute should be. Treating every -/// angle-delimited string as an HTML block opened a -/// blank-line-ended block on the autolink line and swallowed the -/// heading and the valid orphan definition after it (Codex P2 on -/// #1565's seventeenth cut). -fn is_complete_html_tag(trimmed: &str) -> bool { - let bytes = trimmed.as_bytes(); - if bytes.len() < 3 || bytes[0] != b'<' || bytes[bytes.len() - 1] != b'>' { - return false; - } - let inner = &trimmed[1..trimmed.len() - 1]; - let b = inner.as_bytes(); - let (closing, mut pos) = if b.first() == Some(&b'/') { - (true, 1) - } else { - (false, 0) - }; - if !b.get(pos).is_some_and(|c| c.is_ascii_alphabetic()) { - return false; - } - let name_start = pos; - pos += 1; - while b.get(pos).is_some_and(|c| c.is_ascii_alphanumeric() || *c == b'-') { - pos += 1; - } - // Type 1 names never open a type 7 block with an OPENING tag - // (they are handled as marker-ended blocks above); a line - // naming one that reaches here did not match the type-1 - // boundary rule either. The exclusion applies only to opening - // tags: a complete CLOSING tag of any name opens a type-7 - // block, so `` makes the following definition-shaped - // line its literal interior -- rejecting it recovered that - // line as a live definition (Codex P2 on #1565's - // twenty-first cut). - if !closing - && ["script", "pre", "style", "textarea"] - .contains(&inner[name_start..pos].to_ascii_lowercase().as_str()) - { - return false; - } - if closing { - while b.get(pos).is_some_and(|c| c.is_ascii_whitespace()) { - pos += 1; - } - return pos == inner.len(); - } - loop { - let ws_start = pos; - while b.get(pos).is_some_and(|c| c.is_ascii_whitespace()) { - pos += 1; - } - let had_ws = pos > ws_start; - match b.get(pos) { - None => return true, - Some(b'/') => return pos + 1 == inner.len(), - Some(_) if had_ws => { - // Attribute name, then an optional `= value`. - if !b - .get(pos) - .is_some_and(|c| c.is_ascii_alphabetic() || *c == b'_' || *c == b':') - { - return false; - } - pos += 1; - while b.get(pos).is_some_and(|c| { - c.is_ascii_alphanumeric() || matches!(c, b'-' | b'_' | b'.' | b':') - }) { - pos += 1; - } - let mut p2 = pos; - while b.get(p2).is_some_and(|c| c.is_ascii_whitespace()) { - p2 += 1; - } - if b.get(p2) == Some(&b'=') { - p2 += 1; - while b.get(p2).is_some_and(|c| c.is_ascii_whitespace()) { - p2 += 1; - } - match b.get(p2) { - Some(q @ (b'"' | b'\'')) => { - let q = *q; - p2 += 1; - while b.get(p2).is_some_and(|c| *c != q) { - p2 += 1; - } - if b.get(p2).is_none() { - return false; - } - p2 += 1; - } - Some(_) => { - let vstart = p2; - while b.get(p2).is_some_and(|c| { - !c.is_ascii_whitespace() - && !matches!(c, b'"' | b'\'' | b'=' | b'<' | b'>' | b'`') - }) { - p2 += 1; - } - if p2 == vstart { - return false; - } - } - None => return false, - } - pos = p2; - } - } - Some(_) => return false, - } - } -} - -impl HtmlBlockTracker { - fn in_html(&self) -> bool { - self.end.is_some() - } - - /// Forget any open block: a block opened inside a container - /// ends implicitly when the container ends, with no closing - /// line (Codex P2 on #1565's eleventh cut, mirroring - /// FenceTracker::reset). - fn reset(&mut self) { - self.end = None; - } - - /// Feed one line (already stripped of up to three leading - /// spaces). Returns true when the line belongs to an HTML block - /// (its opening line, interior, or closing line). - /// `may_open_type7` is the caller's paragraph context: a type-7 - /// block (a lone complete inline tag) cannot interrupt a - /// paragraph, so when the previous line is paragraph content - /// the caller passes false and a type-7 opening is refused - /// (Codex P2 on #1565's eighteenth cut). Types 1-6 can - /// interrupt a paragraph and are always eligible. - fn feed(&mut self, stripped: &str, may_open_type7: bool) -> bool { - if let Some(end) = self.end { - match end { - HtmlBlockEnd::Marker(marker) => { - if stripped.to_ascii_lowercase().contains(marker) { - self.end = None; - } - } - HtmlBlockEnd::BlankLine => { - if stripped.trim().is_empty() { - self.end = None; - } - } - } - return true; - } - let Some(rest) = stripped.strip_prefix('<') else { - return false; - }; - let lower = stripped.to_ascii_lowercase(); - // Marker-ended blocks (CommonMark types 1-5). The tag-named - // prefixes require a name boundary: `` is not a - // `
` block (nor `` a `"),
-            (""),
-            (""),
-            (""),
-        ] {
-            // The tag-named prefixes follow the CommonMark type-1
-            // boundary exactly: whitespace, '>', or end-of-line
-            // after the name. Anything else (`
`, ``)
-            // is a generic tag block ending at a blank line, not a
-            // marker-ended block (Codex P2 on #1565's tenth cut).
-            let boundary_ok = !prefix[1..].chars().all(|c| c.is_ascii_alphabetic())
-                || match lower.as_bytes().get(prefix.len()) {
-                    None => true,
-                    Some(b) => b.is_ascii_whitespace() || *b == b'>',
-                };
-            // CDATA is case-sensitive (CommonMark): only the
-            // exact uppercase `').
-            if !rest.contains('>') {
-                self.end = Some(HtmlBlockEnd::Marker(">"));
-            }
-            return true;
-        }
-        // Tag-ended blocks (types 6 and 7): a block-level tag, or a
-        // lone complete open/closing tag on the line.
-        let tag_body = rest.strip_prefix('/').unwrap_or(rest);
-        let tag_name: String = tag_body
-            .chars()
-            .take_while(|c| c.is_ascii_alphanumeric() || *c == '-')
-            .collect::()
-            .to_ascii_lowercase();
-        if tag_name.is_empty() {
-            return false;
-        }
-        if HTML_BLOCK_TAGS.contains(&tag_name.as_str())
-            && tag_name_boundary_ok(tag_body, tag_name.len())
-        {
-            self.end = Some(HtmlBlockEnd::BlankLine);
-            return true;
-        }
-        let trimmed = stripped.trim_end();
-        if is_complete_html_tag(trimmed) {
-            if !may_open_type7 {
-                return false;
-            }
-            self.end = Some(HtmlBlockEnd::BlankLine);
-            return true;
-        }
-        let _ = rest;
-        false
-    }
-}
-
-/// Strip block-container prefixes (blockquote `>`, list markers
-/// `-`/`*`/`+`/ordered) from a line, repeatedly, for fence detection:
-/// a fence opened inside a list item or blockquote still makes its
-/// content literal (Codex P2 on #1565's fourth cut -- `- ```` followed
-/// by an indented definition-shaped line parsed as code by comrak,
-/// but the scanner missed the opening fence behind the `- ` marker
-/// and recovered the interior line as a live definition).
-fn strip_container_prefixes(line: &str) -> &str {
-    let mut rest = line;
-    loop {
-        let t = rest.trim_start_matches(' ');
-        if let Some(r) = t.strip_prefix('>') {
-            rest = r.strip_prefix(' ').unwrap_or(r);
-            continue;
-        }
-        let bytes = t.as_bytes();
-        let marker_len = if bytes.len() >= 2
-            && matches!(bytes[0], b'-' | b'*' | b'+')
-            && (bytes[1] == b' ' || bytes[1] == b'\t')
-        {
-            Some(1)
-        } else {
-            let digits = t.chars().take_while(|c| c.is_ascii_digit()).count();
-            if digits >= 1
-                && digits <= 9
-                && matches!(t.as_bytes().get(digits), Some(b'.') | Some(b')'))
-                && matches!(t.as_bytes().get(digits + 1), Some(b' ') | Some(b'\t'))
-            {
-                Some(digits + 1)
-            } else {
-                None
-            }
-        };
-        let Some(marker_len) = marker_len else { break };
-        rest = strip_marker_padding(&t[marker_len..], marker_len);
-    }
-    rest
-}
-
-/// The content after a list marker, CommonMark-style: one to
-/// four columns of padding after the marker are the item's
-/// content indent and are stripped with the marker; FIVE or
-/// more columns mean the content is an indented code block
-/// whose indentation starts after a single padding column, so
-/// only that one column is stripped and the remaining
-/// indentation survives. Removing all the padding turned
-/// `-     ``` ` into a fence opener the document does not have,
-/// and the phantom fence then suppressed the valid reference
-/// definition after it (Codex P2 on #1565's twenty-first cut).
-fn strip_marker_padding(after: &str, marker_end_col: usize) -> &str {
-    let mut col = marker_end_col;
-    let mut end = 0;
-    for c in after.chars() {
-        match c {
-            ' ' => {
-                col += 1;
-                end += 1;
-            }
-            '\t' => {
-                col += 4 - (col % 4);
-                end += 1;
-            }
-            _ => break,
-        }
-    }
-    if col - marker_end_col > 4 {
-        // Keep all but the first padding character (spaces and
-        // tabs are one byte each, so this is a byte offset too).
-        &after[after.chars().next().map_or(0, |_| 1)..]
-    } else {
-        &after[end..]
-    }
-}
-
-/// The container structure of a recorded container prefix, as
-/// a string of marker kinds with all spacing removed: `> ` and
-/// `>` are the same blockquote level, so a fence opened under
-/// one spelling closes under the other (Codex P2 on #1565's
-/// nineteenth cut). Byte-exact prefix matching left such a
-/// fence open and suppressed the definitions after it.
-fn container_signature(prefix: &str) -> String {
-    let mut sig = String::new();
-    let mut rest = prefix;
-    loop {
-        let t = rest.trim_start_matches([' ', '\t']);
-        if let Some(r) = t.strip_prefix('>') {
-            sig.push('>');
-            rest = r;
-            continue;
-        }
-        let bytes = t.as_bytes();
-        if bytes.len() >= 2
-            && matches!(bytes[0], b'-' | b'*' | b'+')
-            && (bytes[1] == b' ' || bytes[1] == b'\t')
-        {
-            sig.push('*');
-            rest = &t[1..];
-            continue;
-        }
-        let digits = t.chars().take_while(|c| c.is_ascii_digit()).count();
-        if digits >= 1
-            && digits <= 9
-            && matches!(t.as_bytes().get(digits), Some(b'.') | Some(b')'))
-            && matches!(t.as_bytes().get(digits + 1), Some(b' ') | Some(b'\t'))
-        {
-            sig.push('#');
-            rest = &t[digits + 1..];
-            continue;
-        }
-        break;
-    }
-    sig
-}
-
-/// Strip at most `levels` container levels (blockquote `>`,
-/// list markers) from a line, mirroring
-/// strip_container_prefixes' per-level shapes.
-fn strip_container_levels(line: &str, levels: usize) -> &str {
-    let mut rest = line;
-    for _ in 0..levels {
-        let t = rest.trim_start_matches(' ');
-        if let Some(r) = t.strip_prefix('>') {
-            rest = r.strip_prefix(' ').unwrap_or(r);
-            continue;
-        }
-        let bytes = t.as_bytes();
-        let marker_len = if bytes.len() >= 2
-            && matches!(bytes[0], b'-' | b'*' | b'+')
-            && (bytes[1] == b' ' || bytes[1] == b'\t')
-        {
-            Some(1)
-        } else {
-            let digits = t.chars().take_while(|c| c.is_ascii_digit()).count();
-            if digits >= 1
-                && digits <= 9
-                && matches!(t.as_bytes().get(digits), Some(b'.') | Some(b')'))
-                && matches!(t.as_bytes().get(digits + 1), Some(b' ') | Some(b'\t'))
-            {
-                Some(digits + 1)
-            } else {
-                None
-            }
-        };
-        let Some(marker_len) = marker_len else { break };
-        rest = strip_marker_padding(&t[marker_len..], marker_len);
-    }
-    rest
-}
-
-/// Whether `stripped` (a line stripped of up to three leading
-/// spaces) carries the recorded container `prefix`, matched
-/// STRUCTURALLY rather than byte-for-byte: the line's own
-/// leading container levels (as many as the recorded prefix
-/// has) must have the same signature as the recorded prefix.
-fn carries_container_prefix(stripped: &str, prefix: &str) -> bool {
-    if prefix.is_empty() {
-        return false;
-    }
-    let levels = container_signature(prefix).chars().count();
-    if levels == 0 {
-        return false;
-    }
-    let own = &stripped[..stripped.len() - strip_container_levels(stripped, levels).len()];
-    !own.is_empty() && container_signature(own) == container_signature(prefix)
-}
-
-/// A footnote definition block found by the source pre-scan (#1565):
-/// its label and the block's verbatim source (the `[^label]:` line
-/// plus any indented continuation lines, trailing blank lines cut).
-struct FootnoteDefinitionBlock {
-    label: String,
-    source: String,
-    /// Zero-based line index of the definition's opening line, for
-    /// interleaving with other source segments in document order.
-    line: usize,
-}
-
-/// The label of a footnote definition starting on `line` (already
-/// stripped of up to three leading spaces), or `None` when the line
-/// does not start one. A definition opens as `[^label]:`.
-fn footnote_definition_label(line: &str) -> Option {
-    let rest = line.strip_prefix("[^")?;
-    // The label ends at the FIRST ']' and a ':' must follow it
-    // immediately. Searching for "]:" instead accepted `a]b` as the
-    // label of `[^a]b]: note` -- a definition comrak does not
-    // recognize, whose probe then looped recovery forever (Codex P1).
-    let close = rest.find(']')?;
-    if !rest[close + 1..].starts_with(':') {
-        return None;
-    }
-    let label = &rest[..close];
-    if label.is_empty() || label.contains('[') {
-        return None;
-    }
-    Some(label.to_string())
-}
-
-/// A thematic break: at least three of the same `-`, `*`, or `_`,
-/// spaces and tabs aside (CommonMark).
-fn is_thematic_break(stripped: &str) -> bool {
-    let compact: String = stripped
-        .chars()
-        .filter(|c| *c != ' ' && *c != '\t')
-        .collect();
-    let first = compact.chars().next();
-    compact.len() >= 3
-        && matches!(first, Some('-' | '*' | '_'))
-        && compact.chars().all(|c| Some(c) == first)
-}
-
-/// A setext heading underline: only `=`s (level 1) or `-`s (level 2).
-fn is_setext_underline(stripped: &str) -> bool {
-    let t = stripped.trim();
-    (!t.is_empty() && t.chars().all(|c| c == '='))
-        || (!t.is_empty() && t.chars().all(|c| c == '-'))
-}
-
-/// Whether a line starts a new block and so cannot be a lazy
-/// paragraph continuation of a footnote definition: another
-/// definition, an ATX heading, a fence, a blockquote, a thematic
-/// break, an HTML block opener, or a list/blockquote container line.
-/// Whether a line is an ATX heading: 1-6 `#`s followed by a
-/// space, a tab, or end-of-line (CommonMark). `#hashtag` is
-/// paragraph text, not a heading (Codex P2 on #1565's tenth cut).
-fn is_atx_heading(stripped: &str) -> bool {
-    let hashes = stripped.bytes().take_while(|&b| b == b'#').count();
-    (1..=6).contains(&hashes)
-        && matches!(stripped.as_bytes().get(hashes), None | Some(b' ') | Some(b'\t'))
-}
-
-
-/// Whether the character after a block-level tag name is a valid
-/// name boundary: whitespace, `/`, `>`, or end-of-line (CommonMark
-/// type 6). `` has no boundary after `div`, so it is
-/// literal paragraph text, not an HTML block (Codex P2 on
-/// #1565's sixteenth cut).
-fn tag_name_boundary_ok(tag_body: &str, name_len: usize) -> bool {
-    matches!(
-        tag_body.as_bytes().get(name_len),
-        None | Some(b' ') | Some(b'\t') | Some(b'>') | Some(b'/')
-    )
-}
-
-/// Whether a line opens an HTML block that can INTERRUPT a
-/// paragraph (CommonMark types 1-6): a comment, a CDATA section,
-/// a processing instruction, a declaration, a script/pre/style/
-/// textarea element, or a block-level tag (opening or closing).
-/// A lone inline tag (``, ``) is type 7, which cannot
-/// interrupt a paragraph: as a footnote definition's next line it
-/// is a lazy continuation of the definition's paragraph, not a
-/// new block (Codex P2 on #1565's eleventh cut).
-fn is_html_block_start(stripped: &str) -> bool {
-    let Some(rest) = stripped.strip_prefix('<') else {
-        return false;
-    };
-    let lower = stripped.to_ascii_lowercase();
-    if lower.starts_with(" comments, and the split sibling lists this
-        // change emits are adjacent by construction - so on reparse the
-        // separator comes back as an HtmlBlock between the lists. It is
-        // a separator, not content: drop it when a neighbouring sibling
-        // is a list. An authored  comment NOT next to
-        // a list still converts exactly as before (an htmlBlock
-        // code_block, #982).
-        if is_end_list_separator(child)
-            && ((idx > 0 && matches!(children[idx - 1].data.borrow().value, NodeValue::List(_)))
-                || children
-                    .get(idx + 1)
-                    .is_some_and(|c| matches!(c.data.borrow().value, NodeValue::List(_))))
-        {
-            continue;
-        }
-        if matches!(child.data.borrow().value, NodeValue::List(_)) {
-            // #1370: a list converts to one or more sibling lists.
-            out.extend(convert_list_runs(child));
-        } else {
-            let converted = convert_node(child, &[]);
-            if !converted.is_null() {
-                out.push(converted);
-            }
-        }
-    }
-    out
-}
-
-/// True for the HtmlBlock comrak's renderer emits between adjacent
-/// lists (see collect_block_children).
-fn is_end_list_separator<'a>(node: &'a AstNode<'a>) -> bool {
-    match &node.data.borrow().value {
-        NodeValue::HtmlBlock(html) => html.literal.trim() == "",
-        _ => false,
-    }
-}
-
-/// Convert a comrak list node to one or more ProseMirror list nodes.
-///
-/// A pure list converts exactly as before (#997/#1036 attrs carried from
-/// the source list). #1370: a list mixing task items with plain items
-/// used to take its type from the first child only and convert the rest
-/// by their own kind, producing a `task_list` holding a `list_item` (or
-/// a plain list holding a `task_list_item`) - a shape the save-side
-/// placement validation and the editor schema both forbid, so the
-/// document could not be saved at all. Instead, group the items into
-/// runs of one kind and emit one sibling list per run, in source order.
-/// Ordered runs carry an `order` start offset by the items before them
-/// so numbering renders unchanged; `tight` is carried from the source
-/// list to every run. Placement validation and the editor schema are
-/// untouched: every emitted list is pure.
-/// #1380: the PM `delimiter` attr spelling for a comrak ordered-list
-/// delimiter (`.` vs `)`). The editor schema mirrors these spellings.
-fn delimiter_attr(delimiter: ListDelimType) -> &'static str {
-    match delimiter {
-        ListDelimType::Period => "period",
-        ListDelimType::Paren => "paren",
-    }
-}
-
-/// #1380: read the PM `delimiter` attr back to a comrak delimiter.
-/// Absent or unknown (legacy PM docs stored by the old codec, which
-/// dropped the delimiter) defaults to Period - exactly how the old
-/// codec saved every ordered list.
-fn delimiter_from_attrs(json: &Value) -> ListDelimType {
-    match json["attrs"]["delimiter"].as_str() {
-        Some("paren") => ListDelimType::Paren,
-        _ => ListDelimType::Period,
-    }
-}
-
-fn convert_list_runs<'a>(node: &'a AstNode<'a>) -> Vec {
-    let (list_type, start, tight, delimiter) = match &node.data.borrow().value {
-        NodeValue::List(list) => (list.list_type, list.start, list.tight, list.delimiter),
-        _ => return Vec::new(),
-    };
-    // (is_task, items before this run, converted items)
-    let mut runs: Vec<(bool, usize, Vec)> = Vec::new();
-    let mut seen = 0usize;
-    for child in node.children() {
-        let is_task = matches!(child.data.borrow().value, NodeValue::TaskItem(_));
-        let item = convert_node(child, &[]);
-        if item.is_null() {
-            continue;
-        }
-        match runs.last_mut() {
-            Some((kind, _, items)) if *kind == is_task => items.push(item),
-            _ => runs.push((is_task, seen, vec![item])),
-        }
-        seen += 1;
-    }
-    runs.into_iter()
-        .map(|(is_task, offset, content)| match (is_task, list_type) {
-            (true, ListType::Ordered) => json!({
-                "type": "task_list",
-                "attrs": {"order": start + offset, "tight": tight, "delimiter": delimiter_attr(delimiter)},
-                "content": content
-            }),
-            (true, ListType::Bullet) => json!({
-                "type": "task_list",
-                "attrs": {"tight": tight},
-                "content": content
-            }),
-            (false, ListType::Ordered) => json!({
-                "type": "ordered_list",
-                "attrs": {"order": start + offset, "tight": tight, "delimiter": delimiter_attr(delimiter)},
-                "content": content
-            }),
-            (false, ListType::Bullet) => json!({
-                "type": "bullet_list",
-                "attrs": {"tight": tight},
-                "content": content
-            }),
-        })
-        .collect()
-}
-
-/// Collect list item children of a list node.
-fn collect_list_items<'a>(node: &'a AstNode<'a>) -> Vec {
-    node.children()
-        .map(|child| convert_node(child, &[]))
-        .filter(|v| !v.is_null())
-        .collect()
-}
-
-/// The literal of an `HtmlInline` node, if `node` is one.
-fn html_inline_literal<'a>(node: &'a AstNode<'a>) -> Option {
-    if let NodeValue::HtmlInline(html) = &node.data.borrow().value {
-        Some(html.clone())
-    } else {
-        None
-    }
-}
-
-/// Detect the split sized-linked-image sequence at the head of `children`
-/// (#893): an `` `HtmlInline`, an `` `HtmlInline`,
-/// and the closing `` `HtmlInline`. Comrak splits the HTML form the
-/// save direction emits for a sized linked image into those three sibling
-/// nodes; merged here they become one image node carrying `linkHref`, and
-/// neither anchor piece falls through as literal text. The closing tag is
-/// optional in the match (consumed when present) so a missing one cannot
-/// strand the opening tag as text either. Returns the merged image node
-/// and how many siblings it consumed.
-fn linked_image_sequence<'a>(children: &[&'a AstNode<'a>]) -> Option<(Value, usize)> {
-    if children.len() < 2 {
-        return None;
-    }
-    let (href, link_title) = parse_anchor_tag(&html_inline_literal(children[0])?)?;
-    let img = parse_img_tag(&html_inline_literal(children[1])?)?;
-    let consumed = if children.len() >= 3
-        && html_inline_literal(children[2]).is_some_and(|h| h.trim().eq_ignore_ascii_case(""))
-    {
-        3
-    } else {
-        2
-    };
-    Some((image_with_link(img, &href, link_title.as_deref()), consumed))
-}
-
-/// Collect inline children of a node, flattening nested mark wrappers.
-fn collect_inline_children<'a>(node: &'a AstNode<'a>, active_marks: &[Mark]) -> Vec {
-    let mut result = Vec::new();
-    let children: Vec<&AstNode<'a>> = node.children().collect();
-    let mut index = 0;
-
-    while index < children.len() {
-        // #893: merge a split  sequence before the pieces
-        // are converted individually (see linked_image_sequence).
-        if let Some((img, consumed)) = linked_image_sequence(&children[index..]) {
-            result.push(img);
-            index += consumed;
-            continue;
-        }
-
-        let child = children[index];
-        index += 1;
-        let child_data = child.data.borrow();
-
-        // Check if this is a mark wrapper (Emph, Strong, Link)
-        let is_mark_wrapper = matches!(
-            child_data.value,
-            NodeValue::Emph | NodeValue::Strong | NodeValue::Link(_) | NodeValue::Strikethrough
-        );
-        drop(child_data);
-
-        let converted = convert_node(child, active_marks);
-        if is_mark_wrapper {
-            // Convert returns an array of children with marks applied
-            if let Some(arr) = converted.as_array() {
-                for item in arr {
-                    if !item.is_null() {
-                        result.push(item.clone());
-                    }
-                }
-            }
-        } else if !converted.is_null() {
-            result.push(converted);
-        }
-    }
-
-    result
-}
-
-/// Get all text content from a node and its descendants.
-fn get_text_content<'a>(node: &'a AstNode<'a>) -> String {
-    let mut text = String::new();
-    collect_text(node, &mut text);
-    text
-}
-
-/// Recursively collect text from a node.
-fn collect_text<'a>(node: &'a AstNode<'a>, text: &mut String) {
-    let data = node.data.borrow();
-
-    match &data.value {
-        NodeValue::Text(t) => text.push_str(t.as_ref()),
-        NodeValue::Code(c) => text.push_str(&c.literal),
-        NodeValue::SoftBreak => text.push(' '),
-        NodeValue::LineBreak => text.push('\n'),
-        _ => {
-            drop(data);
-            for child in node.children() {
-                collect_text(child, text);
-            }
-        }
-    }
-}
-
-/// #1417: serialize an image alt subtree back to markdown form.
-///
-/// The inverse of the save direction's alt re-parse: emphasis, strong,
-/// strikethrough, code spans and links keep their markup; literal text
-/// is escaped so characters that were literal in the source (e.g. an
-/// escaped `\\*`) stay literal when the stored form is re-parsed on
-/// save. Nested images/links inside an alt are serialized recursively,
-/// so a nested-link alt round-trips instead of flattening.
-fn get_alt_markdown<'a>(node: &'a AstNode<'a>) -> String {
-    let mut out = String::new();
-    for child in node.children() {
-        collect_alt_markdown(child, &mut out);
-    }
-    out
-}
-
-fn collect_alt_markdown<'a>(node: &'a AstNode<'a>, out: &mut String) {
-    let data = node.data.borrow();
-    match &data.value {
-        NodeValue::Text(t) => {
-            for ch in t.chars() {
-                if matches!(ch, '\\' | '*' | '_' | '`' | '[' | ']') {
-                    out.push('\\');
-                }
-                out.push(ch);
-            }
-        }
-        NodeValue::Code(c) => {
-            // Fence with one more backtick than the longest run inside.
-            let longest = c
-                .literal
-                .split(|ch| ch != '`')
-                .map(str::len)
-                .max()
-                .unwrap_or(0);
-            let fence = "`".repeat(longest + 1);
-            out.push_str(&fence);
-            if c.literal.starts_with('`') || c.literal.ends_with('`') {
-                out.push(' ');
-                out.push_str(&c.literal);
-                out.push(' ');
-            } else {
-                out.push_str(&c.literal);
-            }
-            out.push_str(&fence);
-        }
-        NodeValue::SoftBreak => out.push(' '),
-        NodeValue::LineBreak => out.push('\n'),
-        NodeValue::HtmlInline(html) => out.push_str(html),
-        NodeValue::Emph => {
-            drop(data);
-            out.push('*');
-            for child in node.children() {
-                collect_alt_markdown(child, out);
-            }
-            out.push('*');
-        }
-        NodeValue::Strong => {
-            drop(data);
-            out.push_str("**");
-            for child in node.children() {
-                collect_alt_markdown(child, out);
-            }
-            out.push_str("**");
-        }
-        NodeValue::Strikethrough => {
-            drop(data);
-            out.push_str("~~");
-            for child in node.children() {
-                collect_alt_markdown(child, out);
-            }
-            out.push_str("~~");
-        }
-        NodeValue::Link(link) => {
-            let url = link.url.clone();
-            let title = link.title.clone();
-            drop(data);
-            out.push('[');
-            for child in node.children() {
-                collect_alt_markdown(child, out);
-            }
-            out.push_str("](");
-            out.push_str(&url);
-            if !title.is_empty() {
-                out.push_str(" \"");
-                out.push_str(&title.replace('"', "\\\""));
-                out.push_str("\"");
-            }
-            out.push(')');
-        }
-        NodeValue::Image(link) => {
-            let url = link.url.clone();
-            let title = link.title.clone();
-            drop(data);
-            out.push_str("![");
-            for child in node.children() {
-                collect_alt_markdown(child, out);
-            }
-            out.push_str("](");
-            out.push_str(&url);
-            if !title.is_empty() {
-                out.push_str(" \"");
-                out.push_str(&title.replace('"', "\\\""));
-                out.push_str("\"");
-            }
-            out.push(')');
-        }
-        _ => {
-            drop(data);
-            for child in node.children() {
-                collect_alt_markdown(child, out);
-            }
-        }
-    }
-}
-
-/// #1417: re-parse a stored markdown-form alt into inline AST nodes in
-/// `arena` (the save direction). Returns the paragraph's children,
-/// detached and ready to append under an Image node. Falls back to a
-/// single plain Text node when the alt does not parse to a paragraph
-/// (defensive; plain alts parse to exactly that anyway).
-fn alt_markdown_to_nodes<'a>(arena: &'a Arena<'a>, alt: &str) -> Vec<&'a AstNode<'a>> {
-    let options = commonmark_options();
-    let root = parse_document(arena, alt, &options);
-    if let Some(paragraph) = root
-        .children()
-        .find(|n| matches!(n.data.borrow().value, NodeValue::Paragraph))
-    {
-        let nodes: Vec<&'a AstNode<'a>> = paragraph.children().collect();
-        for n in &nodes {
-            n.detach();
-        }
-        if !nodes.is_empty() {
-            return nodes;
-        }
-    }
-    vec![&*arena.alloc(AstNode::from(NodeValue::Text(alt.to_owned().into())))]
-}
-
-/// Escape a value for a double-quoted HTML attribute (#873): `&` first, so
-/// the entities introduced here are not themselves re-escaped, then the
-/// quote that would terminate the value, and `<`.
-fn escape_attr_value(value: &str) -> String {
-    value
-        .replace('&', "&")
-        .replace('"', """)
-        .replace('<', "<")
-}
-
-/// Decode the entities [`escape_attr_value`] can emit (plus `>`/`'`
-/// and numeric single-quote) in one left-to-right pass, so `&quot;`
-/// decodes to the literal text `"`, never to `"`.
-fn decode_attr_entities(value: &str) -> String {
-    if !value.contains('&') {
-        return value.to_owned();
-    }
-    let mut out = String::with_capacity(value.len());
-    let mut rest = value;
-    while let Some(idx) = rest.find('&') {
-        out.push_str(&rest[..idx]);
-        let tail = &rest[idx..];
-        let (decoded, len) = if let Some(t) = tail.strip_prefix(""") {
-            ('"', tail.len() - t.len())
-        } else if let Some(t) = tail.strip_prefix("&") {
-            ('&', tail.len() - t.len())
-        } else if let Some(t) = tail.strip_prefix("<") {
-            ('<', tail.len() - t.len())
-        } else if let Some(t) = tail.strip_prefix(">") {
-            ('>', tail.len() - t.len())
-        } else if let Some(t) = tail.strip_prefix("'") {
-            ('\'', tail.len() - t.len())
-        } else if let Some(t) = tail.strip_prefix("'") {
-            ('\'', tail.len() - t.len())
-        } else {
-            out.push('&');
-            rest = &tail[1..];
-            continue;
-        };
-        out.push(decoded);
-        rest = &tail[len..];
-    }
-    out.push_str(rest);
-    out
-}
-
-/// Parse the attributes of an HTML tag, starting just past its ` std::collections::HashMap {
-    let bytes = html.as_bytes();
-    let mut pos = tag_len;
-    let mut map = std::collections::HashMap::new();
-    while pos < bytes.len() {
-        // Skip separators between attributes (whitespace, '/' of '/>').
-        while pos < bytes.len() && (bytes[pos].is_ascii_whitespace() || bytes[pos] == b'/') {
-            pos += 1;
-        }
-        if pos >= bytes.len() || bytes[pos] == b'>' {
-            break;
-        }
-        // Attribute name: up to '=', whitespace, '/' or '>'.
-        let name_start = pos;
-        while pos < bytes.len()
-            && !bytes[pos].is_ascii_whitespace()
-            && !matches!(bytes[pos], b'=' | b'/' | b'>')
-        {
-            pos += 1;
-        }
-        if pos == name_start {
-            break;
-        }
-        let name = html[name_start..pos].to_ascii_lowercase();
-        while pos < bytes.len() && bytes[pos].is_ascii_whitespace() {
-            pos += 1;
-        }
-        let mut value = String::new();
-        if pos < bytes.len() && bytes[pos] == b'=' {
-            pos += 1;
-            while pos < bytes.len() && bytes[pos].is_ascii_whitespace() {
-                pos += 1;
-            }
-            if pos < bytes.len() && matches!(bytes[pos], b'"' | b'\'') {
-                let quote = bytes[pos];
-                pos += 1;
-                let value_start = pos;
-                while pos < bytes.len() && bytes[pos] != quote {
-                    pos += 1;
-                }
-                value = decode_attr_entities(&html[value_start..pos]);
-                if pos < bytes.len() {
-                    pos += 1; // closing quote
-                }
-            } else {
-                let value_start = pos;
-                while pos < bytes.len() && !bytes[pos].is_ascii_whitespace() && bytes[pos] != b'>' {
-                    pos += 1;
-                }
-                value = decode_attr_entities(&html[value_start..pos]);
-            }
-        }
-        // First occurrence wins (HTML duplicate-attribute rule).
-        map.entry(name).or_insert(value);
-    }
-    map
-}
-
-/// Parse an `` width/height value into a pixel count (#2180,
-/// grammar pinned by triage task 3225). The whole stack is
-/// numeric-pixel -- the PM node stores a JSON number, the emitter
-/// writes bare integers, the editor renders `${width}px` -- so only
-/// lossless normalizations are accepted: trim surrounding
-/// whitespace, strip ONE trailing `px` suffix (ASCII
-/// case-insensitive), then the rest must be a pixel integer, where a
-/// decimal form counts only when its value is exactly integral
-/// (`200.0` -> 200, `200.5` refused). Percents, other units, and
-/// junk return `None`; the caller warns instead of dropping the
-/// value silently, as the pre-#2180 bare-`u64` parse did.
-fn parse_integral_decimal(raw: &str) -> Option {
-    let (negative, raw) = if let Some(raw) = raw.strip_prefix('-') {
-        (true, raw)
-    } else {
-        (false, raw.strip_prefix('+').unwrap_or(raw))
-    };
-
-    let (mantissa, exponent) = if let Some(index) = raw.find(|ch| matches!(ch, 'e' | 'E')) {
-        (&raw[..index], raw[index + 1..].parse::().ok()?)
-    } else {
-        (raw, 0)
-    };
-    let (integer, fractional) = mantissa.split_once('.').unwrap_or((mantissa, ""));
-    if integer.is_empty() && fractional.is_empty() {
-        return None;
-    }
-    if !integer.bytes().all(|byte| byte.is_ascii_digit())
-        || !fractional.bytes().all(|byte| byte.is_ascii_digit())
-    {
-        return None;
-    }
-
-    let mut digits = String::with_capacity(integer.len() + fractional.len());
-    digits.push_str(integer);
-    digits.push_str(fractional);
-    let significant = digits.trim_start_matches('0');
-    if significant.is_empty() {
-        // Keep the exact zero spellings accepted by the former float parser,
-        // including -0.0, without converting through f64.
-        return Some(0);
-    }
-
-    let fractional_digits = i32::try_from(fractional.len()).ok()?;
-    let scale = exponent.checked_sub(fractional_digits)?;
-    let integer = if scale >= 0 {
-        let trailing_zeroes = usize::try_from(scale).ok()?;
-        if significant.len().checked_add(trailing_zeroes)? > 20 {
-            return None;
-        }
-        let mut integer = String::with_capacity(significant.len() + trailing_zeroes);
-        integer.push_str(significant);
-        integer.push_str(&"0".repeat(trailing_zeroes));
-        integer.parse::().ok()?
-    } else {
-        let trailing_zeroes = usize::try_from(scale.checked_neg()?).ok()?;
-        if trailing_zeroes > significant.len() {
-            return None;
-        }
-        let split = significant.len() - trailing_zeroes;
-        if significant[split..].bytes().any(|byte| byte != b'0') {
-            return None;
-        }
-        significant[..split].parse::().ok()?
-    };
-
-    if negative && integer != 0 {
-        return None;
-    }
-    Some(integer)
-}
-
-fn parse_dimension(raw: &str) -> Option {
-    let trimmed = raw.trim();
-    // Byte-wise suffix check: slicing the string at len()-2 to test
-    // the suffix would panic when that offset falls inside a multibyte
-    // UTF-8 character (e.g. fullwidth digits). When the last two bytes
-    // are the ASCII bytes p/x, len()-2 is a char boundary, so the
-    // slice below is safe.
-    let bytes = trimmed.as_bytes();
-    let body = if bytes.len() >= 2 && bytes[bytes.len() - 2..].eq_ignore_ascii_case(b"px") {
-        &trimmed[..trimmed.len() - 2]
-    } else {
-        trimmed
-    };
-    if let Ok(n) = body.parse::() {
-        return Some(n);
-    }
-    parse_integral_decimal(body)
-}
-
-/// Parse an HTML `` tag and extract attributes into a `ProseMirror` image node.
-///
-/// Returns `Some(json)` if the input looks like ``, otherwise `None`.
-fn find_ascii_case_insensitive(haystack: &str, needle: &[u8]) -> Option {
-    haystack
-        .as_bytes()
-        .windows(needle.len())
-        .position(|candidate| candidate.eq_ignore_ascii_case(needle))
-}
-
-fn parse_img_tag(html: &str) -> Option {
-    let trimmed = html.trim();
-    let bytes = trimmed.as_bytes();
-    if !bytes
-        .get(..4)
-        .is_some_and(|prefix| prefix.eq_ignore_ascii_case(b"'))
-    {
-        return None;
-    }
-
-    let parsed = parse_tag_attrs(trimmed, 4);
-    let attr = |name: &str| parsed.get(name).map(String::as_str);
-
-    let src = attr("src")?; // src is required
-    let mut attrs = json!({"src": src});
-
-    if let Some(alt) = attr("alt") {
-        attrs["alt"] = json!(alt);
-    }
-    if let Some(title) = attr("title") {
-        attrs["title"] = json!(title);
-    }
-    if let Some(w) = attr("width") {
-        match parse_dimension(w) {
-            Some(n) => attrs["width"] = json!(n),
-            None => tracing::warn!("dropping unsupported image width {w:?} in  import"),
-        }
-    }
-    if let Some(h) = attr("height") {
-        match parse_dimension(h) {
-            Some(n) => attrs["height"] = json!(n),
-            None => tracing::warn!("dropping unsupported image height {h:?} in  import"),
-        }
-    }
-
-    Some(json!({
-        "type": "image",
-        "attrs": attrs
-    }))
-}
-
-/// Parse an HTML `` opening tag, returning its `href` and optional
-/// `title`. Returns `None` for anything else, including an anchor with no
-/// (or an empty) `href`.
-fn parse_anchor_tag(html: &str) -> Option<(String, Option)> {
-    let trimmed = html.trim();
-    let after_name = trimmed.as_bytes().get(2).copied()?;
-    if !trimmed
-        .as_bytes()
-        .get(..2)
-        .is_some_and(|prefix| prefix.eq_ignore_ascii_case(b"')
-    {
-        return None;
-    }
-    let parsed = parse_tag_attrs(trimmed, 2);
-    let href = parsed.get("href")?;
-    if href.is_empty() {
-        return None;
-    }
-    let title = parsed.get("title").filter(|t| !t.is_empty()).cloned();
-    Some((href.clone(), title))
-}
-
-/// Attach a wrapping anchor's link to an image node (#880/#893), in the
-/// same `linkHref`/`linkTitle` attrs the markdown `Image` arm produces.
-fn image_with_link(mut img: Value, href: &str, link_title: Option<&str>) -> Value {
-    img["attrs"]["linkHref"] = json!(href);
-    if let Some(title) = link_title {
-        img["attrs"]["linkTitle"] = json!(title);
-    }
-    img
-}
-
-/// Parse the combined `` form (#893) — the
-/// sized linked image emission when comrak keeps it in a single literal
-/// (e.g. an `HtmlBlock`) instead of splitting it into sibling `HtmlInline`
-/// nodes (that split form is merged in `collect_inline_children`).
-fn parse_linked_img_tag(html: &str) -> Option {
-    let trimmed = html.trim();
-    let (href, link_title) = parse_anchor_tag(trimmed)?;
-    let img_start = find_ascii_case_insensitive(trimmed, b"')
-        || find_ascii_case_insensitive(&trimmed[img_start..], b"").is_none()
-    {
-        return None;
-    }
-    let img = parse_img_tag(&trimmed[img_start..])?;
-    Some(image_with_link(img, &href, link_title.as_deref()))
-}
-
-/// Placement categories for the #1043 validation walk. A node whose type
-/// is not listed here is left to `json_to_ast`, which reports it as
-/// `ConversionError::UnknownType` — validation never masks that error.
-/// (`front_matter` is intentionally unlisted: its doc-first-child rule
-/// needs the child index, so `validate_placement` checks it directly.)
-#[derive(Clone, Copy, PartialEq, Eq)]
-enum Placement {
-    /// Block-level node (`paragraph`, `table`, lists, …).
-    Block,
-    /// Inline node (`text`, `image`, `hard_break`, …).
-    Inline,
-    /// `list_item` — only legal directly inside a bullet/ordered list.
-    ListItem,
-    /// `task_list_item` — only legal directly inside a `task_list`.
-    TaskListItem,
-    /// `table_row` — only legal directly inside a `table`.
-    TableRow,
-    /// `table_header` / `table_cell` — only legal inside a `table_row`.
-    TableCell,
-}
-
-fn placement_of(node_type: &str) -> Option {
-    match node_type {
-        "paragraph"
-        | "heading"
-        | "blockquote"
-        | "code_block"
-        | "horizontal_rule"
-        | "bullet_list"
-        | "ordered_list"
-        | "task_list"
-        | "table"
-        | "footnote_definition" => Some(Placement::Block),
-        "text" | "image" | "hard_break" | "html_inline" | "footnote_reference" => {
-            Some(Placement::Inline)
-        }
-        "list_item" => Some(Placement::ListItem),
-        "task_list_item" => Some(Placement::TaskListItem),
-        "table_row" => Some(Placement::TableRow),
-        "table_header" | "table_cell" => Some(Placement::TableCell),
-        _ => None,
-    }
-}
-
-/// Whether a child of category `child` may appear directly inside a
-/// parent of type `parent`. Mirrors the comrak AST containment rules for
-/// the node kinds this codec emits, at the `ProseMirror` level.
-fn placement_allowed(parent: &str, child: Placement) -> bool {
-    match parent {
-        // The document and block containers hold blocks only.
-        "doc" | "blockquote" | "list_item" | "task_list_item" => child == Placement::Block,
-        // Inline containers hold inline content only.
-        "paragraph" | "heading" => child == Placement::Inline,
-        "bullet_list" | "ordered_list" => child == Placement::ListItem,
-        "task_list" => child == Placement::TaskListItem,
-        "table" => child == Placement::TableRow,
-        "table_row" => child == Placement::TableCell,
-        // PM table cells wrap blocks (unwrapped during conversion) and
-        // footnote definitions carry inline content on the PM side
-        // (re-wrapped during conversion, #945); both shapes are legal.
-        "table_header" | "table_cell" | "footnote_definition" => {
-            child == Placement::Block || child == Placement::Inline
-        }
-        "code_block" => false,
-        // Inline leaves and anything unlisted impose no child rules here;
-        // structural surprises inside them are json_to_ast's to report.
-        _ => true,
-    }
-}
-
-/// Validate block/inline placement over a `ProseMirror` document before
-/// conversion (#1043). `json_to_ast` places any known node type anywhere;
-/// a misplaced node (a `text` node directly under `doc`, a `paragraph`
-/// inside a `paragraph`, …) produces an ill-formed comrak AST that
-/// panics the formatter in debug builds and silently emits invalid
-/// markdown in release builds. Reject those documents up front with
-/// `ConversionError::MisplacedNode` instead.
-fn validate_placement(doc: &Value) -> Result<(), ConversionError> {
-    fn walk(
-        node: &Value,
-        parent: Option<&str>,
-        index_in_parent: Option,
-    ) -> Result<(), ConversionError> {
-        let Some(node_type) = node["type"].as_str() else {
-            // Missing type: json_to_ast reports MissingType; keep that
-            // error's precedence.
-            return Ok(());
-        };
-        // #1369: `front_matter` is legal only as the first child of `doc`
-        // (comrak only parses it there). Anything else is misplaced.
-        if node_type == "front_matter" {
-            let first_child_of_doc = parent == Some("doc") && index_in_parent == Some(0);
-            if !first_child_of_doc {
-                return Err(ConversionError::MisplacedNode {
-                    parent: parent.unwrap_or("").to_owned(),
-                    child: node_type.to_owned(),
-                });
-            }
-        } else if let Some(parent_type) = parent
-            && let Some(category) = placement_of(node_type)
-            && !placement_allowed(parent_type, category)
-        {
-            return Err(ConversionError::MisplacedNode {
-                parent: parent_type.to_owned(),
-                child: node_type.to_owned(),
-            });
-        }
-        // code_block content is literal text children only.
-        if node_type == "code_block" {
-            if let Some(content) = node["content"].as_array() {
-                for child in content {
-                    if child["type"].as_str() != Some("text") {
-                        return Err(ConversionError::MisplacedNode {
-                            parent: node_type.to_owned(),
-                            child: child["type"].as_str().unwrap_or("").to_owned(),
-                        });
-                    }
-                }
-            }
-            return Ok(());
-        }
-        // front_matter carries no PM child content (its payload is the
-        // `text` attr); nothing to recurse into.
-        if node_type == "front_matter" {
-            if node["content"].as_array().is_some_and(|c| !c.is_empty()) {
-                return Err(ConversionError::MisplacedNode {
-                    parent: node_type.to_owned(),
-                    child: "".to_owned(),
-                });
-            }
-            return Ok(());
-        }
-        if let Some(content) = node["content"].as_array() {
-            for (idx, child) in content.iter().enumerate() {
-                walk(child, Some(node_type), Some(idx))?;
-            }
-        }
-        Ok(())
-    }
-    walk(doc, None, None)
-}
-
-/// Convert `ProseMirror` JSON document to markdown text.
-///
-/// # Arguments
-///
-/// * `doc` - The `ProseMirror` JSON document.
-///
-/// # Returns
-///
-/// The markdown text, or an error if conversion fails.
-///
-/// # Errors
-///
-/// Returns `ConversionError` if the JSON structure is invalid.
-pub fn prosemirror_to_markdown(doc: &Value) -> Result {
-    validate_placement(doc)?;
-    let arena = Arena::new();
-    let root = json_to_ast(&arena, doc)?;
-    // #1418: hoist delimiter-mark edge spaces that a word character
-    // touches out of their wrappers, before rendering (see
-    // `hoist_delimiter_edge_spaces`).
-    hoist_delimiter_edge_spaces(&arena, root);
-    // #1496: force info-less code blocks inside blockquotes onto the
-    // renderer's fenced branch via a placeholder info string, stripped
-    // from the rendered output below (see
-    // `force_fenced_code_blocks_in_blockquotes`).
-    let fence_tokens = force_fenced_code_blocks_in_blockquotes(root);
-    // #1019: comrak's renderer percent-encodes a space in a link/image
-    // destination (`my notes.md` -> `my%20notes.md`) instead of emitting
-    // the <...> angle form, silently breaking relative file links and
-    // mutating the PM href on reparse. #1423: the same mangling hits the
-    // other whitespace characters — a tab is encoded to %09 and a newline
-    // destroys the link outright (`% `). The renderer has no angle-form
-    // option, so swap each whitespace-carrying destination for a unique
-    // placeholder before rendering and restore it as 
-    // afterwards.
-    let substitutions = substitute_spaced_destinations(root);
-    let mut output = String::new();
-    format_commonmark(root, &commonmark_options(), &mut output)?;
-    for (placeholder, raw) in substitutions {
-        output = output.replace(&placeholder, &format!("<{raw}>"));
-    }
-    for token in fence_tokens {
-        output = strip_fence_placeholder(&output, &token);
-    }
-    Ok(output)
-}
-
-/// Whether a node value is a delimiter-mark wrapper (#1418): the
-/// marks whose markdown spelling is a delimiter run (`*`/`**`/`~~`)
-/// subject to CommonMark flanking rules. Link (bracket syntax) and
-/// code (backtick syntax) tolerate edge spaces and are excluded.
-fn is_delimiter_wrapper(value: &NodeValue) -> bool {
-    matches!(
-        value,
-        NodeValue::Emph | NodeValue::Strong | NodeValue::Strikethrough
-    )
-}
-
-/// The first text leaf of a mark chain, descending first children
-/// through mark wrappers (#1418). `None` when the first inline is
-/// anything else (an image or html node is a different mechanism —
-/// #1407/#1412 — and keeps the legacy behaviour).
-fn first_text_leaf<'a>(node: &'a AstNode<'a>) -> Option<&'a AstNode<'a>> {
-    let mut current = node;
-    loop {
-        let child = current.first_child()?;
-        let value = child.data.borrow().value.clone();
-        match value {
-            NodeValue::Text(_) => return Some(child),
-            _ if is_mark_wrapper(&value) => current = child,
-            _ => return None,
-        }
-    }
-}
-
-/// The last text leaf of a mark chain; mirror of `first_text_leaf`.
-fn last_text_leaf<'a>(node: &'a AstNode<'a>) -> Option<&'a AstNode<'a>> {
-    let mut current = node;
-    loop {
-        let child = current.last_child()?;
-        let value = child.data.borrow().value.clone();
-        match value {
-            NodeValue::Text(_) => return Some(child),
-            _ if is_mark_wrapper(&value) => current = child,
-            _ => return None,
-        }
-    }
-}
-
-/// The last character a node renders as inline content (#1418):
-/// text/code literals verbatim, breaks as whitespace, mark wrappers
-/// by their last inline descendant. Anything else yields `None`
-/// (treated as a non-word neighbour).
-fn last_rendered_char(node: &AstNode<'_>) -> Option {
-    match &node.data.borrow().value {
-        NodeValue::Text(literal) => literal.to_string().chars().last(),
-        NodeValue::Code(code) => code.literal.chars().last(),
-        NodeValue::LineBreak | NodeValue::SoftBreak => Some('\n'),
-        value if is_mark_wrapper(value) => node.last_child().and_then(last_rendered_char),
-        _ => None,
-    }
-}
-
-/// The first character a node renders as; mirror of
-/// `last_rendered_char`.
-fn first_rendered_char(node: &AstNode<'_>) -> Option {
-    match &node.data.borrow().value {
-        NodeValue::Text(literal) => literal.to_string().chars().next(),
-        NodeValue::Code(code) => code.literal.chars().next(),
-        NodeValue::LineBreak | NodeValue::SoftBreak => Some('\n'),
-        value if is_mark_wrapper(value) => node.first_child().and_then(first_rendered_char),
-        _ => None,
-    }
-}
-
-fn is_word_char(c: char) -> bool {
-    c.is_alphanumeric() || c == '_'
-}
-
-/// Whether the inline character immediately before `node` is a word
-/// character (#1418), climbing through mark-wrapper ancestors while
-/// `node` sits at their leading edge. No rendered neighbour (block
-/// boundary) is not a word character.
-fn preceded_by_word_char(node: &AstNode<'_>) -> bool {
-    let mut current = node;
-    loop {
-        if let Some(prev) = current.previous_sibling() {
-            return last_rendered_char(prev).is_some_and(is_word_char);
-        }
-        match current.parent() {
-            Some(parent) if is_mark_wrapper(&parent.data.borrow().value) => current = parent,
-            _ => return false,
-        }
-    }
-}
-
-/// Whether the inline character immediately after `node` is a word
-/// character; mirror of `preceded_by_word_char`.
-fn followed_by_word_char(node: &AstNode<'_>) -> bool {
-    let mut current = node;
-    loop {
-        if let Some(next) = current.next_sibling() {
-            return first_rendered_char(next).is_some_and(is_word_char);
-        }
-        match current.parent() {
-            Some(parent) if is_mark_wrapper(&parent.data.borrow().value) => current = parent,
-            _ => return false,
-        }
-    }
-}
-
-/// Replace a text leaf's literal, detaching the leaf (and any mark
-/// wrappers it leaves childless) when the replacement is empty
-/// (#1418: a span whose whole text was edge spaces).
-fn set_text_leaf_text(leaf: &AstNode<'_>, new_text: &str) {
-    if !new_text.is_empty() {
-        leaf.data.borrow_mut().value = NodeValue::Text(new_text.to_owned().into());
-        return;
-    }
-    let mut current = leaf.parent();
-    leaf.detach();
-    while let Some(node) = current {
-        if !is_mark_wrapper(&node.data.borrow().value) || node.first_child().is_some() {
-            break;
-        }
-        current = node.parent();
-        node.detach();
-    }
-}
-
-/// Hoist one edge of one delimiter wrapper (#1418): move its leading
-/// (or trailing) spaces to a plain text node just outside the wrapper
-/// — but still inside any outer non-delimiter wrapper such as a link,
-/// which is exactly the sibling position next to this wrapper — when
-/// a word character touches the wrapper on that side.
-fn hoist_one_edge<'a>(arena: &'a Arena<'a>, wrapper: &'a AstNode<'a>, leading: bool) {
-    let touches_word = if leading {
-        preceded_by_word_char(wrapper)
-    } else {
-        followed_by_word_char(wrapper)
-    };
-    if !touches_word {
-        return;
-    }
-    let Some(leaf) = (if leading {
-        first_text_leaf(wrapper)
-    } else {
-        last_text_leaf(wrapper)
-    }) else {
-        return;
-    };
-    let text = match &leaf.data.borrow().value {
-        NodeValue::Text(literal) => literal.to_string(),
-        _ => return,
-    };
-    let spaces_len = if leading {
-        text.len() - text.trim_start_matches(' ').len()
-    } else {
-        text.len() - text.trim_end_matches(' ').len()
-    };
-    if spaces_len == 0 {
-        return;
-    }
-    let (spaces, rest) = if leading {
-        (text[..spaces_len].to_owned(), text[spaces_len..].to_owned())
-    } else {
-        (
-            text[text.len() - spaces_len..].to_owned(),
-            text[..text.len() - spaces_len].to_owned(),
-        )
-    };
-    // Insert the hoisted spaces while the wrapper is still attached:
-    // shrinking the leaf afterwards may detach the wrapper itself
-    // (a span whose whole text was edge spaces), and the space node
-    // must stay at the wrapper's position when that happens.
-    let space_node = arena.alloc(AstNode::from(NodeValue::Text(spaces.into())));
-    if leading {
-        wrapper.insert_before(space_node);
-    } else {
-        wrapper.insert_after(space_node);
-    }
-    set_text_leaf_text(leaf, &rest);
-}
-
-/// #1418: a delimiter-mark span whose text starts or ends with a
-/// space saves with that space inside the delimiters, and comrak
-/// renders it as an ` ` entity (`a* b*`). When a word
-/// character touches the span on that side, the emitted form fails
-/// CommonMark flanking rules on reparse and the mark is destroyed.
-/// Hoist such edge spaces out of the delimiter wrappers so the saved
-/// form reparses with the mark intact; the space becomes unmarked,
-/// which renders identically. Edges a word character does not touch
-/// (paragraph boundaries, space/punctuation neighbours, spans padded
-/// on both edges) keep the ` ` form, which round-trips as-is.
-/// Working on the converted AST — after #968's chain merging — means
-/// only true span edges are considered: an edge space shared with a
-/// neighbouring run of the same span is interior here, not an edge.
-fn hoist_delimiter_edge_spaces<'a>(arena: &'a Arena<'a>, root: &'a AstNode<'a>) {
-    let wrappers: Vec<&AstNode<'a>> = root
-        .descendants()
-        .filter(|node| is_delimiter_wrapper(&node.data.borrow().value))
-        .collect();
-    // Reverse document order: inner wrappers before their outers (a
-    // space hoisted out of an inner wrapper may still sit at the
-    // outer wrapper's edge and be hoisted again by its turn), and a
-    // wrapper's own leading edge before its trailing edge.
-    for wrapper in wrappers.into_iter().rev() {
-        hoist_one_edge(arena, wrapper, true);
-        hoist_one_edge(arena, wrapper, false);
-    }
-}
-
-/// #1496: comrak's CommonMark renderer emits an info-less code block
-/// as an INDENTED block whenever it can (its fenced branch requires a
-/// non-empty info string, the global `prefer_fenced` option, or a few
-/// literal edge cases). Inside a blockquote the indented form drops
-/// the quote prefix for every following sibling, so the saved file
-/// reparses as two blockquotes and everything after the code block
-/// leaves the quote. Give each info-less code block inside a
-/// blockquote a placeholder info string so the renderer takes the
-/// fenced branch, and return the placeholders for stripping from the
-/// rendered output — the same placeholder-and-restore pattern as
-/// `substitute_spaced_destinations`. Code blocks outside blockquotes
-/// are fenced by the global `prefer_fenced` render option (#954); this
-/// placeholder is kept as belt-and-braces for the quoted shape.
-fn force_fenced_code_blocks_in_blockquotes<'a>(root: &'a AstNode<'a>) -> Vec {
-    let mut tokens: Vec = Vec::new();
-    let mut stack: Vec<(&AstNode<'a>, bool)> = vec![(root, false)];
-    while let Some((node, ancestor_is_blockquote)) = stack.pop() {
-        let in_blockquote = ancestor_is_blockquote
-            || matches!(node.data.borrow().value, NodeValue::BlockQuote);
-        for child in node.children() {
-            stack.push((child, in_blockquote));
-        }
-        if !in_blockquote {
-            continue;
-        }
-        let mut data = node.data.borrow_mut();
-        if let NodeValue::CodeBlock(code_block) = &mut data.value
-            && code_block.info.is_empty()
-        {
-            // The trailing `-end` keeps placeholders prefix-free
-            // (`-1-end` is not a prefix of `-10-end`); restoration is
-            // positional regardless (see `strip_fence_placeholder`).
-            let token = format!("idweb-blockquote-fence-{}-end", tokens.len());
-            code_block.info.clone_from(&token);
-            tokens.push(token);
-        }
-    }
-    tokens
-}
-
-/// Remove a #1496 fence placeholder from rendered output — ONLY at
-/// its generated fence-info position: a run of >= 3 backticks
-/// immediately before the placeholder and a newline immediately after
-/// it (the renderer's fence line shape). A plain `str::replace` would
-/// also strip the placeholder text anywhere else it occurs (user prose,
-/// code content) and, with prefix-sharing placeholders, corrupt
-/// neighbouring blocks' info strings (Codex review on PR #3770).
-fn strip_fence_placeholder(output: &str, token: &str) -> String {
-    let mut result = String::with_capacity(output.len());
-    let mut rest = output;
-    while let Some(pos) = rest.find(token) {
-        let before = &rest[..pos];
-        let after = &rest[pos + token.len()..];
-        let fence_run = before.chars().rev().take_while(|c| *c == '`').count();
-        if fence_run >= 3 && after.starts_with('\n') {
-            result.push_str(before);
-            rest = after;
-        } else {
-            result.push_str(&rest[..pos + token.len()]);
-            rest = after;
-        }
-    }
-    result.push_str(rest);
-    result
-}
-
-/// Replace every link/image destination containing whitespace (space,
-/// tab, newline, …) with a unique placeholder token, returning
-/// (placeholder, raw destination) pairs for restoration after rendering
-/// (#1019, #1423). The token is a valid bare destination (no whitespace
-/// or characters comrak encodes), so the renderer emits it verbatim
-/// exactly where the destination belongs. Reference-style links flow
-/// through here too: comrak resolves a reference definition into the
-/// referencing link's `url`, and the PM model stores that href directly,
-/// so no separate definition path exists in this codec.
-fn substitute_spaced_destinations<'a>(root: &'a AstNode<'a>) -> Vec<(String, String)> {
-    let mut substitutions: Vec<(String, String)> = Vec::new();
-    let mut stack: Vec<&AstNode<'a>> = vec![root];
-    while let Some(node) = stack.pop() {
-        stack.extend(node.children());
-        let mut data = node.data.borrow_mut();
-        let url = match &mut data.value {
-            NodeValue::Link(link) | NodeValue::Image(link) => &mut link.url,
-            _ => continue,
-        };
-        if !url.contains(char::is_whitespace) {
-            continue;
-        }
-        if let Some(index) = substitutions
-            .iter()
-            .position(|(_, raw)| raw.as_str() == url.as_str())
-        {
-            *url = substitutions[index].0.clone();
-        } else {
-            let placeholder = format!(
-                "idweb-spaced-destination-{}-placeholder",
-                substitutions.len()
-            );
-            let raw = std::mem::take(url);
-            *url = placeholder.clone();
-            substitutions.push((placeholder, raw));
-        }
-    }
-    substitutions
-}
-
-/// Whether a converted AST node is block-level (as opposed to inline).
-/// Used by the footnote_definition save path (#1031) to tell carried
-/// block children apart from legacy inline children.
-fn is_block_node(node: &AstNode<'_>) -> bool {
-    matches!(
-        node.data.borrow().value,
-        NodeValue::Paragraph
-            | NodeValue::Heading(_)
-            | NodeValue::BlockQuote
-            | NodeValue::List(_)
-            | NodeValue::Item(_)
-            | NodeValue::TaskItem(_)
-            | NodeValue::CodeBlock(_)
-            | NodeValue::HtmlBlock(_)
-            | NodeValue::ThematicBreak
-            | NodeValue::FrontMatter(_)
-            | NodeValue::Table(_)
-            | NodeValue::FootnoteDefinition(_)
-    )
-}
-
-/// Convert `ProseMirror` JSON to comrak AST.
-/// Whether a JSON node is a `text` node carrying no marks (#1420).
-/// Marked runs protect their edge spaces with the marked-span mechanism
-/// (#1418); unmarked runs have no such protection, so the save direction
-/// normalizes their edge whitespace instead (see
-/// `normalize_inline_child_json`).
-fn is_unmarked_text_json(node: &Value) -> bool {
-    node["type"].as_str() == Some("text")
-        && node["marks"]
-            .as_array()
-            .is_none_or(|marks| marks.is_empty())
-}
-
-/// Whether a JSON node is a `hard_break` — the boundary between two
-/// rendered lines inside one block (#1420).
-fn is_hard_break_json(node: &Value) -> bool {
-    node["type"].as_str() == Some("hard_break")
-}
-
-/// Whether an unmarked text node renders as nothing but edge whitespace
-/// (empty, or spaces/tabs only). Such a node never shields a neighbour's
-/// edge from the line boundary: at a line edge its own whitespace is
-/// normalized away too, and mid-line it is a separator either way (#1420).
-fn is_whitespace_only_text_json(node: &Value) -> bool {
-    is_unmarked_text_json(node)
-        && node["text"]
-            .as_str()
-            .unwrap_or("")
-            .chars()
-            .all(|c| c == ' ' || c == '\t')
-}
-
-/// Whether scanning `siblings` (in render order) reaches a line edge —
-/// the start/end of the block or a `hard_break` — before any content
-/// that renders something (#1420).
-fn reaches_line_edge(siblings: impl Iterator) -> bool {
-    for sibling in siblings {
-        if is_hard_break_json(&sibling) {
-            return true;
-        }
-        if !is_whitespace_only_text_json(&sibling) {
-            return false;
-        }
-    }
-    true
-}
-
-/// #1420: normalize one inline child of a block before conversion.
-///
-/// Unmarked text runs are written verbatim on save, but CommonMark
-/// reparse strips edge whitespace (up to 3 leading spaces per line,
-/// trailing spaces ignored) and deletes a whitespace-only paragraph
-/// outright, so the saved file and the reopened doc disagreed. The
-/// pinned policy is normalize-at-save: trim an unmarked run's leading
-/// spaces when it sits at a line start (block start or just after a
-/// `hard_break`) and its trailing spaces when it sits at a line end
-/// (block end or just before a `hard_break`), so the first saved file
-/// is already the fixpoint. A whitespace-only run at a line edge
-/// becomes an empty text node, so a whitespace-only paragraph saves as
-/// an EMPTY paragraph instead of vanishing text. Interior runs (word
-/// separators between words/marks) and marked runs are untouched.
-fn normalize_inline_child_json(content: &[Value], idx: usize) -> std::borrow::Cow<'_, Value> {
-    let child = &content[idx];
-    if !is_unmarked_text_json(child) {
-        return std::borrow::Cow::Borrowed(child);
-    }
-    let trim_start = reaches_line_edge(content[..idx].iter().rev().cloned());
-    let trim_end = reaches_line_edge(content[idx + 1..].iter().cloned());
-    if !trim_start && !trim_end {
-        return std::borrow::Cow::Borrowed(child);
-    }
-    let text = child["text"].as_str().unwrap_or("");
-    let mut normalized = text;
-    if trim_start {
-        normalized = normalized.trim_start_matches([' ', '\t']);
-    }
-    if trim_end {
-        normalized = normalized.trim_end_matches([' ', '\t']);
-    }
-    if normalized == text {
-        return std::borrow::Cow::Borrowed(child);
-    }
-    let mut owned = child.clone();
-    owned["text"] = json!(normalized);
-    std::borrow::Cow::Owned(owned)
-}
-
-fn json_to_ast<'a>(arena: &'a Arena<'a>, json: &Value) -> Result<&'a AstNode<'a>, ConversionError> {
-    let node_type = json["type"].as_str().ok_or(ConversionError::MissingType)?;
-
-    let node_value = match node_type {
-        "doc" => NodeValue::Document,
-
-        "paragraph" => NodeValue::Paragraph,
-
-        "heading" => {
-            let level = json["attrs"]["level"].as_u64().unwrap_or(1).clamp(1, 6);
-            #[allow(clippy::cast_possible_truncation)] // level is clamped to 1-6 before narrowing
-            let level = level as u8;
-            NodeValue::Heading(comrak::nodes::NodeHeading {
-                level,
-                setext: false,
-                closed: false,
-            })
-        }
-
-        "blockquote" => NodeValue::BlockQuote,
-
-        "code_block" => {
-            // #882: editors/collab can split a code block into several text
-            // nodes; concatenate ALL of them instead of keeping only the
-            // first (which silently truncated the block on save).
-            let content = json["content"].as_array().map_or(String::new(), |arr| {
-                arr.iter()
-                    .filter_map(|n| n["text"].as_str())
-                    .collect::()
-            });
-            let content = content.as_str();
-            let info = json["attrs"]["params"].as_str().unwrap_or("");
-
-            // #982: a code_block carrying the htmlBlock provenance attr
-            // (set by the parse direction for blocks converted from raw
-            // HTML) emits as a real HTML block again, not a ```html
-            // fence. Authored fences and already-saved docs have no
-            // attr and keep the fenced emit below — no retro-guessing.
-            if info == "html" && json["attrs"]["htmlBlock"].as_bool() == Some(true) {
-                return Ok(arena.alloc(AstNode::from(NodeValue::HtmlBlock(
-                    comrak::nodes::NodeHtmlBlock {
-                        literal: format!("{content}\n"),
-                        ..Default::default()
-                    },
-                ))));
-            }
-
-            NodeValue::CodeBlock(Box::new(comrak::nodes::NodeCodeBlock {
-                fenced: true,
-                fence_char: b'`',
-                fence_length: 3,
-                fence_offset: 0,
-                info: info.to_owned(),
-                // #954: comrak's own empty-fence literal is empty; appending
-                // the usual trailing newline here renders a spurious blank
-                // line inside the fence ("```\n\n```").
-                literal: if content.is_empty() {
-                    String::new()
-                } else {
-                    format!("{content}\n")
-                },
-                closed: false,
-            }))
-        }
-
-        "horizontal_rule" => NodeValue::ThematicBreak,
-
-        // #1369: YAML front matter (`---` delimiter only; comrak has no
-        // TOML `+++` support) carried verbatim in the `text` attr.
-        "front_matter" => NodeValue::FrontMatter(
-            json["attrs"]["text"].as_str().unwrap_or("").to_owned(),
-        ),
-
-        "bullet_list" => {
-            let tight = json["attrs"]["tight"].as_bool().unwrap_or(false);
-            NodeValue::List(comrak::nodes::NodeList {
-                list_type: ListType::Bullet,
-                tight,
-                bullet_char: b'-',
-                ..Default::default()
-            })
-        }
-
-        "ordered_list" => {
-            #[allow(clippy::cast_possible_truncation)] // order is typically small
-            let order = json["attrs"]["order"].as_u64().unwrap_or(1) as usize;
-            let tight = json["attrs"]["tight"].as_bool().unwrap_or(false);
-            // #1380: carry the delimiter style; absent (legacy docs)
-            // defaults to Period in delimiter_from_attrs.
-            NodeValue::List(comrak::nodes::NodeList {
-                list_type: ListType::Ordered,
-                start: order,
-                tight,
-                delimiter: delimiter_from_attrs(json),
-                ..Default::default()
-            })
-        }
-
-        "list_item" => NodeValue::Item(comrak::nodes::NodeList::default()),
-
-        "task_list" => {
-            // Task list is a list whose children are TaskItems.
-            // #1036: carry `tight` like bullet_list/ordered_list. When the
-            // attr is absent (legacy PM docs stored by the old codec, which
-            // dropped it), infer it: loose if any task_list_item has more
-            // than one block child, else tight — so legacy loose items stop
-            // fusing and legacy tight lists render exactly as before.
-            // #997: when the parse side stored `attrs.order`, rebuild an
-            // ordered list with that start; without it, a bullet list.
-            let tight = json["attrs"]["tight"].as_bool().unwrap_or_else(|| {
-                !json["content"].as_array().is_some_and(|items| {
-                    items.iter().any(|item| {
-                        item["content"]
-                            .as_array()
-                            .is_some_and(|blocks| blocks.len() > 1)
-                    })
-                })
-            });
-            #[allow(clippy::cast_possible_truncation)] // order is typically small
-            let order = json["attrs"]["order"].as_u64().map(|o| o as usize);
-            match order {
-                Some(start) => NodeValue::List(comrak::nodes::NodeList {
-                    list_type: ListType::Ordered,
-                    start,
-                    tight,
-                    // #1380: same delimiter carry as ordered_list.
-                    delimiter: delimiter_from_attrs(json),
-                    ..Default::default()
-                }),
-                None => NodeValue::List(comrak::nodes::NodeList {
-                    list_type: ListType::Bullet,
-                    tight,
-                    bullet_char: b'-',
-                    ..Default::default()
-                }),
-            }
-        }
-
-        "task_list_item" => {
-            let checked = json["attrs"]["checked"].as_bool().unwrap_or(false);
-            NodeValue::TaskItem(comrak::nodes::NodeTaskItem {
-                symbol: checked.then_some('x'),
-                symbol_sourcepos: comrak::nodes::Sourcepos {
-                    start: comrak::nodes::LineColumn { line: 0, column: 0 },
-                    end: comrak::nodes::LineColumn { line: 0, column: 0 },
-                },
-            })
-        }
-
-        "table" => {
-            // Count columns from first row's children, and count rows
-            let rows = json["content"].as_array();
-            let num_columns = rows
-                .and_then(|r| r.first())
-                .and_then(|row| row["content"].as_array())
-                .map_or(0, Vec::len);
-            let num_rows = rows.map_or(0, Vec::len);
-            // #881: read back the alignments convert_node stored on the
-            // table node; absent/short/unknown entries default to None.
-            let mut alignments: Vec = json["attrs"]["alignments"]
-                .as_array()
-                .map(|arr| {
-                    arr.iter()
-                        .map(|a| match a.as_str() {
-                            Some("left") => comrak::nodes::TableAlignment::Left,
-                            Some("center") => comrak::nodes::TableAlignment::Center,
-                            Some("right") => comrak::nodes::TableAlignment::Right,
-                            _ => comrak::nodes::TableAlignment::None,
-                        })
-                        .collect()
-                })
-                .unwrap_or_default();
-            alignments.resize(num_columns, comrak::nodes::TableAlignment::None);
-            alignments.truncate(num_columns);
-            NodeValue::Table(Box::new(comrak::nodes::NodeTable {
-                alignments,
-                num_columns,
-                num_rows,
-                num_nonempty_cells: 0,
-            }))
-        }
-
-        "table_row" => {
-            // Determine if this is a header row by checking if children are table_header
-            let is_header = json["content"]
-                .as_array()
-                .and_then(|arr| arr.first())
-                .and_then(|c| c["type"].as_str())
-                .is_some_and(|t| t == "table_header");
-            NodeValue::TableRow(is_header)
-        }
-
-        "table_header" | "table_cell" => NodeValue::TableCell,
-
-        "image" => {
-            let src = json["attrs"]["src"].as_str().unwrap_or("");
-            let title = json["attrs"]["title"].as_str().unwrap_or("");
-            let alt = json["attrs"]["alt"].as_str().unwrap_or("");
-            let width = json["attrs"]["width"].as_u64();
-            let height = json["attrs"]["height"].as_u64();
-
-            // If image has explicit dimensions, emit as HTML  tag
-            if width.is_some() || height.is_some() {
-                // #873: escape values — a raw `"` truncated the attribute on
-                // reparse and could inject new attributes.
-                let mut tag = format!("\"{}\"",");
-                // #880: a sized image cannot use [![..](..)](..) syntax;
-                // keep its link as an HTML anchor around the  tag.
-                // #893: carry linkTitle too, so the parse direction's
-                // linkTitle survives the next save as well.
-                if let Some(link_href) = json["attrs"]["linkHref"].as_str()
-                    && !link_href.is_empty()
-                {
-                    let mut anchor = format!("{tag}");
-                }
-                NodeValue::HtmlInline(tag)
-            } else {
-                // Standard markdown image syntax
-                NodeValue::Image(Box::new(comrak::nodes::NodeLink {
-                    url: src.to_owned(),
-                    title: title.to_owned(),
-                }))
-            }
-        }
-
-        // #943: raw inline HTML (e.g. , , , ) carried
-        // verbatim; comrak renders HtmlInline without escaping.
-        "html_inline" => {
-            NodeValue::HtmlInline(json["attrs"]["html"].as_str().unwrap_or("").to_owned())
-        }
-
-        // #945: footnote reference atom -> comrak FootnoteReference; the
-        // commonmark formatter renders it natively as [^label].
-        "footnote_reference" => {
-            NodeValue::FootnoteReference(Box::new(comrak::nodes::NodeFootnoteReference {
-                name: json["attrs"]["label"].as_str().unwrap_or("").to_owned(),
-                ..Default::default()
-            }))
-        }
-
-        // #945: footnote definition block -> comrak FootnoteDefinition.
-        // Its content children were stored as inline nodes by the parse
-        // direction; the special case below re-wraps them in a Paragraph
-        // (comrak requires block children) and the formatter renders them
-        // under the [^label]: heading.
-        "footnote_definition" => {
-            NodeValue::FootnoteDefinition(comrak::nodes::NodeFootnoteDefinition {
-                name: json["attrs"]["label"].as_str().unwrap_or("").to_owned(),
-                total_references: 0,
-            })
-        }
-
-        "hard_break" => NodeValue::LineBreak,
-
-        "text" => {
-            let text = json["text"].as_str().unwrap_or("");
-            // Handle marks by wrapping in appropriate nodes
-            if let Some(marks) = json["marks"].as_array() {
-                return Ok(create_marked_text(arena, text, marks));
-            }
-            NodeValue::Text(text.to_owned().into())
-        }
-
-        _ => return Err(ConversionError::UnknownType(node_type.to_owned())),
-    };
-
-    let ast_node = arena.alloc(AstNode::from(node_value));
-
-    // Special case: table cells need paragraph unwrapping.
-    // comrak expects inline content directly in cells, not wrapped in paragraphs.
-    // ProseMirror wraps cell content in paragraphs, so we unwrap them here.
-    if node_type == "table_header" || node_type == "table_cell" {
-        if let Some(content) = json["content"].as_array() {
-            for (idx, child_json) in content.iter().enumerate() {
-                if child_json["type"].as_str() == Some("paragraph") {
-                    // GFM cells cannot contain block breaks. Preserve word
-                    // boundaries when adjacent paragraphs are flattened.
-                    if idx > 0 && content[idx - 1]["type"].as_str() == Some("paragraph") {
-                        ast_node.append(arena.alloc(AstNode::from(NodeValue::Text(" ".into()))));
-                    }
-                    // Unwrap: add paragraph's inline children directly to cell
-                    if let Some(para_content) = child_json["content"].as_array() {
-                        for (inline_idx, _inline_json) in para_content.iter().enumerate() {
-                            let normalized = normalize_inline_child_json(para_content, inline_idx);
-                            let inline_node = json_to_ast(arena, &normalized)?;
-                            append_table_cell_child(arena, ast_node, inline_node);
-                        }
-                    }
-                } else {
-                    let normalized = normalize_inline_child_json(content, idx);
-                    let child = json_to_ast(arena, &normalized)?;
-                    append_table_cell_child(arena, ast_node, child);
-                }
-            }
-        }
-        return Ok(ast_node);
-    }
-
-    // Special case: footnote definitions. The parse direction stores
-    // the definition's BLOCK children on the PM node (#1031), and
-    // comrak's AST requires a FootnoteDefinition's children to be
-    // blocks — append block children directly. Legacy #945-shape docs
-    // store bare inline nodes instead; group consecutive inline
-    // children into a single Paragraph, as before, so those documents
-    // still save as a well-formed definition.
-    if node_type == "footnote_definition" {
-        if let Some(content) = json["content"].as_array() {
-            let mut paragraph: Option<&AstNode<'a>> = None;
-            for (idx, _child_json) in content.iter().enumerate() {
-                let normalized = normalize_inline_child_json(content, idx);
-                let child = json_to_ast(arena, &normalized)?;
-                if is_block_node(child) {
-                    paragraph = None;
-                    ast_node.append(child);
-                } else {
-                    let target = match paragraph {
-                        Some(p) => p,
-                        None => {
-                            // `&*` reborrows the arena's `&mut` as a shared
-                            // reference so `p` stays Copy-usable after
-                            // being stored in `paragraph`.
-                            let p: &'a AstNode<'a> =
-                                &*arena.alloc(AstNode::from(NodeValue::Paragraph));
-                            ast_node.append(p);
-                            paragraph = Some(p);
-                            p
-                        }
-                    };
-                    append_inline_child(arena, target, child);
-                }
-            }
-        }
-        return Ok(ast_node);
-    }
-
-    // Process children (except for code_block which stores content in literal, not as children;
-    // front_matter likewise stores its payload in the `text` attr, #1369)
-    if node_type != "code_block"
-        && node_type != "front_matter"
-        && let Some(content) = json["content"].as_array()
-    {
-        // #1032: coalesce consecutive bullet_list siblings into the first
-        // list. The PM model has no bullet-marker attribute, so adjacent
-        // lists that differed only by marker (- / + / *) are one list in
-        // every way the model can express — but as separate comrak List
-        // nodes the CommonMark renderer separates them with
-        //  comments, which reparse as ```html fences
-        // and grow the file on every save. Move each later list's items
-        // into the first list (the first list's tight wins).
-        // ordered_list is NOT merged (it carries restart numbering) and
-        // task_list is a distinct PM node type, so neither is affected.
-        let mut prev_bullet_list: Option<&AstNode<'a>> = None;
-        for (idx, child_json) in content.iter().enumerate() {
-            let is_bullet_list = child_json["type"].as_str() == Some("bullet_list");
-            let normalized = normalize_inline_child_json(content, idx);
-            let child = json_to_ast(arena, &normalized)?;
-            if is_bullet_list && let Some(list_node) = prev_bullet_list {
-                let items: Vec<&AstNode<'a>> = child.children().collect();
-                for item in items {
-                    item.detach();
-                    list_node.append(item);
-                }
-                continue;
-            }
-            append_inline_child(arena, ast_node, child);
-            prev_bullet_list = if is_bullet_list { Some(child) } else { None };
-        }
-    }
-
-    // #1044: GFM has no headerless-table representation — comrak emits
-    // the delimiter row only when a row is marked as the header row, and
-    // without one the saved table reparses as a plain paragraph, silently
-    // destroying the table. The editor schema permits rows made only of
-    // table_cell, so when no row is a header row, promote the first row:
-    // a faithful rendering preserving every cell's content, and a one-time
-    // normalization (reparse yields table_header cells in row 0, so the
-    // next save is byte-identical). The table's alignments (#881) are
-    // stored on the table node and apply to the promoted row unchanged.
-    if node_type == "table" {
-        let mut first_row: Option<&AstNode<'a>> = None;
-        let mut has_header_row = false;
-        for child in ast_node.children() {
-            if let NodeValue::TableRow(is_header) = &child.data.borrow().value {
-                if first_row.is_none() {
-                    first_row = Some(child);
-                }
-                if *is_header {
-                    has_header_row = true;
-                }
-            }
-        }
-        if !has_header_row && let Some(row) = first_row {
-            row.data.borrow_mut().value = NodeValue::TableRow(true);
-        }
-    }
-
-    // Special case: image needs alt text as child (but NOT for HtmlInline, i.e. sized images)
-    // #1417: the stored alt is markdown form (see convert_node's Image
-    // arm) - re-parse it into inline nodes so emphasis/strong/code-span
-    // markup is emitted as markup, not as one flat (formatter-escaped)
-    // Text child. A plain-text alt re-parses to a single Text node,
-    // exactly the old behaviour.
-    if node_type == "image"
-        && matches!(ast_node.data.borrow().value, NodeValue::Image(_))
-        && let Some(alt) = json["attrs"]["alt"].as_str()
-        && !alt.is_empty()
-    {
-        for alt_node in alt_markdown_to_nodes(arena, alt) {
-            ast_node.append(alt_node);
-        }
-    }
-
-    // #880 + #1407: an image carrying linkHref (a linked image, see
-    // convert_node) and/or a `marks` array (emphasis/strong/
-    // strikethrough wrapping the image) is wrapped in the
-    // corresponding mark chain so save emits [![alt](src)](href),
-    // *![alt](src)*, or both combined. Wrappers use the canonical
-    // nesting order (#944) — the order create_marked_text applies —
-    // and the returned chain goes through append_inline_child's mark
-    // merging (#968), so a marked image inside a marked text span
-    // rejoins the span instead of fragmenting it.
-    if node_type == "image" && matches!(ast_node.data.borrow().value, NodeValue::Image(_)) {
-        let mut wrappers: Vec<(u8, NodeValue)> = Vec::new();
-        if let Some(link_href) = json["attrs"]["linkHref"].as_str()
-            && !link_href.is_empty()
-        {
-            wrappers.push((
-                mark_nesting_rank("link"),
-                NodeValue::Link(Box::new(comrak::nodes::NodeLink {
-                    url: link_href.to_owned(),
-                    title: json["attrs"]["linkTitle"].as_str().unwrap_or("").to_owned(),
-                })),
-            ));
-        }
-        if let Some(marks) = json["marks"].as_array() {
-            for mark in marks {
-                let mark_type = mark["type"].as_str().unwrap_or("");
-                let wrapper = match mark_type {
-                    "em" => NodeValue::Emph,
-                    "strong" => NodeValue::Strong,
-                    "strikethrough" => NodeValue::Strikethrough,
-                    _ => continue,
-                };
-                if !wrappers.iter().any(|(_, w)| same_mark_wrapper(w, &wrapper)) {
-                    wrappers.push((mark_nesting_rank(mark_type), wrapper));
-                }
-            }
-        }
-        if !wrappers.is_empty() {
-            wrappers.sort_by_key(|(rank, _)| *rank);
-            // build_mark_chain consumes innermost-first; the sorted
-            // list above is outermost-first (canonical rank order).
-            let chain: Vec = wrappers
-                .into_iter()
-                .map(|(_, wrapper)| wrapper)
-                .rev()
-                .collect();
-            return Ok(build_mark_chain(arena, ast_node, &chain, 0));
-        }
-    }
-
-    Ok(ast_node)
-}
-
-/// Whether comrak's AST validation accepts this node type as a direct
-/// child of a `TableCell` (#1017). Mirrors `can_contain_type` for
-/// `TableCell` in comrak's nodes.rs (shortcodes/heex variants are not
-/// enabled in this codec).
-fn valid_table_cell_child(value: &NodeValue) -> bool {
-    matches!(
-        value,
-        NodeValue::Text(..)
-            | NodeValue::Code(..)
-            | NodeValue::Emph
-            | NodeValue::Strong
-            | NodeValue::Link(..)
-            | NodeValue::Image(..)
-            | NodeValue::Strikethrough
-            | NodeValue::Highlight
-            | NodeValue::Insert
-            | NodeValue::HtmlInline(..)
-            | NodeValue::Math(..)
-            | NodeValue::WikiLink(..)
-            | NodeValue::FootnoteReference(..)
-            | NodeValue::Superscript
-            | NodeValue::SpoileredText
-            | NodeValue::Underline
-            | NodeValue::Subscript
-            | NodeValue::TaskItem(_)
-            | NodeValue::Escaped
-            | NodeValue::EscapedTag(_)
-    )
-}
-
-/// Append a converted child to a table cell, degrading anything comrak
-/// would reject there instead of building an ill-formed AST that makes
-/// `format_commonmark` panic (#1017):
-///
-/// - valid inline children pass through unchanged;
-/// - a hard/soft break degrades to a single space (a table cell is
-///   single-line content in markdown);
-/// - any other node (a list, code block, heading, nested table, …)
-///   flattens to its plain text, words space-joined.
-fn append_table_cell_child<'a>(
-    arena: &'a Arena<'a>,
-    cell: &'a AstNode<'a>,
-    child: &'a AstNode<'a>,
-) {
-    let value = &child.data.borrow().value;
-    if valid_table_cell_child(value) {
-        append_inline_child(arena, cell, child);
-        return;
-    }
-    if matches!(value, NodeValue::LineBreak | NodeValue::SoftBreak) {
-        let space = arena.alloc(AstNode::from(NodeValue::Text(" ".to_owned().into())));
-        cell.append(space);
-        return;
-    }
-    let mut segments: Vec = Vec::new();
-    collect_cell_text(child, &mut segments);
-    let text = segments
-        .join(" ")
-        .split_whitespace()
-        .collect::>()
-        .join(" ");
-    if !text.is_empty() {
-        let text_node = arena.alloc(AstNode::from(NodeValue::Text(text.into())));
-        cell.append(text_node);
-    }
-}
-
-/// Collect the text of a node being flattened into a table cell (#1017):
-/// text/code literals verbatim, breaks as spaces, and a space segment at
-/// every other node's boundary so sibling blocks cannot fuse into one
-/// word. The caller normalizes whitespace runs.
-fn collect_cell_text<'a>(node: &'a AstNode<'a>, segments: &mut Vec) {
-    match &node.data.borrow().value {
-        NodeValue::Text(literal) => segments.push(literal.to_string()),
-        NodeValue::Code(code) => segments.push(code.literal.clone()),
-        NodeValue::CodeBlock(code_block) => segments.push(code_block.literal.clone()),
-        NodeValue::LineBreak | NodeValue::SoftBreak => segments.push(" ".to_owned()),
-        _ => {
-            for child in node.children() {
-                collect_cell_text(child, segments);
-            }
-            segments.push(" ".to_owned());
-        }
-    }
-}
-
-/// Whether two node values are the same mark wrapper, so adjacent
-/// siblings carrying it are really one marked span (#953).
-fn same_mark_wrapper(a: &NodeValue, b: &NodeValue) -> bool {
-    match (a, b) {
-        (NodeValue::Link(x), NodeValue::Link(y)) => x.url == y.url && x.title == y.title,
-        (NodeValue::Strong, NodeValue::Strong)
-        | (NodeValue::Emph, NodeValue::Emph)
-        | (NodeValue::Strikethrough, NodeValue::Strikethrough) => true,
-        _ => false,
-    }
-}
-
-/// Whether a node value is a mark wrapper (the wrapper kinds
-/// `create_marked_text` chains and `same_mark_wrapper` compares).
-fn is_mark_wrapper(value: &NodeValue) -> bool {
-    matches!(
-        value,
-        NodeValue::Link(..) | NodeValue::Strong | NodeValue::Emph | NodeValue::Strikethrough
-    )
-}
-
-/// Peel a pure mark chain — wrapper → wrapper → … → a single
-/// non-wrapper leaf, as `create_marked_text` builds — into its wrapper
-/// values (outermost first) and the leaf node. Returns `None` for
-/// anything else (no wrappers, a wrapper with several children, a
-/// wrapper bottoming out in another wrapper): those children keep the
-/// legacy append behaviour.
-fn peel_mark_chain<'a>(child: &'a AstNode<'a>) -> Option<(Vec, &'a AstNode<'a>)> {
-    let mut wrappers: Vec = Vec::new();
-    let mut current = child;
-    loop {
-        let value = current.data.borrow().value.clone();
-        if !is_mark_wrapper(&value) {
-            break;
-        }
-        let mut children = current.children();
-        let only = children.next()?;
-        if children.next().is_some() {
-            return None;
-        }
-        wrappers.push(value);
-        current = only;
-    }
-    if wrappers.is_empty() || is_mark_wrapper(¤t.data.borrow().value) {
-        return None;
-    }
-    Some((wrappers, current))
-}
-
-/// Insert a peeled mark chain's leaf under `parent`, reusing the
-/// parent's tail wrapper whenever it carries one of the chain's marks
-/// (#968). Adjacent ProseMirror runs are converted one at a time, each
-/// in canonical rank order, so neighbouring runs that share a mark can
-/// disagree about which shared mark is outermost: `*em **strong**
-/// end*` arrives as Emph, Strong→Emph, Emph and used to render as
-/// three fragmented sibling spans with ` ` boundary entities.
-/// Reusing the tail wrapper for the shared mark — wherever it sits in
-/// the incoming chain — and nesting the chain's remaining wrappers
-/// inside it emits one properly nested span instead. When the tail
-/// shares no mark with the chain, the chain is appended fresh, which
-/// also subsumes the #953 same-wrapper merge (an identical tail
-/// wrapper is simply the shared mark at position 0, recursively).
-fn insert_marked_chain<'a>(
-    arena: &'a Arena<'a>,
-    parent: &'a AstNode<'a>,
-    wrappers: &[NodeValue],
-    leaf: &'a AstNode<'a>,
-) {
-    if !wrappers.is_empty()
-        && let Some(last) = parent.last_child()
-    {
-        let last_value = last.data.borrow().value.clone();
-        if is_mark_wrapper(&last_value)
-            && let Some(shared) = wrappers
-                .iter()
-                .position(|wrapper| same_mark_wrapper(wrapper, &last_value))
-        {
-            let rest: Vec = wrappers
-                .iter()
-                .enumerate()
-                .filter(|(index, _)| *index != shared)
-                .map(|(_, wrapper)| wrapper.clone())
-                .collect();
-            insert_marked_chain(arena, last, &rest, leaf);
-            return;
-        }
-    }
-    let mut current = parent;
-    for wrapper in wrappers {
-        let node = arena.alloc(AstNode::from(wrapper.clone()));
-        current.append(node);
-        current = node;
-    }
-    current.append(leaf);
-}
-
-/// Append an inline child, merging it into the previous sibling when
-/// both are the same mark wrapper (#953): `[a `code` b](href)` reaches
-/// the save direction as three text nodes that share the link mark, and
-/// three sibling Link nodes render as three fragmented links. Moving
-/// the new wrapper's children into the previous wrapper (recursively,
-/// so nested wrappers merge too) emits one link containing all three
-/// segments. Pure mark chains go through the #968 tail insertion
-/// (`insert_marked_chain`), which handles the #953 merge as its
-/// shared-mark case; non-chain children keep the original merge.
-
-/// #1412: adopt trailing `html_inline` atoms into the tail mark
-/// wrapper when a marked chain that shares that wrapper's mark is
-/// about to be inserted. The parse direction emits `html_inline`
-/// atoms markless (see the `NodeValue::HtmlInline` arm of
-/// `convert_node`), so a mark spanning an atom reaches the save
-/// direction as marked run, bare atom, marked run. Appending the
-/// atom as a sibling severs the tail wrapper: the next run opens a
-/// NEW wrapper and the span fragments (`[a x c](/y)` saved as
-/// `[a ](/y)[x](/y)[ c](/y)`, with ` ` leaks at emphasis
-/// seams). When the incoming chain shares a mark with the wrapper
-/// before the atoms, the atoms belong to that span: move them inside
-/// the wrapper (recursing along the chain's shared marks, mirroring
-/// `insert_marked_chain`'s descent, so nested spans adopt at the
-/// deepest shared level), after which the chain insertion merges
-/// into the same wrapper as usual. Atoms not followed by a chain
-/// sharing the preceding wrapper's mark keep their legacy sibling
-/// placement, so unmarked HTML and atoms after a finished span are
-/// unchanged. Extending the atom predicate (e.g. to images, #1407)
-/// generalizes this to the other atom kinds.
-fn adopt_trailing_html_atoms<'a>(parent: &'a AstNode<'a>, wrappers: &[NodeValue]) {
-    let children: Vec<&'a AstNode<'a>> = parent.children().collect();
-    let mut split = children.len();
-    while split > 0
-        && matches!(
-            children[split - 1].data.borrow().value,
-            NodeValue::HtmlInline(..)
-        )
-    {
-        split -= 1;
-    }
-    if split == children.len() || split == 0 {
-        return;
-    }
-    let tail = children[split - 1];
-    let tail_value = tail.data.borrow().value.clone();
-    if !is_mark_wrapper(&tail_value) {
-        return;
-    }
-    let Some(shared) = wrappers
-        .iter()
-        .position(|wrapper| same_mark_wrapper(wrapper, &tail_value))
-    else {
-        return;
-    };
-    for atom in &children[split..] {
-        atom.detach();
-        tail.append(atom);
-    }
-    let rest: Vec = wrappers
-        .iter()
-        .enumerate()
-        .filter(|(index, _)| *index != shared)
-        .map(|(_, wrapper)| wrapper.clone())
-        .collect();
-    adopt_trailing_html_atoms(tail, &rest);
-}
-
-fn append_inline_child<'a>(arena: &'a Arena<'a>, parent: &'a AstNode<'a>, child: &'a AstNode<'a>) {
-    if let Some((wrappers, leaf)) = peel_mark_chain(child) {
-        leaf.detach();
-        // #1412: html_inline atoms sitting between this chain and the
-        // tail mark wrapper join the span before the chain merges in.
-        adopt_trailing_html_atoms(parent, &wrappers);
-        insert_marked_chain(arena, parent, &wrappers, leaf);
-        return;
-    }
-    if let Some(last) = parent.last_child() {
-        let same = {
-            let last_value = last.data.borrow();
-            let child_value = child.data.borrow();
-            same_mark_wrapper(&last_value.value, &child_value.value)
-        };
-        if same {
-            let grandchildren: Vec<&AstNode<'a>> = child.children().collect();
-            for grandchild in grandchildren {
-                grandchild.detach();
-                append_inline_child(arena, last, grandchild);
-            }
-            return;
-        }
-    }
-    parent.append(child);
-}
-
-/// Create marked text node(s) - handles nested marks.
-fn create_marked_text<'a>(arena: &'a Arena<'a>, text: &str, marks: &[Value]) -> &'a AstNode<'a> {
-    if marks.is_empty() {
-        return arena.alloc(AstNode::from(NodeValue::Text(text.to_owned().into())));
-    }
-
-    // A code mark replaces the text node itself (code is the innermost
-    // mark, rank 4) but does NOT discard the other marks (#953): the
-    // remaining marks wrap the Code node via the same chain the plain
-    // text path uses, so [`code`](href) keeps its link and **`code`**
-    // keeps its strong.
-    let has_code = marks
-        .iter()
-        .any(|mark| mark["type"].as_str() == Some("code"));
-
-    // Collect wrapper values in the canonical nesting order, outermost
-    // first (#944): sort the incoming marks — whose array order depends on
-    // which spelling or editor produced the doc — so the same marked text
-    // always saves to the same markdown.
-    let mut sorted_marks: Vec<&Value> = marks.iter().collect();
-    sorted_marks.sort_by_key(|mark| mark_nesting_rank(mark["type"].as_str().unwrap_or("")));
-    let mut wrappers: Vec = Vec::new();
-
-    for mark in sorted_marks {
-        let mark_type = mark["type"].as_str().unwrap_or("");
-        let wrapper_value = match mark_type {
-            "em" => NodeValue::Emph,
-            "strong" => NodeValue::Strong,
-            "strikethrough" => NodeValue::Strikethrough,
-            "link" => {
-                let href = mark["attrs"]["href"].as_str().unwrap_or("");
-                let title = mark["attrs"]["title"].as_str().unwrap_or("");
-                NodeValue::Link(Box::new(comrak::nodes::NodeLink {
-                    url: href.to_owned(),
-                    title: title.to_owned(),
-                }))
-            }
-            _ => continue, // Skip code (handled below) and unknown marks
-        };
-        wrappers.push(wrapper_value);
-    }
-
-    // Start with the innermost node: a Code node when a code mark is
-    // present, otherwise the plain text node.
-    let inner_node = if has_code {
-        arena.alloc(AstNode::from(NodeValue::Code(comrak::nodes::NodeCode {
-            num_backticks: 1,
-            literal: text.to_owned(),
-        })))
-    } else {
-        arena.alloc(AstNode::from(NodeValue::Text(text.to_owned().into())))
-    };
-
-    if wrappers.is_empty() {
-        return inner_node;
-    }
-
-    // Build wrapper chain recursively - innermost mark wraps the inner
-    // node, outer marks wrap that. `build_mark_chain` consumes its list
-    // innermost first, so reverse the canonical outermost-first list.
-    wrappers.reverse();
-    build_mark_chain(arena, inner_node, &wrappers, 0)
-}
-
-/// Build a chain of mark wrappers around a text node.
-fn build_mark_chain<'a>(
-    arena: &'a Arena<'a>,
-    inner: &'a AstNode<'a>,
-    wrappers: &[NodeValue],
-    index: usize,
-) -> &'a AstNode<'a> {
-    if index >= wrappers.len() {
-        return inner;
-    }
-
-    let wrapper = arena.alloc(AstNode::from(wrappers[index].clone()));
-    wrapper.append(inner);
-
-    if index + 1 >= wrappers.len() {
-        wrapper
-    } else {
-        build_mark_chain(arena, wrapper, wrappers, index + 1)
-    }
-}
 
 /// Convert plain text to `ProseMirror` JSON document.
 ///
diff --git a/pkgs/id/src/web/markdown/markdown_scan.rs b/pkgs/id/src/web/markdown/markdown_scan.rs
new file mode 100644
index 0000000000..9bc0a0e5ee
--- /dev/null
+++ b/pkgs/id/src/web/markdown/markdown_scan.rs
@@ -0,0 +1,2187 @@
+//! Source scans and recovery for footnote and link-reference definitions.
+
+use serde_json::Value;
+
+use super::markdown_to_prosemirror_inner;
+use super::parse_helpers::restore_attr_newlines;
+
+/// Fence tracking for the source scans below: a fence opens with a
+/// run of >= 3 backticks or tildes and closes only with a run of the
+/// SAME character at least as long (CommonMark) -- a three-backtick
+/// line inside a four-backtick block is content, not a close (Codex
+/// P2 on the first #1565 cut, which toggled on any fence-shaped line).
+#[derive(Default)]
+struct FenceTracker {
+    open: Option<(char, usize)>,
+}
+
+/// The line to feed the FenceTracker: a fence delimiter may sit
+/// up to three columns in from its container's content edge
+/// (CommonMark), but strip_container_prefixes leaves those columns
+/// in place (`>   ```` arrives as two leading spaces), and
+/// FenceTracker::feed anchors the run at the first character -- so
+/// an indented opening fence inside a blockquote was missed and
+/// the "code" interior was scanned as live text (Codex P2 on
+/// #1565's twenty-fourth cut). Removing up to three leading spaces
+/// here keeps the four-column distinction: a line still indented
+/// after this (or tab-led, which is four columns at column 0)
+/// reaches the tracker space-led and opens no fence, exactly like
+/// indented code.
+fn fence_feed_line(line: &str) -> &str {
+    let spaces = line.chars().take_while(|&c| c == ' ').count().min(3);
+    &line[spaces..]
+}
+
+impl FenceTracker {
+    /// Feed one line (already stripped of up to three leading
+    /// spaces). Returns true when the line is a fence delimiter.
+    fn feed(&mut self, stripped: &str) -> bool {
+        let ch = match stripped.chars().next() {
+            Some(c @ ('`' | '~')) => c,
+            _ => return false,
+        };
+        let run = stripped.chars().take_while(|&c| c == ch).count();
+        if run < 3 {
+            return false;
+        }
+        if self.open.is_none() && ch == '`' && stripped[run..].contains('`') {
+            // A backtick fence's info string cannot contain a
+            // backtick (CommonMark), so a line like ```a`b opens
+            // no fence at all (Codex P2 on #1565's eighth cut).
+            return false;
+        }
+        match self.open {
+            None => {
+                self.open = Some((ch, run));
+                true
+            }
+            Some((open_ch, open_run)) => {
+                if ch == open_ch && run >= open_run && stripped[run..].trim().is_empty() {
+                    self.open = None;
+                    true
+                } else {
+                    false
+                }
+            }
+        }
+    }
+
+    fn in_fence(&self) -> bool {
+        self.open.is_some()
+    }
+
+    /// Forget any open fence: a fence opened inside a container
+    /// ends implicitly when the container ends, with no closing
+    /// delimiter line (Codex P2 on #1565's tenth cut).
+    fn reset(&mut self) {
+        self.open = None;
+    }
+}
+
+/// HTML-block tracking for the source scans below (Codex P2 on
+/// #1565's second cut): comrak parses a raw HTML block -- a comment,
+/// a script/pre/style/textarea element, a block-level tag, or a lone
+/// complete tag -- as literal content until its CommonMark end
+/// condition (the closing marker for comments/CDATA/PIs/tag-bodies,
+/// a blank line for plain block tags). A definition-shaped line in
+/// that interior is literal text, exactly as in a fence; without this
+/// tracking the pre-scan synthesized a live footnote out of a
+/// comment's interior and a save then moved it outside the comment.
+#[derive(Default)]
+struct HtmlBlockTracker {
+    /// What ends the open block: a literal closing marker, or a
+    /// blank line for block-tag (type 6/7) blocks.
+    end: Option,
+}
+
+#[derive(Clone, Copy, PartialEq)]
+enum HtmlBlockEnd {
+    Marker(&'static str),
+    BlankLine,
+}
+
+/// The CommonMark type-6 block-level tag names.
+const HTML_BLOCK_TAGS: &[&str] = &[
+    "address",
+    "article",
+    "aside",
+    "base",
+    "basefont",
+    "blockquote",
+    "body",
+    "caption",
+    "center",
+    "col",
+    "colgroup",
+    "dd",
+    "details",
+    "dialog",
+    "dir",
+    "div",
+    "dl",
+    "dt",
+    "fieldset",
+    "figcaption",
+    "figure",
+    "footer",
+    "form",
+    "frame",
+    "frameset",
+    "h1",
+    "h2",
+    "h3",
+    "h4",
+    "h5",
+    "h6",
+    "head",
+    "header",
+    "hr",
+    "html",
+    "iframe",
+    "legend",
+    "li",
+    "link",
+    "main",
+    "menu",
+    "menuitem",
+    "nav",
+    "noframes",
+    "ol",
+    "optgroup",
+    "option",
+    "p",
+    "param",
+    "search",
+    "section",
+    "summary",
+    "table",
+    "tbody",
+    "td",
+    "tfoot",
+    "th",
+    "thead",
+    "title",
+    "tr",
+    "track",
+    "ul",
+];
+
+/// Whether `trimmed` (a whole line, both ends trimmed) is exactly
+/// one complete HTML open or closing tag -- CommonMark type 7: a
+/// tag name (a letter, then letters/digits/`-`), then for an open
+/// tag any number of whitespace-separated attributes (a name, with
+/// an optional `=` and an unquoted, single-quoted, or
+/// double-quoted value), optional whitespace, an optional `/`,
+/// and the final `>`. A closing tag is ``. Anything else angle-delimited is NOT a tag:
+/// an autolink like `` (the `:` after the
+/// name is not whitespace, `/`, or `>`), or a tag-shaped line with
+/// junk where an attribute should be. Treating every
+/// angle-delimited string as an HTML block opened a
+/// blank-line-ended block on the autolink line and swallowed the
+/// heading and the valid orphan definition after it (Codex P2 on
+/// #1565's seventeenth cut).
+fn is_complete_html_tag(trimmed: &str) -> bool {
+    let bytes = trimmed.as_bytes();
+    if bytes.len() < 3 || bytes[0] != b'<' || bytes[bytes.len() - 1] != b'>' {
+        return false;
+    }
+    let inner = &trimmed[1..trimmed.len() - 1];
+    let b = inner.as_bytes();
+    let (closing, mut pos) = if b.first() == Some(&b'/') {
+        (true, 1)
+    } else {
+        (false, 0)
+    };
+    if !b.get(pos).is_some_and(|c| c.is_ascii_alphabetic()) {
+        return false;
+    }
+    let name_start = pos;
+    pos += 1;
+    while b
+        .get(pos)
+        .is_some_and(|c| c.is_ascii_alphanumeric() || *c == b'-')
+    {
+        pos += 1;
+    }
+    // Type 1 names never open a type 7 block with an OPENING tag
+    // (they are handled as marker-ended blocks above); a line
+    // naming one that reaches here did not match the type-1
+    // boundary rule either. The exclusion applies only to opening
+    // tags: a complete CLOSING tag of any name opens a type-7
+    // block, so `
` makes the following definition-shaped + // line its literal interior -- rejecting it recovered that + // line as a live definition (Codex P2 on #1565's + // twenty-first cut). + if !closing + && ["script", "pre", "style", "textarea"] + .contains(&inner[name_start..pos].to_ascii_lowercase().as_str()) + { + return false; + } + if closing { + while b.get(pos).is_some_and(|c| c.is_ascii_whitespace()) { + pos += 1; + } + return pos == inner.len(); + } + loop { + let ws_start = pos; + while b.get(pos).is_some_and(|c| c.is_ascii_whitespace()) { + pos += 1; + } + let had_ws = pos > ws_start; + match b.get(pos) { + None => return true, + Some(b'/') => return pos + 1 == inner.len(), + Some(_) if had_ws => { + // Attribute name, then an optional `= value`. + if !b + .get(pos) + .is_some_and(|c| c.is_ascii_alphabetic() || *c == b'_' || *c == b':') + { + return false; + } + pos += 1; + while b.get(pos).is_some_and(|c| { + c.is_ascii_alphanumeric() || matches!(c, b'-' | b'_' | b'.' | b':') + }) { + pos += 1; + } + let mut p2 = pos; + while b.get(p2).is_some_and(|c| c.is_ascii_whitespace()) { + p2 += 1; + } + if b.get(p2) == Some(&b'=') { + p2 += 1; + while b.get(p2).is_some_and(|c| c.is_ascii_whitespace()) { + p2 += 1; + } + match b.get(p2) { + Some(q @ (b'"' | b'\'')) => { + let q = *q; + p2 += 1; + while b.get(p2).is_some_and(|c| *c != q) { + p2 += 1; + } + if b.get(p2).is_none() { + return false; + } + p2 += 1; + } + Some(_) => { + let vstart = p2; + while b.get(p2).is_some_and(|c| { + !c.is_ascii_whitespace() + && !matches!(c, b'"' | b'\'' | b'=' | b'<' | b'>' | b'`') + }) { + p2 += 1; + } + if p2 == vstart { + return false; + } + } + None => return false, + } + pos = p2; + } + } + Some(_) => return false, + } + } +} + +impl HtmlBlockTracker { + fn in_html(&self) -> bool { + self.end.is_some() + } + + /// Forget any open block: a block opened inside a container + /// ends implicitly when the container ends, with no closing + /// line (Codex P2 on #1565's eleventh cut, mirroring + /// FenceTracker::reset). + fn reset(&mut self) { + self.end = None; + } + + /// Feed one line (already stripped of up to three leading + /// spaces). Returns true when the line belongs to an HTML block + /// (its opening line, interior, or closing line). + /// `may_open_type7` is the caller's paragraph context: a type-7 + /// block (a lone complete inline tag) cannot interrupt a + /// paragraph, so when the previous line is paragraph content + /// the caller passes false and a type-7 opening is refused + /// (Codex P2 on #1565's eighteenth cut). Types 1-6 can + /// interrupt a paragraph and are always eligible. + fn feed(&mut self, stripped: &str, may_open_type7: bool) -> bool { + if let Some(end) = self.end { + match end { + HtmlBlockEnd::Marker(marker) => { + if stripped.to_ascii_lowercase().contains(marker) { + self.end = None; + } + } + HtmlBlockEnd::BlankLine => { + if stripped.trim().is_empty() { + self.end = None; + } + } + } + return true; + } + let Some(rest) = stripped.strip_prefix('<') else { + return false; + }; + let lower = stripped.to_ascii_lowercase(); + // Marker-ended blocks (CommonMark types 1-5). The tag-named + // prefixes require a name boundary: `` is not a + // `
` block (nor `` a `"),
+            (""),
+            (""),
+            (""),
+        ] {
+            // The tag-named prefixes follow the CommonMark type-1
+            // boundary exactly: whitespace, '>', or end-of-line
+            // after the name. Anything else (`
`, ``)
+            // is a generic tag block ending at a blank line, not a
+            // marker-ended block (Codex P2 on #1565's tenth cut).
+            let boundary_ok = !prefix[1..].chars().all(|c| c.is_ascii_alphabetic())
+                || match lower.as_bytes().get(prefix.len()) {
+                    None => true,
+                    Some(b) => b.is_ascii_whitespace() || *b == b'>',
+                };
+            // CDATA is case-sensitive (CommonMark): only the
+            // exact uppercase `').
+            if !rest.contains('>') {
+                self.end = Some(HtmlBlockEnd::Marker(">"));
+            }
+            return true;
+        }
+        // Tag-ended blocks (types 6 and 7): a block-level tag, or a
+        // lone complete open/closing tag on the line.
+        let tag_body = rest.strip_prefix('/').unwrap_or(rest);
+        let tag_name: String = tag_body
+            .chars()
+            .take_while(|c| c.is_ascii_alphanumeric() || *c == '-')
+            .collect::()
+            .to_ascii_lowercase();
+        if tag_name.is_empty() {
+            return false;
+        }
+        if HTML_BLOCK_TAGS.contains(&tag_name.as_str())
+            && tag_name_boundary_ok(tag_body, tag_name.len())
+        {
+            self.end = Some(HtmlBlockEnd::BlankLine);
+            return true;
+        }
+        let trimmed = stripped.trim_end();
+        if is_complete_html_tag(trimmed) {
+            if !may_open_type7 {
+                return false;
+            }
+            self.end = Some(HtmlBlockEnd::BlankLine);
+            return true;
+        }
+        let _ = rest;
+        false
+    }
+}
+
+/// Strip block-container prefixes (blockquote `>`, list markers
+/// `-`/`*`/`+`/ordered) from a line, repeatedly, for fence detection:
+/// a fence opened inside a list item or blockquote still makes its
+/// content literal (Codex P2 on #1565's fourth cut -- `- ```` followed
+/// by an indented definition-shaped line parsed as code by comrak,
+/// but the scanner missed the opening fence behind the `- ` marker
+/// and recovered the interior line as a live definition).
+fn strip_container_prefixes(line: &str) -> &str {
+    let mut rest = line;
+    loop {
+        let t = rest.trim_start_matches(' ');
+        if let Some(r) = t.strip_prefix('>') {
+            rest = r.strip_prefix(' ').unwrap_or(r);
+            continue;
+        }
+        let bytes = t.as_bytes();
+        let marker_len = if bytes.len() >= 2
+            && matches!(bytes[0], b'-' | b'*' | b'+')
+            && (bytes[1] == b' ' || bytes[1] == b'\t')
+        {
+            Some(1)
+        } else {
+            let digits = t.chars().take_while(|c| c.is_ascii_digit()).count();
+            if digits >= 1
+                && digits <= 9
+                && matches!(t.as_bytes().get(digits), Some(b'.') | Some(b')'))
+                && matches!(t.as_bytes().get(digits + 1), Some(b' ') | Some(b'\t'))
+            {
+                Some(digits + 1)
+            } else {
+                None
+            }
+        };
+        let Some(marker_len) = marker_len else { break };
+        rest = strip_marker_padding(&t[marker_len..], marker_len);
+    }
+    rest
+}
+
+/// The content after a list marker, CommonMark-style: one to
+/// four columns of padding after the marker are the item's
+/// content indent and are stripped with the marker; FIVE or
+/// more columns mean the content is an indented code block
+/// whose indentation starts after a single padding column, so
+/// only that one column is stripped and the remaining
+/// indentation survives. Removing all the padding turned
+/// `-     ``` ` into a fence opener the document does not have,
+/// and the phantom fence then suppressed the valid reference
+/// definition after it (Codex P2 on #1565's twenty-first cut).
+fn strip_marker_padding(after: &str, marker_end_col: usize) -> &str {
+    let mut col = marker_end_col;
+    let mut end = 0;
+    for c in after.chars() {
+        match c {
+            ' ' => {
+                col += 1;
+                end += 1;
+            }
+            '\t' => {
+                col += 4 - (col % 4);
+                end += 1;
+            }
+            _ => break,
+        }
+    }
+    if col - marker_end_col > 4 {
+        // Keep all but the first padding character (spaces and
+        // tabs are one byte each, so this is a byte offset too).
+        &after[after.chars().next().map_or(0, |_| 1)..]
+    } else {
+        &after[end..]
+    }
+}
+
+/// The container structure of a recorded container prefix, as
+/// a string of marker kinds with all spacing removed: `> ` and
+/// `>` are the same blockquote level, so a fence opened under
+/// one spelling closes under the other (Codex P2 on #1565's
+/// nineteenth cut). Byte-exact prefix matching left such a
+/// fence open and suppressed the definitions after it.
+fn container_signature(prefix: &str) -> String {
+    let mut sig = String::new();
+    let mut rest = prefix;
+    loop {
+        let t = rest.trim_start_matches([' ', '\t']);
+        if let Some(r) = t.strip_prefix('>') {
+            sig.push('>');
+            rest = r;
+            continue;
+        }
+        let bytes = t.as_bytes();
+        if bytes.len() >= 2
+            && matches!(bytes[0], b'-' | b'*' | b'+')
+            && (bytes[1] == b' ' || bytes[1] == b'\t')
+        {
+            sig.push('*');
+            rest = &t[1..];
+            continue;
+        }
+        let digits = t.chars().take_while(|c| c.is_ascii_digit()).count();
+        if digits >= 1
+            && digits <= 9
+            && matches!(t.as_bytes().get(digits), Some(b'.') | Some(b')'))
+            && matches!(t.as_bytes().get(digits + 1), Some(b' ') | Some(b'\t'))
+        {
+            sig.push('#');
+            rest = &t[digits + 1..];
+            continue;
+        }
+        break;
+    }
+    sig
+}
+
+/// Strip at most `levels` container levels (blockquote `>`,
+/// list markers) from a line, mirroring
+/// strip_container_prefixes' per-level shapes.
+fn strip_container_levels(line: &str, levels: usize) -> &str {
+    let mut rest = line;
+    for _ in 0..levels {
+        let t = rest.trim_start_matches(' ');
+        if let Some(r) = t.strip_prefix('>') {
+            rest = r.strip_prefix(' ').unwrap_or(r);
+            continue;
+        }
+        let bytes = t.as_bytes();
+        let marker_len = if bytes.len() >= 2
+            && matches!(bytes[0], b'-' | b'*' | b'+')
+            && (bytes[1] == b' ' || bytes[1] == b'\t')
+        {
+            Some(1)
+        } else {
+            let digits = t.chars().take_while(|c| c.is_ascii_digit()).count();
+            if digits >= 1
+                && digits <= 9
+                && matches!(t.as_bytes().get(digits), Some(b'.') | Some(b')'))
+                && matches!(t.as_bytes().get(digits + 1), Some(b' ') | Some(b'\t'))
+            {
+                Some(digits + 1)
+            } else {
+                None
+            }
+        };
+        let Some(marker_len) = marker_len else { break };
+        rest = strip_marker_padding(&t[marker_len..], marker_len);
+    }
+    rest
+}
+
+/// Whether `stripped` (a line stripped of up to three leading
+/// spaces) carries the recorded container `prefix`, matched
+/// STRUCTURALLY rather than byte-for-byte: the line's own
+/// leading container levels (as many as the recorded prefix
+/// has) must have the same signature as the recorded prefix.
+fn carries_container_prefix(stripped: &str, prefix: &str) -> bool {
+    if prefix.is_empty() {
+        return false;
+    }
+    let levels = container_signature(prefix).chars().count();
+    if levels == 0 {
+        return false;
+    }
+    let own = &stripped[..stripped.len() - strip_container_levels(stripped, levels).len()];
+    !own.is_empty() && container_signature(own) == container_signature(prefix)
+}
+
+/// A footnote definition block found by the source pre-scan (#1565):
+/// its label and the block's verbatim source (the `[^label]:` line
+/// plus any indented continuation lines, trailing blank lines cut).
+struct FootnoteDefinitionBlock {
+    label: String,
+    source: String,
+    /// Zero-based line index of the definition's opening line, for
+    /// interleaving with other source segments in document order.
+    line: usize,
+}
+
+/// The label of a footnote definition starting on `line` (already
+/// stripped of up to three leading spaces), or `None` when the line
+/// does not start one. A definition opens as `[^label]:`.
+fn footnote_definition_label(line: &str) -> Option {
+    let rest = line.strip_prefix("[^")?;
+    // The label ends at the FIRST ']' and a ':' must follow it
+    // immediately. Searching for "]:" instead accepted `a]b` as the
+    // label of `[^a]b]: note` -- a definition comrak does not
+    // recognize, whose probe then looped recovery forever (Codex P1).
+    let close = rest.find(']')?;
+    if !rest[close + 1..].starts_with(':') {
+        return None;
+    }
+    let label = &rest[..close];
+    if label.is_empty() || label.contains('[') {
+        return None;
+    }
+    Some(label.to_string())
+}
+
+/// A thematic break: at least three of the same `-`, `*`, or `_`,
+/// spaces and tabs aside (CommonMark).
+fn is_thematic_break(stripped: &str) -> bool {
+    let compact: String = stripped
+        .chars()
+        .filter(|c| *c != ' ' && *c != '\t')
+        .collect();
+    let first = compact.chars().next();
+    compact.len() >= 3
+        && matches!(first, Some('-' | '*' | '_'))
+        && compact.chars().all(|c| Some(c) == first)
+}
+
+/// A setext heading underline: only `=`s (level 1) or `-`s (level 2).
+fn is_setext_underline(stripped: &str) -> bool {
+    let t = stripped.trim();
+    (!t.is_empty() && t.chars().all(|c| c == '=')) || (!t.is_empty() && t.chars().all(|c| c == '-'))
+}
+
+/// Whether a line starts a new block and so cannot be a lazy
+/// paragraph continuation of a footnote definition: another
+/// definition, an ATX heading, a fence, a blockquote, a thematic
+/// break, an HTML block opener, or a list/blockquote container line.
+/// Whether a line is an ATX heading: 1-6 `#`s followed by a
+/// space, a tab, or end-of-line (CommonMark). `#hashtag` is
+/// paragraph text, not a heading (Codex P2 on #1565's tenth cut).
+fn is_atx_heading(stripped: &str) -> bool {
+    let hashes = stripped.bytes().take_while(|&b| b == b'#').count();
+    (1..=6).contains(&hashes)
+        && matches!(
+            stripped.as_bytes().get(hashes),
+            None | Some(b' ') | Some(b'\t')
+        )
+}
+
+/// Whether the character after a block-level tag name is a valid
+/// name boundary: whitespace, `/`, `>`, or end-of-line (CommonMark
+/// type 6). `` has no boundary after `div`, so it is
+/// literal paragraph text, not an HTML block (Codex P2 on
+/// #1565's sixteenth cut).
+fn tag_name_boundary_ok(tag_body: &str, name_len: usize) -> bool {
+    matches!(
+        tag_body.as_bytes().get(name_len),
+        None | Some(b' ') | Some(b'\t') | Some(b'>') | Some(b'/')
+    )
+}
+
+/// Whether a line opens an HTML block that can INTERRUPT a
+/// paragraph (CommonMark types 1-6): a comment, a CDATA section,
+/// a processing instruction, a declaration, a script/pre/style/
+/// textarea element, or a block-level tag (opening or closing).
+/// A lone inline tag (``, ``) is type 7, which cannot
+/// interrupt a paragraph: as a footnote definition's next line it
+/// is a lazy continuation of the definition's paragraph, not a
+/// new block (Codex P2 on #1565's eleventh cut).
+fn is_html_block_start(stripped: &str) -> bool {
+    let Some(rest) = stripped.strip_prefix('<') else {
+        return false;
+    };
+    let lower = stripped.to_ascii_lowercase();
+    if lower.starts_with(" comments, which reparse as ```html fences
+        // and grow the file on every save. Move each later list's items
+        // into the first list (the first list's tight wins).
+        // ordered_list is NOT merged (it carries restart numbering) and
+        // task_list is a distinct PM node type, so neither is affected.
+        let mut prev_bullet_list: Option<&AstNode<'a>> = None;
+        for (idx, child_json) in content.iter().enumerate() {
+            let is_bullet_list = child_json["type"].as_str() == Some("bullet_list");
+            let normalized = normalize_inline_child_json(content, idx);
+            let child = json_to_ast(arena, &normalized)?;
+            if is_bullet_list && let Some(list_node) = prev_bullet_list {
+                let items: Vec<&AstNode<'a>> = child.children().collect();
+                for item in items {
+                    item.detach();
+                    list_node.append(item);
+                }
+                continue;
+            }
+            append_inline_child(arena, ast_node, child);
+            prev_bullet_list = if is_bullet_list { Some(child) } else { None };
+        }
+    }
+
+    // #1044: GFM has no headerless-table representation — comrak emits
+    // the delimiter row only when a row is marked as the header row, and
+    // without one the saved table reparses as a plain paragraph, silently
+    // destroying the table. The editor schema permits rows made only of
+    // table_cell, so when no row is a header row, promote the first row:
+    // a faithful rendering preserving every cell's content, and a one-time
+    // normalization (reparse yields table_header cells in row 0, so the
+    // next save is byte-identical). The table's alignments (#881) are
+    // stored on the table node and apply to the promoted row unchanged.
+    if node_type == "table" {
+        let mut first_row: Option<&AstNode<'a>> = None;
+        let mut has_header_row = false;
+        for child in ast_node.children() {
+            if let NodeValue::TableRow(is_header) = &child.data.borrow().value {
+                if first_row.is_none() {
+                    first_row = Some(child);
+                }
+                if *is_header {
+                    has_header_row = true;
+                }
+            }
+        }
+        if !has_header_row && let Some(row) = first_row {
+            row.data.borrow_mut().value = NodeValue::TableRow(true);
+        }
+    }
+
+    // Special case: image needs alt text as child (but NOT for HtmlInline, i.e. sized images)
+    // #1417: the stored alt is markdown form (see convert_node's Image
+    // arm) - re-parse it into inline nodes so emphasis/strong/code-span
+    // markup is emitted as markup, not as one flat (formatter-escaped)
+    // Text child. A plain-text alt re-parses to a single Text node,
+    // exactly the old behaviour.
+    if node_type == "image"
+        && matches!(ast_node.data.borrow().value, NodeValue::Image(_))
+        && let Some(alt) = json["attrs"]["alt"].as_str()
+        && !alt.is_empty()
+    {
+        for alt_node in alt_markdown_to_nodes(arena, alt) {
+            ast_node.append(alt_node);
+        }
+    }
+
+    // #880 + #1407: an image carrying linkHref (a linked image, see
+    // convert_node) and/or a `marks` array (emphasis/strong/
+    // strikethrough wrapping the image) is wrapped in the
+    // corresponding mark chain so save emits [![alt](src)](href),
+    // *![alt](src)*, or both combined. Wrappers use the canonical
+    // nesting order (#944) — the order create_marked_text applies —
+    // and the returned chain goes through append_inline_child's mark
+    // merging (#968), so a marked image inside a marked text span
+    // rejoins the span instead of fragmenting it.
+    if node_type == "image" && matches!(ast_node.data.borrow().value, NodeValue::Image(_)) {
+        let mut wrappers: Vec<(u8, NodeValue)> = Vec::new();
+        if let Some(link_href) = json["attrs"]["linkHref"].as_str()
+            && !link_href.is_empty()
+        {
+            wrappers.push((
+                mark_nesting_rank("link"),
+                NodeValue::Link(Box::new(comrak::nodes::NodeLink {
+                    url: link_href.to_owned(),
+                    title: json["attrs"]["linkTitle"].as_str().unwrap_or("").to_owned(),
+                })),
+            ));
+        }
+        if let Some(marks) = json["marks"].as_array() {
+            for mark in marks {
+                let mark_type = mark["type"].as_str().unwrap_or("");
+                let wrapper = match mark_type {
+                    "em" => NodeValue::Emph,
+                    "strong" => NodeValue::Strong,
+                    "strikethrough" => NodeValue::Strikethrough,
+                    _ => continue,
+                };
+                if !wrappers.iter().any(|(_, w)| same_mark_wrapper(w, &wrapper)) {
+                    wrappers.push((mark_nesting_rank(mark_type), wrapper));
+                }
+            }
+        }
+        if !wrappers.is_empty() {
+            wrappers.sort_by_key(|(rank, _)| *rank);
+            // build_mark_chain consumes innermost-first; the sorted
+            // list above is outermost-first (canonical rank order).
+            let chain: Vec = wrappers
+                .into_iter()
+                .map(|(_, wrapper)| wrapper)
+                .rev()
+                .collect();
+            return Ok(build_mark_chain(arena, ast_node, &chain, 0));
+        }
+    }
+
+    Ok(ast_node)
+}
+
+/// Whether comrak's AST validation accepts this node type as a direct
+/// child of a `TableCell` (#1017). Mirrors `can_contain_type` for
+/// `TableCell` in comrak's nodes.rs (shortcodes/heex variants are not
+/// enabled in this codec).
+fn valid_table_cell_child(value: &NodeValue) -> bool {
+    matches!(
+        value,
+        NodeValue::Text(..)
+            | NodeValue::Code(..)
+            | NodeValue::Emph
+            | NodeValue::Strong
+            | NodeValue::Link(..)
+            | NodeValue::Image(..)
+            | NodeValue::Strikethrough
+            | NodeValue::Highlight
+            | NodeValue::Insert
+            | NodeValue::HtmlInline(..)
+            | NodeValue::Math(..)
+            | NodeValue::WikiLink(..)
+            | NodeValue::FootnoteReference(..)
+            | NodeValue::Superscript
+            | NodeValue::SpoileredText
+            | NodeValue::Underline
+            | NodeValue::Subscript
+            | NodeValue::TaskItem(_)
+            | NodeValue::Escaped
+            | NodeValue::EscapedTag(_)
+    )
+}
+
+/// Append a converted child to a table cell, degrading anything comrak
+/// would reject there instead of building an ill-formed AST that makes
+/// `format_commonmark` panic (#1017):
+///
+/// - valid inline children pass through unchanged;
+/// - a hard/soft break degrades to a single space (a table cell is
+///   single-line content in markdown);
+/// - any other node (a list, code block, heading, nested table, …)
+///   flattens to its plain text, words space-joined.
+fn append_table_cell_child<'a>(
+    arena: &'a Arena<'a>,
+    cell: &'a AstNode<'a>,
+    child: &'a AstNode<'a>,
+) {
+    let value = &child.data.borrow().value;
+    if valid_table_cell_child(value) {
+        append_inline_child(arena, cell, child);
+        return;
+    }
+    if matches!(value, NodeValue::LineBreak | NodeValue::SoftBreak) {
+        let space = arena.alloc(AstNode::from(NodeValue::Text(" ".to_owned().into())));
+        cell.append(space);
+        return;
+    }
+    let mut segments: Vec = Vec::new();
+    collect_cell_text(child, &mut segments);
+    let text = segments
+        .join(" ")
+        .split_whitespace()
+        .collect::>()
+        .join(" ");
+    if !text.is_empty() {
+        let text_node = arena.alloc(AstNode::from(NodeValue::Text(text.into())));
+        cell.append(text_node);
+    }
+}
+
+/// Collect the text of a node being flattened into a table cell (#1017):
+/// text/code literals verbatim, breaks as spaces, and a space segment at
+/// every other node's boundary so sibling blocks cannot fuse into one
+/// word. The caller normalizes whitespace runs.
+fn collect_cell_text<'a>(node: &'a AstNode<'a>, segments: &mut Vec) {
+    match &node.data.borrow().value {
+        NodeValue::Text(literal) => segments.push(literal.to_string()),
+        NodeValue::Code(code) => segments.push(code.literal.clone()),
+        NodeValue::CodeBlock(code_block) => segments.push(code_block.literal.clone()),
+        NodeValue::LineBreak | NodeValue::SoftBreak => segments.push(" ".to_owned()),
+        _ => {
+            for child in node.children() {
+                collect_cell_text(child, segments);
+            }
+            segments.push(" ".to_owned());
+        }
+    }
+}
+
+/// Whether two node values are the same mark wrapper, so adjacent
+/// siblings carrying it are really one marked span (#953).
+fn same_mark_wrapper(a: &NodeValue, b: &NodeValue) -> bool {
+    match (a, b) {
+        (NodeValue::Link(x), NodeValue::Link(y)) => x.url == y.url && x.title == y.title,
+        (NodeValue::Strong, NodeValue::Strong)
+        | (NodeValue::Emph, NodeValue::Emph)
+        | (NodeValue::Strikethrough, NodeValue::Strikethrough) => true,
+        _ => false,
+    }
+}
+
+/// Whether a node value is a mark wrapper (the wrapper kinds
+/// `create_marked_text` chains and `same_mark_wrapper` compares).
+fn is_mark_wrapper(value: &NodeValue) -> bool {
+    matches!(
+        value,
+        NodeValue::Link(..) | NodeValue::Strong | NodeValue::Emph | NodeValue::Strikethrough
+    )
+}
+
+/// Peel a pure mark chain — wrapper → wrapper → … → a single
+/// non-wrapper leaf, as `create_marked_text` builds — into its wrapper
+/// values (outermost first) and the leaf node. Returns `None` for
+/// anything else (no wrappers, a wrapper with several children, a
+/// wrapper bottoming out in another wrapper): those children keep the
+/// legacy append behaviour.
+fn peel_mark_chain<'a>(child: &'a AstNode<'a>) -> Option<(Vec, &'a AstNode<'a>)> {
+    let mut wrappers: Vec = Vec::new();
+    let mut current = child;
+    loop {
+        let value = current.data.borrow().value.clone();
+        if !is_mark_wrapper(&value) {
+            break;
+        }
+        let mut children = current.children();
+        let only = children.next()?;
+        if children.next().is_some() {
+            return None;
+        }
+        wrappers.push(value);
+        current = only;
+    }
+    if wrappers.is_empty() || is_mark_wrapper(¤t.data.borrow().value) {
+        return None;
+    }
+    Some((wrappers, current))
+}
+
+/// Insert a peeled mark chain's leaf under `parent`, reusing the
+/// parent's tail wrapper whenever it carries one of the chain's marks
+/// (#968). Adjacent ProseMirror runs are converted one at a time, each
+/// in canonical rank order, so neighbouring runs that share a mark can
+/// disagree about which shared mark is outermost: `*em **strong**
+/// end*` arrives as Emph, Strong→Emph, Emph and used to render as
+/// three fragmented sibling spans with ` ` boundary entities.
+/// Reusing the tail wrapper for the shared mark — wherever it sits in
+/// the incoming chain — and nesting the chain's remaining wrappers
+/// inside it emits one properly nested span instead. When the tail
+/// shares no mark with the chain, the chain is appended fresh, which
+/// also subsumes the #953 same-wrapper merge (an identical tail
+/// wrapper is simply the shared mark at position 0, recursively).
+fn insert_marked_chain<'a>(
+    arena: &'a Arena<'a>,
+    parent: &'a AstNode<'a>,
+    wrappers: &[NodeValue],
+    leaf: &'a AstNode<'a>,
+) {
+    if !wrappers.is_empty()
+        && let Some(last) = parent.last_child()
+    {
+        let last_value = last.data.borrow().value.clone();
+        if is_mark_wrapper(&last_value)
+            && let Some(shared) = wrappers
+                .iter()
+                .position(|wrapper| same_mark_wrapper(wrapper, &last_value))
+        {
+            let rest: Vec = wrappers
+                .iter()
+                .enumerate()
+                .filter(|(index, _)| *index != shared)
+                .map(|(_, wrapper)| wrapper.clone())
+                .collect();
+            insert_marked_chain(arena, last, &rest, leaf);
+            return;
+        }
+    }
+    let mut current = parent;
+    for wrapper in wrappers {
+        let node = arena.alloc(AstNode::from(wrapper.clone()));
+        current.append(node);
+        current = node;
+    }
+    current.append(leaf);
+}
+
+/// Append an inline child, merging it into the previous sibling when
+/// both are the same mark wrapper (#953): `[a `code` b](href)` reaches
+/// the save direction as three text nodes that share the link mark, and
+/// three sibling Link nodes render as three fragmented links. Moving
+/// the new wrapper's children into the previous wrapper (recursively,
+/// so nested wrappers merge too) emits one link containing all three
+/// segments. Pure mark chains go through the #968 tail insertion
+/// (`insert_marked_chain`), which handles the #953 merge as its
+/// shared-mark case; non-chain children keep the original merge.
+
+/// #1412: adopt trailing `html_inline` atoms into the tail mark
+/// wrapper when a marked chain that shares that wrapper's mark is
+/// about to be inserted. The parse direction emits `html_inline`
+/// atoms markless (see the `NodeValue::HtmlInline` arm of
+/// `convert_node`), so a mark spanning an atom reaches the save
+/// direction as marked run, bare atom, marked run. Appending the
+/// atom as a sibling severs the tail wrapper: the next run opens a
+/// NEW wrapper and the span fragments (`[a x c](/y)` saved as
+/// `[a ](/y)[x](/y)[ c](/y)`, with ` ` leaks at emphasis
+/// seams). When the incoming chain shares a mark with the wrapper
+/// before the atoms, the atoms belong to that span: move them inside
+/// the wrapper (recursing along the chain's shared marks, mirroring
+/// `insert_marked_chain`'s descent, so nested spans adopt at the
+/// deepest shared level), after which the chain insertion merges
+/// into the same wrapper as usual. Atoms not followed by a chain
+/// sharing the preceding wrapper's mark keep their legacy sibling
+/// placement, so unmarked HTML and atoms after a finished span are
+/// unchanged. Extending the atom predicate (e.g. to images, #1407)
+/// generalizes this to the other atom kinds.
+fn adopt_trailing_html_atoms<'a>(parent: &'a AstNode<'a>, wrappers: &[NodeValue]) {
+    let children: Vec<&'a AstNode<'a>> = parent.children().collect();
+    let mut split = children.len();
+    while split > 0
+        && matches!(
+            children[split - 1].data.borrow().value,
+            NodeValue::HtmlInline(..)
+        )
+    {
+        split -= 1;
+    }
+    if split == children.len() || split == 0 {
+        return;
+    }
+    let tail = children[split - 1];
+    let tail_value = tail.data.borrow().value.clone();
+    if !is_mark_wrapper(&tail_value) {
+        return;
+    }
+    let Some(shared) = wrappers
+        .iter()
+        .position(|wrapper| same_mark_wrapper(wrapper, &tail_value))
+    else {
+        return;
+    };
+    for atom in &children[split..] {
+        atom.detach();
+        tail.append(atom);
+    }
+    let rest: Vec = wrappers
+        .iter()
+        .enumerate()
+        .filter(|(index, _)| *index != shared)
+        .map(|(_, wrapper)| wrapper.clone())
+        .collect();
+    adopt_trailing_html_atoms(tail, &rest);
+}
+
+fn append_inline_child<'a>(arena: &'a Arena<'a>, parent: &'a AstNode<'a>, child: &'a AstNode<'a>) {
+    if let Some((wrappers, leaf)) = peel_mark_chain(child) {
+        leaf.detach();
+        // #1412: html_inline atoms sitting between this chain and the
+        // tail mark wrapper join the span before the chain merges in.
+        adopt_trailing_html_atoms(parent, &wrappers);
+        insert_marked_chain(arena, parent, &wrappers, leaf);
+        return;
+    }
+    if let Some(last) = parent.last_child() {
+        let same = {
+            let last_value = last.data.borrow();
+            let child_value = child.data.borrow();
+            same_mark_wrapper(&last_value.value, &child_value.value)
+        };
+        if same {
+            let grandchildren: Vec<&AstNode<'a>> = child.children().collect();
+            for grandchild in grandchildren {
+                grandchild.detach();
+                append_inline_child(arena, last, grandchild);
+            }
+            return;
+        }
+    }
+    parent.append(child);
+}
+
+/// Create marked text node(s) - handles nested marks.
+fn create_marked_text<'a>(arena: &'a Arena<'a>, text: &str, marks: &[Value]) -> &'a AstNode<'a> {
+    if marks.is_empty() {
+        return arena.alloc(AstNode::from(NodeValue::Text(text.to_owned().into())));
+    }
+
+    // A code mark replaces the text node itself (code is the innermost
+    // mark, rank 4) but does NOT discard the other marks (#953): the
+    // remaining marks wrap the Code node via the same chain the plain
+    // text path uses, so [`code`](href) keeps its link and **`code`**
+    // keeps its strong.
+    let has_code = marks
+        .iter()
+        .any(|mark| mark["type"].as_str() == Some("code"));
+
+    // Collect wrapper values in the canonical nesting order, outermost
+    // first (#944): sort the incoming marks — whose array order depends on
+    // which spelling or editor produced the doc — so the same marked text
+    // always saves to the same markdown.
+    let mut sorted_marks: Vec<&Value> = marks.iter().collect();
+    sorted_marks.sort_by_key(|mark| mark_nesting_rank(mark["type"].as_str().unwrap_or("")));
+    let mut wrappers: Vec = Vec::new();
+
+    for mark in sorted_marks {
+        let mark_type = mark["type"].as_str().unwrap_or("");
+        let wrapper_value = match mark_type {
+            "em" => NodeValue::Emph,
+            "strong" => NodeValue::Strong,
+            "strikethrough" => NodeValue::Strikethrough,
+            "link" => {
+                let href = mark["attrs"]["href"].as_str().unwrap_or("");
+                let title = mark["attrs"]["title"].as_str().unwrap_or("");
+                NodeValue::Link(Box::new(comrak::nodes::NodeLink {
+                    url: href.to_owned(),
+                    title: title.to_owned(),
+                }))
+            }
+            _ => continue, // Skip code (handled below) and unknown marks
+        };
+        wrappers.push(wrapper_value);
+    }
+
+    // Start with the innermost node: a Code node when a code mark is
+    // present, otherwise the plain text node.
+    let inner_node = if has_code {
+        arena.alloc(AstNode::from(NodeValue::Code(comrak::nodes::NodeCode {
+            num_backticks: 1,
+            literal: text.to_owned(),
+        })))
+    } else {
+        arena.alloc(AstNode::from(NodeValue::Text(text.to_owned().into())))
+    };
+
+    if wrappers.is_empty() {
+        return inner_node;
+    }
+
+    // Build wrapper chain recursively - innermost mark wraps the inner
+    // node, outer marks wrap that. `build_mark_chain` consumes its list
+    // innermost first, so reverse the canonical outermost-first list.
+    wrappers.reverse();
+    build_mark_chain(arena, inner_node, &wrappers, 0)
+}
+
+/// Build a chain of mark wrappers around a text node.
+fn build_mark_chain<'a>(
+    arena: &'a Arena<'a>,
+    inner: &'a AstNode<'a>,
+    wrappers: &[NodeValue],
+    index: usize,
+) -> &'a AstNode<'a> {
+    if index >= wrappers.len() {
+        return inner;
+    }
+
+    let wrapper = arena.alloc(AstNode::from(wrappers[index].clone()));
+    wrapper.append(inner);
+
+    if index + 1 >= wrappers.len() {
+        wrapper
+    } else {
+        build_mark_chain(arena, wrapper, wrappers, index + 1)
+    }
+}
diff --git a/pkgs/id/src/web/markdown/parse_helpers.rs b/pkgs/id/src/web/markdown/parse_helpers.rs
new file mode 100644
index 0000000000..2a11874f5a
--- /dev/null
+++ b/pkgs/id/src/web/markdown/parse_helpers.rs
@@ -0,0 +1,375 @@
+//! Parsing safeguards for destinations, tables, and restored attributes.
+
+use serde_json::Value;
+
+/// Replace each newline inside an angle-form link/image destination
+/// (`](<...>)` inline, `]: <...>` reference definition) with a token
+/// comrak keeps verbatim in the parsed URL, returning the protected
+/// source and the token used (`None` when no destination needed
+/// protection). Literal contexts are skipped — a destination-shaped
+/// string inside a fenced code block, an inline code span, or an
+/// indented code block is literal text, not a link (#1707). Fence
+/// tracking respects the opening fence's character and length. A
+/// candidate destination that hits a blank line — including a
+/// whitespace-only one — or another `<` before its closing `>` is
+/// not a destination and is left alone.
+pub(super) fn protect_newline_destinations(markdown: &str) -> (String, Option) {
+    if !markdown.contains('\n') {
+        return (markdown.to_string(), None);
+    }
+    let mut token = String::from("idweb-newline-0-token");
+    let mut counter = 0;
+    while markdown.contains(&token) {
+        counter += 1;
+        token = format!("idweb-newline-{counter}-token");
+    }
+    let bytes = markdown.as_bytes();
+    let mut out = String::with_capacity(markdown.len());
+    let mut i = 0;
+    // The open fence, when inside one: its character and run length.
+    // A closing fence must use the same character and be at least as
+    // long as the opener — a shorter fence line inside a longer
+    // fence is literal content, not the end of the block (#1707).
+    let mut fence: Option<(u8, usize)> = None;
+    // Whether the current line is a fence line (opens, closes, or is
+    // checked against an open fence): its backticks are fence syntax,
+    // never an inline code span opener.
+    let mut fence_line = false;
+    // The open inline code span's backtick run length, when inside
+    // one: span content is literal text, so a destination-shaped
+    // string inside it must not be protected (#1707).
+    let mut span: Option = None;
+    // Whether the current line is an indented code block line
+    // (4+ space indent at the start of a block): literal text too.
+    let mut in_indented = false;
+    let mut prev_line_blank = true;
+    let mut prev_line_indented = false;
+    let mut protected_any = false;
+    while i < bytes.len() {
+        // Line-start classification: fences, indented code blocks.
+        if i == 0 || bytes[i - 1] == b'\n' {
+            let mut j = i;
+            while j < bytes.len() && bytes[j] == b' ' {
+                j += 1;
+            }
+            let indent = j - i;
+            let line_blank = j >= bytes.len() || bytes[j] == b'\n';
+            // Fences are recognised at up to 3 spaces of indent.
+            let fence_run =
+                if indent <= 3 && j < bytes.len() && (bytes[j] == b'`' || bytes[j] == b'~') {
+                    let ch = bytes[j];
+                    let mut n = 0;
+                    while j + n < bytes.len() && bytes[j + n] == ch {
+                        n += 1;
+                    }
+                    if n >= 3 { Some((ch, n)) } else { None }
+                } else {
+                    None
+                };
+            let was_in_fence = fence.is_some();
+            match (fence, fence_run) {
+                (None, Some(open)) => fence = Some(open),
+                (Some((ch, n)), Some((cch, cn))) if cch == ch && cn >= n => fence = None,
+                _ => {}
+            }
+            fence_line = fence_run.is_some() && (was_in_fence || fence.is_some());
+            // An indented code block starts on a 4+ indented line
+            // after a blank line (or at the start, or continuing an
+            // indented block); a 4+ indented line inside a paragraph
+            // is a lazy continuation, not code.
+            in_indented = indent >= 4 && fence.is_none() && (prev_line_blank || prev_line_indented);
+            prev_line_indented = in_indented || (indent >= 4 && line_blank && prev_line_indented);
+            prev_line_blank = line_blank;
+        }
+        let literal_line = fence.is_some() || in_indented || fence_line;
+        if !literal_line
+            && span.is_none()
+            && (markdown[i..].starts_with("](<") || markdown[i..].starts_with("]: <"))
+        {
+            let lt = if markdown[i..].starts_with("](<") {
+                i + 2
+            } else {
+                i + 3
+            };
+            // Find the closing '>' before any blank line (a line of
+            // only spaces/tabs between the newlines is blank too —
+            // the paragraph break ends any destination, #1707) or a
+            // nested '<'.
+            let mut end = None;
+            let mut k = lt + 1;
+            while k < bytes.len() {
+                match bytes[k] {
+                    b'>' => {
+                        end = Some(k);
+                        break;
+                    }
+                    b'<' => break,
+                    b'\n' => {
+                        let mut m = k + 1;
+                        while m < bytes.len()
+                            && (bytes[m] == b' ' || bytes[m] == b'\t' || bytes[m] == b'\r')
+                        {
+                            m += 1;
+                        }
+                        if m >= bytes.len() || bytes[m] == b'\n' {
+                            break;
+                        }
+                        k += 1;
+                    }
+                    _ => k += 1,
+                }
+            }
+            if let Some(gt) = end {
+                let dest = &markdown[lt + 1..gt];
+                if dest.contains('\n') {
+                    out.push_str(&markdown[i..=lt]);
+                    out.push_str(&dest.replace('\n', &token));
+                    i = gt;
+                    protected_any = true;
+                    continue;
+                }
+            }
+        }
+        // Inline code span tracking (#1707): a run of backticks
+        // outside fences/indented code opens a span closed by a run
+        // of the same length; everything between is literal. Fence
+        // lines were already classified at line start, so a run seen
+        // here at a line start is a span only when it did not form a
+        // fence (shorter than 3, or inside a fence — but fence lines
+        // never reach here as non-literal).
+        if !literal_line && bytes[i] == b'`' {
+            let mut n = 0;
+            while i + n < bytes.len() && bytes[i + n] == b'`' {
+                n += 1;
+            }
+            match span {
+                None => span = Some(n),
+                Some(open) if n == open => span = None,
+                _ => {}
+            }
+            out.push_str(&markdown[i..i + n]);
+            i += n;
+            continue;
+        }
+        let Some(ch) = markdown[i..].chars().next() else {
+            break;
+        };
+        let ch_len = ch.len_utf8();
+        out.push_str(&markdown[i..i + ch_len]);
+        i += ch_len;
+    }
+    if protected_any {
+        (out, Some(token))
+    } else {
+        (markdown.to_string(), None)
+    }
+}
+
+/// Whether `line` is a GFM table delimiter row (`| --- | :---: |`,
+/// `--- | ---`, …): optional outer pipes, every cell a run of dashes
+/// with an optional alignment colon on each side. The line must contain
+/// a pipe — a bare `---` is a setext underline or thematic break, and
+/// every table comrak itself renders carries pipes in its delimiter
+/// row.
+fn is_table_delimiter_row(line: &str) -> bool {
+    let trimmed = line.trim();
+    if !trimmed.contains('-') || !trimmed.contains('|') {
+        return false;
+    }
+    let body = trimmed.strip_prefix('|').unwrap_or(trimmed);
+    let body = body.strip_suffix('|').unwrap_or(body);
+    if body.trim().is_empty() {
+        return false;
+    }
+    body.split('|').all(|cell| {
+        let cell = cell.trim();
+        let cell = cell.strip_prefix(':').unwrap_or(cell);
+        let cell = cell.strip_suffix(':').unwrap_or(cell);
+        !cell.is_empty() && cell.bytes().all(|b| b == b'-')
+    })
+}
+
+/// Whether the byte at `i` is backslash-escaped: preceded by an odd
+/// number of backslashes.
+fn byte_is_escaped(bytes: &[u8], i: usize) -> bool {
+    let mut backslashes = 0;
+    let mut j = i;
+    while j > 0 && bytes[j - 1] == b'\\' {
+        backslashes += 1;
+        j -= 1;
+    }
+    backslashes % 2 == 1
+}
+
+/// Escape every unescaped pipe inside a code span on a single line
+/// (#1424). A code span opens at an unescaped backtick run and closes
+/// at the next run of exactly the same length on the same line; an
+/// unmatched run is literal text and is left alone, as is everything
+/// outside code spans (plain-text pipes are the row syntax itself).
+fn escape_code_span_pipes_in_line(line: &str) -> String {
+    let bytes = line.as_bytes();
+    let mut out = String::with_capacity(line.len() + 8);
+    let mut i = 0;
+    while i < bytes.len() {
+        if bytes[i] == b'`' && !byte_is_escaped(bytes, i) {
+            let mut run = 0;
+            while i + run < bytes.len() && bytes[i + run] == b'`' {
+                run += 1;
+            }
+            // Find the closing run of exactly `run` backticks.
+            let mut close = None;
+            let mut j = i + run;
+            while j < bytes.len() {
+                if bytes[j] == b'`' {
+                    let mut r = 0;
+                    while j + r < bytes.len() && bytes[j + r] == b'`' {
+                        r += 1;
+                    }
+                    if r == run {
+                        close = Some((j, j + r));
+                        break;
+                    }
+                    j += r;
+                } else {
+                    j += 1;
+                }
+            }
+            if let Some((close_start, close_end)) = close {
+                out.push_str(&line[i..i + run]);
+                let mut backslashes = 0usize;
+                for ch in line[i + run..close_start].chars() {
+                    if ch == '|' && backslashes % 2 == 0 {
+                        out.push('\\');
+                    }
+                    if ch == '\\' {
+                        backslashes += 1;
+                    } else {
+                        backslashes = 0;
+                    }
+                    out.push(ch);
+                }
+                out.push_str(&line[close_start..close_end]);
+                i = close_end;
+                continue;
+            }
+            out.push_str(&line[i..i + run]);
+            i += run;
+            continue;
+        }
+        let ch_len = line[i..].chars().next().unwrap().len_utf8();
+        out.push_str(&line[i..i + ch_len]);
+        i += ch_len;
+    }
+    out
+}
+
+/// Escape pipes inside code spans in the rows of every table in
+/// `markdown` (#1424): the header row (identified by the delimiter row
+/// that follows it), and the body rows that follow the delimiter row
+/// up to the next blank line. Lines outside tables are returned
+/// untouched — outside a table `\|` inside a code span is literal
+/// text, not an escape, so escaping there would corrupt the span.
+/// Fenced code blocks are skipped for the same reason (#2362): a
+/// table example inside a fence is literal text comrak renders
+/// verbatim, not a live table — the fence tracking mirrors
+/// `protect_newline_destinations`.
+/// A fence delimiter line (CommonMark §4.5): up to three leading
+/// spaces, then a run of at least three backticks or tildes. Either
+/// character toggles — the same approximation
+/// `protect_newline_destinations` makes.
+fn is_fence_line(line: &str) -> bool {
+    let mut spaces = 0;
+    let mut chars = line.chars();
+    let first = loop {
+        match chars.next() {
+            Some(' ') => {
+                spaces += 1;
+                if spaces > 3 {
+                    return false;
+                }
+            }
+            Some(c) => break c,
+            None => return false,
+        }
+    };
+    if first != '`' && first != '~' {
+        return false;
+    }
+    1 + chars.take_while(|&c| c == first).count() >= 3
+}
+
+pub(super) fn escape_table_code_span_pipes(markdown: &str) -> String {
+    if !markdown.contains('`') || !markdown.contains('|') {
+        return markdown.to_string();
+    }
+    let lines: Vec<&str> = markdown.split_inclusive('\n').collect();
+    let mut out = String::with_capacity(markdown.len() + 16);
+    let mut in_table = false;
+    let mut in_fence = false;
+    for (idx, raw) in lines.iter().enumerate() {
+        let line = raw.strip_suffix('\n').unwrap_or(raw);
+        let line = line.strip_suffix('\r').unwrap_or(line);
+        let ending = &raw[line.len()..];
+        if is_fence_line(line) {
+            in_fence = !in_fence;
+            if in_fence {
+                // A table cannot span a fence; a delimiter-looking
+                // row inside the fence must not arm `in_table` for
+                // whatever follows the fence either.
+                in_table = false;
+            }
+            out.push_str(raw);
+            continue;
+        }
+        if in_fence {
+            out.push_str(raw);
+            continue;
+        }
+        if is_table_delimiter_row(line) {
+            in_table = true;
+            out.push_str(raw);
+            continue;
+        }
+        if in_table && line.trim().is_empty() {
+            in_table = false;
+        }
+        let header_row = lines
+            .get(idx + 1)
+            .is_some_and(|next| is_table_delimiter_row(next));
+        if in_table || header_row {
+            out.push_str(&escape_code_span_pipes_in_line(line));
+            out.push_str(ending);
+        } else {
+            out.push_str(raw);
+        }
+    }
+    out
+}
+
+/// Restore protected newlines in the converted document: the token
+/// only ever stands inside a link `href` or image `src` attr (the
+/// parse produced it from a destination), so only those string attrs
+/// are rewritten — literal text that happens to contain the token
+/// string is untouched.
+pub(super) fn restore_attr_newlines(value: &mut Value, token: &str) {
+    match value {
+        Value::Object(map) => {
+            for (key, val) in map.iter_mut() {
+                if (key == "href" || key == "src")
+                    && let Value::String(text) = val
+                    && text.contains(token)
+                {
+                    *text = text.replace(token, "\n");
+                } else {
+                    restore_attr_newlines(val, token);
+                }
+            }
+        }
+        Value::Array(items) => {
+            for item in items {
+                restore_attr_newlines(item, token);
+            }
+        }
+        _ => {}
+    }
+}
diff --git a/pkgs/id/src/web/markdown/prosemirror_json.rs b/pkgs/id/src/web/markdown/prosemirror_json.rs
new file mode 100644
index 0000000000..15fb4863cd
--- /dev/null
+++ b/pkgs/id/src/web/markdown/prosemirror_json.rs
@@ -0,0 +1,1318 @@
+//! Conversion from comrak AST nodes to ProseMirror JSON.
+
+use comrak::nodes::{AstNode, ListDelimType, ListType, NodeValue};
+use comrak::{Arena, parse_document};
+use serde_json::{Value, json};
+
+use super::{ConversionError, commonmark_options};
+
+/// Active marks being applied to inline content.
+#[derive(Clone)]
+pub(super) struct Mark {
+    mark_type: &'static str,
+    attrs: Option,
+}
+
+/// Canonical mark nesting order, outermost first (#944).
+///
+/// Both conversion directions agree on this order, so a marked text node
+/// has exactly one markdown spelling: the parse direction sorts the marks
+/// it emits into this order (see [`text_node_with_marks`]) and the save
+/// direction sorts incoming marks into this order before wrapping (see
+/// `create_marked_text`). Without the shared order, `**[text](url)` and
+/// `[**text**](url)` converted into each other on every save — the parse
+/// direction appends marks outermost-first (wrapper arms push as they
+/// nest) while the save direction treated the array as innermost-first.
+pub(super) fn mark_nesting_rank(mark_type: &str) -> u8 {
+    match mark_type {
+        "link" => 0,
+        "strong" => 1,
+        "em" => 2,
+        "strikethrough" => 3,
+        "code" => 4,
+        _ => 5,
+    }
+}
+
+/// Convert a comrak AST node to `ProseMirror` JSON.
+pub(super) fn convert_node<'a>(node: &'a AstNode<'a>, active_marks: &[Mark]) -> Value {
+    let data = node.data.borrow();
+
+    match &data.value {
+        NodeValue::Document => {
+            let content = collect_block_children(node);
+            json!({
+                "type": "doc",
+                "content": if content.is_empty() {
+                    vec![json!({"type": "paragraph"})]
+                } else {
+                    content
+                }
+            })
+        }
+
+        NodeValue::Paragraph => {
+            let content = collect_inline_children(node, active_marks);
+            if content.is_empty() {
+                json!({"type": "paragraph"})
+            } else {
+                json!({
+                    "type": "paragraph",
+                    "content": content
+                })
+            }
+        }
+
+        NodeValue::Heading(heading) => {
+            let content = collect_inline_children(node, active_marks);
+            let mut node_json = json!({
+                "type": "heading",
+                "attrs": {"level": heading.level}
+            });
+            if !content.is_empty() {
+                node_json["content"] = json!(content);
+            }
+            node_json
+        }
+
+        NodeValue::BlockQuote => {
+            let content = collect_block_children(node);
+            json!({
+                "type": "blockquote",
+                "content": if content.is_empty() {
+                    vec![json!({"type": "paragraph"})]
+                } else {
+                    content
+                }
+            })
+        }
+
+        NodeValue::CodeBlock(code_block) => {
+            let text = &code_block.literal;
+            // Remove trailing newline if present (ProseMirror doesn't expect it)
+            let text = text.strip_suffix('\n').unwrap_or(text);
+
+            let mut node_json = json!({"type": "code_block"});
+
+            // Add params attribute if there's an info string
+            if !code_block.info.is_empty() {
+                node_json["attrs"] = json!({"params": code_block.info});
+            }
+
+            if !text.is_empty() {
+                node_json["content"] = json!([{"type": "text", "text": text}]);
+            }
+
+            node_json
+        }
+
+        NodeValue::ThematicBreak => {
+            json!({"type": "horizontal_rule"})
+        }
+
+        NodeValue::FrontMatter(text) => {
+            json!({
+                "type": "front_matter",
+                "attrs": {
+                    "text": text,
+                }
+            })
+        }
+
+        NodeValue::List(_) => {
+            // #1370: a mixed task/plain list converts to several sibling
+            // lists (see convert_list_runs); block parents splice them in
+            // via collect_block_children. A direct call gets the first
+            // run - the remaining call sites are the document root and
+            // list-item collection, where a list is always reached
+            // through its parent's block children instead.
+            convert_list_runs(node)
+                .into_iter()
+                .next()
+                .unwrap_or(Value::Null)
+        }
+
+        NodeValue::Item(_) => {
+            let content = collect_block_children(node);
+            json!({
+                "type": "list_item",
+                "content": if content.is_empty() {
+                    vec![json!({"type": "paragraph"})]
+                } else {
+                    content
+                }
+            })
+        }
+
+        NodeValue::Text(text) => text_node_with_marks(text.as_ref(), active_marks),
+
+        NodeValue::SoftBreak => {
+            // Soft breaks become spaces in ProseMirror
+            text_node_with_marks(" ", active_marks)
+        }
+
+        NodeValue::LineBreak => {
+            json!({"type": "hard_break"})
+        }
+
+        NodeValue::Code(code) => {
+            // Inline code - add code mark to the text
+            let mut marks = active_marks.to_vec();
+            marks.push(Mark {
+                mark_type: "code",
+                attrs: None,
+            });
+            text_node_with_marks(&code.literal, &marks)
+        }
+
+        NodeValue::Emph => {
+            // Emphasis - collect children with em mark added
+            let mut marks = active_marks.to_vec();
+            marks.push(Mark {
+                mark_type: "em",
+                attrs: None,
+            });
+            // Return children directly (will be flattened by caller)
+            json!(collect_inline_children(node, &marks))
+        }
+
+        NodeValue::Strong => {
+            // Strong - collect children with strong mark added
+            let mut marks = active_marks.to_vec();
+            marks.push(Mark {
+                mark_type: "strong",
+                attrs: None,
+            });
+            json!(collect_inline_children(node, &marks))
+        }
+
+        NodeValue::Link(link) => {
+            // Link - collect children with link mark added
+            let mut marks = active_marks.to_vec();
+            let mut attrs = json!({"href": link.url});
+            if !link.title.is_empty() {
+                attrs["title"] = json!(link.title);
+            }
+            marks.push(Mark {
+                mark_type: "link",
+                attrs: Some(attrs),
+            });
+            let children = collect_inline_children(node, &marks);
+            if children.is_empty() {
+                // #996: an empty-text link has no inline children to
+                // carry the link mark, so without this the mark — and
+                // the href — vanish and save emits nothing. Synthesize
+                // an empty text node carrying the mark; the save side
+                // wraps it back into a Link node (create_marked_text),
+                // so `[](url)` round-trips.
+                return json!(vec![text_node_with_marks("", &marks)]);
+            }
+            json!(children)
+        }
+
+        NodeValue::Image(image) => {
+            let mut attrs = json!({
+                "src": image.url
+            });
+
+            // #1417: store the alt in markdown form, not flattened plain
+            // text - get_text_content dropped emphasis/strong/code-span
+            // structure, so `![*alt*](/x)` saved back as `![alt](/x)`.
+            // The PM image node carries `alt` as a plain string
+            // (editor.ts schema), so that string IS the markdown source
+            // for the alt; the save direction re-parses it into inline
+            // nodes (see json_to_ast's image special case). Plain-text
+            // alts are unchanged by this encoding. Editor limitation:
+            // the alt popover shows/edits the markdown form (e.g.
+            // `*alt*`), which is the documented trade-off for #1417.
+            let alt = get_alt_markdown(node);
+            if !alt.is_empty() {
+                attrs["alt"] = json!(alt);
+            }
+
+            if !image.title.is_empty() {
+                attrs["title"] = json!(image.title);
+            }
+
+            // #880: an image inside a link arrives here with a link mark in
+            // active_marks (the Link arm is a mark wrapper). Carry the link
+            // on the image node itself — the editor schema has no way to
+            // wrap an image node in a mark — so the href survives to save.
+            if let Some(link_mark) = active_marks.iter().find(|m| m.mark_type == "link")
+                && let Some(link_attrs) = &link_mark.attrs
+            {
+                if let Some(href) = link_attrs["href"].as_str() {
+                    attrs["linkHref"] = json!(href);
+                }
+                if let Some(link_title) = link_attrs["title"].as_str() {
+                    attrs["linkTitle"] = json!(link_title);
+                }
+            }
+
+            // #1407: emphasis/strong/strikethrough wrapping an image
+            // ride on the image node as a `marks` array (the text-node
+            // shape) — like the link above, the editor schema cannot
+            // wrap an image node in a mark, so the marks travel on the
+            // node and the save direction re-wraps (see the image case
+            // in json_to_ast). The link stays in linkHref (#880).
+            let wrap_marks: Vec = active_marks
+                .iter()
+                .filter(|m| matches!(m.mark_type, "em" | "strong" | "strikethrough"))
+                .map(|m| json!({"type": m.mark_type}))
+                .collect();
+            let mut image_node = json!({
+                "type": "image",
+                "attrs": attrs
+            });
+            if !wrap_marks.is_empty() {
+                image_node["marks"] = json!(wrap_marks);
+            }
+            image_node
+        }
+
+        // Unsupported nodes - pass through as best we can
+        NodeValue::HtmlBlock(html) => {
+            // Check if this is an  tag with width/height, or the
+            // combined  sized linked image form (#893)
+            let trimmed = html.literal.trim();
+            if let Some(img_node) = parse_linked_img_tag(trimmed).or_else(|| parse_img_tag(trimmed))
+            {
+                // Wrap in paragraph since this is block-level
+                return json!({
+                    "type": "paragraph",
+                    "content": [img_node]
+                });
+            }
+            // Convert HTML blocks to code blocks (safe fallback), with
+            // a provenance attr (#982, cf. the #880 linkHref precedent):
+            // in PM shape a converted block is otherwise identical to an
+            // authored ```html fence, so the save direction uses
+            // `htmlBlock` to tell them apart and emit a real HtmlBlock
+            // for converted blocks while authored fences stay fenced.
+            let text = html.literal.strip_suffix('\n').unwrap_or(&html.literal);
+            if text.is_empty() {
+                json!({"type": "paragraph"})
+            } else {
+                json!({
+                    "type": "code_block",
+                    "attrs": {"params": "html", "htmlBlock": true},
+                    "content": [{"type": "text", "text": text}]
+                })
+            }
+        }
+
+        NodeValue::HtmlInline(html) => {
+            // Check if this is an  tag with width/height, or the
+            // combined  form in a single literal (#893; the
+            // split form is merged in collect_inline_children)
+            if let Some(img_attrs) = parse_linked_img_tag(html).or_else(|| parse_img_tag(html)) {
+                return img_attrs;
+            }
+            // #943: other inline HTML passes through as an html_inline
+            // atom node carrying the raw tag, so the save direction emits
+            // it verbatim (NodeValue::HtmlInline) instead of the comrak
+            // text renderer backslash-escaping it as literal text.
+            json!({
+                "type": "html_inline",
+                "attrs": {"html": html}
+            })
+        }
+
+        NodeValue::Table(table) => {
+            let children = collect_block_children(node);
+            let mut table_json = json!({
+                "type": "table",
+                "content": if children.is_empty() {
+                    vec![json!({"type": "table_row", "content": [{"type": "table_cell", "content": [{"type": "paragraph"}]}]})]
+                } else {
+                    children
+                }
+            });
+            // #881: carry column alignments on the table node (absent = all
+            // None, exactly as before) so the delimiter row survives save.
+            if table
+                .alignments
+                .iter()
+                .any(|a| !matches!(a, comrak::nodes::TableAlignment::None))
+            {
+                let alignments: Vec = table
+                    .alignments
+                    .iter()
+                    .map(|a| {
+                        json!(match a {
+                            comrak::nodes::TableAlignment::Left => "left",
+                            comrak::nodes::TableAlignment::Center => "center",
+                            comrak::nodes::TableAlignment::Right => "right",
+                            comrak::nodes::TableAlignment::None => "none",
+                        })
+                    })
+                    .collect();
+                table_json["attrs"] = json!({ "alignments": alignments });
+            }
+            table_json
+        }
+
+        NodeValue::TableRow(is_header) => {
+            let cell_type = if *is_header {
+                "table_header"
+            } else {
+                "table_cell"
+            };
+            let children: Vec = node
+                .children()
+                .map(|child| {
+                    // Table cells contain inline content in comrak,
+                    // but ProseMirror needs block content (paragraphs)
+                    let inline_content = collect_inline_children(child, active_marks);
+                    let content = if inline_content.is_empty() {
+                        vec![json!({"type": "paragraph"})]
+                    } else {
+                        vec![json!({"type": "paragraph", "content": inline_content})]
+                    };
+                    json!({
+                        "type": cell_type,
+                        "content": content
+                    })
+                })
+                .collect();
+            json!({
+                "type": "table_row",
+                "content": children
+            })
+        }
+
+        NodeValue::TableCell => {
+            // Fallback: normally handled by TableRow above
+            let inline_content = collect_inline_children(node, active_marks);
+            let content = if inline_content.is_empty() {
+                vec![json!({"type": "paragraph"})]
+            } else {
+                vec![json!({"type": "paragraph", "content": inline_content})]
+            };
+            json!({
+                "type": "table_cell",
+                "content": content
+            })
+        }
+
+        NodeValue::TaskItem(task) => {
+            // Task items have a checked state (symbol present = checked)
+            let checked = task.symbol.is_some();
+            let content = collect_block_children(node);
+            json!({
+                "type": "task_list_item",
+                "attrs": { "checked": checked },
+                "content": if content.is_empty() {
+                    vec![json!({"type": "paragraph"})]
+                } else {
+                    content
+                }
+            })
+        }
+
+        NodeValue::Strikethrough => {
+            // Strikethrough - collect children with strikethrough mark added
+            let mut marks = active_marks.to_vec();
+            marks.push(Mark {
+                mark_type: "strikethrough",
+                attrs: None,
+            });
+            json!(collect_inline_children(node, &marks))
+        }
+
+        NodeValue::FootnoteReference(reference) => {
+            // #945: carry the reference as a dedicated inline atom node so
+            // the save direction can emit [^label] again instead of the
+            // reference being dropped / backslash-escaped as plain text.
+            json!({
+                "type": "footnote_reference",
+                "attrs": {"label": reference.name}
+            })
+        }
+
+        NodeValue::FootnoteDefinition(definition) => {
+            // #945: carry the definition as a dedicated node with the
+            // label, mirroring the reference arm. #1031: carry its BLOCK
+            // children (paragraphs, lists, code blocks) as blocks —
+            // flattening them to inline content fused multi-paragraph
+            // definitions into one run of text on save and silently
+            // dropped code blocks (their literal has no child nodes).
+            json!({
+                "type": "footnote_definition",
+                "attrs": {"label": definition.name},
+                "content": collect_block_children(node)
+            })
+        }
+
+        // Other unsupported nodes
+        _ => {
+            // Try to get text content and return as paragraph
+            let text = get_text_content(node);
+            if text.is_empty() {
+                json!(null)
+            } else {
+                json!({
+                    "type": "paragraph",
+                    "content": [{"type": "text", "text": text}]
+                })
+            }
+        }
+    }
+}
+
+/// Create a text node with the given marks.
+fn text_node_with_marks(text: &str, marks: &[Mark]) -> Value {
+    // An empty text node with no marks carries nothing and is dropped,
+    // but an empty text node WITH marks is information-bearing: it is
+    // the only representation of an empty-text link (#996).
+    if text.is_empty() && marks.is_empty() {
+        return json!(null);
+    }
+
+    let mut node = json!({
+        "type": "text",
+        "text": text
+    });
+
+    if !marks.is_empty() {
+        // #944: emit marks in the canonical nesting order so every
+        // spelling of the same marked text parses to the same PM doc.
+        let mut sorted: Vec = marks.to_vec();
+        sorted.sort_by_key(|m| mark_nesting_rank(m.mark_type));
+        let marks_json: Vec = sorted
+            .iter()
+            .map(|m| {
+                if let Some(attrs) = &m.attrs {
+                    json!({"type": m.mark_type, "attrs": attrs})
+                } else {
+                    json!({"type": m.mark_type})
+                }
+            })
+            .collect();
+        node["marks"] = json!(marks_json);
+    }
+
+    node
+}
+
+/// Collect block-level children of a node.
+pub(super) fn collect_block_children<'a>(node: &'a AstNode<'a>) -> Vec {
+    let children: Vec<&AstNode<'a>> = node.children().collect();
+    let mut out = Vec::new();
+    for (idx, child) in children.iter().enumerate() {
+        // #1370: comrak's renderer separates adjacent lists with
+        //  comments, and the split sibling lists this
+        // change emits are adjacent by construction - so on reparse the
+        // separator comes back as an HtmlBlock between the lists. It is
+        // a separator, not content: drop it when a neighbouring sibling
+        // is a list. An authored  comment NOT next to
+        // a list still converts exactly as before (an htmlBlock
+        // code_block, #982).
+        if is_end_list_separator(child)
+            && ((idx > 0 && matches!(children[idx - 1].data.borrow().value, NodeValue::List(_)))
+                || children
+                    .get(idx + 1)
+                    .is_some_and(|c| matches!(c.data.borrow().value, NodeValue::List(_))))
+        {
+            continue;
+        }
+        if matches!(child.data.borrow().value, NodeValue::List(_)) {
+            // #1370: a list converts to one or more sibling lists.
+            out.extend(convert_list_runs(child));
+        } else {
+            let converted = convert_node(child, &[]);
+            if !converted.is_null() {
+                out.push(converted);
+            }
+        }
+    }
+    out
+}
+
+/// True for the HtmlBlock comrak's renderer emits between adjacent
+/// lists (see collect_block_children).
+fn is_end_list_separator<'a>(node: &'a AstNode<'a>) -> bool {
+    match &node.data.borrow().value {
+        NodeValue::HtmlBlock(html) => html.literal.trim() == "",
+        _ => false,
+    }
+}
+
+/// Convert a comrak list node to one or more ProseMirror list nodes.
+///
+/// A pure list converts exactly as before (#997/#1036 attrs carried from
+/// the source list). #1370: a list mixing task items with plain items
+/// used to take its type from the first child only and convert the rest
+/// by their own kind, producing a `task_list` holding a `list_item` (or
+/// a plain list holding a `task_list_item`) - a shape the save-side
+/// placement validation and the editor schema both forbid, so the
+/// document could not be saved at all. Instead, group the items into
+/// runs of one kind and emit one sibling list per run, in source order.
+/// Ordered runs carry an `order` start offset by the items before them
+/// so numbering renders unchanged; `tight` is carried from the source
+/// list to every run. Placement validation and the editor schema are
+/// untouched: every emitted list is pure.
+/// #1380: the PM `delimiter` attr spelling for a comrak ordered-list
+/// delimiter (`.` vs `)`). The editor schema mirrors these spellings.
+fn delimiter_attr(delimiter: ListDelimType) -> &'static str {
+    match delimiter {
+        ListDelimType::Period => "period",
+        ListDelimType::Paren => "paren",
+    }
+}
+
+/// #1380: read the PM `delimiter` attr back to a comrak delimiter.
+/// Absent or unknown (legacy PM docs stored by the old codec, which
+/// dropped the delimiter) defaults to Period - exactly how the old
+/// codec saved every ordered list.
+pub(super) fn delimiter_from_attrs(json: &Value) -> ListDelimType {
+    match json["attrs"]["delimiter"].as_str() {
+        Some("paren") => ListDelimType::Paren,
+        _ => ListDelimType::Period,
+    }
+}
+
+fn convert_list_runs<'a>(node: &'a AstNode<'a>) -> Vec {
+    let (list_type, start, tight, delimiter) = match &node.data.borrow().value {
+        NodeValue::List(list) => (list.list_type, list.start, list.tight, list.delimiter),
+        _ => return Vec::new(),
+    };
+    // (is_task, items before this run, converted items)
+    let mut runs: Vec<(bool, usize, Vec)> = Vec::new();
+    let mut seen = 0usize;
+    for child in node.children() {
+        let is_task = matches!(child.data.borrow().value, NodeValue::TaskItem(_));
+        let item = convert_node(child, &[]);
+        if item.is_null() {
+            continue;
+        }
+        match runs.last_mut() {
+            Some((kind, _, items)) if *kind == is_task => items.push(item),
+            _ => runs.push((is_task, seen, vec![item])),
+        }
+        seen += 1;
+    }
+    runs.into_iter()
+        .map(|(is_task, offset, content)| match (is_task, list_type) {
+            (true, ListType::Ordered) => json!({
+                "type": "task_list",
+                "attrs": {"order": start + offset, "tight": tight, "delimiter": delimiter_attr(delimiter)},
+                "content": content
+            }),
+            (true, ListType::Bullet) => json!({
+                "type": "task_list",
+                "attrs": {"tight": tight},
+                "content": content
+            }),
+            (false, ListType::Ordered) => json!({
+                "type": "ordered_list",
+                "attrs": {"order": start + offset, "tight": tight, "delimiter": delimiter_attr(delimiter)},
+                "content": content
+            }),
+            (false, ListType::Bullet) => json!({
+                "type": "bullet_list",
+                "attrs": {"tight": tight},
+                "content": content
+            }),
+        })
+        .collect()
+}
+
+/// Collect list item children of a list node.
+fn collect_list_items<'a>(node: &'a AstNode<'a>) -> Vec {
+    node.children()
+        .map(|child| convert_node(child, &[]))
+        .filter(|v| !v.is_null())
+        .collect()
+}
+
+/// The literal of an `HtmlInline` node, if `node` is one.
+fn html_inline_literal<'a>(node: &'a AstNode<'a>) -> Option {
+    if let NodeValue::HtmlInline(html) = &node.data.borrow().value {
+        Some(html.clone())
+    } else {
+        None
+    }
+}
+
+/// Detect the split sized-linked-image sequence at the head of `children`
+/// (#893): an `` `HtmlInline`, an `` `HtmlInline`,
+/// and the closing `` `HtmlInline`. Comrak splits the HTML form the
+/// save direction emits for a sized linked image into those three sibling
+/// nodes; merged here they become one image node carrying `linkHref`, and
+/// neither anchor piece falls through as literal text. The closing tag is
+/// optional in the match (consumed when present) so a missing one cannot
+/// strand the opening tag as text either. Returns the merged image node
+/// and how many siblings it consumed.
+fn linked_image_sequence<'a>(children: &[&'a AstNode<'a>]) -> Option<(Value, usize)> {
+    if children.len() < 2 {
+        return None;
+    }
+    let (href, link_title) = parse_anchor_tag(&html_inline_literal(children[0])?)?;
+    let img = parse_img_tag(&html_inline_literal(children[1])?)?;
+    let consumed = if children.len() >= 3
+        && html_inline_literal(children[2]).is_some_and(|h| h.trim().eq_ignore_ascii_case(""))
+    {
+        3
+    } else {
+        2
+    };
+    Some((image_with_link(img, &href, link_title.as_deref()), consumed))
+}
+
+/// Collect inline children of a node, flattening nested mark wrappers.
+fn collect_inline_children<'a>(node: &'a AstNode<'a>, active_marks: &[Mark]) -> Vec {
+    let mut result = Vec::new();
+    let children: Vec<&AstNode<'a>> = node.children().collect();
+    let mut index = 0;
+
+    while index < children.len() {
+        // #893: merge a split  sequence before the pieces
+        // are converted individually (see linked_image_sequence).
+        if let Some((img, consumed)) = linked_image_sequence(&children[index..]) {
+            result.push(img);
+            index += consumed;
+            continue;
+        }
+
+        let child = children[index];
+        index += 1;
+        let child_data = child.data.borrow();
+
+        // Check if this is a mark wrapper (Emph, Strong, Link)
+        let is_mark_wrapper = matches!(
+            child_data.value,
+            NodeValue::Emph | NodeValue::Strong | NodeValue::Link(_) | NodeValue::Strikethrough
+        );
+        drop(child_data);
+
+        let converted = convert_node(child, active_marks);
+        if is_mark_wrapper {
+            // Convert returns an array of children with marks applied
+            if let Some(arr) = converted.as_array() {
+                for item in arr {
+                    if !item.is_null() {
+                        result.push(item.clone());
+                    }
+                }
+            }
+        } else if !converted.is_null() {
+            result.push(converted);
+        }
+    }
+
+    result
+}
+
+/// Get all text content from a node and its descendants.
+fn get_text_content<'a>(node: &'a AstNode<'a>) -> String {
+    let mut text = String::new();
+    collect_text(node, &mut text);
+    text
+}
+
+/// Recursively collect text from a node.
+fn collect_text<'a>(node: &'a AstNode<'a>, text: &mut String) {
+    let data = node.data.borrow();
+
+    match &data.value {
+        NodeValue::Text(t) => text.push_str(t.as_ref()),
+        NodeValue::Code(c) => text.push_str(&c.literal),
+        NodeValue::SoftBreak => text.push(' '),
+        NodeValue::LineBreak => text.push('\n'),
+        _ => {
+            drop(data);
+            for child in node.children() {
+                collect_text(child, text);
+            }
+        }
+    }
+}
+
+/// #1417: serialize an image alt subtree back to markdown form.
+///
+/// The inverse of the save direction's alt re-parse: emphasis, strong,
+/// strikethrough, code spans and links keep their markup; literal text
+/// is escaped so characters that were literal in the source (e.g. an
+/// escaped `\\*`) stay literal when the stored form is re-parsed on
+/// save. Nested images/links inside an alt are serialized recursively,
+/// so a nested-link alt round-trips instead of flattening.
+fn get_alt_markdown<'a>(node: &'a AstNode<'a>) -> String {
+    let mut out = String::new();
+    for child in node.children() {
+        collect_alt_markdown(child, &mut out);
+    }
+    out
+}
+
+fn collect_alt_markdown<'a>(node: &'a AstNode<'a>, out: &mut String) {
+    let data = node.data.borrow();
+    match &data.value {
+        NodeValue::Text(t) => {
+            for ch in t.chars() {
+                if matches!(ch, '\\' | '*' | '_' | '`' | '[' | ']') {
+                    out.push('\\');
+                }
+                out.push(ch);
+            }
+        }
+        NodeValue::Code(c) => {
+            // Fence with one more backtick than the longest run inside.
+            let longest = c
+                .literal
+                .split(|ch| ch != '`')
+                .map(str::len)
+                .max()
+                .unwrap_or(0);
+            let fence = "`".repeat(longest + 1);
+            out.push_str(&fence);
+            if c.literal.starts_with('`') || c.literal.ends_with('`') {
+                out.push(' ');
+                out.push_str(&c.literal);
+                out.push(' ');
+            } else {
+                out.push_str(&c.literal);
+            }
+            out.push_str(&fence);
+        }
+        NodeValue::SoftBreak => out.push(' '),
+        NodeValue::LineBreak => out.push('\n'),
+        NodeValue::HtmlInline(html) => out.push_str(html),
+        NodeValue::Emph => {
+            drop(data);
+            out.push('*');
+            for child in node.children() {
+                collect_alt_markdown(child, out);
+            }
+            out.push('*');
+        }
+        NodeValue::Strong => {
+            drop(data);
+            out.push_str("**");
+            for child in node.children() {
+                collect_alt_markdown(child, out);
+            }
+            out.push_str("**");
+        }
+        NodeValue::Strikethrough => {
+            drop(data);
+            out.push_str("~~");
+            for child in node.children() {
+                collect_alt_markdown(child, out);
+            }
+            out.push_str("~~");
+        }
+        NodeValue::Link(link) => {
+            let url = link.url.clone();
+            let title = link.title.clone();
+            drop(data);
+            out.push('[');
+            for child in node.children() {
+                collect_alt_markdown(child, out);
+            }
+            out.push_str("](");
+            out.push_str(&url);
+            if !title.is_empty() {
+                out.push_str(" \"");
+                out.push_str(&title.replace('"', "\\\""));
+                out.push_str("\"");
+            }
+            out.push(')');
+        }
+        NodeValue::Image(link) => {
+            let url = link.url.clone();
+            let title = link.title.clone();
+            drop(data);
+            out.push_str("![");
+            for child in node.children() {
+                collect_alt_markdown(child, out);
+            }
+            out.push_str("](");
+            out.push_str(&url);
+            if !title.is_empty() {
+                out.push_str(" \"");
+                out.push_str(&title.replace('"', "\\\""));
+                out.push_str("\"");
+            }
+            out.push(')');
+        }
+        _ => {
+            drop(data);
+            for child in node.children() {
+                collect_alt_markdown(child, out);
+            }
+        }
+    }
+}
+
+/// #1417: re-parse a stored markdown-form alt into inline AST nodes in
+/// `arena` (the save direction). Returns the paragraph's children,
+/// detached and ready to append under an Image node. Falls back to a
+/// single plain Text node when the alt does not parse to a paragraph
+/// (defensive; plain alts parse to exactly that anyway).
+pub(super) fn alt_markdown_to_nodes<'a>(arena: &'a Arena<'a>, alt: &str) -> Vec<&'a AstNode<'a>> {
+    let options = commonmark_options();
+    let root = parse_document(arena, alt, &options);
+    if let Some(paragraph) = root
+        .children()
+        .find(|n| matches!(n.data.borrow().value, NodeValue::Paragraph))
+    {
+        let nodes: Vec<&'a AstNode<'a>> = paragraph.children().collect();
+        for n in &nodes {
+            n.detach();
+        }
+        if !nodes.is_empty() {
+            return nodes;
+        }
+    }
+    vec![&*arena.alloc(AstNode::from(NodeValue::Text(alt.to_owned().into())))]
+}
+
+/// Escape a value for a double-quoted HTML attribute (#873): `&` first, so
+/// the entities introduced here are not themselves re-escaped, then the
+/// quote that would terminate the value, and `<`.
+pub(super) fn escape_attr_value(value: &str) -> String {
+    value
+        .replace('&', "&")
+        .replace('"', """)
+        .replace('<', "<")
+}
+
+/// Decode the entities [`escape_attr_value`] can emit (plus `>`/`'`
+/// and numeric single-quote) in one left-to-right pass, so `&quot;`
+/// decodes to the literal text `"`, never to `"`.
+fn decode_attr_entities(value: &str) -> String {
+    if !value.contains('&') {
+        return value.to_owned();
+    }
+    let mut out = String::with_capacity(value.len());
+    let mut rest = value;
+    while let Some(idx) = rest.find('&') {
+        out.push_str(&rest[..idx]);
+        let tail = &rest[idx..];
+        let (decoded, len) = if let Some(t) = tail.strip_prefix(""") {
+            ('"', tail.len() - t.len())
+        } else if let Some(t) = tail.strip_prefix("&") {
+            ('&', tail.len() - t.len())
+        } else if let Some(t) = tail.strip_prefix("<") {
+            ('<', tail.len() - t.len())
+        } else if let Some(t) = tail.strip_prefix(">") {
+            ('>', tail.len() - t.len())
+        } else if let Some(t) = tail.strip_prefix("'") {
+            ('\'', tail.len() - t.len())
+        } else if let Some(t) = tail.strip_prefix("'") {
+            ('\'', tail.len() - t.len())
+        } else {
+            out.push('&');
+            rest = &tail[1..];
+            continue;
+        };
+        out.push(decoded);
+        rest = &tail[len..];
+    }
+    out.push_str(rest);
+    out
+}
+
+/// Parse the attributes of an HTML tag, starting just past its ` std::collections::HashMap {
+    let bytes = html.as_bytes();
+    let mut pos = tag_len;
+    let mut map = std::collections::HashMap::new();
+    while pos < bytes.len() {
+        // Skip separators between attributes (whitespace, '/' of '/>').
+        while pos < bytes.len() && (bytes[pos].is_ascii_whitespace() || bytes[pos] == b'/') {
+            pos += 1;
+        }
+        if pos >= bytes.len() || bytes[pos] == b'>' {
+            break;
+        }
+        // Attribute name: up to '=', whitespace, '/' or '>'.
+        let name_start = pos;
+        while pos < bytes.len()
+            && !bytes[pos].is_ascii_whitespace()
+            && !matches!(bytes[pos], b'=' | b'/' | b'>')
+        {
+            pos += 1;
+        }
+        if pos == name_start {
+            break;
+        }
+        let name = html[name_start..pos].to_ascii_lowercase();
+        while pos < bytes.len() && bytes[pos].is_ascii_whitespace() {
+            pos += 1;
+        }
+        let mut value = String::new();
+        if pos < bytes.len() && bytes[pos] == b'=' {
+            pos += 1;
+            while pos < bytes.len() && bytes[pos].is_ascii_whitespace() {
+                pos += 1;
+            }
+            if pos < bytes.len() && matches!(bytes[pos], b'"' | b'\'') {
+                let quote = bytes[pos];
+                pos += 1;
+                let value_start = pos;
+                while pos < bytes.len() && bytes[pos] != quote {
+                    pos += 1;
+                }
+                value = decode_attr_entities(&html[value_start..pos]);
+                if pos < bytes.len() {
+                    pos += 1; // closing quote
+                }
+            } else {
+                let value_start = pos;
+                while pos < bytes.len() && !bytes[pos].is_ascii_whitespace() && bytes[pos] != b'>' {
+                    pos += 1;
+                }
+                value = decode_attr_entities(&html[value_start..pos]);
+            }
+        }
+        // First occurrence wins (HTML duplicate-attribute rule).
+        map.entry(name).or_insert(value);
+    }
+    map
+}
+
+/// Parse an `` width/height value into a pixel count (#2180,
+/// grammar pinned by triage task 3225). The whole stack is
+/// numeric-pixel -- the PM node stores a JSON number, the emitter
+/// writes bare integers, the editor renders `${width}px` -- so only
+/// lossless normalizations are accepted: trim surrounding
+/// whitespace, strip ONE trailing `px` suffix (ASCII
+/// case-insensitive), then the rest must be a pixel integer, where a
+/// decimal form counts only when its value is exactly integral
+/// (`200.0` -> 200, `200.5` refused). Percents, other units, and
+/// junk return `None`; the caller warns instead of dropping the
+/// value silently, as the pre-#2180 bare-`u64` parse did.
+fn parse_integral_decimal(raw: &str) -> Option {
+    let (negative, raw) = if let Some(raw) = raw.strip_prefix('-') {
+        (true, raw)
+    } else {
+        (false, raw.strip_prefix('+').unwrap_or(raw))
+    };
+
+    let (mantissa, exponent) = if let Some(index) = raw.find(|ch| matches!(ch, 'e' | 'E')) {
+        (&raw[..index], raw[index + 1..].parse::().ok()?)
+    } else {
+        (raw, 0)
+    };
+    let (integer, fractional) = mantissa.split_once('.').unwrap_or((mantissa, ""));
+    if integer.is_empty() && fractional.is_empty() {
+        return None;
+    }
+    if !integer.bytes().all(|byte| byte.is_ascii_digit())
+        || !fractional.bytes().all(|byte| byte.is_ascii_digit())
+    {
+        return None;
+    }
+
+    let mut digits = String::with_capacity(integer.len() + fractional.len());
+    digits.push_str(integer);
+    digits.push_str(fractional);
+    let significant = digits.trim_start_matches('0');
+    if significant.is_empty() {
+        // Keep the exact zero spellings accepted by the former float parser,
+        // including -0.0, without converting through f64.
+        return Some(0);
+    }
+
+    let fractional_digits = i32::try_from(fractional.len()).ok()?;
+    let scale = exponent.checked_sub(fractional_digits)?;
+    let integer = if scale >= 0 {
+        let trailing_zeroes = usize::try_from(scale).ok()?;
+        if significant.len().checked_add(trailing_zeroes)? > 20 {
+            return None;
+        }
+        let mut integer = String::with_capacity(significant.len() + trailing_zeroes);
+        integer.push_str(significant);
+        integer.push_str(&"0".repeat(trailing_zeroes));
+        integer.parse::().ok()?
+    } else {
+        let trailing_zeroes = usize::try_from(scale.checked_neg()?).ok()?;
+        if trailing_zeroes > significant.len() {
+            return None;
+        }
+        let split = significant.len() - trailing_zeroes;
+        if significant[split..].bytes().any(|byte| byte != b'0') {
+            return None;
+        }
+        significant[..split].parse::().ok()?
+    };
+
+    if negative && integer != 0 {
+        return None;
+    }
+    Some(integer)
+}
+
+fn parse_dimension(raw: &str) -> Option {
+    let trimmed = raw.trim();
+    // Byte-wise suffix check: slicing the string at len()-2 to test
+    // the suffix would panic when that offset falls inside a multibyte
+    // UTF-8 character (e.g. fullwidth digits). When the last two bytes
+    // are the ASCII bytes p/x, len()-2 is a char boundary, so the
+    // slice below is safe.
+    let bytes = trimmed.as_bytes();
+    let body = if bytes.len() >= 2 && bytes[bytes.len() - 2..].eq_ignore_ascii_case(b"px") {
+        &trimmed[..trimmed.len() - 2]
+    } else {
+        trimmed
+    };
+    if let Ok(n) = body.parse::() {
+        return Some(n);
+    }
+    parse_integral_decimal(body)
+}
+
+/// Parse an HTML `` tag and extract attributes into a `ProseMirror` image node.
+///
+/// Returns `Some(json)` if the input looks like ``, otherwise `None`.
+fn find_ascii_case_insensitive(haystack: &str, needle: &[u8]) -> Option {
+    haystack
+        .as_bytes()
+        .windows(needle.len())
+        .position(|candidate| candidate.eq_ignore_ascii_case(needle))
+}
+
+pub(super) fn parse_img_tag(html: &str) -> Option {
+    let trimmed = html.trim();
+    let bytes = trimmed.as_bytes();
+    if !bytes
+        .get(..4)
+        .is_some_and(|prefix| prefix.eq_ignore_ascii_case(b"'))
+    {
+        return None;
+    }
+
+    let parsed = parse_tag_attrs(trimmed, 4);
+    let attr = |name: &str| parsed.get(name).map(String::as_str);
+
+    let src = attr("src")?; // src is required
+    let mut attrs = json!({"src": src});
+
+    if let Some(alt) = attr("alt") {
+        attrs["alt"] = json!(alt);
+    }
+    if let Some(title) = attr("title") {
+        attrs["title"] = json!(title);
+    }
+    if let Some(w) = attr("width") {
+        match parse_dimension(w) {
+            Some(n) => attrs["width"] = json!(n),
+            None => tracing::warn!("dropping unsupported image width {w:?} in  import"),
+        }
+    }
+    if let Some(h) = attr("height") {
+        match parse_dimension(h) {
+            Some(n) => attrs["height"] = json!(n),
+            None => tracing::warn!("dropping unsupported image height {h:?} in  import"),
+        }
+    }
+
+    Some(json!({
+        "type": "image",
+        "attrs": attrs
+    }))
+}
+
+/// Parse an HTML `` opening tag, returning its `href` and optional
+/// `title`. Returns `None` for anything else, including an anchor with no
+/// (or an empty) `href`.
+fn parse_anchor_tag(html: &str) -> Option<(String, Option)> {
+    let trimmed = html.trim();
+    let after_name = trimmed.as_bytes().get(2).copied()?;
+    if !trimmed
+        .as_bytes()
+        .get(..2)
+        .is_some_and(|prefix| prefix.eq_ignore_ascii_case(b"')
+    {
+        return None;
+    }
+    let parsed = parse_tag_attrs(trimmed, 2);
+    let href = parsed.get("href")?;
+    if href.is_empty() {
+        return None;
+    }
+    let title = parsed.get("title").filter(|t| !t.is_empty()).cloned();
+    Some((href.clone(), title))
+}
+
+/// Attach a wrapping anchor's link to an image node (#880/#893), in the
+/// same `linkHref`/`linkTitle` attrs the markdown `Image` arm produces.
+fn image_with_link(mut img: Value, href: &str, link_title: Option<&str>) -> Value {
+    img["attrs"]["linkHref"] = json!(href);
+    if let Some(title) = link_title {
+        img["attrs"]["linkTitle"] = json!(title);
+    }
+    img
+}
+
+/// Parse the combined `` form (#893) — the
+/// sized linked image emission when comrak keeps it in a single literal
+/// (e.g. an `HtmlBlock`) instead of splitting it into sibling `HtmlInline`
+/// nodes (that split form is merged in `collect_inline_children`).
+pub(super) fn parse_linked_img_tag(html: &str) -> Option {
+    let trimmed = html.trim();
+    let (href, link_title) = parse_anchor_tag(trimmed)?;
+    let img_start = find_ascii_case_insensitive(trimmed, b"')
+        || find_ascii_case_insensitive(&trimmed[img_start..], b"").is_none()
+    {
+        return None;
+    }
+    let img = parse_img_tag(&trimmed[img_start..])?;
+    Some(image_with_link(img, &href, link_title.as_deref()))
+}
+
+/// Placement categories for the #1043 validation walk. A node whose type
+/// is not listed here is left to `json_to_ast`, which reports it as
+/// `ConversionError::UnknownType` — validation never masks that error.
+/// (`front_matter` is intentionally unlisted: its doc-first-child rule
+/// needs the child index, so `validate_placement` checks it directly.)
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum Placement {
+    /// Block-level node (`paragraph`, `table`, lists, …).
+    Block,
+    /// Inline node (`text`, `image`, `hard_break`, …).
+    Inline,
+    /// `list_item` — only legal directly inside a bullet/ordered list.
+    ListItem,
+    /// `task_list_item` — only legal directly inside a `task_list`.
+    TaskListItem,
+    /// `table_row` — only legal directly inside a `table`.
+    TableRow,
+    /// `table_header` / `table_cell` — only legal inside a `table_row`.
+    TableCell,
+}
+
+fn placement_of(node_type: &str) -> Option {
+    match node_type {
+        "paragraph"
+        | "heading"
+        | "blockquote"
+        | "code_block"
+        | "horizontal_rule"
+        | "bullet_list"
+        | "ordered_list"
+        | "task_list"
+        | "table"
+        | "footnote_definition" => Some(Placement::Block),
+        "text" | "image" | "hard_break" | "html_inline" | "footnote_reference" => {
+            Some(Placement::Inline)
+        }
+        "list_item" => Some(Placement::ListItem),
+        "task_list_item" => Some(Placement::TaskListItem),
+        "table_row" => Some(Placement::TableRow),
+        "table_header" | "table_cell" => Some(Placement::TableCell),
+        _ => None,
+    }
+}
+
+/// Whether a child of category `child` may appear directly inside a
+/// parent of type `parent`. Mirrors the comrak AST containment rules for
+/// the node kinds this codec emits, at the `ProseMirror` level.
+fn placement_allowed(parent: &str, child: Placement) -> bool {
+    match parent {
+        // The document and block containers hold blocks only.
+        "doc" | "blockquote" | "list_item" | "task_list_item" => child == Placement::Block,
+        // Inline containers hold inline content only.
+        "paragraph" | "heading" => child == Placement::Inline,
+        "bullet_list" | "ordered_list" => child == Placement::ListItem,
+        "task_list" => child == Placement::TaskListItem,
+        "table" => child == Placement::TableRow,
+        "table_row" => child == Placement::TableCell,
+        // PM table cells wrap blocks (unwrapped during conversion) and
+        // footnote definitions carry inline content on the PM side
+        // (re-wrapped during conversion, #945); both shapes are legal.
+        "table_header" | "table_cell" | "footnote_definition" => {
+            child == Placement::Block || child == Placement::Inline
+        }
+        "code_block" => false,
+        // Inline leaves and anything unlisted impose no child rules here;
+        // structural surprises inside them are json_to_ast's to report.
+        _ => true,
+    }
+}
+
+/// Validate block/inline placement over a `ProseMirror` document before
+/// conversion (#1043). `json_to_ast` places any known node type anywhere;
+/// a misplaced node (a `text` node directly under `doc`, a `paragraph`
+/// inside a `paragraph`, …) produces an ill-formed comrak AST that
+/// panics the formatter in debug builds and silently emits invalid
+/// markdown in release builds. Reject those documents up front with
+/// `ConversionError::MisplacedNode` instead.
+pub(super) fn validate_placement(doc: &Value) -> Result<(), ConversionError> {
+    fn walk(
+        node: &Value,
+        parent: Option<&str>,
+        index_in_parent: Option,
+    ) -> Result<(), ConversionError> {
+        let Some(node_type) = node["type"].as_str() else {
+            // Missing type: json_to_ast reports MissingType; keep that
+            // error's precedence.
+            return Ok(());
+        };
+        // #1369: `front_matter` is legal only as the first child of `doc`
+        // (comrak only parses it there). Anything else is misplaced.
+        if node_type == "front_matter" {
+            let first_child_of_doc = parent == Some("doc") && index_in_parent == Some(0);
+            if !first_child_of_doc {
+                return Err(ConversionError::MisplacedNode {
+                    parent: parent.unwrap_or("").to_owned(),
+                    child: node_type.to_owned(),
+                });
+            }
+        } else if let Some(parent_type) = parent
+            && let Some(category) = placement_of(node_type)
+            && !placement_allowed(parent_type, category)
+        {
+            return Err(ConversionError::MisplacedNode {
+                parent: parent_type.to_owned(),
+                child: node_type.to_owned(),
+            });
+        }
+        // code_block content is literal text children only.
+        if node_type == "code_block" {
+            if let Some(content) = node["content"].as_array() {
+                for child in content {
+                    if child["type"].as_str() != Some("text") {
+                        return Err(ConversionError::MisplacedNode {
+                            parent: node_type.to_owned(),
+                            child: child["type"].as_str().unwrap_or("").to_owned(),
+                        });
+                    }
+                }
+            }
+            return Ok(());
+        }
+        // front_matter carries no PM child content (its payload is the
+        // `text` attr); nothing to recurse into.
+        if node_type == "front_matter" {
+            if node["content"].as_array().is_some_and(|c| !c.is_empty()) {
+                return Err(ConversionError::MisplacedNode {
+                    parent: node_type.to_owned(),
+                    child: "".to_owned(),
+                });
+            }
+            return Ok(());
+        }
+        if let Some(content) = node["content"].as_array() {
+            for (idx, child) in content.iter().enumerate() {
+                walk(child, Some(node_type), Some(idx))?;
+            }
+        }
+        Ok(())
+    }
+    walk(doc, None, None)
+}