provui-core 0.5.1

A frontend-neutral UI composition core over prov: a prov-aware structural metadata editor (flower over prov), a document session composing flower metadata and leaf body over one prov document, the prov-config → flower-schema adapters, and the frontmatter classification and link resolution a prov-aware editor navigates by.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
//! provui-core — a frontend-neutral UI composition core over
//! [`prov`](https://docs.rs/prov).
//!
//! prov describes a plaintext workspace; [`flower`](https://docs.rs/flower-core)
//! edits structured metadata; [`leaf`](https://docs.rs/leaf-core) edits prose.
//! This crate is the composition of the three, with no opinion about what draws
//! it — the same core is meant to sit under a TUI, a SwiftUI app behind UniFFI,
//! or a test harness:
//!
//! - [`ProvBackend`] — a [`flower_core::Backend`] that edits a prov document's
//!   embedded metadata through prov's carrier-aware
//!   [`prov::edit::MetaEditor`]. Lossless: comments, key order, the
//!   carrier/format, and the prose body are all preserved. Unlike
//!   [`flower_core::FigBackend`] (a standalone config file, schema-free), a
//!   `ProvBackend` can carry the workspace **schema** — the controlled
//!   vocabularies and relations resolved from the prov config — so a frontend
//!   renders term pickers, spanning-link widgets, and type-directed edits.
//! - [`DocumentSession`] — one open prov document edited through a flower metadata
//!   model *and* a leaf body editor, reconciled on save.
//! - [`schema_from_config`] — the adapter turning a resolved prov
//!   [`WorkspaceConfig`](prov::config::WorkspaceConfig) (+ its vocabularies) into a
//!   generic [`flower_core::Schema`] for the workspace's **content** documents.
//!   This is where prov's controlled vocabularies and spanning relation reach the
//!   UI. [`schema_for_document`] is the same adapter for one document: a field
//!   prov declares `under:` an index governs only the documents below it, so
//!   which declaration a document is edited under is a fact about where it sits.
//! - [`config_schema()`] — the same trick turned on the config document itself, so
//!   the metadata editor a frontend already ships can edit a workspace's policy
//!   instead of a hand-written settings form.
//! - [`facets`] — what each frontmatter key *is* to prov: a relation, a pointer
//!   at machinery, identity, policy, a declared field, or a value prov only
//!   carries. Read off the workspace's own vocabulary rather than a list this
//!   crate keeps.
//! - [`links`] — the links a document's *frontmatter* declares, each with the
//!   metadata **path** it sits at, so "is the row under the cursor a link?" is a
//!   question with an answer. Lexical: no filesystem, no registry.
//! - [`mod@body_links`] — the same question of the *prose*, answered with a byte
//!   range into the body instead of a metadata path. Both kinds carry a
//!   [`prov::Link`] and a [`TargetKind`], and [`AnyLink`] is what lets one
//!   resolver answer for both — so following a link from the body caret and
//!   following one from the metadata cursor are the same code.
//! - [`findings`] — what prov's integrity check says about one document,
//!   placed: a broken link becomes a metadata path or a byte range in the body,
//!   which is a place an editor can draw. prov reports a relation's *name*; this
//!   recovers the list index where the document's own links make that
//!   unambiguous, and says so where they do not.
//!   [`DocumentSession::apply_findings`] then hands each half to the editor that
//!   owns it — leaf highlights under the prose, flower
//!   [`Annotation`](flower_core::Annotation)s on the rows — so both widgets draw
//!   them without the host drawing anything.
//! - [`workspace`] — [`WorkspaceView`], which finds the workspace a document
//!   belongs to and resolves a link to a document you can open. The one piece
//!   that reads the filesystem, and read-only. It also runs that backwards:
//!   [`WorkspaceView::reference_to`] and [`reference_here`] give the link text
//!   to *write* to a document — or to a place inside one — in the workspace's
//!   own reference style. Still a read; nothing is written and nothing is
//!   registered.
//!
//! ## What this crate will not do for you
//!
//! It classifies, and it never arranges. Nothing here hides a row, sinks one,
//! reorders them, or makes one read-only — even where it plainly knows enough
//! to: [`Facets`] can tell you `id` is minted and `contents` is structure, and
//! hands you the lists shaped to go straight into flower's `derived` and
//! `demoted` sets, and then stops.
//!
//! That is deliberate. An application over prov usually does separate prov's
//! structure from the values a person typed — diaryx does — but *how* is a
//! product decision, and a mobile inspector, a terminal band and a settings
//! sheet do not want the same one. The classification is general and lives here
//! once; the arrangement is local and lives in the frontend. `provui-tui`'s
//! `nav` module is a worked example of the whole policy, and it is two lines.
//!
//! Scope: the single-document metadata surface (prov's `edit` layer), plus
//! read-only navigation across documents. Relation fields that *maintain inverse
//! links* across documents belong to prov's `mutate` layer — a later,
//! relationship-aware backend, not this one. Following a link reads; retargeting
//! one would write two documents, and this crate's backend edits one.

pub mod body_links;
pub mod config_schema;
pub mod facets;
pub mod findings;
pub mod links;
pub mod rules;
pub mod schema;
mod session;
pub mod workspace;

pub use body_links::{BodyLink, body_link_at, body_links};
pub use config_schema::{CONFIG_READONLY_KEYS, config_schema};
pub use facets::{Facet, Facets};
pub use findings::{Finding, Severity, Site};
pub use links::{AnyLink, MetaLink, TargetKind, link_at, links_in, links_under};
pub use schema::{Vocabularies, schema_for_document, schema_from_config};
pub use session::{DocumentSession, Heading, Region, SessionError, annotations_of};
pub use workspace::{Destination, WorkspaceView, reference_here, reference_without_workspace};

use std::collections::HashMap;

use fig::Value;
use flower_core::schema::FieldRuleExt;
use flower_core::tree::{self, to_fig};
use flower_core::{Backend, BackendError, Choice, EditOp, Schema, Seg};
use prov::edit::MetaEditor;
use prov::{Document, MetaCarrier};

fn be(e: impl std::fmt::Display) -> BackendError {
    BackendError(e.to_string())
}

/// Run one expression against whichever fig editor sits behind a
/// [`MetaEditor`]. The fenced and whole-file editors share every comment
/// method by name and signature without sharing a trait, so a comment op is
/// one body written once and matched into both arms.
macro_rules! with_fig {
    ($editor:expr, |$e:ident| $body:expr) => {
        match $editor {
            MetaEditor::Fenced($e) => $body,
            MetaEditor::Whole($e) => $body,
        }
    };
}

/// A comment read is an answer, not a failure, on a format with no comment
/// syntax: a page over JSON frontmatter has no comments on it, rather than a
/// read error on every row. A write to such a format still refuses.
fn comment_read(read: Result<Option<String>, fig::Error>) -> Result<Option<String>, BackendError> {
    match read {
        Err(fig::Error::UnsupportedFormat) => Ok(None),
        other => other.map_err(be),
    }
}

/// A backend over a single prov document, editing its embedded metadata.
pub struct ProvBackend {
    /// The document path — drives carrier/format detection (extension for a
    /// whole-file config doc, content sniffing for a fenced block).
    path: std::path::PathBuf,
    /// The current full document text (frontmatter + body); the source of truth.
    text: String,
    /// The schema governing this document, when the embedder resolved one from the
    /// workspace config (see [`schema_from_config`]). Returned via
    /// [`Backend::schema`] so the flower model validates values and a frontend can
    /// pick schema-driven widgets. `None` for a bare document with no workspace.
    schema: Option<Schema>,
    /// What a picker on a reference field should offer, per **relation** — the
    /// answer to [`Backend::candidates`], injected because this backend cannot
    /// work it out.
    ///
    /// Empty by default, which is the honest state of a backend over a document
    /// with no workspace behind it: there is nothing to enumerate, and flower
    /// opens a text line instead
    /// ([`Model::begin_choose`](flower_core::Model::begin_choose) falls back).
    /// See [`set_candidates`](Self::set_candidates).
    candidates: HashMap<String, Vec<Choice>>,
}

impl ProvBackend {
    /// Open a prov document from its full `text`, with no schema. Errors if prov
    /// cannot parse it.
    pub fn open(
        path: impl Into<std::path::PathBuf>,
        text: impl Into<String>,
    ) -> Result<Self, BackendError> {
        Self::open_with_schema_opt(path, text, None)
    }

    /// Open a prov document carrying the workspace `schema` — the prov-aware path,
    /// so the flower model validates controlled fields and offers pickers.
    pub fn open_with_schema(
        path: impl Into<std::path::PathBuf>,
        text: impl Into<String>,
        schema: Schema,
    ) -> Result<Self, BackendError> {
        Self::open_with_schema_opt(path, text, Some(schema))
    }

    fn open_with_schema_opt(
        path: impl Into<std::path::PathBuf>,
        text: impl Into<String>,
        schema: Option<Schema>,
    ) -> Result<Self, BackendError> {
        let path = path.into();
        let text = text.into();
        // Fail fast if the document doesn't parse.
        Document::parse(&path, &text).map_err(be)?;
        Ok(Self {
            path,
            text,
            schema,
            candidates: HashMap::new(),
        })
    }

    fn document(&self) -> Result<Document, BackendError> {
        Document::parse(&self.path, &self.text).map_err(be)
    }

    /// An editor over the metadata block as it stands, for a read — `None` when
    /// the document has no block, which is a document with no comments on it.
    /// (`apply` opens with `open_or_init` instead, since an edit to a block-less
    /// document synthesizes one.)
    fn editor(&self) -> Result<Option<MetaEditor>, BackendError> {
        match self.document()?.carrier {
            Some(carrier) => MetaEditor::open(&self.text, carrier).map(Some).map_err(be),
            None => Ok(None),
        }
    }

    /// The prose body outside the metadata block — the region a `leaf` editor
    /// would own. Empty for a whole-file config document.
    pub fn body(&self) -> Result<String, BackendError> {
        Ok(self.document()?.body)
    }

    /// Whether the document has an editable prose body (a fenced carrier). A
    /// whole-file config document has none — its body cannot be replaced.
    pub fn has_body(&self) -> Result<bool, BackendError> {
        Ok(matches!(
            self.document()?.carrier,
            Some(MetaCarrier::Fenced(_))
        ))
    }

    /// Tell the backend what a picker on each **relation**'s field should
    /// offer — the injection [`Backend::candidates`] exists for.
    ///
    /// A reference field's candidates are *other documents*, and this backend is
    /// one document with a path: it can say which relation a path is, from the
    /// schema it is already carrying, and nothing about what else exists. So the
    /// list arrives from whoever has a workspace —
    /// [`WorkspaceView::candidates_map`] builds one, and
    /// [`WorkspaceView::open_document`] hands it over at open.
    ///
    /// ## What it costs, and when it is paid
    ///
    /// Enumerating a workspace's documents is a **walk**. It is paid once, when
    /// the map is built, and never again: this is a lookup by relation name
    /// against an owned map, so the picker opens in constant time however many
    /// times it is opened. A census per open, never per keystroke. The
    /// staleness that buys is the staleness a per-document check already has — a
    /// document created in another window is not on the list until this one is
    /// reopened — and it is the right trade for a key pressed on a keystroke.
    ///
    /// Keyed by relation rather than by path so that `contents`, `contents[4]`
    /// and the append position `contents[len]` are one entry: the schema rule at
    /// each of those names the same relation, and a list of link targets does
    /// not change because the index did.
    ///
    /// Replaces the whole map; an empty one puts the backend back where it
    /// started.
    pub fn set_candidates(&mut self, candidates: HashMap<String, Vec<Choice>>) {
        self.candidates = candidates;
    }

    /// The relation a metadata `path` is a reference for, according to the
    /// schema this backend carries — `None` for a path that is not a reference
    /// field, and for a backend with no schema.
    ///
    /// **A reified vocabulary answers `None` here, and that is the point.** A
    /// key that is both a declared field with a vocabulary and a relation gets
    /// two rules from [`schema_from_config`], the field's first; a schema
    /// resolves first-match-wins, so the rule at that path is the
    /// [`Enum`](flower_core::Constraint::Enum) and flower answers the picker
    /// from the vocabulary's own terms without asking a backend at all. Reading
    /// the same rule here is what keeps the two from disagreeing — there is no
    /// second precedence rule written down anywhere.
    pub fn relation_at(&self, path: &[Seg]) -> Option<&str> {
        self.schema.as_ref()?.rule_for(path)?.reference()
    }

    /// Replace the prose body, leaving the metadata block untouched — the write
    /// path for edits a `leaf` editor makes to [`body`](Self::body).
    ///
    /// Uses fig's `Embed::replace_body` (the same lossless primitive prov edits
    /// through). A frontend that wants fixity/`updated` restamping routes this
    /// through prov's write path instead; here it demonstrates that the metadata
    /// and body regions edit independently over one document.
    pub fn set_body(&mut self, body: &str) -> Result<(), BackendError> {
        match self.document()?.carrier {
            Some(MetaCarrier::Fenced(kind)) => {
                let mut embed = fig::Embed::open(self.text.as_bytes(), kind).map_err(be)?;
                embed.replace_body(body).map_err(be)?;
                self.text = embed.render().map_err(be)?.to_string();
                Ok(())
            }
            _ => Err(BackendError(
                "document has no fenced body to replace".into(),
            )),
        }
    }
}

impl Backend for ProvBackend {
    fn apply(&mut self, op: EditOp) -> Result<(), BackendError> {
        let carrier = self.document()?.carrier;
        // `open_or_init` so an edit to a document with no block synthesizes one
        // (frontmatter for a prose file) rather than failing.
        let mut editor = MetaEditor::open_or_init(&self.text, carrier).map_err(be)?;

        match op {
            EditOp::ReplaceValue { path, value } => {
                let segs = to_fig(&path);
                // Mirror prov's `set_in_text`: an index-terminated path is a pure
                // replacement (there is no "insert at absent index"); a
                // key-terminated path upserts.
                match path.last() {
                    Some(Seg::Index(_)) => editor.replace_value(&segs, value).map_err(be)?,
                    _ => editor.set_value(&segs, value).map_err(be)?,
                }
            }
            EditOp::DeleteKey { path } => editor.delete(&to_fig(&path)).map_err(be)?,
            EditOp::RemoveItem { seq_path, index } => {
                editor.remove_item(&to_fig(&seq_path), index).map_err(be)?
            }
            // prov's MetaEditor has no distinct "insert": `set_value` at the new
            // key path upserts, which is exactly an insert for an absent key.
            EditOp::InsertKey {
                map_path,
                key,
                value,
            } => {
                let mut path = map_path;
                path.push(Seg::Key(key));
                editor.set_value(&to_fig(&path), value).map_err(be)?
            }
            EditOp::AppendItem { seq_path, value } => {
                editor.append_value(&to_fig(&seq_path), value).map_err(be)?
            }
            // No `move_item` on MetaEditor; express the move as a full index
            // permutation through `reorder_items`, sized from the current sequence.
            // The index arithmetic is flower's, so a move here means what a move
            // means through any other backend.
            EditOp::MoveItem { seq_path, from, to } => {
                let len = tree::seq_len(&self.to_value()?, &seq_path)
                    .ok_or_else(|| BackendError("target is not a sequence".into()))?;
                if let Some(order) = flower_core::backend::move_permutation(len, from, to) {
                    editor
                        .reorder_items(&to_fig(&seq_path), &order)
                        .map_err(be)?;
                }
            }
            EditOp::ReorderKeys { map_path, keys } => {
                editor.reorder_keys(&to_fig(&map_path), &keys).map_err(be)?
            }
            EditOp::RenameKey { path, new_key } => {
                editor.replace_key(&to_fig(&path), &new_key).map_err(be)?
            }
            // `MetaEditor` stops at the value ops prov's own mutations need; the
            // comment surface is fig's, reached through whichever editor is
            // behind it. Two fig calls for a leading set, and still atomic: the
            // text is only replaced once every call has succeeded, so a refused
            // add after a delete leaves the document as it was.
            EditOp::SetLeadingComment { path, text } => {
                let path = to_fig(&path);
                with_fig!(&mut editor, |e| {
                    e.delete_leading_comments(&path).map_err(be)?;
                    if let Some(text) = &text {
                        e.add_leading_comment(&path, text).map_err(be)?;
                    }
                })
            }
            EditOp::SetTrailingComment { path, text } => {
                let path = to_fig(&path);
                with_fig!(&mut editor, |e| match &text {
                    Some(text) => e.set_trailing_comment(&path, text).map_err(be)?,
                    None => e.delete_trailing_comment(&path).map_err(be)?,
                })
            }
        }

        self.text = editor.render().map_err(be)?;
        Ok(())
    }

    fn to_value(&self) -> Result<Value, BackendError> {
        // prov's metadata tree → fig's value tree (the serde-free bridge).
        Ok(Value::from(&self.document()?.meta))
    }

    fn source(&self) -> Result<String, BackendError> {
        Ok(self.text.clone())
    }

    fn schema(&self) -> Option<Schema> {
        self.schema.clone()
    }

    fn leading_comment(&self, path: &[Seg]) -> Result<Option<String>, BackendError> {
        let Some(editor) = self.editor()? else {
            return Ok(None);
        };
        let path = to_fig(path);
        comment_read(with_fig!(&editor, |e| e.leading_comment(&path)))
    }

    fn trailing_comment(&self, path: &[Seg]) -> Result<Option<String>, BackendError> {
        let Some(editor) = self.editor()? else {
            return Ok(None);
        };
        let path = to_fig(path);
        comment_read(with_fig!(&editor, |e| e.trailing_comment(&path)))
    }

    /// The documents a picker on this reference field should offer — whatever
    /// [`set_candidates`](Self::set_candidates) was given for the relation the
    /// schema says `path` is.
    ///
    /// `None` for anything that is not a reference field, for a relation the map
    /// has no entry for, and always for a backend outside a workspace. A
    /// controlled vocabulary never reaches here: flower asks its own schema
    /// first — see [`relation_at`](Self::relation_at).
    fn candidates(&self, path: &[Seg]) -> Result<Option<Vec<Choice>>, BackendError> {
        Ok(self
            .relation_at(path)
            .and_then(|relation| self.candidates.get(relation))
            .cloned())
    }

    /// What an item of a relation's list *is*, across a reorder: the document it
    /// points at.
    ///
    /// A path addresses a sequence item by position, so a reorder re-points
    /// every path after the item that moved — a page opened on `contents[1]`
    /// goes on showing `contents[1]`, which is now a different document. A
    /// link's **target** survives that, and survives a relabel with it:
    /// `[The Vault](/README.md)` and `[Home](/README.md)` are one edge with a
    /// different word on it, and the word is the part a reader edits. So a
    /// reorder moves the page with the item, and retitling the item does not
    /// move it at all.
    ///
    /// [`Link::addressed_target`](prov::Link::addressed_target), so the
    /// `#locator` is stripped: `a.md#one` and `a.md#two` are one identity, and
    /// the first of them wins — which is [`Backend::item_key`]'s documented
    /// behaviour for a repeated key rather than a loss. Two items pointing into
    /// the same document are two ways of saying where to look, and a page that
    /// lands on the first has landed in the right document.
    ///
    /// `None` for a list that is not a relation's, for an item that is not a
    /// scalar, and for an empty target. flower's own fallback — a mapping item's
    /// title, a scalar's own text — is the better answer for those, and it is
    /// what it uses when this declines.
    fn item_key(&self, seq_path: &[Seg], index: usize) -> Result<Option<String>, BackendError> {
        if self.relation_at(seq_path).is_none() {
            return Ok(None);
        }
        let mut path = seq_path.to_vec();
        path.push(Seg::Index(index));
        let Some(Value::Str(text)) = tree::value_at(&self.to_value()?, &path).cloned() else {
            return Ok(None);
        };
        let target = prov::Link::parse(&text).addressed_target().to_string();
        Ok((!target.is_empty()).then_some(target))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use flower_core::{Mode, Model};

    const DOC: &str = "\
---
# the title
title: Old Title
draft: true
tags:
- a
- b
---
# Heading

Body prose that must survive metadata edits.
";

    fn model() -> Model<ProvBackend> {
        let backend = ProvBackend::open("note.md", DOC).expect("open prov doc");
        Model::new(backend).expect("build model")
    }

    fn select(model: &mut Model<ProvBackend>, path: &[Seg]) {
        // `select_row`, not a write to `selected`: the field is flower's own now,
        // and the setter is what asserts the tree projection this index belongs to.
        let index = model
            .rows
            .iter()
            .position(|r| r.path == path)
            .unwrap_or_else(|| panic!("no row for {path:?}"));
        model.select_row(index);
    }

    fn type_value(model: &mut Model<ProvBackend>, text: &str) {
        // `..`: an edit now also carries the path it belongs to, which this
        // helper has no use for — it types into whatever is already open.
        if let Mode::Editing { buffer, .. } = &mut model.mode {
            buffer.clear();
        }
        for c in text.chars() {
            model.edit_push(c);
        }
        model.edit_commit();
    }

    /// The `EditOp` contract, checked against flower's own suite.
    ///
    /// `ProvBackend` is the second implementation of that trait, and a trait with
    /// one implementation has only a behavior — this is where the two would
    /// silently part ways. Running flower's suite rather than restating it means a
    /// guarantee added upstream arrives here as a failing test, not as a difference
    /// nobody looked for.
    ///
    /// The fixture is written as frontmatter because that is the carrier a prose
    /// vault uses; the suite asserts on the value tree, so the format is ours to
    /// pick.
    #[test]
    fn prov_backend_satisfies_the_edit_op_contract() {
        const FIXTURE: &str = "\
---
title: note
tags:
- alpha
- beta
- gamma
nested:
  k: v
  j: w
---
# Note

Body prose.
";
        flower_core::backend::conformance::check(|| {
            ProvBackend::open("note.md", FIXTURE).expect("open fixture")
        })
        .expect("prov backend honors the EditOp contract");
    }

    #[test]
    fn renders_frontmatter_as_a_tree() {
        let model = model();
        let keys: Vec<&str> = model
            .rows
            .iter()
            .filter(|r| r.depth == 0)
            .map(|r| r.label.as_str())
            .collect();
        assert_eq!(
            keys,
            ["title", "draft", "tags"],
            "top-level frontmatter keys"
        );
    }

    #[test]
    fn edits_metadata_leaving_the_body_untouched() {
        let mut model = model();

        select(&mut model, &[Seg::Key("title".into())]);
        model.begin_edit();
        type_value(&mut model, "New Title");

        let out = model.source_snapshot();
        assert!(out.contains("title: New Title"), "value changed:\n{out}");
        assert!(out.contains("# the title"), "comment preserved:\n{out}");
        assert!(out.starts_with("---\n"), "fences intact:\n{out}");
        assert!(
            out.contains("Body prose that must survive metadata edits."),
            "body preserved:\n{out}"
        );
    }

    #[test]
    fn deletes_a_key() {
        let mut model = model();

        select(&mut model, &[Seg::Key("draft".into())]);
        model.delete_selected();

        let out = model.source_snapshot();
        assert!(!out.contains("draft:"), "key removed:\n{out}");
        assert!(out.contains("title: Old Title"), "siblings kept:\n{out}");
        assert!(out.contains("Body prose"), "body kept:\n{out}");
    }

    #[test]
    fn comments_are_read_per_node_and_edited_in_place_leaving_the_body_alone() {
        let backend = ProvBackend::open("note.md", DOC).expect("open");
        let mut model = Model::new(backend).expect("model");
        let title = [Seg::Key("title".into())];
        let draft = [Seg::Key("draft".into())];

        // The block above `title` is read through the backend, into the page.
        assert_eq!(
            model.leading_comment_at(&title).as_deref(),
            Some("the title")
        );
        assert_eq!(model.leading_comment_at(&draft), None);
        assert_eq!(model.trailing_comment_at(&title), None);

        model.set_leading_comment(&title, Some("what it is called"));
        model.set_trailing_comment(&draft, Some("for now"));
        let out = model.source_snapshot();
        assert!(
            out.contains("# what it is called\ntitle: Old Title"),
            "{out}"
        );
        assert!(
            !out.contains("# the title"),
            "the block is replaced:\n{out}"
        );
        assert!(out.contains("draft: true # for now"), "{out}");
        assert!(
            out.contains("Body prose that must survive"),
            "body kept:\n{out}"
        );

        model.set_leading_comment(&title, None);
        let out = model.source_snapshot();
        assert!(out.starts_with("---\ntitle: Old Title"), "{out}");
    }

    #[test]
    fn a_comment_write_that_fig_refuses_leaves_the_document_as_it_was() {
        let mut backend = ProvBackend::open("note.md", DOC).expect("open");
        let before = backend.source().unwrap();
        // A trailing comment is one line; a second line is refused whole, and
        // the text is not replaced by a partial edit.
        let result = backend.apply(EditOp::SetTrailingComment {
            path: vec![Seg::Key("title".into())],
            text: Some("two\nlines".into()),
        });
        assert!(result.is_err());
        assert_eq!(backend.source().unwrap(), before);
    }

    #[test]
    fn json_frontmatter_has_no_comments_to_read_and_refuses_to_write_one() {
        // `;;;` is the JSON frontmatter fence; `---` around `{…}` would be
        // YAML, which a `{…}` is a flow mapping of, and which has comments.
        let doc = ";;;\n{\"title\": \"Note\"}\n;;;\n# Note\n";
        let mut backend = ProvBackend::open("note.md", doc).expect("open");
        let title = vec![Seg::Key("title".into())];
        assert_eq!(backend.leading_comment(&title).unwrap(), None);
        assert_eq!(backend.trailing_comment(&title).unwrap(), None);
        let before = backend.source().unwrap();
        assert!(
            backend
                .apply(EditOp::SetLeadingComment {
                    path: title,
                    text: Some("nope".into()),
                })
                .is_err()
        );
        assert_eq!(backend.source().unwrap(), before);
    }

    #[test]
    fn a_document_with_no_metadata_block_has_no_comments() {
        let backend = ProvBackend::open("note.md", "# Just prose\n").expect("open");
        assert_eq!(
            backend
                .leading_comment(&[Seg::Key("title".into())])
                .unwrap(),
            None
        );
    }

    /// A relation's list item is known by the document it points at, not by its
    /// position and not by its label — so a reorder carries the page with the
    /// item, and retitling the item does not move it at all.
    ///
    /// Driven through `Model`, which is the only caller that matters: it asks
    /// the backend first and falls back to its own guess, and the fallback here
    /// would be the item's whole text — which changes when the label does, and
    /// is exactly the wrong answer.
    #[test]
    fn a_relations_item_is_identified_by_its_target_not_its_position_or_label() {
        const INDEX: &str = "\
---
title: Index
contents:
- '[One](one.md)'
- '[Two](two.md)'
- '[Three](three.md)'
tags:
- alpha
- beta
---
# Index
";
        let schema = schema_from_config(
            &prov::config::WorkspaceConfig::default(),
            &std::collections::BTreeMap::new(),
        );
        let backend = ProvBackend::open_with_schema("index.md", INDEX, schema).expect("open");
        let mut model = Model::new(backend).expect("model");
        let contents = [Seg::Key("contents".into())];

        // The target, locator and label stripped — not the item's text.
        assert_eq!(model.item_key(&contents, 0).as_deref(), Some("one.md"));
        assert_eq!(model.item_key(&contents, 1).as_deref(), Some("two.md"));
        assert_eq!(model.item_key(&contents, 2).as_deref(), Some("three.md"));

        // A list that is not a relation's is flower's own business, and its
        // answer is the scalar itself.
        let tags = [Seg::Key("tags".into())];
        assert_eq!(model.item_key(&tags, 0).as_deref(), Some("alpha"));

        // Stand on the second item, in the page projection the widgets draw.
        let second = [Seg::Key("contents".into()), Seg::Index(1)];
        model.focus_on(&second);
        assert_eq!(
            model.page_item().map(|i| i.path.clone()),
            Some(second.to_vec()),
            "the cursor is on the item that was opened on"
        );

        // Move it up. The page cursor is now at index 0 — and it is the *same
        // document*, which is the whole claim: without an identity the cursor
        // would have stayed on index 1 and be looking at `one.md`.
        model.move_selected_up();
        let landed = model.page_item().expect("still on an item").path.clone();
        assert_eq!(landed, [Seg::Key("contents".into()), Seg::Index(0)]);
        assert_eq!(
            model.item_key(&contents, 0).as_deref(),
            Some("two.md"),
            "the item moved, and the cursor moved with it"
        );
        assert_eq!(model.item_key(&contents, 1).as_deref(), Some("one.md"));

        // Relabelling is not a move. The item's text changes entirely and its
        // identity does not, so nothing re-points.
        model.set_value_at(&landed, Value::Str("[The Second One](two.md)".into()));
        assert_eq!(model.item_key(&contents, 0).as_deref(), Some("two.md"));
        assert_eq!(
            model.page_item().map(|i| i.path.clone()),
            Some(landed),
            "the cursor did not go looking for a document that never moved"
        );

        // A locator is not part of the identity: the item names a place inside
        // a document, and the document is what the page is standing in.
        model.set_value_at(
            &[Seg::Key("contents".into()), Seg::Index(1)],
            Value::Str("[One](one.md#a-heading)".into()),
        );
        assert_eq!(model.item_key(&contents, 1).as_deref(), Some("one.md"));
    }

    #[test]
    fn schema_backed_backend_rejects_a_term_outside_a_closed_vocabulary() {
        use flower_core::schema::{Constraint, FieldRule};
        use flower_core::{FieldType, PathPat, Term};
        // A prov document whose `audience` is a closed vocabulary.
        let doc = "---\ntitle: Note\naudience:\n- public\n---\n# Note\n";
        let schema = Schema::new(vec![
            FieldRule::new(PathPat::each_item_of("audience"))
                .ty(FieldType::Str)
                .constraint(Constraint::Enum {
                    values: vec![Term::value("public"), Term::value("private")],
                    closed: true,
                }),
        ]);
        let backend = ProvBackend::open_with_schema("note.md", doc, schema).expect("open");
        let mut model = Model::new(backend).expect("model");

        // The schema traveled through the backend into the model: an unknown
        // term is rejected, the document untouched.
        select(&mut model, &[Seg::Key("audience".into()), Seg::Index(0)]);
        model.begin_edit();
        type_value(&mut model, "familly");
        assert!(
            model.status.contains("rejected"),
            "status: {}",
            model.status
        );
        assert!(model.source_snapshot().contains("- public"), "unchanged");

        // A known value commits.
        model.begin_edit();
        type_value(&mut model, "private");
        assert!(model.source_snapshot().contains("- private"), "applied");
    }
}