# Native chat Markdown

Branch: `native/markdown`. This includes the 2026-11-23 implementation and the
review follow-ups to `506fafca` and `5a1fe0d1`. The web's Render and RenderDraft remain the
contract, including absolute HTTP/HTTPS and mailto links.

## What a person sees

On iPhone and Mac, Paul's complete reply has three paragraphs, a bold
“Why they look different:” lead-in, and a blue task title which opens the
native task screen. Lists, emphasis, code spans and hard breaks follow the
web. Headings have its paragraph treatment and rules have no output. HTML is
text. Unsupported links keep their words. Relative project links open at the
account's origin because there is no native project detail screen. Absolute
web links use the browser; mailto uses the system mail handler.

Draft markers wait, partial links show their words, and unmatched delimiters
follow RenderDraft. An open fence has its final paste-box layout with Copy
disabled. Closing it enables Copy without changing its anchor or size. Prompt
and Text wrap; other code scrolls horizontally in a system monospaced font.
Copy removes exactly one final newline. Paste boxes have VoiceOver labels.

Replies up to 16 KiB, including small drafts, parse synchronously before the
first layout. A bounded cache holds trees by account, message ID and revision
(the exact source plus draft/completed state), so scrolling does not reparse.
Larger inputs parse on a concurrent executor while the previous revision or a
multiline plain-text fallback stays visible. A cancelled task cannot publish
its old result. Mac height changes resize only that reply and shift following
rows, preserving host identity and scroll position. Mac reply text remains 14 points,
matching the existing `MacType.line`; iPhone text uses Dynamic Type's body font.
Deep lists use flat layout rows with indentation capped at four levels.

## Parser choice and parity

Equipo still uses swift-cmark's core CommonMark parser, without GFM extensions
or smart punctuation, pinned by revision to
`08ddb528923cc1a6527e02b7a1aee9e516ca749a` in both package files. The core exposes
list tightness, block buffers and parser transitions needed here. The higher
level swift-markdown wrapper does not expose all of these. A separate hand
parser would duplicate the block and reference grammar.

The projection walks iteratively. Inline coordinates are mapped through the
retained original block buffer and cached line offsets, so continuation
indentation does not select another span or URL. Unicode classification is
adapted only in the parser's private buffer; displayed text and destinations
come from the retained original. Text and link entities have separate decoders
because the web uses different rules for them. Reference definitions are
compiled and scanned once per message. Explicit fence transitions, including
longer-than-255-character fences, determine Copy availability.

`internal/chatmarkdown/native_test.go` projects the actual Render/RenderDraft
HTML into canonical JSON, only in tests. There are **3,510 checked-in fixtures**,
plus **32,000 distinct fixed-seed generated inputs** written at check time. The native
gate gives Swift that same generated file. Every block, inline, target, label
and Copy state is compared. The corpus includes Paul's full reply, streaming
cuts, whitespace and lazy continuations, nested formatting, raw HTML, entities,
Unicode symbols, CRLF and CR-only input, 300-character fences and code spans,
rejected URL schemes, angle destinations with edge whitespace, EOF labels,
soft-break whitespace, HTML after paragraphs, reference definitions, and every
character cut through escaped and open spans.

The one production web change fixes destination entity decoding. A complete,
known entity decodes once; `&timestamp`, `&region`, and unknown names remain
literal. This preserves query parameters instead of corrupting them. The
`golang.org/x/net` test import is now a direct module dependency.

The complete swift-cmark copyright and licence notices remain bundled and are
now reachable from the Account screen on both platforms, under swift-cmark.

## First review findings and regression evidence

| Finding | Change and regression |
| --- | --- |
| P1.1, stack overflow | Iterative projection; 200, 1,000 and 5,000 quotes run on a 1 MB stack. |
| P1.2, draft regex | Linear marker scanner; 800, 1,600 and 3,200 spaces stay below one second. Large inputs parse off the main actor. |
| P1.3, continuation ranges | Retained block buffers and cached coordinate mapping; code spans and good/evil URL continuation fixtures. |
| P2.4, open-fence Copy | Parser transitions distinguish an explicit closer from EOF or leaving a list/quote. Indented false closers remain content. |
| P2.5, schemes | Fixtures and action tests reject file, ftp, tel, sms, blob, vbscript, custom schemes and protocol-relative URLs. |
| P2.6, URL rules | ASCII destination trimming and Go-compatible host/userinfo/escape validation. Odd web-allowed hosts remain actionable through validated original targets. |
| P2.7, web entities | Complete entities only, decoded once; query-name, unknown-name and nested-entity Go tests. |
| P2.8, list layout | Flat layout with bounded indentation; a 60-level list renders at 390 points within three seconds. |
| P3, Unicode emphasis | Symbol and whitespace classification matches Goldmark, including emoji, currency, NEL and line separators. |
| P3, small tree differences | HTML EOF newlines, EOF fence labels, escaped entities, CRLF, code spans and angle destinations are in the goldens. |
| P3, reference cost | One reference scan and one coordinate map per block; 2,000 references parse within two seconds. |
| P3, dependency pin | Both package files use the immutable cmark revision. |
| P3, licence | A source guard keeps the bundled notice reachable from Account. |
| P3, module tidy | `x/net` is direct; `check-fixtures.py` runs `go mod tidy -diff`, including in the native gate. |
| P3, accessibility/copy | Paste labels are reused for VoiceOver; the unused coordinator spoken-format key is removed. |
| P3, Mac typography | A regression fixes the reply font at the previous 14-point size. |

Tests were added before each implementation. The original small-stack test
crashed. The original marker, reference and layout tests exceeded their bounds
and were terminated by the harness. The generated corpus exposed additional
entity and fence-label differences, which were retained and fixed.

Focused commands:

```sh
EQUIPO_MARKDOWN_DIFFERENTIAL="$PWD/native/build/markdown-differential.json" \
  swift test --package-path native/apple --filter 'ChatMarkdownTests|MarkdownLayoutTests'
GOTOOLCHAIN=go1.26.11 CGO_ENABLED=0 go test ./internal/chatmarkdown -count=1
native/scripts/check-native.sh
```

All **28 deliberate mutations were caught**, then restored. This includes
restoring recursive walking/layout and the backtracking regex, moving parsing
onto the main actor, breaking source mapping, enabling open-fence Copy, adding
ftp, loosening URL/userinfo/zone checks, restoring legacy web entities, breaking
Unicode/CRLF/HTML/EOF/escape handling, restoring per-link reference scanning,
removing the revision pin/licence/accessibility wiring, restoring the unused
spoken key, changing Mac text to 13 points, truncating long fence lengths,
breaking odd-host actions, changing entity-pass order, and trusting a source
candidate without checking the parser-selected target.

The first review follow-up passed with **zero mismatches across 26,724 trees**. The
2,000-reference case takes about 0.14 seconds; the 60-level phone-width list
renders in under 0.5 seconds. The marker scan takes about a millisecond and
5,000 quotes take under 0.05 seconds on the 1 MB stack. Timings are local Mac
measurements; the tests enforce wider explicit bounds.

That revision’s full native gate passed: **152 Swift tests** (one existing marked Oficina
ID issue), 2,724 checked-in trees plus 24,000 distinct generated inputs with
zero mismatches, 173 strings, 28 web/native copy pairs, reference inventory,
Mac build and unsigned iOS Simulator build.

Go gates passed with Go 1.26.11 and CGO disabled: all chatmarkdown tests,
`go vet ./internal/chatmarkdown`, staticcheck v0.7.0 for that package,
`make fmt-check` with the pinned GOROOT on PATH, and `go mod tidy -diff`.
The post-commit reference scan and branch CI verdict are recorded in the
controller handoff.
Local evidence is under `native/build/logs/review-*` and `mutation-*`.

## Re-review at 5a1fe0d1

| Finding | Fix and regression |
| --- | --- |
| P2.1, byte leak and restoration cost | Each physical LF line, including an empty one, maps to its original line. Restoration never searches later blocks. A 3,000-block test checks every copied body and a two-second bound (about 0.2 seconds locally). Every golden and generated tree also checks that introduced control bytes do not leak; legitimate entity-decoded controls must equal the web. |
| P2.2, blank first frame | Small replies parse before layout. A live host asserts nonzero height immediately. Cache tests verify exact revision reuse, draft/completion identity, previous-tree retention and a nonempty multiline fallback for large replies. The Mac callback resizes the affected row instead of rebuilding the transcript. |
| P3.1, angle whitespace | Retain the original angle destination even when cmark trims it. Apply the web URL policy to that original, including its fragment rules. |
| P3.2, EOF labels | The web drops a single byte immediately after the EOF fence, before whitespace trimming; surrounding whitespace and longer labels survive. A 120-case whitespace/label cross-product pins this distinction. |
| P3.3, soft breaks | Trim trailing spaces and tabs before soft breaks as well as hard breaks. |
| P3.4, HTML separator | The test-only Go projection removes the formatting newline after a block element. Render/RenderDraft HTML is unchanged. |
| P3.5, scheme property | The allowed set is exactly http, https and mailto. Property checks apply case variants and generated valid scheme names to opaque, hierarchical and mail-style destinations. Adding webcal fails. |
| P3.6, draft spans | A parsed delimiter ends the watched fallback backtick span. A backslash escapes one delimiter byte, not its whole run. Cross-product streaming cuts cover quotes, list prefixes, escapes, backticks, emphasis and links. |
| P3.7, tidy gate | The fixture gate now executes `go mod tidy -diff` with Go 1.26.11 and CGO disabled. Marking the direct x/net import indirect makes that gate fail. |

The deterministic differential corpus now has **32,000 unique sources**, plus
**3,510 checked-in cases**, with **zero mismatches across all 35,510 trees**.
CR-only generation also exposed a parser line-count crash, now prevented by
width-preserving CR adaptation in both block and inline buffers. Long inline
backtick runs are adapted to cmark’s 80-byte limit while preserving original
code bytes and coordinates. These cases stay in the corpus.

Tests were added before the fixes. The first-frame test failed with zero
height; the original byte-restoration test failed both content and time checks;
the expanded parity run initially failed and crashed on CR-only input. Extra
escaped-span cuts then caught five more draft mismatches before their fix.
Commands and outcomes are under `native/build/logs/review2-*`.

All **19 new mutations were caught and restored**. They broke blank-line
mapping, first-frame content, revision caching, large-input background parsing,
large-input fallback content and line layout, completion revision identity,
Mac row resizing, angle whitespace, EOF labels (both length rules), soft-break
trimming, HTML separators, the scheme allowlist, backtick fallback boundaries,
escaped delimiter runs, CR-only adaptation, long code spans and module tidiness.
The harness log records each command, failure and restoration in
`native/build/logs/review2-mutations.json`.

Final gates passed: **157 Swift tests in 18 suites** (one existing marked
Oficina ID issue), **35,510 comparisons with zero mismatches**, 173 strings,
28 web/native copy pairs, the reference inventory, the Mac build and unsigned
iOS Simulator build. Go tests, vet and staticcheck for chatmarkdown, repository
fmt-check and module tidy all passed with Go 1.26.11 and CGO disabled.
The post-commit reference scan and branch CI verdict are in the handoff.

## Visual and platform checks

Layout tests render the screenshot reply, a wrapping prompt, nested lists and
long scrollable commands at 390 and 760 points. Open and closed code boxes
have the same measured size and source anchor. A live NSHostingView test
verifies the first layout already contains content and subsequent revisions report their new height.
The new captures were inspected: the full task title wraps cleanly, the bold
lead-in has no delimiter marks, the prompt wraps inside its box, and the long
command clips horizontally without widening the transcript. Captures are in
`native/build/markdown-screenshots-review2/`.
These are Mac renders at phone and desktop widths, not physical iPhone
screenshots. The native gate builds the unsigned iOS Simulator app.

The existing marked Oficina ID test issue remains outside this change: a
permission refusal during a Home outage can discard the kit session. No
signed build, production account, merge, deployment or upload is involved.

## Strings for Luna

No new product strings in this follow-up. The five existing native keys still
reuse web copy exactly: `chat.paste.copy` (Copy), `chat.paste.copied` (Copied),
`chat.paste.prompt` (Prompt), `chat.paste.text` (Text), and
`chat.paste.command` (Command). These also supply paste-box accessibility labels.

Removed the unused native key `message.coordinator_spoken %@ %@` from the
source strings and both catalogs. The dependency's proper name and verbatim
copyright/licence text are displayed in its disclosure.
