Skip to main content

quillmark_core/document/
mod.rs

1//! Parsing and typed in-memory model for Quillmark card-yaml documents.
2//!
3//! A [`Document`] holds a root [`Card`] plus ordered composable cards; each
4//! card carries a [`Payload`], source-ordered items ([`PayloadItem`]:
5//! `$quill`/`$kind`/`$ext` metadata, user fields, and comments, in the order
6//! they appear in the block's YAML content), and a Markdown body.
7//! [`Document::parse`] returns errors for malformed YAML, unclosed
8//! fences, a missing root `$quill`, or unknown `$`-prefixed system keys.
9//!
10//! See [markdown-spec.md](https://github.com/borb-sh/quillmark/blob/main/prose/references/markdown-spec.md)
11//! for the card-yaml format specification.
12
13use serde::{Deserialize, Serialize};
14
15use quillmark_content::import::{from_markdown as import_markdown, ImportError};
16use quillmark_content::Content;
17
18use crate::error::ParseError;
19use crate::version::QuillReference;
20use crate::Diagnostic;
21
22/// The single markdown→content boundary for card bodies. Every construction path
23/// that starts from an authored markdown string ([`Document::parse`],
24/// wire/storage deserialization, seeding, blueprint) routes through it, so the
25/// markdown parser is reached from exactly one helper. An empty string yields
26/// the empty content without invoking the parser.
27pub(crate) fn import_body(md: &str) -> Result<Content, ImportError> {
28    if md.is_empty() {
29        Ok(Content::empty())
30    } else {
31        import_markdown(md)
32    }
33}
34
35/// Which encoding a `decode_richtext_value` failure came from, so a call site
36/// can prefix its diagnostic per encoding without re-deriving the dispatch.
37/// Surfaced publicly as the error of [`Card::field_richtext`].
38#[derive(Debug, Clone, PartialEq, Eq)]
39#[non_exhaustive]
40pub enum RichtextDecodeError {
41    /// A JSON object that is not a valid canonical content.
42    NotContent(String),
43    /// A markdown string that failed to import.
44    BadMarkdown(String),
45}
46
47impl RichtextDecodeError {
48    /// The inner failure message, without an encoding-specific prefix.
49    pub fn into_message(self) -> String {
50        match self {
51            RichtextDecodeError::NotContent(m) | RichtextDecodeError::BadMarkdown(m) => m,
52        }
53    }
54}
55
56/// Decode a JSON value in either accepted richtext encoding: a canonical content
57/// **object** ([`from_canonical_value`](quillmark_content::serial::from_canonical_value))
58/// or an authored markdown **string** (via [`import_body`], the single markdown
59/// boundary). The one place the object-vs-string dispatch lives; a call site
60/// handles the shapes that are neither (`null`, array, scalar) and maps the
61/// error into its own type.
62///
63/// - `Some(Ok(rt))`: decoded.
64/// - `Some(Err(e))`: an object that is not a content, or a string that failed
65///   to import; `e` names the encoding so the caller can prefix its message.
66/// - `None`: the value is neither an object nor a string.
67pub(crate) fn decode_richtext_value(
68    value: &serde_json::Value,
69) -> Option<Result<Content, RichtextDecodeError>> {
70    match value {
71        serde_json::Value::Object(_) => Some(
72            quillmark_content::serial::from_canonical_value(value)
73                .map_err(|e| RichtextDecodeError::NotContent(e.to_string())),
74        ),
75        serde_json::Value::String(md) => {
76            Some(import_body(md).map_err(|e| RichtextDecodeError::BadMarkdown(e.to_string())))
77        }
78        _ => None,
79    }
80}
81
82/// Decode a JSON value for a `plaintext` field: a canonical content **object**
83/// (revalidated) or a literal **string** imported verbatim
84/// ([`from_plaintext`](quillmark_content::from_plaintext), never markdown, so
85/// `*hi*` stays four plain characters). The plaintext twin of
86/// [`decode_richtext_value`]: the string branch is infallible (literal import
87/// can't fail), so only the object branch yields `Err` (`String` message). A
88/// call site handles the shapes that are neither: `null`, array, scalar. This
89/// is the single plaintext object-vs-string dispatch, shared by the coercion
90/// literal-import site and the validation shape check.
91///
92/// - `Some(Ok(rt))`: decoded.
93/// - `Some(Err(msg))`: an object that is not a valid content.
94/// - `None`: the value is neither an object nor a string.
95pub(crate) fn decode_plaintext_value(
96    value: &serde_json::Value,
97) -> Option<Result<Content, String>> {
98    match value {
99        serde_json::Value::Object(_) => {
100            Some(quillmark_content::serial::from_canonical_value(value).map_err(|e| e.to_string()))
101        }
102        serde_json::Value::String(s) => Some(Ok(quillmark_content::from_plaintext(s))),
103        _ => None,
104    }
105}
106
107pub mod assemble;
108pub mod dto;
109pub mod edit;
110pub mod emit;
111pub mod fences;
112pub mod limits;
113pub mod meta;
114pub mod payload;
115pub(crate) mod prescan;
116pub mod wire;
117pub(crate) mod yaml_hints;
118
119pub use dto::{peek_schema_version, StorageError, StoredDocument, SCHEMA_V0_93_0};
120pub use edit::EditError;
121pub use meta::{is_valid_kind_name, validate_composable_kind, CardKindError};
122pub use payload::{MetaKey, Payload, PayloadItem};
123// Reachable through `PayloadItem::nested_comments`, so nameable from here.
124pub use prescan::{CommentPathSegment, NestedComment};
125pub use wire::{CardWire, PayloadItemWire, WireError};
126
127/// Authoring-format rules for the `~~~` card-yaml markdown surface.
128///
129/// Surfaced verbatim to LLM/MCP consumers (and to CLI / Python bindings via
130/// the same text) so error parity holds: every consumer reads the same
131/// rules. This is the single source of truth; bindings should call into it
132/// rather than re-stating the rules in their own glue.
133pub const FORMAT_RULES: &str = "Document format rules:
134\u{2022} Block opener and closer are EXACTLY `~~~` (three tildes, no info string). The `~~~card-yaml` opener is also accepted as a non-canonical alias.
135\u{2022} A blank line must precede every `~~~` block opener (unless it is line 1), and the opener must be at column zero (no leading spaces). An indented `~~~` is an ordinary code block, not a card.
136\u{2022} The first block is the root and MUST contain `$quill: <name>@<version>`. Its `$kind` is `main` by position \u{2014} an explicit `$kind: main` is accepted but not required. Additional blocks declare composable cards via `$kind: <card_kind>`.
137\u{2022} Reserved `$`-keys: `$quill`, `$kind`, `$ext`, `$seed`. User fields use lowercase snake_case.
138\u{2022} Prose body is the text after a block's closing `~~~`, up to the next opener or EOF. To include a literal fenced code block in prose, use a backtick fence (```); any column-zero `~~~` block is parsed as card metadata.
139\u{2022} A field that already shows a concrete value carries a default and is shippable as-is \u{2014} keep the line, override the value, or delete it to fall back to the default. A blank or null value (`field:`, `field: null`, `field: ~`) is treated the same as omitting the field: it falls back to the default, or to the type-empty zero value.
140\u{2022} `field: !must_fill <value>` marks a placeholder awaiting your input \u{2014} replace it with a real value and drop the `!must_fill` tag before shipping. A bare `field: !must_fill` is an empty placeholder. A leftover marker never blocks rendering, but it is reported as a warning until you replace it.
141\u{2022} Numbers and booleans MUST be unquoted (`year: 2025`, `pinned: true`); quoting turns them into strings and fails validation.
142\u{2022} Plain-scalar values cannot start with `*` or `&` (YAML alias/anchor markers) and cannot contain `: ` (colon-space). For markdown emphasis, embedded colons, or other special prefixes, quote the value: `field: '**bold**'` or `field: \"Name: subtitle\"`. Multi-line values use `|-`, not multi-line quoted scalars.";
143
144/// Authoring-ergonomics header that introduces a blueprint to an LLM/MCP
145/// consumer. The `{quill}` placeholder is substituted with the quill name.
146/// Designed to be shown above [`FORMAT_RULES`], which covers field-level
147/// semantics like the `!must_fill` marker: keep the wording tight here so the
148/// two strings do not duplicate guidance.
149const BLUEPRINT_INSTRUCTION_TEMPLATE: &str =
150    "Fill in the `{quill}` blueprint below: replace each `!must_fill` placeholder with a real \
151value and edit the body prose. Submit the filled markdown as `content` to `create_document`.";
152
153/// Render the blueprint-instruction header with `quill_name` substituted in.
154/// Single source of truth for the prose so every binding shows identical text.
155pub fn blueprint_instruction(quill_name: &str) -> String {
156    BLUEPRINT_INSTRUCTION_TEMPLATE.replace("{quill}", quill_name)
157}
158
159#[cfg(test)]
160mod tests;
161
162/// The record of one load: the [`Document`] and any non-fatal warnings.
163/// Returned by both doors, the quill-free [`Document::parse`] and the bound
164/// [`Quill::parse`](crate::Quill::parse), whose `warnings` carry the parse's
165/// plus the `conform::*` ones. Warnings live here and only here: `Document` is
166/// the value (equality, the storage DTO, and mutators all exclude warnings);
167/// `Parsed` is the load *event*. A caller that wants only the document writes
168/// `Document::parse(md)?.document`.
169#[derive(Debug)]
170#[must_use = "carries parse warnings; read `.document`/`.warnings` or bind it"]
171#[non_exhaustive]
172pub struct Parsed {
173    pub document: Document,
174    pub warnings: Vec<Diagnostic>,
175}
176
177/// A single card-yaml block (root or composable). `body` is the content
178/// ([`Content`]) form of the prose after the closing fence: the empty content
179/// when none follows; check `card.body().is_blank()`. Markdown is a projection:
180/// [`Card::body_markdown`] re-emits it.
181#[derive(Debug, Clone, PartialEq)]
182pub struct Card {
183    payload: Payload,
184    body: Content,
185}
186
187impl Card {
188    /// Create a `Card` from its parts without validation. `body` is the content
189    /// form; to build from an authored markdown string, import it first via the
190    /// crate-internal `import_body` boundary. For user-facing construction of
191    /// composable cards use [`Card::new`].
192    pub fn from_parts(payload: Payload, body: Content) -> Self {
193        Self { payload, body }
194    }
195
196    pub fn quill(&self) -> Option<&QuillReference> {
197        self.payload.quill()
198    }
199
200    pub fn kind(&self) -> Option<&str> {
201        self.payload.kind()
202    }
203
204    /// Opaque `$ext` map for out-of-band extension data (UI editor state,
205    /// agent annotations, …). Carried through Markdown and storage DTO
206    /// round-trips; never emitted into the plate JSON consumed by
207    /// backends.
208    pub fn ext(&self) -> Option<&serde_json::Map<String, serde_json::Value>> {
209        self.payload.ext()
210    }
211
212    pub fn payload(&self) -> &Payload {
213        &self.payload
214    }
215
216    pub fn payload_mut(&mut self) -> &mut Payload {
217        &mut self.payload
218    }
219
220    /// The card body as a [`Content`] content: the canonical content model.
221    /// For the markdown projection use [`Card::body_markdown`].
222    pub fn body(&self) -> &Content {
223        &self.body
224    }
225
226    /// The card body rendered back to its markdown projection. This is a
227    /// derived view (`export ∘ body`), not stored state; a `Document` round-trip
228    /// therefore canonicalizes the body (e.g. `__b__` → `**b**`).
229    pub fn body_markdown(&self) -> String {
230        quillmark_content::export::to_markdown(&self.body)
231    }
232
233    pub(crate) fn overwrite_body(&mut self, body: Content) {
234        self.body = body;
235    }
236
237    pub(crate) fn body_mut(&mut self) -> &mut Content {
238        &mut self.body
239    }
240
241    /// Read a richtext-valued user field back as a [`Content`] content: the
242    /// field-level twin of [`Card::body`]. Decodes the stored value through the
243    /// same object-or-markdown dispatch the writer
244    /// ([`commit_field`](Card::commit_field)) commits, so a field
245    /// stored as a canonical content reads back losslessly (identity marks
246    /// intact) and a still-authored markdown string imports.
247    ///
248    /// - `None`: the field is absent.
249    /// - `Some(Ok(rt))`: decoded content.
250    /// - `Some(Err(_))`: the field is present but neither a content object nor
251    ///   an importable markdown string (e.g. a bare number a `store_field` wrote).
252    ///
253    /// A `Document` carries no schema, so this cannot itself tell a richtext
254    /// field from a plain string field; the caller names a field it knows is
255    /// richtext, exactly as it does when writing.
256    pub fn field_richtext(&self, name: &str) -> Option<Result<Content, RichtextDecodeError>> {
257        let value = self.payload.get(name)?.as_json();
258        Some(match crate::document::decode_richtext_value(value) {
259            Some(result) => result,
260            None => match value {
261                serde_json::Value::Null => Ok(Content::empty()),
262                _ => Err(RichtextDecodeError::NotContent(
263                    "expected a richtext content object or a markdown string".to_string(),
264                )),
265            },
266        })
267    }
268
269    /// The markdown projection of a richtext-valued field (`export ∘ decode`):
270    /// the field-level twin of [`Card::body_markdown`], and the projection an
271    /// emit or a markdown save writes for a content-valued field. The projection
272    /// twin of [`field_richtext`](Card::field_richtext), carrying its `Ok`/`Err`
273    /// decode outcome:
274    ///
275    /// - `None`: the field is absent.
276    /// - `Some(Ok(md))`: the projected markdown.
277    /// - `Some(Err(_))`: the field is present but does not decode as richtext
278    ///   (a scalar/array/object a `store_field` wrote, or a non-content object).
279    ///
280    /// Absence returns `None`; a present non-richtext value returns `Some(Err)`,
281    /// so the projection surfaces the type mismatch instead of blanking on it.
282    pub fn field_markdown(&self, name: &str) -> Option<Result<String, RichtextDecodeError>> {
283        Some(self.field_richtext(name)?.map(|rt| quillmark_content::export::to_markdown(&rt)))
284    }
285
286    /// Read a plaintext-valued user field back as a [`Content`] content: the
287    /// literal-codec twin of [`field_richtext`](Card::field_richtext). A stored
288    /// string imports verbatim (`*hi*` is four characters, not emphasis), an
289    /// already-canonical content decodes losslessly: the same dispatch coercion
290    /// and validation run for a `plaintext` field, so the read and the render
291    /// agree on the codec.
292    ///
293    /// - `None`: the field is absent.
294    /// - `Some(Ok(rt))`: decoded content.
295    /// - `Some(Err(_))`: the field is present but neither a content object nor a
296    ///   string (e.g. a bare number a `store_field` wrote).
297    ///
298    /// A `Document` carries no schema, so the caller names a field it knows is
299    /// plaintext; the schema-bound door is
300    /// [`TypedReader::get_content`](crate::TypedReader::get_content).
301    pub fn field_plaintext_content(
302        &self,
303        name: &str,
304    ) -> Option<Result<Content, RichtextDecodeError>> {
305        let value = self.payload.get(name)?.as_json();
306        Some(match crate::document::decode_plaintext_value(value) {
307            Some(result) => result.map_err(RichtextDecodeError::NotContent),
308            None => match value {
309                serde_json::Value::Null => Ok(Content::empty()),
310                _ => Err(RichtextDecodeError::NotContent(
311                    "expected a plaintext content object or a string".to_string(),
312                )),
313            },
314        })
315    }
316
317    /// The plaintext projection of a content-valued field (`to_plaintext ∘
318    /// decode`), the literal-codec twin of [`field_markdown`](Card::field_markdown),
319    /// for a `plaintext`-typed field: marks are never interpreted, so the text is
320    /// verbatim both ways. Carries
321    /// [`field_plaintext_content`](Card::field_plaintext_content)'s `Ok`/`Err`
322    /// decode outcome:
323    ///
324    /// - `None`: the field is absent.
325    /// - `Some(Ok(text))`: the projected literal text.
326    /// - `Some(Err(_))`: the field is present but does not decode as content.
327    pub fn field_plaintext(&self, name: &str) -> Option<Result<String, RichtextDecodeError>> {
328        Some(
329            self.field_plaintext_content(name)?
330                .map(|rt| quillmark_content::export::to_plaintext(&rt)),
331        )
332    }
333}
334
335/// A parsed, per-kind **seed overlay**: the sparse fields (and optional body)
336/// a newly-added card of a given kind starts with. Built from a `$seed[<kind>]`
337/// entry of the main card's [`Card::seed`] map via [`SeedOverlay::from_json`],
338/// and layered over the quill's schema-example seed by
339/// [`crate::Quill::seed_card`] (overlay › example › absent). The reserved inner
340/// key `$body` carries the body override; every other user field becomes an
341/// entry, while any other `$`-prefixed key is reserved and dropped.
342#[derive(Debug, Clone, PartialEq, Default)]
343#[non_exhaustive]
344pub struct SeedOverlay {
345    /// Field-value overrides, keyed by field name.
346    pub fields: indexmap::IndexMap<String, crate::value::QuillValue>,
347    /// Body override, when the overlay declares a `$body` string.
348    pub body: Option<String>,
349}
350
351impl SeedOverlay {
352    /// Parse an overlay from a `$seed[<kind>]` JSON value, or `None` when it is
353    /// not a mapping. Use this to turn the raw overlay object a consumer reads
354    /// from the main card's `$seed` map ([`Card::seed`]) into a typed overlay to
355    /// hand to [`crate::Quill::seed_card`]; e.g.
356    /// `doc.main().seed().and_then(|m| m.get(kind)).and_then(SeedOverlay::from_json)`.
357    pub fn from_json(value: &serde_json::Value) -> Option<Self> {
358        value.as_object().map(Self::from_json_map)
359    }
360
361    /// Build an overlay from a single `$seed[<kind>]` JSON map: the reserved
362    /// `$body` string becomes [`body`](Self::body); every other user-field entry
363    /// becomes a field. A non-string `$body` is ignored (no body override). Any
364    /// other `$`-prefixed key is reserved and dropped (never stored as a user
365    /// field) since an overlay only ever carries user fields plus `$body`.
366    fn from_json_map(map: &serde_json::Map<String, serde_json::Value>) -> Self {
367        let mut fields = indexmap::IndexMap::new();
368        let mut body = None;
369        for (key, value) in map {
370            if key == "$body" {
371                if let Some(s) = value.as_str() {
372                    body = Some(s.to_string());
373                }
374            } else if key.starts_with('$') {
375                // Reserved key other than `$body`: not a user field. Drop it
376                // rather than smuggle a `$`-key into the field set.
377                continue;
378            } else {
379                fields.insert(
380                    key.clone(),
381                    crate::value::QuillValue::from_json(value.clone()),
382                );
383            }
384        }
385        SeedOverlay { fields, body }
386    }
387}
388
389/// A fully-parsed Quillmark document. Serde routes through [`StoredDocument`];
390/// for the plate wire shape see [`Document::to_plate_json`].
391///
392/// Parse-time warnings are *not* document state: they ride out-of-band on
393/// [`Parsed`] from [`Document::parse`], the single owner. Equality and the
394/// storage DTO therefore cover only structural content (`main` and `cards`).
395#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
396#[serde(into = "StoredDocument", try_from = "StoredDocument")]
397pub struct Document {
398    main: Card,
399    cards: Vec<Card>,
400}
401
402impl Document {
403    /// Create a blank document: a main card carrying only `$quill`, an empty
404    /// body, and no composable cards. The programmatic blank canvas: every
405    /// schema field is absent and resolves at render time (`default`, else
406    /// type-empty zero), so nothing the caller did not set reaches the
407    /// output. For an example-filled starter shaped like the blueprint, use
408    /// `Quill::seed_document`.
409    pub fn new(quill: QuillReference) -> Self {
410        let mut payload = Payload::new();
411        payload.set_quill(quill);
412        // Parsed main cards always carry `$kind: main` (the parser normalizes
413        // it in); match that shape so a blank document round-trips equal.
414        payload.set_kind("main");
415        Self {
416            main: Card::from_parts(payload, Content::empty()),
417            cards: Vec::new(),
418        }
419    }
420
421    /// Create a `Document` from a pre-built main card and composable cards.
422    /// `main` must carry `$quill`; composable cards must not.
423    pub fn from_main_and_cards(main: Card, cards: Vec<Card>) -> Self {
424        debug_assert!(main.quill().is_some(), "main card must carry `$quill`");
425        debug_assert!(
426            cards.iter().all(|c| c.quill().is_none()),
427            "composable cards must not carry `$quill`"
428        );
429        debug_assert!(
430            cards.iter().all(|c| c.seed().is_none()),
431            "composable cards must not carry `$seed`"
432        );
433        Self { main, cards }
434    }
435
436    /// Parse card-yaml Markdown into a [`Parsed`]: the [`Document`] plus any
437    /// non-fatal warnings. The single parse entry; a caller that wants only the
438    /// document writes `Document::parse(md)?.document`. Errors on malformed
439    /// YAML, a missing root `$quill`, an over-size input, and the other
440    /// [`ParseError`] variants.
441    #[doc(alias = "from_markdown")]
442    pub fn parse(markdown: &str) -> Result<Parsed, ParseError> {
443        assemble::decompose_with_warnings(markdown)
444            .map(|(document, warnings)| Parsed { document, warnings })
445    }
446
447    pub fn main(&self) -> &Card {
448        &self.main
449    }
450
451    pub fn main_mut(&mut self) -> &mut Card {
452        &mut self.main
453    }
454
455    /// The `$quill` reference from the root block. Always present on parsed documents.
456    pub fn quill_reference(&self) -> QuillReference {
457        self.main
458            .quill()
459            .cloned()
460            .expect("root block's $quill is validated at parse time")
461    }
462
463    pub fn cards(&self) -> &[Card] {
464        &self.cards
465    }
466
467    pub fn cards_mut(&mut self) -> &mut [Card] {
468        &mut self.cards
469    }
470
471    /// A single composable card by index: the immutable twin of
472    /// [`card_mut`](Document::card_mut), so reading one card's payload does not
473    /// require materializing every card via [`cards`](Document::cards). `None`
474    /// when out of range.
475    pub fn card(&self, index: usize) -> Option<&Card> {
476        self.cards.get(index)
477    }
478
479    pub(crate) fn cards_vec_mut(&mut self) -> &mut Vec<Card> {
480        &mut self.cards
481    }
482
483    /// Serialize to the JSON wire shape consumed by backend plates. This is
484    /// the **only** place in `quillmark-core` that produces this shape:
485    ///
486    /// ```json
487    /// {
488    ///   "$quill": "<ref>",
489    ///   "$body": { "text": "…", "lines": [...], "marks": [...], "islands": [...] },
490    ///   "$cards": [{ "$kind": "<tag>", "$body": <content>, "<field>": <value>, ... }],
491    ///   "<field>": <value>, ...
492    /// }
493    /// ```
494    ///
495    /// `$body` (global and per-card) is canonical Content-JSON: the content as
496    /// a nested object, not a markdown string. Richtext payload fields likewise
497    /// cross as content objects (committed at coercion time).
498    ///
499    /// `$`-prefixed keys carry document-level metadata (quill ref, body
500    /// text, card list, card kind). User payload fields stay flat at the
501    /// root: they cannot collide with `$` keys because user field names are
502    /// never `$`-prefixed (they match `[A-Za-z_][A-Za-z0-9_]*`).
503    ///
504    /// `$kind` is document-defined and omitted for a kindless card (never a
505    /// fabricated `""`). This method is schema-free and emits `$body` for every
506    /// card and the root; the schema-gated render plate
507    /// (`QuillConfig::compile_data`) instead calls `to_plate_json_gated` with the
508    /// per-card body-presence it resolved, so a card whose kind enables no body
509    /// carries no `$body`: issue 1030's "absent on undefined".
510    pub fn to_plate_json(&self) -> serde_json::Value {
511        // Schema-free: the root and every card carry `$body`.
512        self.to_plate_json_gated(true, None)
513    }
514
515    /// [`to_plate_json`](Self::to_plate_json) with the body-presence decision
516    /// supplied by the caller: the root carries `$body` iff `main_body`, and card
517    /// *i* iff `card_bodies` is `None` (all present) or `card_bodies[i]` holds.
518    /// The schema-gated render plate (`QuillConfig::compile_data`) passes the
519    /// body-enabled bit it already resolved per card, so a body-disabled card
520    /// never carries `$body` (issue 1030, "absent on undefined") and the decision
521    /// is never re-derived from the serialized plate. `Document` stays schema-free:
522    /// it receives the decision, not a schema.
523    pub(crate) fn to_plate_json_gated(
524        &self,
525        main_body: bool,
526        card_bodies: Option<&[bool]>,
527    ) -> serde_json::Value {
528        let mut map = serde_json::Map::new();
529
530        map.insert(
531            "$quill".to_string(),
532            serde_json::Value::String(self.quill_reference().to_string()),
533        );
534
535        // The seam carries the body as canonical Content-JSON (Option A): a
536        // nested content object, byte-identical to `to_canonical_json`, never a lossy
537        // markdown string. Backends lower the content (typst → markup + source
538        // map; pdfform → `.text`); the markdown projection is `body_markdown`.
539        if main_body {
540            map.insert(
541                "$body".to_string(),
542                quillmark_content::serial::to_canonical_value(self.main.body()),
543            );
544        }
545
546        let cards_array: Vec<serde_json::Value> = self
547            .cards
548            .iter()
549            .enumerate()
550            .map(|(i, card)| {
551                let mut card_map = serde_json::Map::new();
552                // A kindless card carries no `$kind`, never a fabricated `""`:
553                // matching the resolved view's `kind: None`.
554                if let Some(kind) = card.kind() {
555                    card_map.insert(
556                        "$kind".to_string(),
557                        serde_json::Value::String(kind.to_string()),
558                    );
559                }
560                // `$body` iff the caller's schema defines a body for this card.
561                if card_bodies.map_or(true, |f| f.get(i).copied().unwrap_or(true)) {
562                    card_map.insert(
563                        "$body".to_string(),
564                        quillmark_content::serial::to_canonical_value(card.body()),
565                    );
566                }
567                for (key, value) in card.payload.iter() {
568                    card_map.insert(key.clone(), value.as_json().clone());
569                }
570                serde_json::Value::Object(card_map)
571            })
572            .collect();
573
574        map.insert("$cards".to_string(), serde_json::Value::Array(cards_array));
575
576        for (key, value) in self.main.payload.iter() {
577            map.insert(key.clone(), value.as_json().clone());
578        }
579
580        serde_json::Value::Object(map)
581    }
582}