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