Skip to main content

quillmark_core/document/
edit.rs

1//! Typed mutators for [`Document`] and [`Card`] with invariant enforcement.
2//!
3//! Every successful mutator leaves the document with every user field name
4//! matching `[A-Za-z_][A-Za-z0-9_]*` and every composable `$kind` passing
5//! `meta::is_valid_kind_name`, so the result is safely serializable via
6//! [`Document::to_plate_json`]. Mutators never modify `warnings` — those
7//! are immutable parse-time observations.
8//!
9//! Payload/body mutators (field store/fill/remove, `$ext` and `$seed`
10//! namespace writers, body replacement) live on [`Card`]; [`Document`] keeps
11//! document-level ops (quill-ref, push/insert/remove/move card).
12//!
13//! The `$ext` mutators carry no field-name invariant ($ext is an opaque
14//! mapping that never reaches the plate JSON backends consume), but they do
15//! enforce the §8 value-depth bound: `$ext` flows through the recursive
16//! emit and DTO paths like any other value.
17
18use unicode_normalization::UnicodeNormalization;
19
20use quillmark_content::delta::diff_import;
21use quillmark_content::import::ImportError;
22use quillmark_content::{ApplyError, Delta, LineOp, MarkOp, Content};
23
24use crate::document::meta::{validate_composable_kind, CardKindError};
25use crate::document::{Card, Document, Payload};
26use crate::quill::{CoercionError, FieldSchema, Leniency, QuillConfig};
27use crate::value::QuillValue;
28use crate::version::QuillReference;
29
30/// `true` if `name` matches `[A-Za-z_][A-Za-z0-9_]*` after NFC normalisation.
31///
32/// Lowercase is the recommended (canonical) convention, but uppercase ASCII
33/// letters are accepted and preserved verbatim. Collision-safety with system
34/// metadata comes entirely from the `$`-prefix exclusion — `$`-prefixed keys
35/// are reserved, so a user field can never shadow one regardless of case.
36pub fn is_valid_field_name(name: &str) -> bool {
37    let normalized: String = name.nfc().collect();
38    if normalized.is_empty() {
39        return false;
40    }
41    let mut chars = normalized.chars();
42    let first = chars.next().unwrap();
43    if !first.is_ascii_alphabetic() && first != '_' {
44        return false;
45    }
46    for ch in chars {
47        if !ch.is_ascii_alphanumeric() && ch != '_' {
48            return false;
49        }
50    }
51    true
52}
53
54/// Errors returned by document and card mutators.
55#[derive(Debug, Clone, PartialEq, thiserror::Error)]
56pub enum EditError {
57    #[error("invalid field name '{0}': must match [A-Za-z_][A-Za-z0-9_]*")]
58    InvalidFieldName(String),
59
60    /// A typed write ([`TypedWriter::set`](crate::TypedWriter::set) /
61    /// [`CardWriter::set`](crate::CardWriter::set)) addressed a well-formed name
62    /// that the bound schema does not declare (or a card whose `$kind` carries
63    /// no schema). The typed path resolves every name to a schema type, so an
64    /// undeclared name is a typo, not a fallback — it fails here instead of
65    /// landing silently in the opaque store. Reach for the raw
66    /// [`Card::store_field`](Card::store_field) when opaque storage is the intent.
67    #[error("field '{0}' is not declared in the schema")]
68    UnknownField(String),
69
70    #[error("invalid card kind '{0}': must match [a-z_][a-z0-9_]*")]
71    InvalidKindName(String),
72
73    #[error("card kind 'main' is reserved for the document root")]
74    ReservedKind,
75
76    #[error("index {index} is out of range (len = {len})")]
77    IndexOutOfRange { index: usize, len: usize },
78
79    #[error("value nests deeper than the maximum of {max} levels")]
80    ValueTooDeep { max: usize },
81
82    /// Markdown import failed — the content codec rejected the input for a body
83    /// *or* a field path (e.g. container nesting past
84    /// [`MAX_NESTING_DEPTH`](quillmark_content::MAX_NESTING_DEPTH)). Returned
85    /// instead of silently degrading the target to empty on a rejected import.
86    #[error("markdown import failed: {0}")]
87    Import(ImportError),
88
89    /// A richtext field value in the content-or-markdown encoding could not be
90    /// decoded: a JSON object that is not a canonical richtext content, a
91    /// markdown string that failed to import, or a shape that is neither
92    /// object, string, nor null. Returned by
93    /// [`Card::commit_field`](Card::commit_field) on a richtext field, by
94    /// [`Card::revise_field`](Card::revise_field) on a present non-content field,
95    /// and by [`Card::apply_field_richtext_change`](Card::apply_field_richtext_change).
96    #[error("richtext field '{field}' decode failed: {message}")]
97    FieldRichtextDecode { field: String, message: String },
98
99    /// A richtext field written under the `richtext(inline)` constraint decoded
100    /// to a multi-block content (more than one line, a container, or an island).
101    /// The write-time counterpart of the coercion/validation `richtext(inline)`
102    /// check; returned by [`Card::commit_field`](Card::commit_field) when the
103    /// field's schema is `richtext` with `inline: true`.
104    #[error("richtext field '{0}' is not inline: richtext(inline) requires a single paragraph line with no list/quote container and no islands")]
105    FieldRichtextNotInline(String),
106
107    /// A typed write ([`Card::commit_field`](Card::commit_field)) could not
108    /// conform the value to the field's schema type — the general write-commit
109    /// failure for scalar/array/object types (a `"x"` for an `integer`, a
110    /// non-object for an `object`, …). Richtext fields report through the
111    /// dedicated [`FieldRichtextDecode`](Self::FieldRichtextDecode) /
112    /// [`FieldRichtextNotInline`](Self::FieldRichtextNotInline) variants
113    /// instead, so the richtext write surface is unchanged.
114    #[error("field '{field}' does not conform to its schema type: {message}")]
115    FieldConform { field: String, message: String },
116
117    /// A content field-change bundle (text delta, line ops, mark ops) applied
118    /// out of bounds or broke an invariant normalization could not repair.
119    #[error("content apply failed: {0:?}")]
120    ContentApply(ApplyError),
121}
122
123impl EditError {
124    /// The bare variant name (e.g. `"InvalidFieldName"`). Retained as the
125    /// stable variant discriminator behind [`code`](Self::code); defined once
126    /// here so a new variant cannot drift between the two binding error mappers.
127    pub fn variant_name(&self) -> &'static str {
128        match self {
129            EditError::InvalidFieldName(_) => "InvalidFieldName",
130            EditError::UnknownField(_) => "UnknownField",
131            EditError::InvalidKindName(_) => "InvalidKindName",
132            EditError::ReservedKind => "ReservedKind",
133            EditError::IndexOutOfRange { .. } => "IndexOutOfRange",
134            EditError::ValueTooDeep { .. } => "ValueTooDeep",
135            EditError::Import(_) => "Import",
136            EditError::FieldRichtextDecode { .. } => "FieldRichtextDecode",
137            EditError::FieldRichtextNotInline(_) => "FieldRichtextNotInline",
138            EditError::FieldConform { .. } => "FieldConform",
139            EditError::ContentApply(_) => "ContentApply",
140        }
141    }
142
143    /// The namespaced diagnostic `code` (e.g. `"edit::invalid_field_name"`),
144    /// one per variant. This is the machine-routable identity both bindings
145    /// stamp onto the `Diagnostic` they raise — the `edit::*` peer of
146    /// `parse::*`, `validation::*`, and the rest of the taxonomy in
147    /// `prose/canon/ERROR.md`. Consumers route on this, not on message text.
148    pub fn code(&self) -> &'static str {
149        match self {
150            EditError::InvalidFieldName(_) => "edit::invalid_field_name",
151            EditError::UnknownField(_) => "edit::unknown_field",
152            EditError::InvalidKindName(_) => "edit::invalid_kind_name",
153            EditError::ReservedKind => "edit::reserved_kind",
154            EditError::IndexOutOfRange { .. } => "edit::index_out_of_range",
155            EditError::ValueTooDeep { .. } => "edit::value_too_deep",
156            EditError::Import(_) => "edit::import",
157            EditError::FieldRichtextDecode { .. } => "edit::field_richtext_decode",
158            EditError::FieldRichtextNotInline(_) => "edit::field_richtext_not_inline",
159            EditError::FieldConform { .. } => "edit::field_conform",
160            EditError::ContentApply(_) => "edit::content_apply",
161        }
162    }
163
164    /// The [`DocPath`](crate::path::DocPath) this error anchors to, relative to
165    /// `base` — the card root the mutator ran against (`main` for a main-card
166    /// mutator, `cards.<kind>[i]` for a composable card, `cards[i]` for a
167    /// structural op on the array; empty only for a card built before it is
168    /// placed, which has no index yet).
169    ///
170    /// A field-named variant anchors at its field under `base`
171    /// (`main.<field>`, `cards.<kind>[i].<field>`, or a bare `<field>` when
172    /// `base` is empty — the pre-placement card);
173    /// [`IndexOutOfRange`](Self::IndexOutOfRange) at the document-array slot
174    /// `cards[index]`, base-independent — a structural op names a slot, not a
175    /// field; and the remaining variants (kind errors, depth, content
176    /// apply/import) anchor at `base` itself when it names a card, else carry no
177    /// anchor (a config-space `$seed` error keeps an empty base). Both
178    /// bindings route through this so a mutator diagnostic is addressable the
179    /// same way a validation diagnostic is.
180    pub fn doc_path(&self, base: &crate::path::DocPath) -> Option<crate::path::DocPath> {
181        use crate::path::DocPath;
182        match self {
183            EditError::InvalidFieldName(f)
184            | EditError::UnknownField(f)
185            | EditError::FieldRichtextNotInline(f)
186            | EditError::FieldConform { field: f, .. }
187            | EditError::FieldRichtextDecode { field: f, .. } => Some(base.field(f)),
188            EditError::IndexOutOfRange { index, .. } => Some(DocPath::card(None, *index)),
189            _ => (!base.segs().is_empty()).then(|| base.clone()),
190        }
191    }
192}
193
194/// A field-level invariant violation, shared by every payload ingestion path.
195///
196/// Each boundary maps it to its own error type (`ParseError`,
197/// `StorageError`, `WireError`, `EditError`), so the invariant — every user
198/// field name matches `[A-Za-z_][A-Za-z0-9_]*` and no value nests past the §8
199/// depth limit — is enforced once, here, and a constructed `Document` can
200/// never violate it.
201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
202pub enum FieldViolation {
203    /// The field name does not match `[A-Za-z_][A-Za-z0-9_]*` (spec §3.4 / §10).
204    InvalidName,
205    /// The value nests deeper than [`MAX_YAML_DEPTH`](crate::document::limits::MAX_YAML_DEPTH)
206    /// (spec §8).
207    TooDeep,
208}
209
210/// Map a [`FieldViolation`] to the mutator error surface — the single
211/// translation the `Card` mutators and the validating
212/// [`Payload::insert`](crate::document::Payload::insert) both route through.
213pub(crate) fn edit_error_from_violation(name: &str, v: FieldViolation) -> EditError {
214    match v {
215        FieldViolation::InvalidName => EditError::InvalidFieldName(name.to_string()),
216        FieldViolation::TooDeep => EditError::ValueTooDeep {
217            max: crate::document::limits::MAX_YAML_DEPTH,
218        },
219    }
220}
221
222/// Validate a user field at the mutator boundary, mapping a violation to the
223/// mutator error surface.
224fn check_field(name: &str, value: &serde_json::Value) -> Result<(), EditError> {
225    validate_field(name, value).map_err(|v| edit_error_from_violation(name, v))
226}
227
228/// Depth-bound an out-of-band meta map (`$ext` / `$seed`). Both ride the same
229/// recursive emit/DTO paths, so they carry the same §8 depth bound.
230fn check_meta_depth(map: &serde_json::Map<String, serde_json::Value>) -> Result<(), EditError> {
231    crate::value::depth_check_meta_map(map.clone(), |max| EditError::ValueTooDeep { max })?;
232    Ok(())
233}
234
235/// Validate a user field at the payload boundary: name conformance and
236/// value-depth bound. See [`FieldViolation`] for the invariant.
237pub fn validate_field(key: &str, value: &serde_json::Value) -> Result<(), FieldViolation> {
238    if !is_valid_field_name(key) {
239        return Err(FieldViolation::InvalidName);
240    }
241    if crate::value::json_depth_exceeds(value, crate::document::limits::MAX_YAML_DEPTH) {
242        return Err(FieldViolation::TooDeep);
243    }
244    Ok(())
245}
246
247/// Map a strict-write [`CoercionError`] to the field-write [`EditError`] surface.
248///
249/// A failed richtext coercion routes to the dedicated `FieldRichtext*` variants
250/// — the same surface [`Card::apply_field_richtext_change`] produces, and the
251/// one the wasm/Python error mappers (and their tests) key on. This keys on the
252/// coercion `target`, not the top-level field type, because the richtext
253/// constraint can be **nested**: an `array` of `richtext(inline)` items fails
254/// with `target == "richtext(inline)"` while the field's own type is `Array`.
255/// The richtext coercion emits exactly `"richtext"` / `"richtext(inline)"`
256/// (see `QuillConfig::conform_value`); every other target uses the general
257/// [`EditError::FieldConform`].
258fn conform_error_to_edit(name: &str, err: CoercionError) -> EditError {
259    let CoercionError::Uncoercible { target, reason, .. } = err;
260    match target.as_str() {
261        "richtext(inline)" => EditError::FieldRichtextNotInline(name.to_string()),
262        "richtext" => EditError::FieldRichtextDecode {
263            field: name.to_string(),
264            message: reason,
265        },
266        _ => EditError::FieldConform {
267            field: name.to_string(),
268            message: reason,
269        },
270    }
271}
272
273/// Compute the canonical stored form of a typed field write **without applying
274/// it** — the dry-run shared by [`Card::commit_field`] and the batched,
275/// all-or-nothing [`TypedWriter::set_all`](crate::TypedWriter::set_all).
276///
277/// Strict `Leniency::Write` conform against `schema`; the name and stored-value
278/// depth are validated too, so a batch can collect every violation before any
279/// mutation. The unknown-name case never reaches here — the editor rejects it
280/// with [`EditError::UnknownField`] before there is a schema to conform against.
281pub(crate) fn resolve_field_write(
282    name: &str,
283    value: QuillValue,
284    schema: &FieldSchema,
285) -> Result<QuillValue, EditError> {
286    if !is_valid_field_name(name) {
287        return Err(EditError::InvalidFieldName(name.to_string()));
288    }
289    let stored = QuillConfig::conform_value(&value, schema, name, Leniency::Write)
290        .map_err(|e| conform_error_to_edit(name, e))?;
291    // Depth-bound the stored form (name already validated above).
292    check_field(name, stored.as_json())?;
293    Ok(stored)
294}
295
296impl Document {
297    pub fn set_quill_ref(&mut self, reference: QuillReference) {
298        self.main_mut().payload_mut().set_quill(reference);
299    }
300
301    pub fn card_mut(&mut self, index: usize) -> Option<&mut Card> {
302        self.cards_mut().get_mut(index)
303    }
304
305    /// Append a composable card. Its `$kind` must be a valid, non-reserved
306    /// composable kind ([`EditError::InvalidKindName`] /
307    /// [`EditError::ReservedKind`] otherwise) — the invariant for any card in
308    /// the cards list, enforced here so every entry path shares it.
309    pub fn push_card(&mut self, card: Card) -> Result<(), EditError> {
310        Self::check_composable_kind(&card)?;
311        self.cards_vec_mut().push(card);
312        Ok(())
313    }
314
315    /// Insert a composable card at `index` (`index > len` →
316    /// [`EditError::IndexOutOfRange`]; invalid `$kind` →
317    /// [`EditError::InvalidKindName`] / [`EditError::ReservedKind`]).
318    pub fn insert_card(&mut self, index: usize, card: Card) -> Result<(), EditError> {
319        let len = self.cards().len();
320        if index > len {
321            return Err(EditError::IndexOutOfRange { index, len });
322        }
323        Self::check_composable_kind(&card)?;
324        self.cards_vec_mut().insert(index, card);
325        Ok(())
326    }
327
328    /// Validate that `card`'s `$kind` is a valid, non-reserved composable kind.
329    /// A card with no `$kind` is rejected as an invalid (empty) name.
330    fn check_composable_kind(card: &Card) -> Result<(), EditError> {
331        let kind = card.kind().unwrap_or("");
332        validate_composable_kind(kind).map_err(|e| match e {
333            CardKindError::InvalidName => EditError::InvalidKindName(kind.to_string()),
334            CardKindError::Reserved => EditError::ReservedKind,
335        })
336    }
337
338    pub fn remove_card(&mut self, index: usize) -> Option<Card> {
339        if index >= self.cards().len() {
340            return None;
341        }
342        Some(self.cards_vec_mut().remove(index))
343    }
344
345    /// Replace the `$kind` of the composable card at `index`.
346    ///
347    /// Only the `$kind` metadata changes; the payload and body are untouched
348    /// (field-bag semantics). Old-schema fields linger in the bag; new-schema
349    /// fields are absent until set explicitly. Schema migration is the caller's
350    /// responsibility — this is a structural primitive.
351    ///
352    /// Returns [`EditError::IndexOutOfRange`], [`EditError::InvalidKindName`],
353    /// or [`EditError::ReservedKind`] on constraint violations.
354    pub fn set_card_kind(
355        &mut self,
356        index: usize,
357        new_kind: impl Into<String>,
358    ) -> Result<(), EditError> {
359        let new_kind = new_kind.into();
360        validate_composable_kind(&new_kind).map_err(|e| match e {
361            CardKindError::InvalidName => EditError::InvalidKindName(new_kind.clone()),
362            CardKindError::Reserved => EditError::ReservedKind,
363        })?;
364        let len = self.cards().len();
365        let card = self
366            .card_mut(index)
367            .ok_or(EditError::IndexOutOfRange { index, len })?;
368        card.payload_mut().set_kind(new_kind);
369        Ok(())
370    }
371
372    /// Move card at `from` to position `to`. No-op when `from == to`.
373    /// Either index out of range → [`EditError::IndexOutOfRange`].
374    pub fn move_card(&mut self, from: usize, to: usize) -> Result<(), EditError> {
375        let len = self.cards().len();
376        if from >= len {
377            return Err(EditError::IndexOutOfRange { index: from, len });
378        }
379        if to >= len {
380            return Err(EditError::IndexOutOfRange { index: to, len });
381        }
382        if from == to {
383            return Ok(());
384        }
385        let card = self.cards_vec_mut().remove(from);
386        self.cards_vec_mut().insert(to, card);
387        Ok(())
388    }
389}
390
391impl Card {
392    /// Create a composable card with the given kind, no fields, and an empty body.
393    pub fn new(kind: impl Into<String>) -> Result<Self, EditError> {
394        let kind = kind.into();
395        validate_composable_kind(&kind).map_err(|e| match e {
396            CardKindError::InvalidName => EditError::InvalidKindName(kind.clone()),
397            CardKindError::Reserved => EditError::ReservedKind,
398        })?;
399        let mut payload = Payload::new();
400        payload.set_kind(kind);
401        Ok(Card::from_parts(
402            payload,
403            quillmark_content::Content::empty(),
404        ))
405    }
406
407    /// Store a payload field verbatim, clearing any `!must_fill` marker on that
408    /// key — the opaque store (**store** = verbatim, coercion deferred to render;
409    /// contrast the typed [`TypedWriter::set`](crate::TypedWriter::set)). Scalars
410    /// convert in place (`store_field("qty", 3)`); see the `From` impls on
411    /// [`QuillValue`].
412    ///
413    /// Returns [`EditError::InvalidFieldName`] when `name` does not match
414    /// `[A-Za-z_][A-Za-z0-9_]*`.
415    pub fn store_field(&mut self, name: &str, value: impl Into<QuillValue>) -> Result<(), EditError> {
416        self.payload_mut()
417            .insert(name.to_string(), value.into())
418            .map_err(|v| edit_error_from_violation(name, v))?;
419        Ok(())
420    }
421
422    /// Store a payload field verbatim and mark it as a `!must_fill` placeholder.
423    /// `Null` emits as `key: !must_fill`; scalars/sequences as `key: !must_fill <value>`.
424    /// The opaque store's fill variant (quill-free, verbatim); same validation as
425    /// [`Card::store_field`].
426    pub fn store_fill(&mut self, name: &str, value: impl Into<QuillValue>) -> Result<(), EditError> {
427        self.payload_mut()
428            .insert_fill(name.to_string(), value.into())
429            .map_err(|v| edit_error_from_violation(name, v))?;
430        Ok(())
431    }
432
433    /// Store several payload fields verbatim and atomically, clearing any
434    /// `!must_fill` marker on each key — the opaque store's batch (contrast the
435    /// typed [`TypedWriter::set_all`](crate::TypedWriter::set_all)). The whole
436    /// batch is validated first — on any violation nothing is applied and every
437    /// offending field is reported as a `(name, error)` pair, so a caller feeding
438    /// externally-sourced names (database columns, form keys) sees all violations
439    /// in one pass instead of fix-rerun-repeat. Per-field rules are those of
440    /// [`Card::store_field`]; insertion order follows the iterator, and a
441    /// repeated name behaves like repeated `store_field` calls (last value
442    /// wins, first position kept).
443    pub fn store_fields<K, V, I>(&mut self, fields: I) -> Result<(), Vec<(String, EditError)>>
444    where
445        K: Into<String>,
446        V: Into<QuillValue>,
447        I: IntoIterator<Item = (K, V)>,
448    {
449        let fields: Vec<(String, QuillValue)> = fields
450            .into_iter()
451            .map(|(k, v)| (k.into(), v.into()))
452            .collect();
453        let errors: Vec<(String, EditError)> = fields
454            .iter()
455            .filter_map(|(name, value)| {
456                check_field(name, value.as_json())
457                    .err()
458                    .map(|e| (name.clone(), e))
459            })
460            .collect();
461        if !errors.is_empty() {
462            return Err(errors);
463        }
464        // Batch validated above; apply through the unchecked insert so the
465        // whole-batch check is not re-run per field.
466        for (name, value) in fields {
467            self.payload_mut().insert_unchecked(name, value);
468        }
469        Ok(())
470    }
471
472    /// Remove a payload field; returns `Ok(None)` if the name is absent.
473    /// Removal has no lane — the one verb serves every write path. Same
474    /// validation as [`Card::store_field`].
475    pub fn remove_field(&mut self, name: &str) -> Result<Option<QuillValue>, EditError> {
476        if !is_valid_field_name(name) {
477            return Err(EditError::InvalidFieldName(name.to_string()));
478        }
479        Ok(self.payload_mut().remove(name))
480    }
481
482    /// Replace the card's opaque `$ext` map wholesale, inserting it at the
483    /// canonical position (after `$quill`/`$kind`/`$id`, before user fields)
484    /// when none existed. Passing an empty map records an explicit `$ext: {}`.
485    ///
486    /// `$ext` carries out-of-band consumer state (editor renames, agent
487    /// annotations, …) and is stripped from [`Document::to_plate_json`], so a
488    /// write here can never affect a render. Any nested comments attached to a
489    /// replaced `$ext` are dropped.
490    /// Returns [`EditError::ValueTooDeep`] when the map nests past the §8
491    /// depth limit — `$ext` never reaches the plate JSON, but it does flow
492    /// through the recursive emit and DTO paths, so it carries the same
493    /// depth bound as user fields.
494    ///
495    /// Quill-free and never coerced — an opaque `store_*` verb by the vocabulary
496    /// rule, not a typed `set`.
497    pub fn store_ext(
498        &mut self,
499        value: serde_json::Map<String, serde_json::Value>,
500    ) -> Result<(), EditError> {
501        check_meta_depth(&value)?;
502        self.payload_mut().set_ext(value);
503        Ok(())
504    }
505
506    /// Remove the card's `$ext` map *entirely*, returning the previous map if
507    /// present. This is a blunt escape hatch — it discards every namespace
508    /// (`$ext.editor`, `$ext.agent`, …) at once. To clear consumer
509    /// state, prefer [`Card::remove_ext_namespace`], which drops only your
510    /// own slot and leaves sibling consumers' state intact.
511    pub fn remove_ext(&mut self) -> Option<serde_json::Map<String, serde_json::Value>> {
512        self.payload_mut().take_ext()
513    }
514
515    /// Merge `value` into the card's `$ext` map under `namespace`, creating
516    /// the map when absent and replacing any existing value at that key.
517    ///
518    /// This is the recommended way to write `$ext`: it preserves sibling
519    /// namespaces, so independent consumers keying on their own slot
520    /// (`$ext.editor`, `$ext.agent`, …) don't clobber each other.
521    /// Returns [`EditError::ValueTooDeep`] when the merged map nests past
522    /// the §8 depth limit (see [`Card::store_ext`]); the card's `$ext` is
523    /// unchanged on error. Quill-free and never coerced — an opaque `store_*`
524    /// verb.
525    pub fn store_ext_namespace(
526        &mut self,
527        namespace: impl Into<String>,
528        value: serde_json::Value,
529    ) -> Result<(), EditError> {
530        let mut map = self.payload_mut().ext().cloned().unwrap_or_default();
531        map.insert(namespace.into(), value);
532        check_meta_depth(&map)?;
533        self.payload_mut().take_ext();
534        self.payload_mut().set_ext(map);
535        Ok(())
536    }
537
538    /// Remove `namespace` from the card's `$ext` map, returning the value
539    /// that was stored there (or `None` when the map or the key was absent).
540    ///
541    /// This is the recommended way to clear `$ext` state: it is the
542    /// namespace-scoped inverse of [`Card::store_ext_namespace`] and preserves
543    /// sibling namespaces, where [`Card::remove_ext`] would wipe them all.
544    /// When removing the last namespace empties the map, the `$ext` entry is
545    /// dropped entirely (not left as `$ext: {}`), so
546    /// `store_ext_namespace(ns, v)` followed by `remove_ext_namespace(ns)`
547    /// restores a card that had no `$ext` to its original state.
548    pub fn remove_ext_namespace(&mut self, namespace: &str) -> Option<serde_json::Value> {
549        let mut map = self.payload_mut().take_ext()?;
550        let removed = map.remove(namespace);
551        if !map.is_empty() {
552            self.payload_mut().set_ext(map);
553        }
554        removed
555    }
556
557    /// The raw `$seed` map (keyed by card-kind), or `None`. For a parsed,
558    /// per-kind overlay, index this map by kind and pass the entry to
559    /// [`crate::SeedOverlay::from_json`]. Only the main card carries `$seed`.
560    pub fn seed(&self) -> Option<&serde_json::Map<String, serde_json::Value>> {
561        self.payload().seed()
562    }
563
564    /// Merge a card-kind's seed overlay `value` into the card's `$seed` map
565    /// under `card_kind`, creating the map when absent and replacing any
566    /// existing overlay for that kind. Sibling kinds are preserved — this is
567    /// the per-kind-safe writer, the seed analogue of
568    /// [`Card::store_ext_namespace`]. `card_kind` must be a valid, non-reserved
569    /// composable kind ([`EditError::InvalidKindName`] / [`EditError::ReservedKind`]
570    /// otherwise) — `$seed` is keyed by composable card-kind, unlike the
571    /// free-form namespaces of `$ext`. Returns [`EditError::ValueTooDeep`] when
572    /// the merged map nests past the §8 depth limit; the card is unchanged on
573    /// error. Quill-free and never coerced — an opaque `store_*` verb.
574    pub fn store_seed_namespace(
575        &mut self,
576        card_kind: impl Into<String>,
577        value: serde_json::Value,
578    ) -> Result<(), EditError> {
579        let card_kind = card_kind.into();
580        validate_composable_kind(&card_kind).map_err(|e| match e {
581            CardKindError::InvalidName => EditError::InvalidKindName(card_kind.clone()),
582            CardKindError::Reserved => EditError::ReservedKind,
583        })?;
584        let mut map = self.payload_mut().seed().cloned().unwrap_or_default();
585        map.insert(card_kind, value);
586        check_meta_depth(&map)?;
587        self.payload_mut().take_seed();
588        self.payload_mut().set_seed(map);
589        Ok(())
590    }
591
592    /// Remove `card_kind` from the card's `$seed` map, returning the overlay
593    /// stored there (or `None`). When removing the last kind empties the map,
594    /// the `$seed` entry is dropped entirely (not left as `$seed: {}`).
595    /// The seed analogue of [`Card::remove_ext_namespace`].
596    pub fn remove_seed_namespace(&mut self, card_kind: &str) -> Option<serde_json::Value> {
597        let mut map = self.payload_mut().take_seed()?;
598        let removed = map.remove(card_kind);
599        if !map.is_empty() {
600            self.payload_mut().set_seed(map);
601        }
602        removed
603    }
604
605    /// Install the body content directly from a pre-built [`Content`] — **value
606    /// semantics**, the native richtext writer. A content is valid by
607    /// construction, so this is infallible: no markdown import, no diff, no
608    /// schema check; the identity anchors of the previous body are *gone*
609    /// (install-this-exact-value, so a `to_markdown → install` round-trip cannot
610    /// resurrect them). Use it when the caller already holds a content (a decoded
611    /// canonical-JSON body, another field's value, an editor's serialized state).
612    /// For "here's new authored markdown," use [`revise_body`](Self::revise_body),
613    /// which rebases surviving anchors; the cold-import path is spelled at the
614    /// call site as `install_body(import_body(md)?)`.
615    pub fn install_body(&mut self, content: Content) {
616        self.overwrite_body(content);
617    }
618
619    /// Install a richtext field's content directly from a pre-built [`Content`]
620    /// — the field-level twin of [`install_body`](Self::install_body). Value
621    /// semantics: stores the canonical content JSON verbatim (identity marks and
622    /// content-only marks such as `underline` intact), no diff, no schema check
623    /// (schema-blind, like [`apply_field_richtext_change`](Self::apply_field_richtext_change)
624    /// — [`commit_field`](Self::commit_field) is the typed door). Returns
625    /// [`EditError::InvalidFieldName`] for a malformed name.
626    pub fn install_field(&mut self, name: &str, content: Content) -> Result<(), EditError> {
627        if !is_valid_field_name(name) {
628            return Err(EditError::InvalidFieldName(name.to_string()));
629        }
630        self.store_field_content(name, &content);
631        Ok(())
632    }
633
634    /// Store `content` as the canonical content-JSON value of field `name` — the
635    /// one place a richtext field's content is committed to the payload, shared by
636    /// [`install_field`](Self::install_field), [`revise_field`](Self::revise_field),
637    /// and [`apply_field_richtext_change`](Self::apply_field_richtext_change).
638    /// Assumes `name` is already validated (all three callers check it or resolve
639    /// an existing field first).
640    fn store_field_content(&mut self, name: &str, content: &Content) {
641        let canonical = quillmark_content::serial::to_canonical_value(content);
642        self.payload_mut()
643            .insert_unchecked(name.to_string(), QuillValue::from_json(canonical));
644    }
645
646    /// Write-time commit: validate and normalize `value` per the field's schema
647    /// `type` and store the canonical form. The typed sibling of the opaque
648    /// [`store_field`](Self::store_field) — the one write verb for *every* field
649    /// type (richtext today, any future content model tomorrow), dispatching on
650    /// the [`FieldSchema`] rather than growing a per-type method.
651    ///
652    /// The two write disciplines: [`store_field`](Self::store_field) stores the
653    /// value opaquely and defers coercion to render (keystroke-level state,
654    /// data-in-flight); `commit_field` canonicalizes now and fails now (an
655    /// editor blur/save, an agent write). Neither is forced on the other.
656    ///
657    /// Behavior by `type`:
658    /// - **richtext** — imports a markdown string / adopts a content object and
659    ///   stores canonical content JSON, so identity marks (anchors, island ids)
660    ///   live on the stored value from the write; a `richtext(inline)` schema
661    ///   rejects a multi-block value with [`EditError::FieldRichtextNotInline`].
662    /// - **scalars** (`string`/`integer`/`number`/`boolean`/`datetime`) — stores
663    ///   the coerced canonical (`"3"` → `3`), applying only value-parsing
664    ///   normalizations; a cross-type value that the render floor would coerce
665    ///   (e.g. `1` → `true`) or a shape mismatch fails here instead.
666    /// - **array** / **object** — coerces each element/property against the
667    ///   element/property schema.
668    /// - **null** — passes through unchanged (the null ≡ absent rule); nothing
669    ///   is coerced (a richtext `null` reads back as the empty content via
670    ///   [`field_richtext`](Self::field_richtext)).
671    ///
672    /// The caller supplies the `schema` because a [`Document`] holds only a
673    /// `$quill` *reference*, not the resolved schema; an editor holds it (see
674    /// [`crate::TypedWriter`], which resolves the schema per field and calls
675    /// this).
676    ///
677    /// Returns [`EditError::InvalidFieldName`] for a malformed name,
678    /// [`EditError::FieldRichtextDecode`] / [`EditError::FieldRichtextNotInline`]
679    /// for a richtext field, [`EditError::FieldConform`] for any other type
680    /// mismatch, and [`EditError::ValueTooDeep`] when the stored value nests
681    /// past the §8 depth limit.
682    pub fn commit_field(
683        &mut self,
684        name: &str,
685        value: impl Into<QuillValue>,
686        schema: &FieldSchema,
687    ) -> Result<(), EditError> {
688        let stored = resolve_field_write(name, value.into(), schema)?;
689        // `resolve_field_write` already validated name + stored-value depth.
690        self.payload_mut().insert_unchecked(name.to_string(), stored);
691        Ok(())
692    }
693
694    /// Revise the body from an authored markdown string — **edit semantics**,
695    /// the whole-document (stale-text / LLM / MCP) writer, and the receipt-
696    /// returning default write path. Imports the markdown, diffs it against the
697    /// current body, and rebases surviving identity anchors onto the new text
698    /// (cold import + [`diff_import`]), then returns the text [`Delta`] from the
699    /// old body to the new one — the change an editor bridge maps its own
700    /// positions through across a whole-document replace ([`Delta::map_pos`]).
701    /// Surviving identity anchors rebase; formatting marks are re-derived by the
702    /// fresh import. A pathologically over-nested input (`> MAX_NESTING_DEPTH`)
703    /// returns [`EditError::Import`] rather than silently degrading to the
704    /// empty content. Discard the receipt with `let _ = card.revise_body(md)?;`
705    /// when caret stability is not needed.
706    pub fn revise_body(&mut self, body: impl Into<String>) -> Result<Delta, EditError> {
707        let (content, delta) =
708            diff_import(self.body(), &body.into()).map_err(EditError::Import)?;
709        self.overwrite_body(content);
710        Ok(delta)
711    }
712
713    /// Decode the field's current content (an absent field imports from empty),
714    /// diff `body` against it so surviving anchors rebase, and return the new
715    /// content with its text [`Delta`] — the shared preamble of
716    /// [`revise_field`](Self::revise_field) and
717    /// [`revise_field_checked`](Self::revise_field_checked). Neither stores; the
718    /// caller lands the diffed content (raw, or schema-checked).
719    fn diff_field(
720        &self,
721        name: &str,
722        body: impl Into<String>,
723    ) -> Result<(Content, Delta), EditError> {
724        if !is_valid_field_name(name) {
725            return Err(EditError::InvalidFieldName(name.to_string()));
726        }
727        let base = match self.field_richtext(name) {
728            Some(Ok(rt)) => rt,
729            Some(Err(e)) => {
730                return Err(EditError::FieldRichtextDecode {
731                    field: name.to_string(),
732                    message: e.into_message(),
733                })
734            }
735            None => Content::empty(),
736        };
737        diff_import(&base, &body.into()).map_err(EditError::Import)
738    }
739
740    /// Revise a richtext field from an authored markdown string — the
741    /// field-level twin of [`revise_body`](Self::revise_body), and the
742    /// field-level `diff_import` the write surface previously lacked (the only
743    /// field-content writers were the cold [`commit_field`](Self::commit_field)
744    /// and the splice [`apply_field_richtext_change`](Self::apply_field_richtext_change),
745    /// so an LLM rewriting a richtext field's markdown had no anchor-preserving
746    /// path). Decodes the field's current content as the diff base (an **absent**
747    /// field cold-imports from empty), rebases surviving anchors onto the new
748    /// text, re-stores the canonical content, and returns the text [`Delta`].
749    ///
750    /// Schema-blind by design — the content-writer stratum splices without the
751    /// quill (like [`apply_field_richtext_change`](Self::apply_field_richtext_change));
752    /// [`commit_field`](Self::commit_field) is the typed door that enforces
753    /// `richtext(inline)`, and a violation otherwise surfaces at validate/render.
754    ///
755    /// Returns [`EditError::InvalidFieldName`] for a malformed name,
756    /// [`EditError::FieldRichtextDecode`] when the field is present but is not a
757    /// richtext content (a scalar a `store_field` wrote), and
758    /// [`EditError::Import`] on an over-nested markdown input.
759    pub fn revise_field(&mut self, name: &str, body: impl Into<String>) -> Result<Delta, EditError> {
760        let (content, delta) = self.diff_field(name, body)?;
761        self.store_field_content(name, &content);
762        Ok(delta)
763    }
764
765    /// Revise a richtext field from markdown **with schema enforcement** — the
766    /// typed *and* anchor-preserving field write that neither
767    /// [`revise_field`](Self::revise_field) nor [`commit_field`](Self::commit_field)
768    /// provides alone. [`revise_field`](Self::revise_field) rebases anchors but is
769    /// schema-blind; [`commit_field`](Self::commit_field) enforces the schema but
770    /// cold-imports (the previous value's anchors are gone). This does both: diff
771    /// the markdown against the field's current content so surviving anchors rebase
772    /// (as [`revise_field`](Self::revise_field)), then enforce `schema` on the
773    /// *diffed result* through the same typed-conform path
774    /// [`commit_field`](Self::commit_field) runs — so a `richtext(inline)` schema
775    /// rejects a multi-block result with [`EditError::FieldRichtextNotInline`],
776    /// the error surface unchanged, while the anchors survive. Returns the text
777    /// [`Delta`] receipt.
778    ///
779    /// The primitive that [`TypedWriter::revise_field`](crate::TypedWriter::revise_field)
780    /// and [`CardWriter::revise_field`](crate::CardWriter::revise_field) wrap: they
781    /// resolve `schema` from the bound quill and call here. The schema runs on the
782    /// content the diff produced, so a non-richtext `schema` (nothing to preserve)
783    /// fails with the same [`EditError::FieldConform`]
784    /// [`commit_field`](Self::commit_field) would raise.
785    ///
786    /// Errors: [`EditError::InvalidFieldName`], [`EditError::FieldRichtextDecode`]
787    /// when the field is present but not a richtext content, [`EditError::Import`]
788    /// on an over-nested markdown input, and the conform errors of
789    /// [`commit_field`](Self::commit_field) on the diffed result. On any error the
790    /// field is unchanged.
791    pub fn revise_field_checked(
792        &mut self,
793        name: &str,
794        body: impl Into<String>,
795        schema: &FieldSchema,
796    ) -> Result<Delta, EditError> {
797        let (content, delta) = self.diff_field(name, body)?;
798        // Enforce `schema` on the diffed (anchor-rebased) content through the same
799        // typed path `commit_field` uses: re-canonicalizing a content object keeps
800        // its identity marks (`decode_richtext_value`), so the inline check fires
801        // on the value anchors survived onto and the error surface is identical.
802        let canonical = quillmark_content::serial::to_canonical_value(&content);
803        let stored = resolve_field_write(name, QuillValue::from_json(canonical), schema)?;
804        self.payload_mut().insert_unchecked(name.to_string(), stored);
805        Ok(delta)
806    }
807
808    /// Apply a committed field-change bundle to the body content — the native
809    /// form-editor writer. Order is text delta → line ops → mark ops, then one
810    /// terminal normalization ([`Content::apply_field_change`]); mark ranges are
811    /// in final-text coordinates. Returns
812    /// [`EditError::ContentApply`] when an op is out of bounds; the apply is
813    /// all-or-nothing ([`Content::apply_field_change`]), so the body is
814    /// unchanged on error — apply the bundle against the body the delta was
815    /// computed from.
816    pub fn apply_body_change(
817        &mut self,
818        text_delta: &Delta,
819        line_ops: &[LineOp],
820        mark_ops: &[MarkOp],
821    ) -> Result<(), EditError> {
822        self.body_mut()
823            .apply_field_change(text_delta, line_ops, mark_ops)
824            .map_err(EditError::ContentApply)
825    }
826
827    /// Splice a content field-change bundle into a **richtext-valued field**'s
828    /// stored content — the field-path twin of [`apply_body_change`](Self::apply_body_change),
829    /// and what lets identity marks (anchors, island ids) persist on field
830    /// content across incremental edits. Decodes the field's canonical content,
831    /// applies the text delta plus any line/mark ops in the same all-or-nothing
832    /// bundle, and re-stores the canonical result.
833    ///
834    /// Returns [`EditError::FieldRichtextDecode`] when the field is absent or its
835    /// stored value is not a richtext content (the caller addresses a field it
836    /// knows is richtext, exactly as when writing it), and
837    /// [`EditError::ContentApply`] when the bundle applies out of bounds.
838    pub fn apply_field_richtext_change(
839        &mut self,
840        name: &str,
841        text_delta: &Delta,
842        line_ops: &[LineOp],
843        mark_ops: &[MarkOp],
844    ) -> Result<(), EditError> {
845        let mut content = match self.field_richtext(name) {
846            Some(Ok(rt)) => rt,
847            Some(Err(e)) => {
848                return Err(EditError::FieldRichtextDecode {
849                    field: name.to_string(),
850                    message: e.into_message(),
851                })
852            }
853            None => {
854                return Err(EditError::FieldRichtextDecode {
855                    field: name.to_string(),
856                    message: "field is absent".to_string(),
857                })
858            }
859        };
860        content
861            .apply_field_change(text_delta, line_ops, mark_ops)
862            .map_err(EditError::ContentApply)?;
863        self.store_field_content(name, &content);
864        Ok(())
865    }
866}
867
868#[cfg(test)]
869mod tests {
870    use super::*;
871    use crate::path::DocPath;
872
873    #[test]
874    fn field_error_anchors_under_the_card_base() {
875        // A main field write: the `main` base roots the field path.
876        let main = DocPath::main();
877        assert_eq!(
878            EditError::FieldConform {
879                field: "font_size".into(),
880                message: "x".into(),
881            }
882            .doc_path(&main)
883            .unwrap()
884            .to_string(),
885            "main.font_size"
886        );
887        // A card field write: the card root qualifies the field.
888        let card = DocPath::card(Some("indorsement"), 1);
889        assert_eq!(
890            EditError::UnknownField("signature_block".into())
891                .doc_path(&card)
892                .unwrap()
893                .to_string(),
894            "cards.indorsement[1].signature_block"
895        );
896    }
897
898    #[test]
899    fn index_out_of_range_anchors_at_the_array_slot() {
900        // Structural op: names a slot, base-independent.
901        for base in [DocPath::main(), DocPath::card(Some("note"), 0)] {
902            assert_eq!(
903                EditError::IndexOutOfRange { index: 4, len: 2 }
904                    .doc_path(&base)
905                    .unwrap()
906                    .to_string(),
907                "cards[4]"
908            );
909        }
910    }
911
912    #[test]
913    fn kind_and_depth_errors_anchor_at_base_or_nowhere() {
914        // A kind error on a structural op carries the slot base it was given.
915        assert_eq!(
916            EditError::ReservedKind
917                .doc_path(&DocPath::card(None, 2))
918                .unwrap()
919                .to_string(),
920            "cards[2]"
921        );
922        // A config-space `$seed` depth error keeps an empty base — no anchor.
923        assert_eq!(
924            EditError::ValueTooDeep { max: 8 }.doc_path(&DocPath::new()),
925            None
926        );
927        // A main-card depth error roots at `main` (its base names the card).
928        assert_eq!(
929            EditError::ValueTooDeep { max: 8 }
930                .doc_path(&DocPath::main())
931                .unwrap()
932                .to_string(),
933            "main"
934        );
935    }
936}