Skip to main content

justerm_core/
serialize.rs

1//! Issue #6 — binary, reference-based wire format for a damage frame.
2//!
3//! `encode` a [`Frame`] to bytes, `decode` them back; the round-trip is the
4//! contract. Reference-based (colour refs, Unicode scalars — never resolved RGB
5//! or atlas ids) so the engine stays theme- and font-agnostic; the consumer's
6//! adapter resolves references before handing cells to the renderer. Format spec
7//! and rationale: `docs/architecture.md` §Serialization + ADR-0005.
8
9use crate::cell::{Cell, CellFlags};
10use crate::color::Color;
11use crate::cursor::CursorShape;
12use crate::damage::ScrollOp;
13use crate::input::MouseEvents;
14use crate::selection::SelectionSpan;
15use crate::term::MIN_COLUMNS;
16use core::num::NonZeroU32;
17use std::collections::BTreeMap;
18
19/// Wire magic ("juSTerm") + format version.
20///
21/// **A new feature bumps `VERSION` when it changes the bytes — not when it changes the
22/// meaning.** The rule read "a new feature bumps `VERSION`" until #829/#830/#831, which is the
23/// first feature to falsify it: the underline style (`SGR 4 : Ps`) rides in bits 11..=13 of the
24/// per-cell flag `u16` that every version since v1 has carried, and those bits were zero in every
25/// frame ever encoded. No field changes width, no group is added, no offset moves — so a decoder
26/// gated on the version byte would be rejecting frames it can read.
27///
28/// The reasoning, recorded here because a decision not to bump leaves no other trace:
29///
30/// - **Neither skew direction mis-reads — but an older decoder does not *keep* the field, it
31///   drops it.** `decode` reassembles the flag set with `from_bits_retain`, and that retention
32///   lasts only until `Cell::from_parts`: a pre-#829 `flag_words` masks `f & 0x0700` into the
33///   content word, so bits 11..=13 never reach that build's cells and never reach its `flags`
34///   column. What survives is bit 3, written by the new encoder, which the old build still lifts
35///   to a plain underline. Degradation, not corruption — but a stale decoder cannot forward the
36///   style to a newer renderer, and anyone reasoning from "unknown bits are retained" would
37///   conclude that it can. (Measured on `dba8065`, the commit before #829.) In the other
38///   direction `flag_words` normalises a styleless `UNDERLINE`, which is exactly the word a
39///   pre-#829 encoder wrote, to `Single`.
40/// - **The claim is tested, not asserted**, in `justerm-wasm-decode`
41///   (`a_frame_written_before_the_style_existed_reads_as_a_single_underline` forges that historical
42///   word into a real encoded frame; `a_reader_that_cannot_name_the_style_still_sees_an_underline`
43///   pins the derived flag for all five lit styles).
44/// - **What a bump would not have fixed.** The one real hazard is a consumer assuming bits outside
45///   the decoder's *named* map are unset, and a version byte does not tell it otherwise. #831
46///   answers that where it is actually asked, by naming the field on the published surface
47///   (`underlineStyle`), which is why this decision is recorded rather than deferred to a number.
48/// - **What the decision costs, stated because "degradation" reads as free and it is not.** A
49///   version bump is the family's only *loud* signal: `decodeFrame` returns `BadVersion` and a
50///   stale artifact fails at load. Declining it means a mixed-version install — the npm caret on a
51///   0.x pin resolves a whole minor range independently per package — can pair a style-capable
52///   renderer with a decoder that strips the field, and every curl silently flattens to a straight
53///   line with no error anywhere. That is a real trade and it was taken deliberately: the loud
54///   failure would have rejected frames every one of those decoders can otherwise read correctly,
55///   which is a larger harm than one flattened mark.
56const MAGIC: [u8; 2] = *b"JT";
57const VERSION: u8 = 16; // v16 removes the fourth overlay group — every live marker's absolute line — and adds `marker_count` (u32) to the header in its place: the group was measured at 37-70% of an 80x24 frame at ordinary OSC-133 densities and is the R3 violation ADR-0020 records against itself, so a consumer pulls the index once (`Engine::marker_index`, v15) and the count is its check against drift (#490). The *viewport* marker group stays: it is what command-announce consumes, it is row-filtered, and its population is bounded by MAX_MARKERS (#721) ; v15 adds the marker-index basis to the header — `evicted_total` (u64) and `marker_epoch` (u32) — so a consumer can pull the marker set once and keep it valid instead of being handed every live marker in every frame; the marker groups stayed one version as an oracle for the consumer index and the absolute-line one left in v16 (#490); v14 moves combining clusters and hyperlink refs off the fixed cell record (18 B -> 14 B) into per-span sparse groups, inlining the cluster (no side-table) but keeping the URI table interned, and widens every count/length prefix they use to u32 — the engine could hold a cluster, a URI, or a viewport its own decoder then rejected or, worse, mis-read as Ok (#621); v13 adds a per-span underline-colour group: sparse (col, Color) pairs for cells drawing a coloured underline (SGR 58, #520); v12 adds a fifth overlay group: the consumer-designated active search match's spans (#428); v11 adds a fourth overlay group: every live marker's absolute buffer line for the overview ruler (#120 S3); v10 adds a marker kind discriminant + optional i32 exit to the overlay marker group (#159); v9 adds the alt-screen flag in the header (#149); v8 adds the mouse wanted-events mask in the header (#129/ADR-0016); v7 overlay marker group (#118/ADR-0015); v6 overlay selection + search-match spans (#108/ADR-0014); v5 scroll position (#112/ADR-0013); v4 cursor shape+blink (#81); v3 cursor row/col/visibility (#38)
58
59/// The wire-format version (the gating `VERSION` byte), exposed so a binding can
60/// assert at load that its decoder matches the backend encoder (#34/ADR-0008).
61pub const WIRE_VERSION: u8 = VERSION;
62
63/// The largest `ScrollOp::count` magnitude this format can carry — the field rides
64/// as `i16` (#661).
65///
66/// [`crate::Term::scroll_delta`] caps against **both** this and the scroll region's
67/// own height. The height alone is not enough: [`crate::MAX_ROWS`] is `u16::MAX`, so
68/// a region can be taller than `i16::MAX` and a count legitimately below its height
69/// can still be unrepresentable. That corner truncates the magnitude; what it must
70/// never do is wrap, because a wrapped count arrives with the **opposite sign** and
71/// the consumer shifts the region the wrong way.
72pub(crate) const MAX_SCROLL_COUNT: isize = i16::MAX as isize;
73
74/// Whether a frame redraws everything or just its spans.
75///
76/// **Deliberately exhaustive (#843), and this one is closed by a louder gate than
77/// semver.** A new frame kind is a wire change, so it moves [`WIRE_VERSION`]
78/// (ADR-0008) — which a consumer cannot miss. `#[non_exhaustive]` would only soften
79/// the quieter of the two signals. Left exhaustive on purpose, not by omission.
80///
81/// **`Default` is `Full` because the wire says so (#844).** The discriminant encodes as `0` and
82/// `Partial` as `1`, and every other field of a defaulted [`Frame`] is its own zero — a default
83/// that disagreed with the wire's zero byte would be two spellings of the same empty frame that
84/// do not round-trip to each other. It is not a claim that `Full` is the more useful kind.
85#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
86pub enum FrameKind {
87    /// Every row is present (resize / alt-screen clear).
88    #[default]
89    Full,
90    /// Only the listed spans changed since the consumer's ack.
91    Partial,
92}
93
94/// A damaged column run on one line, with its cells.
95///
96/// `combining` and `links` map a span-relative column to what that cell carries —
97/// combining clusters (#45) and hyperlinks (#46) live in per-row maps, so neither
98/// rides the cell. Since v14 (#621) both are **sparse wire groups of their own**,
99/// not indices in the cell record, which is what removed the `u16` ceilings the
100/// engine could legitimately exceed.
101///
102/// The two are deliberately **not** symmetric, and the asymmetry is measured rather
103/// than stylistic:
104///
105/// - `combining` holds the cluster **inline**. `Term::frame` pushes one entry per
106///   combining cell with no interning, so an index bought nothing but a level of
107///   indirection and a table to count. Inlining is size-neutral (measured: −0.5% on
108///   a combining-heavy frame) and buys the deletion of both.
109/// - `links` holds a **1-based index into [`Frame::link_table`]**, because that
110///   table *is* interned (`Term::frame`'s `link_remap` ships each referenced URI
111///   once). Inlining a URI at every linked cell was measured at +171…403% on
112///   link-dense frames, and all three references share one copy across cells —
113///   ghostty ref-counts its hyperlink set explicitly *"so that a set of cells can
114///   share the same hyperlink without duplicating the data"*, xterm.js keys cells to
115///   an `OscLinkService` id, alacritty holds `Arc<HyperlinkInner>`.
116///
117/// A column is present in either map iff its cell carries the matching bit — and,
118/// as with `ucolors` below, that bit does **not** travel on the wire (the record
119/// encodes `cell.c()` and `encode_color(bg)`, which drop `C_COMBINED` and
120/// `LINK_PRESENT` respectively). `decode` re-arms both from these maps' own entries.
121/// A `Span` built by hand for a test owes the same pairing.
122///
123/// **No `#[non_exhaustive]` (#844), on #843's rule rather than on a lack of growth.** It does grow
124/// with the wire — `combining`, `links` and `ucolors` all arrived as new groups — but the attribute
125/// is not what absorbs that. A `Default` would, at the caller's choice, and 15 out-of-crate literal
126/// sites are what it would spare; that is the follow-up recorded in
127/// `docs/map/territory/published-surface.md`, not this attribute.
128#[derive(Clone, PartialEq, Eq, Debug)]
129pub struct Span {
130    pub line: u16,
131    pub left: u16,
132    pub right: u16,
133    pub cells: Vec<Cell>,
134    pub combining: BTreeMap<usize, Vec<char>>,
135    pub links: BTreeMap<usize, NonZeroU32>,
136    /// Underline colours (SGR 58, #520): span-relative column → the `Color`
137    /// reference the cell's coloured underline draws in. Sparse — only cells that
138    /// carry a non-default underline colour appear (gated on the `UNDERLINE`
139    /// attribute at parse time). Unlike `combining`/`links` this is a colour
140    /// reference, not a side-table index, so it ships inline (no `_table` on the
141    /// [`Frame`]). Kept off the per-cell record so a plain-text frame pays nothing
142    /// (ADR-0020: no inert per-cell payload).
143    ///
144    /// Like `combining` and `links`, a column here is present iff its cell carries
145    /// the matching bit ([`Cell::is_ucolored`]) — but that bit does **not** travel on
146    /// the wire (`encode_color` keeps only mode+value, and `CellFlags` holds no
147    /// presence bits), so `decode` re-arms it from this map's own entries. A `Span`
148    /// built by hand for a test owes the same pairing: an entry here without
149    /// [`Cell::set_ucolored`] on the cell is a column the gated readers cannot see.
150    /// (#531)
151    pub ucolors: BTreeMap<usize, Color>,
152}
153
154/// A stable handle to a buffer line, handed out by `Engine::add_marker` (#118).
155/// Monotonic per engine. The consumer attaches a decoration to the id; the frame
156/// reports where the marker currently sits, and `TermEvent::MarkerDisposed`
157/// signals when its line has left the buffer.
158///
159/// **No `#[non_exhaustive]` (#844).** A `u32` newtype has no second field to gain, so the attribute
160/// would be permanent restriction bought against a change that cannot happen.
161#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
162pub struct MarkerId(pub u32);
163
164/// What a marker means (#158). A plain `add_marker` decoration carries no
165/// semantics ([`MarkerKind::Plain`]); OSC 133 shell-integration marks carry the
166/// command-boundary role (prompt/command/output start, or command finished with
167/// its optional exit code). The engine only *parses and anchors* these — the
168/// success/failure colour, earcon and prompt-to-prompt navigation are consumer
169/// policy (ADR-0017), driven off the kind + exit the wire (#159) carries.
170///
171/// **Deliberately exhaustive (#843), and the first draft of that sweep got this
172/// one wrong — the compiler caught it.** The reasoning that failed: OSC 133 has
173/// more subcommands than the four modelled, and [`MarkerKind::Plain`] is already
174/// the shape an unrecognised mark takes, so a *consumer* meeting a new member has
175/// somewhere to put it. True, and not the whole question.
176///
177/// **This enum rides the wire, so a new member is not a consumer's problem
178/// first — it is an encoder's.** `justerm-wasm-decode` maps every member onto a
179/// numeric wire triple, and marking this non-exhaustive forces a `_` arm there,
180/// which converts a future *compile error* into a silently wrong wire value. That
181/// is the exact trade [`FrameKind`] is left exhaustive for, one type over in this
182/// same file: a new member here moves [`WIRE_VERSION`] (ADR-0008), and a wire bump
183/// is a **louder** gate than semver, so the attribute would soften the quieter
184/// signal while removing the loud one.
185///
186/// **The rule, stated by mechanism rather than by symptom**, because the first
187/// phrasing — *"a wire-carried enum stays exhaustive"* — misclassified at both
188/// ends. It over-captured [`DecodeError`], which ADR-0008 makes a wire contract by
189/// *name* yet which crosses the boundary through `Debug` (total, no arms) and is
190/// therefore free to take the attribute; and it under-captured
191/// [`crate::CursorShape`], which is not obviously "wire-carried" from its own
192/// module and is mapped exactly like this one. The mechanism:
193///
194/// > **An enum whose members are mapped onto wire values by a `match` *outside*
195/// > this crate stays exhaustive.**
196///
197/// Measured over `justerm-wasm-decode/src` — the published encoder, and the only
198/// place the boundary bites — that is **four**: [`crate::CursorShape`]
199/// (`lib.rs:198`), [`FrameKind`] (`:192`), this one (`:233`), and
200/// [`crate::UnderlineStyle`], which joined when #831 gave the style a name on the
201/// published surface. Every other public enum has zero such sites, so no other
202/// call turns on this rule.
203///
204/// **Do not read that count from here.** It was "exactly three" until #831 and this
205/// paragraph is prose, checked by nothing — the executable roster is
206/// `justerm-wasm-decode/tests/wire_enum_stays_exhaustive.rs`, which derives the set
207/// from core's own sources and is what noticed that `cell.rs` was outside its scan.
208///
209/// Nothing but `cargo test --workspace` would have said so: `#[non_exhaustive]`
210/// binds only **across a crate boundary**, so the defect compiles fine inside
211/// `justerm-core` and a bare `cargo test` never sees it. That is the load-bearing
212/// half of the `--workspace` `release.md` insists on.
213///
214/// **But do not mistake that gate for a detector of this rule.** It fired here by
215/// the accident that this enum's wire mapping lives one crate over. [`Color`] is
216/// wire-carried too (`encode_color`, below) and its only exhaustive `match` is
217/// *inside* this crate, where the attribute does nothing — so marking `Color`
218/// would leave the workspace **green** and put the attribute on a wire-carried
219/// enum unnoticed. The rule is currently held by this paragraph and by nothing
220/// executable.
221///
222/// **Why the direction is asymmetric at all**, which is the fact the whole sweep
223/// turns on and is easy to state backwards: an exhaustive enum does not *force* a
224/// consumer to handle a new member — they may write `_` whenever they like. It
225/// **preserves their option** to be forced. `#[non_exhaustive]` removes that
226/// option, and on stable Rust it is irreversible: measured on this repo's pinned
227/// 1.96.0, `#![deny(non_exhaustive_omitted_patterns)]` is an *unknown lint*, so a
228/// consumer cannot opt back in. One direction is a default the consumer can
229/// change; the other is a decision taken on their behalf for good.
230///
231/// **And #843 runs on two axes, not one.** The first draft wrote down only the
232/// first, which left five calls looking arbitrary until a refuting pass named the
233/// gap. They answer different questions and neither substitutes for the other:
234///
235/// - **Openness — can this set actually grow?** This decides whether the attribute
236///   is *warranted*. Putting it on a closed set states something false in the type;
237///   [`crate::Side`] will not gain a third member, and saying it might is worse
238///   than saying nothing.
239/// - **Direction — does a consumer ever *receive* one?** This decides the *cost*,
240///   not the need. Where nothing public hands the enum outward, there is no match
241///   to preserve and the attribute costs a consumer nothing — so a genuine doubt
242///   about openness resolves toward marking. Where the enum comes outward, the
243///   option being removed is real and closure has to be shown.
244///
245/// Read together they explain the whole roster: [`crate::Key`] is inward *and*
246/// open, so it is marked; [`crate::SelectionType`] is inward and **closed** by
247/// convergence, so it is not; [`crate::Color`] comes outward and is closed, so it
248/// is not twice over.
249#[derive(Clone, Copy, PartialEq, Eq, Debug)]
250pub enum MarkerKind {
251    /// A `add_marker` decoration anchor (#118) — no OSC-133 semantics.
252    Plain,
253    /// OSC `133;A` — the shell prompt begins here.
254    PromptStart,
255    /// OSC `133;B` — the typed command begins here (the prompt ended).
256    CommandStart,
257    /// OSC `133;C` — the command was submitted; its output begins here.
258    OutputStart,
259    /// OSC `133;D[;exit]` — the command finished, with its exit code if reported
260    /// (absent, empty or non-numeric → `None`).
261    CommandFinished(Option<i32>),
262}
263
264/// A marker projected onto the viewport (#118): its id, the row it sits on, and
265/// its kind (#159). Only markers visible in the current viewport are reported; an
266/// off-screen marker is omitted but still alive (death comes via `MarkerDisposed`,
267/// not absence — so the consumer can tell "scrolled away" from "gone"). The kind
268/// carries the OSC 133 command-boundary role + exit code so the consumer can drive
269/// prompt-to-prompt navigation and success/fail signals (#160).
270///
271/// **No `#[non_exhaustive]` (#844).** 25 out-of-crate literal sites and the same reading as
272/// [`crate::Span`]: it rides the wire and can grow, and what would absorb that is a `Default` the
273/// caller opts into, not an attribute imposed on every literal.
274#[derive(Clone, Copy, PartialEq, Eq, Debug)]
275pub struct MarkerPosition {
276    pub id: MarkerId,
277    pub row: usize,
278    pub kind: MarkerKind,
279}
280
281/// Interaction overlays projected onto the viewport (#108): highlight spans the
282/// engine carries on the frame so a frame-mode consumer can paint them without
283/// an in-process model query. Positions only — highlight colour is the
284/// consumer's (theme-agnostic). Coordinates are viewport rows/cols, re-projected
285/// by `frame()` against the scroll offset so the engine stays the single
286/// anchoring authority.
287///
288/// **No `#[non_exhaustive]` (#844).** It grows with the wire like [`crate::Frame`], and like
289/// `Frame` it has a derived `Default`, so a new overlay group reaches an out-of-crate literal
290/// through `..Default::default()`.
291#[derive(Clone, PartialEq, Eq, Debug, Default)]
292pub struct Overlay {
293    /// The live selection projected onto visible rows (`selection_range`).
294    pub selection: Vec<SelectionSpan>,
295    /// The search highlights projected onto visible rows. Search matches
296    /// are consumer-owned (next/prev navigation holds the `Vec<Match>`), so the
297    /// consumer hands the highlight set back via `set_search_highlights` and the
298    /// engine projects it here — mirroring how the engine-owned selection rides.
299    pub matches: Vec<SelectionSpan>,
300    /// Engine-owned markers visible in this viewport (#118): persistent line
301    /// anchors for decorations. Unlike the selection (cleared on a screen swap)
302    /// and search highlights (invalidated on output), markers re-anchor through
303    /// buffer mutation and survive an alt-screen excursion; only their viewport
304    /// position rides here.
305    pub markers: Vec<MarkerPosition>,
306    /// The *active* (current) search match's spans (#428, v12): the member of
307    /// `matches` the consumer designated via `set_active_search_highlight`
308    /// (which match is active is consumer policy — next/prev navigation).
309    /// Projected by the same mechanism as `matches`, and *also* present there —
310    /// the renderer's highlight ranking resolves the overlap (#424), not
311    /// exclusion here. Empty when nothing is designated.
312    pub active_match: Vec<SelectionSpan>,
313}
314
315/// One serialized damage cycle: the decoded logical form that `encode`/`decode`
316/// round-trip. `link_table` holds this frame's OSC 8 hyperlink URIs, each shipped
317/// once and referenced by [`Span::links`]. Grapheme clusters have **no** table —
318/// since v14 (#621) they are inlined at their column in [`Span::combining`],
319/// because nothing interned them and the table only bought an index to overflow.
320/// # `Default`, and why this type has one rather than `#[non_exhaustive]` (#844)
321///
322/// This struct grows for a reason outside any one decision: the VT tail is perpetual (#47) and each
323/// feature that reaches the consumer moves [`WIRE_VERSION`], which has gone v3 → v16. Every such
324/// bump used to edit **every** out-of-crate literal, because none of them could say "and the rest
325/// as usual" — 34 sites across five files, all spelling all 19 fields.
326///
327/// `Default` gives them that sentence. `Frame { cols, rows, kind, ..Default::default() }` names what
328/// a caller means and absorbs the next field silently.
329///
330/// **`#[non_exhaustive]` is deliberately NOT here, and the two do not combine.** Measured: with the
331/// attribute, that same literal is `error[E0639]: cannot create non-exhaustive struct using struct
332/// expression` from outside the crate — functional-update syntax is banned too, leaving only
333/// `let mut f = Frame::default();` plus assignments. So the attribute does not *add* forward
334/// compatibility on top of `Default`; it removes the caller's choice of how to get it. That is the
335/// same trade #843 settled for the enums — *"an exhaustive type does not force anyone; it preserves
336/// their option to be forced"* — and it lands the same way here, with the extra note from
337/// [`FrameKind`] that a wire change already moves `WIRE_VERSION` where a consumer cannot miss it.
338#[derive(Clone, PartialEq, Eq, Debug, Default)]
339pub struct Frame {
340    pub cols: u16,
341    pub rows: u16,
342    pub kind: FrameKind,
343    /// Cursor row/col in screen coordinates (0-based), and whether the engine
344    /// shows it (DECTCEM). Rides in the header because the cursor moves with
345    /// almost every frame (#38). *Drawing* the cursor — cell-invert / overlay —
346    /// stays the consumer's renderer adapter; the engine only reports state.
347    pub cursor_row: u16,
348    pub cursor_col: u16,
349    pub cursor_visible: bool,
350    /// The caret shape (DECSCUSR #89) and whether it blinks (att610 ?12, #81).
351    /// Reported for the renderer; drawing/animation stays the consumer's.
352    pub cursor_shape: CursorShape,
353    pub cursor_blink: bool,
354    /// Viewport scroll position (#112 / ADR-0013), for the consumer's scrollbar.
355    /// `display_offset` = lines scrolled up from the bottom (0 = following the
356    /// live screen); `scrollback_len` = history lines (total = `+ rows`). Ride in
357    /// the header like the cursor — per-frame viewport state, not cell content.
358    pub display_offset: u32,
359    pub scrollback_len: u32,
360    /// Lines popped off the front of scrollback since startup or RIS (#490). The
361    /// basis a consumer rebases a *pulled* marker index by: eviction shifts every
362    /// absolute line by the same amount, so the whole class is one number.
363    ///
364    /// `u64` on purpose. A `u32` wraps after 2^32 evicted lines, which is reachable
365    /// in exactly the long high-throughput session this field exists to serve — and
366    /// a wrapped basis is silent, producing a plausible line that names other
367    /// content. The narrowing invariant asks the width question per field, and four
368    /// bytes is the cheapest possible answer here.
369    pub evicted_total: u64,
370    /// Bumped whenever a held marker line went stale for a reason `evicted_total`
371    /// cannot express — a reflow, a region rotate that moved a surviving marker, an
372    /// alt-screen switch (#490). A consumer compares it against the epoch its index
373    /// was pulled at and re-pulls on a difference.
374    ///
375    /// Deliberately *not* bumped by a disposal: that arrives as
376    /// `TermEvent::MarkerDisposed`, which the consumer already handles, so it costs
377    /// no re-pull.
378    pub marker_epoch: u32,
379    /// How many markers are live in the **active** buffer (#490, v16).
380    ///
381    /// Not a shrunken marker group — the groups left this frame in v16, and re-adding a
382    /// bounded one would be the same R3 violation with a smaller constant. This is a
383    /// *check*: a consumer that pulled the index compares this against what it holds and
384    /// re-pulls on a mismatch. It exists for the consumer that wired the pull but not the
385    /// create/dispose events, which would otherwise drift silently — and a silently wrong
386    /// decoration is the failure this whole layer is arranged to avoid.
387    ///
388    /// It cannot catch a create and a dispose inside one frame (the count is unchanged),
389    /// which is why it is a net and not the mechanism.
390    pub marker_count: u32,
391    /// The mouse tracking mode as a *wanted-events* mask (#129): which mouse
392    /// event categories the app asked to receive, so the consumer routes an event
393    /// to the app (bit set) or keeps it local. `empty()` = no reporting. Rides the
394    /// header like the cursor — per-frame mode state the consumer reads, not cell
395    /// content. Positions/encoding never cross; the backend encodes via
396    /// `encode_mouse`.
397    pub mouse_events: MouseEvents,
398    /// Whether the alternate screen (`?1049`/`?47`) is active (#149). Buffer-global
399    /// state a frame-mode consumer can't derive from viewport damage — the
400    /// accessibility announce policy (#119) gates on it (suppress TUI repaints).
401    /// Rides the header like the cursor scalars (ADR-0014).
402    pub alt_screen: bool,
403    pub scroll: Option<ScrollOp>,
404    pub spans: Vec<Span>,
405    pub link_table: Vec<String>,
406    /// Interaction overlays for this viewport (#108): selection, search
407    /// highlights, the active match, and markers — see [`Overlay`].
408    pub overlay: Overlay,
409}
410
411/// Why a byte buffer could not be decoded into a [`Frame`].
412///
413/// **`#[non_exhaustive]` (#843).** A decode error is displayed, never branched on
414/// for correctness, so a new variant is one a consumer can safely fall through on.
415/// See the `BadScroll` note on [`DecodeError::BadGeometry`] — this attribute is what
416/// changes that trade.
417#[non_exhaustive]
418#[derive(Clone, Copy, PartialEq, Eq, Debug)]
419pub enum DecodeError {
420    /// Ran out of bytes mid-field.
421    Truncated,
422    /// First two bytes are not the wire magic.
423    BadMagic,
424    /// Unsupported format version.
425    BadVersion(u8),
426    /// A tag/kind byte held a value outside its defined set.
427    BadTag,
428    /// The frame's **own** declared geometry is one no terminal can have: fewer than
429    /// [`MIN_COLUMNS`](crate::MIN_COLUMNS) columns, or no rows at all (#663).
430    ///
431    /// Distinct from [`BadSpan`](Self::BadSpan), and the distinction is the *direction of
432    /// the comparison* rather than a shade of severity. `BadSpan` means a part of the
433    /// frame does not fit the geometry the header declares; this means the header itself
434    /// declares a geometry the engine defines as impossible and clamps away at every entry
435    /// point (`Term::with_scrollback` and [`Term::resize`](crate::Term::resize) widen
436    /// `cols` to `MIN_COLUMNS` and `rows` to 1). Nothing this crate encodes can carry it,
437    /// so it is malformed input by the same rule `BadSpan` applies one level in.
438    ///
439    /// The floor imports no policy: xterm.js clamps to the same pair for the same reason
440    /// (`MINIMUM_COLS = 2`, *"Less than 2 can mess with wide chars"*, and
441    /// `MINIMUM_ROWS = 1`). There is deliberately **no ceiling** error — `cols`/`rows` are
442    /// `u16` on the wire and [`MAX_COLUMNS`](crate::MAX_COLUMNS) is `u16::MAX` for exactly
443    /// that reason, so the upper end is bounded by the field and needs no check.
444    ///
445    /// This variant is what `BadSpan`'s doc-comment deferred to *"the next release that is
446    /// breaking anyway"* — #663 changes what `decode` accepts, so the version that carries
447    /// it is that release, and the marginal cost of the enum growing is paid there rather
448    /// than on its own. Measured at the time: no exhaustive match on `DecodeError` exists
449    /// in this workspace, `justerm-wasm-decode` formats the variant with `{:?}` (so the
450    /// name reaches JS unaided, #662), and penterm holds no reference to the type.
451    BadGeometry,
452    /// A part of the frame does not fit the geometry the frame itself declares: a span
453    /// whose `left` is past its `right` (which would underflow the cell count), a span
454    /// reaching past `cols` or sitting past `rows`, a sparse group entry keyed outside
455    /// its own span, or a scroll region whose `bottom` is past the last row (#582).
456    ///
457    /// One rule, one error: a coordinate describing a cell the frame says does not exist
458    /// is malformed input, and the consumer must not be handed it.
459    ///
460    /// A dedicated `BadScroll` was considered and **not** taken, and the trade is worth
461    /// stating honestly rather than as a slogan. Against it: this enum is `pub` and not
462    /// `#[non_exhaustive]`, so a new variant is a breaking change for any downstream
463    /// exhaustive match — of which there are, measured, **none in this workspace**; the
464    /// cost is borne only by an external matcher nobody has seen. For it: this variant is
465    /// now the whole diagnostic for six distinct malformations, and the JS side has no
466    /// more to work with (`justerm-wasm-decode` formats the variant name into the thrown
467    /// `Error`'s `message`, #662). The distinction is real but belongs to the next
468    /// release that is breaking anyway — a version bump spent on a diagnostic label, on
469    /// a crate published in lockstep with an npm package, is the more expensive half of
470    /// this trade today.
471    ///
472    /// **That condition arrived, and only for the case it names (#663).**
473    /// [`BadGeometry`](Self::BadGeometry) split off because #663 changes what `decode`
474    /// *accepts*, so its release is the breaking one this paragraph was waiting for. It is
475    /// not a precedent for splitting the six below: the new variant answers a comparison
476    /// pointing the other way (the header against the engine, not a part against the
477    /// header), whereas `BadScroll` would still be one of these six re-labelled. The trade
478    /// above is unchanged for them and they stay merged.
479    ///
480    /// **And the *against* half of that trade is now void (#843).** The paragraph rests on
481    /// this enum being *"`pub` and not `#[non_exhaustive]`"*, which stopped being true when
482    /// the attribute landed on it: a seventh variant is no longer a breaking change **for
483    /// a Rust consumer**, so splitting `BadScroll` off no longer has to wait for a release
484    /// that is breaking for some other reason.
485    ///
486    /// The qualifier is not pedantry. The variant *name* is a cross-language contract —
487    /// ADR-0008 has `justerm-wasm-decode` throw it as the JS `Error` message — and
488    /// `#[non_exhaustive]` does nothing for that consumer. (It is already approximate
489    /// there, since `BadVersion(11)` formats as more than a name.) The ecosystem vote
490    /// points the same way for *this* type specifically: among justerm's own
491    /// dependencies, `regex` and `regex-syntax` mark **error types** non-exhaustive with
492    /// that reason spelled out, while `vte` — a published, semver'd VT crate in the same
493    /// domain — marks **none** of its 17 public enums. Errors yes, domain enums no, which
494    /// is the line this sweep drew before the vote was counted.
495    ///
496    /// What survives is the *for* half — whether six malformations
497    /// deserve six labels — and that is a diagnostics question to answer on its merits,
498    /// with the version-bump argument removed from the scale rather than answered.
499    ///
500    /// The paragraphs above are deliberately not rewritten. They record what was decided
501    /// and on what, and a reader who cannot see the old grounds cannot tell that the
502    /// conclusion outlived them.
503    BadSpan,
504}
505
506/// Serialize a frame to the binary wire format.
507pub fn encode(frame: &Frame) -> Vec<u8> {
508    let mut out = Vec::new();
509    out.extend_from_slice(&MAGIC);
510    out.push(VERSION);
511    out.push(frame.scroll.is_some() as u8);
512    out.push(match frame.kind {
513        FrameKind::Full => 0,
514        FrameKind::Partial => 1,
515    });
516    out.extend_from_slice(&frame.cols.to_le_bytes());
517    out.extend_from_slice(&frame.rows.to_le_bytes());
518    out.extend_from_slice(&frame.cursor_row.to_le_bytes());
519    out.extend_from_slice(&frame.cursor_col.to_le_bytes());
520    out.push(frame.cursor_visible as u8);
521    out.push(match frame.cursor_shape {
522        CursorShape::Block => 0,
523        CursorShape::Underline => 1,
524        CursorShape::Bar => 2,
525    });
526    out.push(frame.cursor_blink as u8);
527    out.extend_from_slice(&frame.display_offset.to_le_bytes());
528    out.extend_from_slice(&frame.scrollback_len.to_le_bytes());
529    // Marker-index basis (#490): the two scalars a consumer needs to keep a pulled
530    // index valid without being handed every marker in every frame.
531    out.extend_from_slice(&frame.evicted_total.to_le_bytes());
532    out.extend_from_slice(&frame.marker_epoch.to_le_bytes());
533    out.extend_from_slice(&frame.marker_count.to_le_bytes());
534    // Mouse wanted-events mask (#129): one byte in the header, like the cursor
535    // scalars. Off = 0.
536    out.push(frame.mouse_events.bits());
537    // Alt-screen flag (#149): one byte in the header, like the cursor scalars.
538    out.push(frame.alt_screen as u8);
539    if let Some(s) = frame.scroll {
540        out.extend_from_slice(&(s.top as u16).to_le_bytes());
541        out.extend_from_slice(&(s.bottom as u16).to_le_bytes());
542        out.extend_from_slice(&(s.count as i16).to_le_bytes());
543    }
544    out.extend_from_slice(&(frame.spans.len() as u16).to_le_bytes());
545    for span in &frame.spans {
546        out.extend_from_slice(&span.line.to_le_bytes());
547        out.extend_from_slice(&span.left.to_le_bytes());
548        out.extend_from_slice(&span.right.to_le_bytes());
549        for cell in &span.cells {
550            out.extend_from_slice(&encode_cell_record(cell));
551        }
552    }
553    // Hyperlink table (#26), interned: each referenced URI ships once as a
554    // length-prefixed UTF-8 run, and `Span::links` points at it. Both the count and
555    // the length are u32 since v14 — the old u16 length rejected a URI the engine
556    // stores happily, and the old u16 count could not describe one entry per cell of
557    // a viewport the header's own `cols`/`rows` (u16 *each*) permit (#621).
558    out.extend_from_slice(&(frame.link_table.len() as u32).to_le_bytes());
559    for uri in &frame.link_table {
560        out.extend_from_slice(&(uri.len() as u32).to_le_bytes());
561        out.extend_from_slice(uri.as_bytes());
562    }
563    // Combining-cluster group (#45, v14): one sparse map per span, in span order, so
564    // the column keys need no span index — the same positional convention `ucolors`
565    // uses below. Each entry is `(col u16, len u32, len * char u32)`, the cluster
566    // inline. There is no side-table and no index: nothing interned them, so the
567    // indirection only bought a second count to overflow (#621).
568    //
569    // **An entry keyed outside its span is dropped, not narrowed (#582).** `Span`'s maps
570    // are `pub` and keyed by `usize` while the wire key is a `u16`, so `col as u16` did
571    // not lose an out-of-range entry — it *moved* it onto a different, live column
572    // (measured: 65539 encoded as 3 and armed the cell 'D'; 65540 in this group armed
573    // 'E'). Dropping is the only answer that fails in the harmless direction, the same
574    // asymmetry [`Term::damage_span`] records from ghostty — "may have false positives
575    // but should never have false negatives".
576    //
577    // The `debug_assert` is the detector and the drop is the release backstop, again as
578    // `damage_span`: `Term::frame` cannot build such a key (it inserts `col - left` for
579    // `col` in `left..=right`), so one arriving here is a justerm bug and should name its
580    // producer at the site — but justerm is a library, and a panic crosses into the
581    // consumer's process.
582    //
583    // The keys are sorted, so the writable entries are a prefix and the *last* key decides
584    // whether any were dropped: when none were — every frame the engine produces — the
585    // count is still `len()`, O(1), and only the write loop walks the map. Counting the
586    // range unconditionally would have replaced an O(1) read with a walk per span per
587    // group on the encode hot path, to describe a case that cannot occur.
588    for span in &frame.spans {
589        debug_assert!(
590            span.combining.keys().all(|&c| c < span.cells.len()),
591            "combining key past the end of its {}-cell span",
592            span.cells.len()
593        );
594        let n = if span
595            .combining
596            .last_key_value()
597            .is_none_or(|(&k, _)| k < span.cells.len())
598        {
599            span.combining.len()
600        } else {
601            span.combining.range(..span.cells.len()).count()
602        };
603        out.extend_from_slice(&(n as u32).to_le_bytes());
604        for (&col, cluster) in span.combining.range(..span.cells.len()) {
605            out.extend_from_slice(&(col as u16).to_le_bytes());
606            out.extend_from_slice(&(cluster.len() as u32).to_le_bytes());
607            for &ch in cluster {
608                out.extend_from_slice(&(ch as u32).to_le_bytes());
609            }
610        }
611    }
612    // Hyperlink reference group (#46, v14): same positional shape, but the value is a
613    // 1-based index into `link_table` rather than the URI — see `Span`'s doc for why
614    // this half stays interned where the one above does not.
615    // Out-of-span keys are dropped here for the reason written out at the combining group
616    // above; every group answers the question the same way or the rule is not a rule.
617    for span in &frame.spans {
618        debug_assert!(
619            span.links.keys().all(|&c| c < span.cells.len()),
620            "link key past the end of its {}-cell span",
621            span.cells.len()
622        );
623        let n = if span
624            .links
625            .last_key_value()
626            .is_none_or(|(&k, _)| k < span.cells.len())
627        {
628            span.links.len()
629        } else {
630            span.links.range(..span.cells.len()).count()
631        };
632        out.extend_from_slice(&(n as u32).to_le_bytes());
633        for (&col, &idx) in span.links.range(..span.cells.len()) {
634            out.extend_from_slice(&(col as u16).to_le_bytes());
635            out.extend_from_slice(&idx.get().to_le_bytes());
636        }
637    }
638    // Underline-colour group (SGR 58, #520, v13): one sparse map per span, in span
639    // order, so the column keys need no span index — the decoder reads exactly
640    // `span_count` maps and attaches each to its span. Each entry is `(col u16,
641    // colour u32)`, the colour packed by the same `encode_color` as fg/bg. A frame
642    // with no coloured underlines pays 2 bytes per span (the zero count).
643    // Out-of-span keys are dropped here too — see the combining group above for why.
644    for span in &frame.spans {
645        debug_assert!(
646            span.ucolors.keys().all(|&c| c < span.cells.len()),
647            "underline-colour key past the end of its {}-cell span",
648            span.cells.len()
649        );
650        let n = if span
651            .ucolors
652            .last_key_value()
653            .is_none_or(|(&k, _)| k < span.cells.len())
654        {
655            span.ucolors.len()
656        } else {
657            span.ucolors.range(..span.cells.len()).count()
658        };
659        out.extend_from_slice(&(n as u16).to_le_bytes());
660        for (&col, &color) in span.ucolors.range(..span.cells.len()) {
661            out.extend_from_slice(&(col as u16).to_le_bytes());
662            out.extend_from_slice(&encode_color(color).to_le_bytes());
663        }
664    }
665    // Overlay section (#108): each group is a u16 count then that many
666    // `(row, left, right)` u16 viewport triples. Selection first, then search
667    // matches. Append-only, version-gated — a future group (markers, #118) adds
668    // a third count here at the next version bump.
669    encode_overlay_spans(&mut out, &frame.overlay.selection);
670    encode_overlay_spans(&mut out, &frame.overlay.matches);
671    // Third overlay group (#118): markers as `(id u32, row u16)` pairs — a
672    // different record shape from the span groups (a marker is a line anchor,
673    // not a column run). v10 (#159) appends a kind discriminant (u8, like
674    // `cursor_shape`), and — only for `CommandFinished` — a presence byte + i32
675    // exit code (the presence pattern mirrors the header's `scroll` option).
676    out.extend_from_slice(&(frame.overlay.markers.len() as u16).to_le_bytes());
677    for m in &frame.overlay.markers {
678        out.extend_from_slice(&m.id.0.to_le_bytes());
679        out.extend_from_slice(&(m.row as u16).to_le_bytes());
680        out.push(match m.kind {
681            MarkerKind::Plain => 0,
682            MarkerKind::PromptStart => 1,
683            MarkerKind::CommandStart => 2,
684            MarkerKind::OutputStart => 3,
685            MarkerKind::CommandFinished(_) => 4,
686        });
687        if let MarkerKind::CommandFinished(exit) = m.kind {
688            out.push(exit.is_some() as u8);
689            out.extend_from_slice(&exit.unwrap_or(0).to_le_bytes());
690        }
691    }
692    // The fourth overlay group — every live marker's absolute line (v11) — LEFT the frame
693    // in v16 (#490). It was the payload: measured at 37-70% of an 80x24 frame at ordinary
694    // OSC-133 densities, and ADR-0020's R3 violation. A consumer pulls the index once
695    // (`Engine::marker_index`) and keeps it current from the header basis plus the marker
696    // events; `marker_count` in the header is the check that it has not drifted.
697    //
698    // Fourth (was fifth) overlay group (#428, v12): the active search match's spans, same
699    // count + `(row, left, right)` shape as the selection/match groups. Appended
700    // at the tail so the section stays append-only.
701    encode_overlay_spans(&mut out, &frame.overlay.active_match);
702    out
703}
704
705/// Encode one overlay group: a u32 span count, then each span as three u16s
706/// (`row`, `left`, `right`) in viewport coordinates.
707///
708/// The count is u32 since v14 (#621), and this is the *same* defect as the cluster
709/// and URI fields — found by that issue's own acceptance item ("do not assume those
710/// two are the only `as u16` narrowings"), which the first sweep answered for the
711/// `(row, left, right)` triples and not for the count above them. A one-character
712/// search over a large viewport reaches it: measured at 1000×133, 66 000 highlight
713/// spans wrapped the count to 464, and `decode` returned **`Ok`** having also
714/// fabricated 928 marker-lines and 3 active-match spans the engine never had — the
715/// wrapped count leaves the reader mid-group, and every group after it is read from
716/// the wrong offset.
717///
718/// **This widens the three viewport-projected groups and deliberately not the marker
719/// group**, which keeps its `u16` count a few lines below. `frame()` clips selection /
720/// matches / active-match to the viewport, so their counts are `O(viewport)` — ADR-0020
721/// R3 satisfied, and widening entrenches nothing. The marker group is not
722/// viewport-bounded either (several marks share a line), so widening it would entrench
723/// the R3 violation ADR-0020 still records against it — the *other* one, the
724/// absolute-line group, left the frame in v16 (#490).
725///
726/// **Why the marker count is nonetheless safe at `u16` (#721).** Not because the group is
727/// small: the *producer* is bounded. `MAX_MARKERS` caps a buffer's live population at
728/// `u16::MAX`, and `marker_positions` projects the **active** buffer only, so the count
729/// cannot reach a value it cannot declare. (The cap is per buffer, so the global live
730/// population can be twice that — the binding fact is which deque is projected.) That bound had to exist for its own reason — the marks are allocated by
731/// an untrusted stream — and it closes this hazard as a consequence rather than as
732/// its purpose.
733///
734/// **And the reason it is unbounded is not the one this comment used to give.** It said
735/// *"the marker groups report every live marker, on-screen or not"* — true of the
736/// absolute-line group, **false of this one**, which `marker_positions` filters to
737/// visible rows. It is unbounded because several marks legitimately share one line and
738/// nothing dedups them — measured at 70 000 records in this group on an 80x24 grid
739/// (#721). The wrong reason mattered: it made ADR-0020's "one stated violation" framing
740/// read as if only the absolute-line group were at issue.
741fn encode_overlay_spans(out: &mut Vec<u8>, spans: &[SelectionSpan]) {
742    out.extend_from_slice(&(spans.len() as u32).to_le_bytes());
743    for s in spans {
744        out.extend_from_slice(&(s.row as u16).to_le_bytes());
745        out.extend_from_slice(&(s.left as u16).to_le_bytes());
746        out.extend_from_slice(&(s.right as u16).to_le_bytes());
747    }
748}
749
750/// Length in bytes of one fixed-width wire cell record (see
751/// [`encode_cell_record`]).
752pub const CELL_RECORD_LEN: usize = 14;
753
754/// Encode one [`Cell`] to its fixed 14-byte little-endian record:
755/// `c` u32 (Unicode scalar) · `fg` u32 · `bg` u32 · `flags` u16. Width derives
756/// from `flags`.
757///
758/// **The record carries no grapheme or hyperlink reference (v14, #621).** Both were
759/// `u16` fields on every cell, and widening them to hold what the engine can
760/// legitimately store would have inflated a record every cell pays — the trade
761/// ADR-0008's Axis 4 already rejected in the other direction. They moved to sparse
762/// per-[`Span`] groups instead, which is why this record *shrank* by 4 bytes:
763/// measured, −20.9% on an ordinary frame that carries neither.
764///
765/// This is the single definition of the cell record layout — [`encode`] writes
766/// it per span cell, and an alternate consumer (the WASM decoder, #34/ADR-0008)
767/// reuses it to lay decoded cells out flat without re-implementing the layout,
768/// so the two cannot drift.
769pub fn encode_cell_record(cell: &Cell) -> [u8; CELL_RECORD_LEN] {
770    let mut r = [0u8; CELL_RECORD_LEN];
771    r[0..4].copy_from_slice(&(cell.c() as u32).to_le_bytes());
772    r[4..8].copy_from_slice(&encode_color(cell.fg()).to_le_bytes());
773    r[8..12].copy_from_slice(&encode_color(cell.bg()).to_le_bytes());
774    r[12..14].copy_from_slice(&cell.flags().bits().to_le_bytes());
775    r
776}
777
778/// A colour reference as a tagged u32: high byte = tag
779/// (0 = Default, 1 = Indexed, 2 = Rgb), low 24 bits = payload. The tag is
780/// mandatory so `Default`, `Indexed(0)`, and `Rgb(0,0,0)` stay distinct.
781///
782/// Public so an alternate consumer (the WASM decoder's structure-of-arrays
783/// `fg`/`bg` columns, #35) reuses this single definition of the colour-ref
784/// encoding instead of re-implementing the tag packing — no drift.
785pub fn encode_color(c: Color) -> u32 {
786    match c {
787        Color::Default => 0,
788        Color::Indexed(i) => (1 << 24) | i as u32,
789        Color::Rgb(r, g, b) => (2 << 24) | (r as u32) << 16 | (g as u32) << 8 | b as u32,
790    }
791}
792
793/// Deserialize the binary wire format back into a [`Frame`].
794pub fn decode(bytes: &[u8]) -> Result<Frame, DecodeError> {
795    let mut r = Reader::new(bytes);
796    if r.take(2)? != MAGIC {
797        return Err(DecodeError::BadMagic);
798    }
799    let version = r.u8()?;
800    if version != VERSION {
801        return Err(DecodeError::BadVersion(version));
802    }
803    let has_scroll = r.u8()? != 0;
804    let kind = match r.u8()? {
805        0 => FrameKind::Full,
806        1 => FrameKind::Partial,
807        _ => return Err(DecodeError::BadTag),
808    };
809    let cols = r.u16()?;
810    let rows = r.u16()?;
811    // The header is read against the engine's own floor before anything is read against
812    // the header (#663). #582 made every *part* of a frame answer to the declared
813    // geometry; this asks whether that geometry is one a terminal can have at all.
814    //
815    // `MIN_COLUMNS = 2` is not a number picked here: a width-2 glyph needs a `WIDE_CHAR`
816    // lead and its `WIDE_CHAR_SPACER`, so one column cannot hold one (ADR-0025 D4's stated
817    // precondition, #547), and `Term::with_scrollback` / `Term::resize` clamp `cols` up to
818    // it and `rows` up to 1 on every path. So nothing this crate encodes can declare
819    // either — measured, not assumed (`tests/header_geometry_floor.rs` drives the engine
820    // at every geometry from 0×0 up through the floor). xterm.js reaches the same pair
821    // from the same cause: `MINIMUM_COLS = 2` ("Less than 2 can mess with wide chars") and
822    // `MINIMUM_ROWS = 1`, applied on every resize.
823    //
824    // Rejected rather than clamped — and **the references do not decide that**, which is
825    // worth stating because the tempting derivation is wrong. They split on the form, all
826    // three at a site they own: alacritty and xterm.js clamp, ghostty *rejects*
827    // (`Terminal.zig:3721` @ `e6e26e16`, `if (opts.cols == 0 or opts.rows == 0) return
828    // error.InvalidValue`, guarding its own `resize`). So "who owns the number" separates
829    // nothing — ghostty owns it and refuses anyway.
830    //
831    // What decides it here is that this boundary cannot *repair*. `decode` reads bytes a
832    // consumer hands back over its own transport (ADR-0008; `tests/robustness.rs` names
833    // them attacker-influenced), and the payload behind this header was laid out for the
834    // width it declares — so widening `cols` does not fix a frame, it re-indexes one, and
835    // the caller gets cells in the wrong places with no error. Reject and "hand back wrong
836    // content" are the only two total answers, which is not a choice. No reference
837    // arbitrates the site because none of them decodes a serialized grid at all
838    // (`docs/map/territory/wire-format.md`); what ghostty does supply is that refusing an
839    // impossible geometry outright is ordinary terminal behaviour, not an invention here.
840    //
841    // **Deliberately no ceiling**, and this comment is where a later reader is stopped
842    // from adding the "obvious symmetric half": `cols`/`rows` are `u16` and `MAX_COLUMNS`
843    // is `u16::MAX` for exactly that representational reason (#621), so the upper end is
844    // bounded by the field's own width. xterm.js has no maximum at all, and the one layer
845    // that could know a real one — `justerm-renderer` — asks the GL implementation rather
846    // than predicting it. A number chosen here would be the only arbitrary constant in the
847    // stack.
848    //
849    // Before the span loop rather than inside it, and that ordering is asserted: a frame
850    // whose declared width is shrunk below the floor usually has an out-of-frame span too,
851    // and `BadSpan` would name the consequence instead of the cause.
852    if (cols as usize) < MIN_COLUMNS || rows == 0 {
853        return Err(DecodeError::BadGeometry);
854    }
855    let cursor_row = r.u16()?;
856    let cursor_col = r.u16()?;
857    let cursor_visible = r.u8()? != 0;
858    let cursor_shape = match r.u8()? {
859        0 => CursorShape::Block,
860        1 => CursorShape::Underline,
861        2 => CursorShape::Bar,
862        _ => return Err(DecodeError::BadTag),
863    };
864    let cursor_blink = r.u8()? != 0;
865    let display_offset = r.u32()?;
866    let scrollback_len = r.u32()?;
867    let evicted_total = r.u64()?;
868    let marker_epoch = r.u32()?;
869    let marker_count = r.u32()?;
870    let mouse_events = MouseEvents::from_bits_retain(r.u8()?);
871    let alt_screen = r.u8()? != 0;
872    let scroll = if has_scroll {
873        let top = r.u16()? as usize;
874        let bottom = r.u16()? as usize;
875        let count = (r.u16()? as i16) as isize;
876        // A scroll region is a write index in a consumer, not an annotation (#582):
877        // `justerm-web`'s `cell-mirror.ts` assigns `cells[y * cols + x]` for every `y` in
878        // `top..=bottom` with nothing bounding it against `rows`. The renderer already
879        // rejects the same value (`FrameGrid::validate` → `ScrollOutsideGrid`) after a
880        // `line == rows` off-by-one trapped the wasm module and left it poisoned (#355).
881        //
882        // **This is deliberately one notch stricter than the renderer, and the difference
883        // is not an oversight.** `FrameGrid::validate` gates its check on `kind != Full`,
884        // because a Full frame repaints everything and its own `shift_region` is skipped.
885        // The web mirror does not have that exemption: it blanks the grid on a Full frame
886        // and *then* still runs `shiftRegion` if the frame carries a scroll op. So the two
887        // consumers disagree about whether a Full frame's scroll op is live, and the wire
888        // is the wrong place to encode either answer — it rejects a region that cannot be
889        // applied to the frame it rides on, whatever the consumer then does with it.
890        //
891        // `top > bottom` is an empty region, not an error — no consumer iterates it, and
892        // the renderer says so explicitly. Rejecting it would be new strictness with no
893        // failure behind it.
894        //
895        // Still not checked here: `count` — but the reason changed with #661, and the
896        // difference matters to anyone extending this guard. It *was* that the engine
897        // legitimately produced counts this field cannot hold (`Term::record_scroll`
898        // accumulated without a cap, and a single 32 770-byte `feed()` of newlines
899        // encoded 32 768 as **−32 768**), so rejecting them here would have rejected
900        // frames the encoder emits — exactly what #582 promised not to do. That is
901        // fixed at the producer: `Term::scroll_delta` caps the count at the region's
902        // height and at [`MAX_SCROLL_COUNT`], so nothing this crate encodes overflows.
903        //
904        // A *foreign* frame carrying an over-height count is still accepted, and that is
905        // a decision rather than the leftover of one. Bounding it became possible once
906        // the engine stopped producing them — but there is no failure behind it, which
907        // is the same reason `top > bottom` rides through above. Measured: every count
908        // across the full `i16` range, both signs, blanks the region in the renderer
909        // and returns `Ok`; `shift_region` / `shiftRegion` / `shiftPrev` all bound the
910        // *source* row against `[top, bottom]` before indexing, so an over-height count
911        // cannot address a cell outside the region it already declared. It costs the
912        // consumer a wasted region-sized shift, and the spans repaint over it.
913        //
914        // Unlike a span's `right`, this is not a write index a consumer walks off — the
915        // distinction `docs/map/territory/wire-format.md` draws between a payload's
916        // placement and its annotations. Rejecting it would be new strictness with no
917        // defect behind it.
918        if top <= bottom && bottom >= rows as usize {
919            return Err(DecodeError::BadSpan);
920        }
921        Some(ScrollOp { top, bottom, count })
922    } else {
923        None
924    };
925    let span_count = r.u16()?;
926    let mut spans = Vec::with_capacity(span_count as usize);
927    for _ in 0..span_count {
928        let line = r.u16()?;
929        let left = r.u16()?;
930        let right = r.u16()?;
931        // A span is read against the frame's own header, not just against itself (#582).
932        // Before this, a frame could declare a 4×2 grid and carry a span claiming column 8
933        // of line 99 and still decode `Ok` — and the consumer that writes those cells does
934        // not fail on it either: `cell-mirror.ts` keeps the viewport as one flat array, so
935        // a column past `cols` lands in the *next row's* slot and silently overwrites it.
936        // A screen reader then announces, and a copy produces, characters that are not on
937        // that line. `decode`'s own input is attacker-influenced (`tests/robustness.rs`),
938        // and rejecting malformed input rather than repairing it is what ADR-0008 makes
939        // this boundary for.
940        if right < left || right >= cols || line >= rows {
941            return Err(DecodeError::BadSpan);
942        }
943        // Widen before the arithmetic: `right - left + 1` in `u16` overflows when
944        // `right == u16::MAX` (e.g. left=0, right=65535), panicking under overflow checks
945        // (#33, found by `cargo fuzz`). `right >= left` is enforced just above, so the
946        // subtraction in `usize` cannot underflow.
947        //
948        // Since #582 this can no longer be *reached*: `right < cols` and `cols` is a u16,
949        // so `right <= 65534` and the sum fits. Kept anyway, and deliberately — it is the
950        // cheaper of the two guarantees and it does not depend on the check above keeping
951        // its position. Deleting it would make a reordering of this function silently
952        // reintroduce a panic that a fuzz run had to find once already.
953        let n = right as usize - left as usize + 1;
954        let mut cells = Vec::with_capacity(n);
955        for _ in 0..n {
956            cells.push(decode_cell(&mut r)?);
957        }
958        spans.push(Span {
959            line,
960            left,
961            right,
962            cells,
963            // Filled from their own groups below (v14): the record no longer carries
964            // either reference, so neither the maps nor the cells' presence bits can
965            // be built here.
966            combining: BTreeMap::new(),
967            links: BTreeMap::new(),
968            ucolors: BTreeMap::new(),
969        });
970    }
971    // Counts and lengths are u32 since v14 — see `encode`. Note the deliberate loss of
972    // `Vec::with_capacity`: these counts are attacker-influenced (`tests/robustness.rs`
973    // drives `decode` from arbitrary bytes) and a u32 one can now declare 4 billion
974    // entries, so reserving up front would turn a 12-byte buffer into an OOM. Growing
975    // as the entries actually arrive is bounded by the input's own length.
976    let link_count = r.u32()?;
977    let mut link_table = Vec::new();
978    for _ in 0..link_count {
979        let len = r.u32()? as usize;
980        let bytes = r.take(len)?;
981        link_table.push(String::from_utf8_lossy(bytes).into_owned());
982    }
983    // Combining group (v14, #621): inverse of the encode above — one sparse map per
984    // span, in span order, attached to `spans[i]` positionally.
985    //
986    // Re-arming `C_COMBINED` here is not a nicety, it is the only place left that can.
987    // The bit never travels *as a bit*: the record encodes `cell.c()`, the char, so
988    // the content word's marker is dropped. Until v14 `decode_cell` could reconstruct
989    // it inline from `extra != 0` because the index rode the record; now that it does
990    // not, this loop inherits that duty — the same reconstruction `ucolors` has always
991    // done, and the defect #531 was filed for when it was missing.
992    //
993    // A key outside its span is rejected, not tolerated (#582, answering the question this
994    // comment used to defer): `col` is attacker-influenced and nothing on the wire bounds
995    // it against the span's width, and an entry addressing a cell the span does not have
996    // describes nothing the frame contains. It used to arm no cell and stay in the map,
997    // which handed the consumer a coordinate it is free to index with.
998    for span in &mut spans {
999        let count = r.u32()?;
1000        for _ in 0..count {
1001            let col = r.u16()? as usize;
1002            let len = r.u32()?;
1003            let mut cluster = Vec::new();
1004            for _ in 0..len {
1005                cluster.push(char::from_u32(r.u32()?).ok_or(DecodeError::BadTag)?);
1006            }
1007            let Some(cell) = span.cells.get_mut(col) else {
1008                return Err(DecodeError::BadSpan);
1009            };
1010            cell.set_combined(true);
1011            span.combining.insert(col, cluster);
1012        }
1013    }
1014    // Hyperlink reference group (v14, #621): same shape, and `LINK_PRESENT` is re-armed
1015    // for the same reason — it lives in the bg word, which `encode_color` drops.
1016    for span in &mut spans {
1017        let count = r.u32()?;
1018        for _ in 0..count {
1019            let col = r.u16()? as usize;
1020            let idx = NonZeroU32::new(r.u32()?).ok_or(DecodeError::BadTag)?;
1021            let Some(cell) = span.cells.get_mut(col) else {
1022                return Err(DecodeError::BadSpan);
1023            };
1024            cell.set_linked(true);
1025            span.links.insert(col, idx);
1026        }
1027    }
1028    // Underline-colour group (v13, #520): inverse of the encode above — one sparse
1029    // map per span, in span order, so each attaches to `spans[i]` positionally.
1030    for span in &mut spans {
1031        let count = r.u16()?;
1032        for _ in 0..count {
1033            let col = r.u16()? as usize;
1034            let color = decode_color(r.u32()?)?;
1035            // Re-arm `UCOLOR_PRESENT` from the group (#531). On this wire a presence
1036            // bit never travels *as a bit*: it lives in the bg word (`BG_UCOLOR`),
1037            // which `encode_color` drops when it keeps only mode+value, and
1038            // `CellFlags` carries no presence bits. So every one of them is
1039            // *reconstructed* from whether its group carries an entry — the same
1040            // derivation `decode_cell` performs for `combined`/`linked`, which can do
1041            // it inline only because `extra`/`link` ride the cell record while a
1042            // colour reference rides a separate group. `Row::ucolor_at` gates the map
1043            // read on this bit, so without the re-arm `Cell::is_ucolored()` returns
1044            // false on a decoded cell whose column *does* carry a colour.
1045            //
1046            // `col` is attacker-influenced (see `tests/robustness.rs`) and nothing on
1047            // the wire bounds it against the span's width, so an unchecked
1048            // `span.cells[col]` would panic where ADR-0008 owes a typed error. #531
1049            // bought the safety with a gate that kept the entry; #582 answers the
1050            // question that gate deferred — the entry is rejected, because a colour for
1051            // a cell this span does not have is not a colour the frame carries.
1052            let Some(cell) = span.cells.get_mut(col) else {
1053                return Err(DecodeError::BadSpan);
1054            };
1055            cell.set_ucolored(true);
1056            span.ucolors.insert(col, color);
1057        }
1058    }
1059    // Overlay section (#108): selection group then match group, each a count +
1060    // `(row, left, right)` triples (inverse of `encode_overlay_spans`).
1061    let selection = decode_overlay_spans(&mut r)?;
1062    let matches = decode_overlay_spans(&mut r)?;
1063    // Third group (#118): marker `(id u32, row u16)` records, each followed by a
1064    // kind discriminant (v10, #159) and — for `CommandFinished` — a presence byte
1065    // + i32 exit (inverse of the marker encode loop).
1066    let marker_group_len = r.u16()?;
1067    let mut markers = Vec::with_capacity(marker_group_len as usize);
1068    for _ in 0..marker_group_len {
1069        let id = MarkerId(r.u32()?);
1070        let row = r.u16()? as usize;
1071        let kind = match r.u8()? {
1072            0 => MarkerKind::Plain,
1073            1 => MarkerKind::PromptStart,
1074            2 => MarkerKind::CommandStart,
1075            3 => MarkerKind::OutputStart,
1076            4 => {
1077                // Always read presence + i32 (the encoder writes both); a 0
1078                // presence means the exit bytes are padding to discard.
1079                let present = r.u8()? != 0;
1080                let exit = r.u32()? as i32;
1081                MarkerKind::CommandFinished(present.then_some(exit))
1082            }
1083            _ => return Err(DecodeError::BadTag),
1084        };
1085        markers.push(MarkerPosition { id, row, kind });
1086    }
1087    // Fifth group (#428, v12): the active search match's spans (inverse of the
1088    // tail `encode_overlay_spans` call).
1089    let active_match = decode_overlay_spans(&mut r)?;
1090    let overlay = Overlay {
1091        selection,
1092        matches,
1093        markers,
1094        active_match,
1095    };
1096    Ok(Frame {
1097        cols,
1098        rows,
1099        kind,
1100        cursor_row,
1101        cursor_col,
1102        cursor_visible,
1103        cursor_shape,
1104        cursor_blink,
1105        display_offset,
1106        scrollback_len,
1107        evicted_total,
1108        marker_epoch,
1109        marker_count,
1110        mouse_events,
1111        alt_screen,
1112        scroll,
1113        spans,
1114        link_table,
1115        overlay,
1116    })
1117}
1118
1119/// Decode one overlay group: a u16 span count, then that many `(row, left,
1120/// right)` u16 triples back into viewport [`SelectionSpan`]s (inverse of
1121/// [`encode_overlay_spans`]).
1122fn decode_overlay_spans(r: &mut Reader) -> Result<Vec<SelectionSpan>, DecodeError> {
1123    let count = r.u32()?;
1124    // No `with_capacity`: the count is attacker-influenced and now u32 — see `decode`.
1125    let mut spans = Vec::new();
1126    for _ in 0..count {
1127        let row = r.u16()? as usize;
1128        let left = r.u16()? as usize;
1129        let right = r.u16()? as usize;
1130        spans.push(SelectionSpan { row, left, right });
1131    }
1132    Ok(spans)
1133}
1134
1135/// Decode one 14-byte cell record (inverse of [`encode_cell_record`]).
1136///
1137/// **No presence bit is re-armed here — since v14 (#621), none of the three can be.**
1138/// They are reconstructed rather than transmitted (they live in the packed content
1139/// and colour words, which [`encode_color`] and `Cell::c` strip), and every one of
1140/// them now has its evidence in a sparse group read further down the buffer:
1141/// `C_COMBINED` and `LINK_PRESENT` from the combining and link groups, and
1142/// `UCOLOR_PRESENT` from the underline-colour group as it always was (#531).
1143///
1144/// This doc used to say *two of the three are re-armed here*, and that exception —
1145/// "mine rides the record, so it needs nothing" — is the reading #531 was filed for.
1146/// There is no longer a member of the set it could apply to.
1147fn decode_cell(r: &mut Reader) -> Result<Cell, DecodeError> {
1148    let c = char::from_u32(r.u32()?).ok_or(DecodeError::BadTag)?;
1149    let fg = decode_color(r.u32()?)?;
1150    let bg = decode_color(r.u32()?)?;
1151    let flags = CellFlags::from_bits_retain(r.u16()?);
1152    // `C_COMBINED` and `LINK_PRESENT` are deliberately left off here and re-armed by
1153    // `decode` from the per-span groups (v14, #621). This function used to set them
1154    // from the record's `extra`/`link`; with those gone it has nothing to read, and
1155    // guessing `false` is correct precisely because the groups are the authority.
1156    Ok(Cell::from_parts(c, fg, bg, flags))
1157}
1158
1159/// Decode a tagged-u32 colour reference (inverse of [`encode_color`]).
1160fn decode_color(v: u32) -> Result<Color, DecodeError> {
1161    let payload = v & 0x00FF_FFFF;
1162    match v >> 24 {
1163        0 => Ok(Color::Default),
1164        1 => Ok(Color::Indexed(payload as u8)),
1165        2 => Ok(Color::Rgb(
1166            (payload >> 16) as u8,
1167            (payload >> 8) as u8,
1168            payload as u8,
1169        )),
1170        _ => Err(DecodeError::BadTag),
1171    }
1172}
1173
1174/// A little-endian cursor over the wire bytes.
1175struct Reader<'a> {
1176    bytes: &'a [u8],
1177    pos: usize,
1178}
1179
1180impl<'a> Reader<'a> {
1181    fn new(bytes: &'a [u8]) -> Self {
1182        Reader { bytes, pos: 0 }
1183    }
1184
1185    fn take(&mut self, n: usize) -> Result<&'a [u8], DecodeError> {
1186        let end = self.pos.checked_add(n).ok_or(DecodeError::Truncated)?;
1187        let slice = self
1188            .bytes
1189            .get(self.pos..end)
1190            .ok_or(DecodeError::Truncated)?;
1191        self.pos = end;
1192        Ok(slice)
1193    }
1194
1195    fn u8(&mut self) -> Result<u8, DecodeError> {
1196        Ok(self.take(1)?[0])
1197    }
1198
1199    fn u16(&mut self) -> Result<u16, DecodeError> {
1200        let b = self.take(2)?;
1201        Ok(u16::from_le_bytes([b[0], b[1]]))
1202    }
1203
1204    fn u32(&mut self) -> Result<u32, DecodeError> {
1205        let b = self.take(4)?;
1206        Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
1207    }
1208
1209    /// Only the marker-index basis needs eight bytes (#490) — see `Frame::evicted_total`
1210    /// for why that one is not a `u32` like every other header scalar.
1211    fn u64(&mut self) -> Result<u64, DecodeError> {
1212        let b = self.take(8)?;
1213        Ok(u64::from_le_bytes([
1214            b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7],
1215        ]))
1216    }
1217}