diff --git a/doc/2026-11-10_design_id5858.md b/doc/2026-11-10_design_id5858.md new file mode 100644 index 0000000000..8b6c1b3dcc --- /dev/null +++ b/doc/2026-11-10_design_id5858.md @@ -0,0 +1,410 @@ +# Design decision record: portable theme format & precedence + +Issue: #5858 (follow-on design from parent #5680, decomposition item 3). +Programme: epic #2056. Boards v1: #2054. Status: decided (this record), +2026-11-10. Implementation is a separate, later decision — this record +settles the shape only, per the parent issue's filing note. + +Baseline: `origin/main` at `ca9a49543c5eecbfff300fc0cd624f595de92e5f` +(code claims re-verified 2026-11-10), worktree `~/git/fleet/13767`. +Verified at that baseline: `pkgs/id/src/boards.rs` already implements a +signed, portable `Theme` object — `name`, `tokens: BTreeMap` (at most `MAX_THEME_TOKENS` = 64 entries, values 1–512 bytes, +no NUL, token names validated as lower-case ASCII identifiers of at +most 64 bytes), one `layout` from the closed set `ThemeLayout { List, +Grid, Compact }`, `assets: Vec` (content-addressed +references only, at most 128, no duplicates; payloads are never +embedded), and `forked_from` lineage (insertion rejects a self-fork and +requires the lineage target to be a theme object). A board applies one +theme by reference through `Board::theme_ref: Option` +(the field was added additively, with a legacy-decode test), and +`BoardGraph::compose_view` already subjects the board's theme to the +host and personal view layers: a theme hidden by the host layer, hidden +by the personal layer, or authored by a muted author is suppressed and +reported in `hidden`. What does **not** exist at this baseline: any +theme reference on `Post` (a post carries `board`, `thread`, +`parent_post`, `body`, `attachments`, `embed_ref` only), any merge or +precedence rule between more than one theme layer, any value-shape or +contrast validation of token values (validation checks sizes, name +charset and reference counts only — a token value is an opaque string), +and any machine-readable board policy for foreign themes (`Rules` is +human-readable text, revisioned, with no interpreted fields). + +## Scope and non-goals + +This record settles the three things issue #5858 names: the portable +theme format (theme-as-object), the post/board/viewer precedence order, +and safety validation for portable themes. + +Not settled here, and not re-decided: + +- **Post semantics** — reference vs. snapshot, pins, withdrawal, + attribution chains: #5856 (`doc/2026-11-08_design_id5856.md`, PR + #7605). This record relies on its rule that a post's signed content + and its references travel together; a post theme is one more such + reference, nothing more. +- **Per-target rendering mappings** — how semantic roles become + Tailwind utilities, native controls, or terminal output: #5849 + (semantic markup vocabulary), #5851 (assertion → Tailwind mapping, + `doc/2026-11-09_decision_id5851_assertion_tailwind_mapping.md`), + #5852, #5853, #5854. Those records own the mapping from roles to a + target; this record fixes the token contract they consume (Decision + 2's reserved roles) and the cascade that feeds it. +- **Embed contract for live objects**: #5859. A theme never styles the + inside of an embedded live object (Decision 4, invariant 7). +- **Moderation roles, reports, appeals**: #5861 on #835. Theme + suppression by hosts and viewers already exists in the view layers + and is a moderation-adjacent act; this record does not extend it. +- **Theme gallery / marketplace**: the parent notes it and explicitly + does not ask this design for a store. Out of scope. +- **Note themes**: #5830 decided note→board sharing; whether a note + carries a theme when rendered off-board is not opened here. + +This record does not change any #2054 v1 object semantic, does not let +a theme reach outside presentation, and does not introduce a second +identity or signature system. + +## Decision 1 — The v1 `Theme` object is the portable format; posts gain a theme reference + +The signed `Theme` object on main **is** the portable theme format, +affirmed rather than replaced: a theme is data (a token map, one +layout from a closed set, content-addressed asset references), it is +content-addressed and signed like every board object, it names no +board, and it is forkable with derived lineage. Portability follows +from those properties — a theme replicates with any object set that +references it, verifies offline, and renders from the same bytes +everywhere. + +The one addition this record makes: + +```text +Post.theme_ref: Option // additive, exactly as Board::theme_ref was added +``` + +- A post may carry its own theme. That is what makes the parent's + "travels with shared posts" rule implementable: when a post is + shared onward — including board-to-board reposts under #5856, where + the source post is referenced, not copied — the post's `theme_ref` + is read from the post (or its source post) and offered to the + receiving board's cascade (Decision 2). +- The field is added with the same serde discipline `Board::theme_ref` + used: `#[serde(default, skip_serializing_if = "Option::is_none")]`, + so posts written before the field existed decode as `None` and keep + verifying. `Post` is `#[serde(deny_unknown_fields)]`; this is a + schema change and must land with its canonical round-trip tests. +- Application is always **by hash**. A board or post names an exact + theme object; a theme author publishing a new version creates a new + object, and existing applications do not move until the board/post + author supersedes their reference. There is no "latest theme" + pointer anywhere in the format. (Fork lineage is how "based on" + is expressed; it confers no automatic updates.) +- A theme reference whose object a peer does not hold degrades, never + fails: the cascade proceeds without that layer and the surface + labels the render "theme unavailable" (Decision 4). This mirrors + #5856's unavailable-state rule for unreadable post targets. + +## Decision 2 — Precedence is a per-token cascade: viewer accessibility > viewer preference > post > board > platform default + +Precedence is resolved **per token**, never winner-take-all per theme. +Each layer may supply any subset of tokens; for each token, the +highest layer that supplies it wins. The order, highest first: + +1. **Viewer accessibility overrides** — reserved tokens only the + viewer layer may set (Decision 3): forced high-contrast palette, + reduced motion, minimum type scale. No lower layer can + countermand, dilute, or rename around them. +2. **Viewer preference** — the viewer's own theme or token overrides, + including the existing view-layer power to suppress a theme + entirely (host/personal `hidden`, muted authors), which + `compose_view` already implements for the board layer and which + this record extends unchanged to the post layer. +3. **Post theme** — the theme the post carries (its own `theme_ref`, + or its source post's, across a repost), subject to the receiving + board's foreign-theme mode (Decision 4). +4. **Board theme** — the receiving board's `theme_ref`. +5. **Platform default theme** — the renderer's built-in complete + theme; it guarantees every reserved role has a value, so a + conforming render never has an unstyled semantic role. + +Two scoping rules keep the cascade predictable: + +- **Layout is not cascaded.** A theme's `layout` is a property of the + surface it was authored for. Inside a board, the board theme's + layout governs; a post theme contributes **tokens only**. When a + post is rendered standalone (its own permalink/full view, outside + any board), its own theme's layout governs, falling back to the + platform default layout. This is the one place layout is read from + a post theme. +- **The cascade is computed at render (in `compose_view`'s + successor), never stored.** No object records a merged theme; the + merge is a pure function of (viewer layers, post ref, board ref, + platform default) so suppression, muting and accessibility changes + take effect on the next render with no writes — the same + projection discipline the view layers already use. + +### Reserved roles give tokens portable meaning + +v1 token names are free-form ASCII identifiers; free-form names carry +no cross-renderer guarantee. The portable contract is a **reserved +role vocabulary** — the semantic colour, type, spacing, corner, +elevation and motion roles the rendering records (#5849/#5851) +already map per target: + +- A token whose name is a reserved role (e.g. `surface`, `on-surface`, + `accent`, `type-body-size`, `motion-duration`) has the meaning the + vocabulary assigns, on every conforming renderer. +- A token with any other valid name is **custom data**: renderers may + use it for renderer-specific flourishes, must ignore it if + unrecognised, and must never error on it. Custom tokens are the + extension path; promoting one to a reserved role is a vocabulary + change in #5849's record, not a theme-author act. +- Two namespaces are **not theme-settable at all**: platform chrome + and safety affordances (system dialogs, permission prompts, the + board's own moderation affordances, link affordance — see Decision + 3). Reserved-role status is what makes this enforceable: chrome + roles simply have no theme-layer binding. + +## Decision 3 — Safety validation in three rings: publish, render, and the accessibility floor + +A theme is data, not code, **by construction** — the format has no +markup, no expressions, no URLs, no executable surface: a closed +layout enum, a string→string token map, hash-only asset references. +That eliminates the code-injection class entirely; what remains is +deception and harm through *values*, and validation is organised +against exactly that. + +**Ring 1 — publish-time (exists in v1; affirmed, one extension).** +The insertion validation on main stands: token count/value caps, name +charset, asset count/dedup, hash-only references, lineage checks. +Extension decided here: asset references must resolve to blobs whose +declared media type is an image or a font; a theme asset reference to +any other blob kind is rejected at insertion. (Assets are rendered by +reference, so their kind is part of the theme's safety surface.) + +**Ring 2 — render-time value validation (new; the current gap).** +Token values are opaque strings at publish; they acquire meaning only +through the per-target mappings. Therefore: + +- Values for reserved roles are **parsed per role** at render: a + colour role must parse as a colour in the role's grammar, a size as + a length in range, a font name as a name from the renderer's font + resolution (never a path, never a URL). A value that does not parse + is **dropped to the next cascade layer**, never passed through to + an emitter, and never an error that blocks the render. +- Raw CSS / raw style text is a separate, author-trusted path in the + rendering records (#5851 layer 5). Theme values never enter it. + The Tailwind mapping consumes token values only through its role + emitters (§3.1–3.6 of that record), which is what makes a hostile + value inert rather than a class-injection. +- Font and image assets are fetched **only** from the content-addressed + store by hash. No remote fetch exists in the format, so a theme + cannot beacon, track, or hot-link. + +**Ring 3 — the accessibility and anti-deception floor (new; renderer-enforced, theme-independent).** + +- **Contrast floor.** For every text-bearing reserved role pair + (foreground on its surface), the renderer computes the effective + contrast after the cascade. A pair below WCAG AA for normal text + (4.5:1) is clamped: the foreground (or, failing that, the surface) + is replaced by the nearest conforming value from the viewer's + layer or the platform default, and the surface marks the render + "theme adjusted for readability". A theme therefore cannot ship a + contrast trap (invisible text, camouflaged actions) to any viewer, + including viewers who set no preferences. +- **Affordance distinguishability.** Links and actionable elements + must remain distinguishable from body text by more than colour + alone after theming (the vocabulary's link role carries an + underline/weight component themes cannot remove — it is not a + theme-settable binding). A theme cannot make a post's links, or a + fake "system notice" styling, impersonate platform UI, because + chrome has no theme bindings at all (Decision 2). +- **Motion.** Any motion-related role resolves through the viewer's + reduced-motion override first (cascade layer 1); with reduced + motion on, animated values render as their static equivalents. +- **Validation tooling.** Theme publish runs rings 1–2 plus the + static part of ring 3 (pairs fully determined by the theme alone) + and produces a **validation report** — derived metadata shown at + publish and on the theme's page ("2 pairs adjusted by the contrast + floor for default viewers"). The report is not signed content and + never gates replication; insertion gating is ring 1 only, so an + older graph never rejects a theme a newer validator dislikes — + renderers clamp instead (invariant 9). + +## Decision 4 — Receiving boards set a foreign-theme mode; degradation is labelled, never silent + +The parent gives the receiving board's design an explicit override. +It is expressed as machine-readable board policy, added additively +alongside `theme_ref`: + +```text +Board.foreign_theme_mode: Honor | TokensOnly | Flatten // default: Honor +``` + +- `Honor` — post themes enter the cascade at layer 3 in full (tokens; + layout still follows Decision 2's scoping rule). +- `TokensOnly` — reserved for boards that pin a house subset: post + themes contribute only non-colour roles (type, spacing, density); + colour roles always resolve from the board layer down. (Named for + what it restricts in practice: chromatic identity stays the board's.) +- `Flatten` — post themes do not enter the cascade; every post renders + in the board theme. This is the parent's "explicitly overrides", + made an explicit signed choice of the board author rather than a + renderer default. + +The mode is part of the board root (author-signed, versioned by +supersede like every board change). It constrains **presentation +only**: it never alters the post, its own theme reference, or how the +same post renders on other boards or standalone. + +Degradation rules, uniform across layers: a missing theme object, a +missing asset blob, a dropped unparseable value, a clamped contrast +pair, and a suppressed theme each degrade exactly one step (skip the +layer/step, label where the surface can) and none of them fail a +render or hide the post itself. An embedded live object's interior is +never themed by any layer (Decision 2 styles the post's frame and +card, not the embed) — that boundary belongs to #5859's contract and +is stated here so the cascade cannot grow into it. + +## Invariants implementation must hold + +1. **Data, not code.** A theme can express only token values, one + closed-set layout, and hash references. No field of any theme or + theme-carrying object is ever interpreted as markup, CSS, script, + or a URL. +2. **Application is by hash and immutable.** Theme updates are new + objects; boards and posts change themes only by superseding their + own reference. No layer of the cascade follows a mutable pointer. +3. **Fixed cascade order.** Viewer accessibility > viewer preference > + post > board > platform default, resolved per token. No renderer + may reorder, skip the viewer layers, or cache a merged result + across a change in any input layer. +4. **Accessibility is non-countermandable.** Reserved accessibility + tokens bind only at the viewer layer; the contrast floor and + affordance-distinguishability floor apply even when the viewer has + set nothing. +5. **Chrome is unthemeable.** Platform UI and safety affordances have + no theme bindings; a theme cannot restyle, hide, or imitate them. +6. **No remote references.** Themes and their assets resolve only + from the content-addressed store, by hash. Rendering a theme + performs no network fetch. +7. **Themes stop at the embed boundary.** A theme styles the post and + board surfaces; the interior of an embedded live object is styled + by the object alone. +8. **Attribution is derived.** Theme authorship and fork lineage come + from signed objects (`forked_from` chains), never from a name or + text field a theme asserts about another theme. +9. **Renderers clamp, never reject, never crash.** Publish-time + validation gates ring 1 only. Every later check (value shape, + contrast, missing objects) degrades one labelled step at render. + A theme valid under an old renderer stays renderable under a new + one, and vice versa. +10. **Parity.** The cascade, floors, and degradation labels behave + identically on web, native, terminal, CLI/script and agent + surfaces; a surface that cannot apply a layer (e.g. terminal + colour depth) degrades by the same one-step rule. + +## Alternatives considered and rejected + +| Option | Why rejected | +|---|---| +| **CSS / stylesheet files as the theme format** | Code, not data: reintroduces every injection and impersonation class ring 2–3 exist to exclude, is not content-addressable as a semantic bundle, and cannot be value-validated per role. The parent fixes "data, not code" outright. | +| **Winner-take-all precedence (one theme wins whole)** | Too coarse in both directions: board-wins kills the parent's travels-with-the-post rule; post-wins lets any shared post restyle a curated board wholesale. Per-token cascade is what lets a post keep its identity inside a board's structure. | +| **Closed token vocabulary only (no custom tokens)** | Makes every experiment a vocabulary amendment and guarantees forks of the format. Reserved roles for the portable contract + ignore-unknown custom tokens gives the same guarantees with an extension path. | +| **URL- or host-referenced themes/assets** | Host dependence, remote fetch, tracking beacons, and link rot — contradicts the graph's host independence (#2054) and #5856's host-independent references rule. | +| **Themes follow "latest" (mutable pointer to newest version)** | Silent restyling of every board and post that applied the theme — the theme analogue of the unpinned live reference #5856 rejected for post targets. | +| **Viewer cannot override (author's theme is the work)** | Directly contradicts the parent: accessibility needs "always win over a theme". Suppression/muting of themes also already exists in the view layers; pretending otherwise forks the model. | +| **Publish-time-only validation (reject non-conforming themes at insertion)** | A stricter future validator would make already-replicated themes uninsertable on older/newer graphs inconsistently, and contrast depends on cascade inputs a publisher cannot see. Insertion gates structure (ring 1); meaning is enforced at render (rings 2–3). | +| **Board override by renderer/board-client default (no signed mode)** | The parent's override must be the board's *design* choice — visible, attributable, and identical for every viewer of that board; a client default is none of those. Hence `foreign_theme_mode` on the board root. | +| **Theme the embed interior too (full-bleed styling)** | Violates the embed contract's isolation (#5859): the board's or post's author styling a live object's interior breaks its capability boundary and its own authorial identity. | + +## Parent-decision check + +Nothing here changes a decision in parent #5680; this record answers +its §2, which the parent's decomposition names as this ticket's: + +- *"a portable, named bundle … that can be applied to a board and + travels with shared posts"* — answered in Decision 1: the v1 signed + `Theme` object affirmed as the format; `Post::theme_ref` added so a + post carries its theme through shares and reposts. +- *"unless the receiving board's design explicitly overrides"* — + answered in Decision 4: the signed `foreign_theme_mode` on the + board root (`Honor` / `TokensOnly` / `Flatten`). +- *"built on the style-assertion/token model … a theme is data, not + code; themes are themselves ID objects — shareable, forkable, + versioned"* — affirmed from the baseline (signed object, fork + lineage, content-addressed versions) and connected to the assertion + model through the reserved role vocabulary in Decision 2. +- *"precedence: post theme vs. board theme vs. viewer preference + (including accessibility overrides — a viewer's + high-contrast/reduced-motion needs always win)"* — answered in + Decision 2's five-layer per-token cascade, with accessibility as + the non-countermandable top layer. +- *"theme safety: no executable content; asset rules and size limits; + malicious-theme considerations (contrast traps, misleading styling) + and validation tooling"* — answered in Decision 3's three rings, + including the contrast floor, chrome reservation, and the publish + validation report. +- *"gallery/marketplace … the design only needs theme application and + portability, not a store"* — honoured as a non-goal above. + +Where this record touches an adjacent decided design it applies it +rather than forking it: #5856's reference/pin and unavailable-state +rules for shared posts, #5830's pin-plus-live discipline where a theme +meets shared notes (not opened here), #5849/#5851's role vocabulary +and per-target mappings, and #2054's append-only/supersede mechanics +and three-layer view composition — the cascade is defined as an +extension of `compose_view`'s existing theme handling, not a parallel +path. + +## Implementation notes and hazards (for the follow-on) + +1. **`compose_view` is the cascade's home.** It already resolves the + board theme against host/personal layers and reports suppression + in `hidden`. The post layer, the platform default, and the floors + belong in the same projection, with `hidden`-style reporting + extended to name cascade adjustments (clamped pairs, dropped + values, unavailable themes) so surfaces can label them. +2. **Serde discipline is the hazard, as with `Board::theme_ref`.** + `Post` and `Board` are `deny_unknown_fields` with canonical + re-serialisation checks (`BoardObject::from_artifact`); both new + fields (`Post::theme_ref`, `Board::foreign_theme_mode`) need the + default/skip pattern and legacy-decode tests, or pre-change + objects stop verifying. +3. **The reserved role vocabulary is shared state.** It lives with + #5849's semantic vocabulary; theme validation and every renderer's + mapping must consume one list. A role added to the vocabulary + without renderer support degrades by the ignore/drop rules — that + is by design, but the vocabulary version a theme was authored + against is worth recording in the validation report. +4. **Contrast computation needs colour parsing to be shared too.** + One colour parser/contrast implementation in `pkgs/id` (or its + rendering crate), used by publish tooling and all renderers; + per-renderer reimplementations will drift on exactly the pairs + the floor exists to catch. +5. **Property tests belong with the fields:** cascade order per token + under all layer subsets; accessibility layer supremacy (no lower + input changes an accessibility-bound token); `foreign_theme_mode` + respected in all three modes; unparseable values drop one layer; + missing theme/asset objects degrade with labels; contrast floor + clamps known-bad pairs; legacy posts/boards (no new fields) decode + and render identically to today. + +## Follow-on + +Implementation is a separate decision (per the parent, possibly +months out). When scheduled it splits as: + +1. Schema: `Post::theme_ref` + `Board::foreign_theme_mode` with + legacy-decode and canonical round-trip tests. +2. Cascade: `compose_view` extension — post layer, platform default, + per-token resolution, adjustment reporting. +3. Reserved role vocabulary binding: publish/render value-shape + validation per role, consumed from #5849's vocabulary. +4. Floors: contrast clamp + affordance distinguishability + motion + resolution, with the shared colour/contrast implementation. +5. Tooling: publish-time validation report; theme page display of + lineage, applications, and report. + +Each split is a separate issue when implementation is scheduled; none +of them may re-decide Decisions 1–4 without amending this record +explicitly.