flower-core 0.1.0

Frontend-neutral structural editing model for config files, over fig.
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
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
//! The frontend-neutral editor model and its structural operations.
//!
//! `Model` is generic over a [`Backend`]: it builds path-addressed [`EditOp`]s,
//! applies them through the backend, and re-derives its view from
//! [`Backend::to_value`] after each change. It owns no editor, no format, no
//! filesystem, and no terminal — the backend owns the document; the embedder
//! owns file I/O and rendering.

use std::collections::HashSet;

use anyhow::Result;
use fig::Value;

use crate::backend::{Backend, EditOp};
use crate::schema::{FieldRule, Schema};
use fig_schema::{Issue, SegPat, Validation};
use crate::tree::{self, Row, Seg};

/// Interaction mode: normal navigation, or editing a scalar's text.
pub enum Mode {
    Normal,
    Editing { buffer: String },
}

pub struct Model<B> {
    backend: B,

    /// Derived view state, rebuilt from `backend.to_value()` after every edit.
    value: Value,
    pub rows: Vec<Row>,
    collapsed: HashSet<Vec<Seg>>,
    /// Top-level mapping keys to hide from the row projection (but keep in the
    /// document). Empty for a standalone config; a prov/diaryx embedder passes the
    /// managed-key set so those fields stay lossless and out of view.
    hidden: HashSet<String>,
    /// Top-level mapping keys the *workspace* maintains: shown, but not editable.
    ///
    /// The complement of [`hidden`](Self::hidden), for the other kind of managed
    /// field. A hidden key is edited through some other affordance (a title bar,
    /// a link view) and would only clutter the list; a derived key — a recomputed
    /// timestamp, a content hash — has no other affordance because *nothing*
    /// edits it by hand: the workspace overwrites it on the next write. Hiding
    /// those two alike leaves a user wondering where a field they can see in the
    /// file went, so a derived key keeps its row and declines edits instead.
    derived: HashSet<String>,
    /// The schema governing this document, if any — from the backend
    /// ([`Backend::schema`]) or injected by the embedder ([`Model::set_schema`]).
    /// Drives type-directed parsing and commit-time value validation; absent, the
    /// model behaves exactly as before.
    schema: Option<Schema>,

    pub selected: usize,
    pub mode: Mode,
    pub status: String,
    pub dirty: bool,
}

impl<B: Backend> Model<B> {
    /// Build a model over `backend`.
    pub fn new(backend: B) -> Result<Self> {
        Self::with_hidden(backend, Vec::new())
    }

    /// Build a model that hides the given **top-level** mapping keys from the row
    /// projection while keeping them in the document (see
    /// [`tree::build_rows`](crate::tree::build_rows)). For an embedder whose
    /// format reserves some top-level keys (prov/diaryx-managed frontmatter).
    pub fn with_hidden(backend: B, hidden: Vec<String>) -> Result<Self> {
        Self::with_managed(backend, hidden, Vec::new())
    }

    /// Build a model over `backend` distinguishing the two kinds of managed key:
    /// `hidden` ones produce no row (edited through another affordance), while
    /// `derived` ones keep their row but decline every edit (the workspace
    /// maintains them — see [`derived`](Self::derived)).
    ///
    /// A key in both is hidden: no row means nothing to mark read-only.
    pub fn with_managed(backend: B, hidden: Vec<String>, derived: Vec<String>) -> Result<Self> {
        Self::with_collapsed(backend, hidden, derived, Vec::new())
    }

    /// Build a model whose containers at `collapsed` arrive **shut**, before the
    /// first row list is ever built.
    ///
    /// A document can have one field nobody reads as a list: an index document's
    /// `contents` is one row per child — ninety-five of them in a year index,
    /// ahead of the four fields anyone types by hand. Such a section wants to open
    /// as a summary, not a wall you scroll past. Toggling it afterwards through
    /// [`activate`](Self::activate) would work, but that is the *interactive*
    /// door: it moves the selection and rebuilds the row list once per container.
    /// Seeding the set here costs neither — the paths are in place before
    /// `reload`, so the opening frame is already correct.
    ///
    /// A path that names a scalar (or nothing at all) is inert rather than an
    /// error, so a caller can name the keys it *wants* collapsed without first
    /// checking which of them turned out to be containers.
    pub fn with_collapsed(
        backend: B,
        hidden: Vec<String>,
        derived: Vec<String>,
        collapsed: Vec<Vec<Seg>>,
    ) -> Result<Self> {
        // The backend supplies the schema when it knows one (a prov backend);
        // otherwise it stays `None` until an embedder injects one.
        let schema = backend.schema();
        let mut model = Model {
            backend,
            value: Value::Null,
            rows: Vec::new(),
            collapsed: collapsed.into_iter().collect(),
            hidden: hidden.into_iter().collect(),
            derived: derived.into_iter().collect(),
            schema,
            selected: 0,
            mode: Mode::Normal,
            status: "opened".to_string(),
            dirty: false,
        };
        model.reload()?;
        Ok(model)
    }

    /// Inject a schema out-of-band — the embedder precedent, mirroring
    /// [`with_hidden`](Self::with_hidden). For a host whose backend does not
    /// supply one but that *knows* the governing schema (a diaryx host feeding a
    /// fig-backed frontmatter block plus its resolved workspace config).
    pub fn set_schema(&mut self, schema: Schema) {
        self.schema = Some(schema);
    }

    /// The schema governing the document, if any.
    pub fn schema(&self) -> Option<&Schema> {
        self.schema.as_ref()
    }

    /// The schema rule governing the node at `path`, if any — for a frontend
    /// deciding a widget (a picker for an enum field) or presentation.
    pub fn rule_at(&self, path: &[Seg]) -> Option<&FieldRule> {
        self.schema.as_ref().and_then(|s| s.rule_for(path))
    }

    /// The kind of the document root, for a frontend deciding how to add a
    /// top-level entry: `"map"`, `"seq"`, or `"scalar"`.
    pub fn root_kind(&self) -> &'static str {
        match self.value {
            Value::Map(_) => "map",
            Value::Seq(_) => "seq",
            _ => "scalar",
        }
    }

    /// How many of the hidden top-level keys are actually present in the document
    /// — for a "N managed fields" affordance.
    pub fn hidden_present(&self) -> usize {
        match &self.value {
            Value::Map(entries) => entries
                .iter()
                .filter(|(k, _)| matches!(k, Value::Str(s) if self.hidden.contains(s)))
                .count(),
            _ => 0,
        }
    }

    /// Whether the node at `path` sits under a workspace-maintained (derived)
    /// top-level key — for a frontend rendering it read-only rather than as an
    /// editable control. Edits to it are declined at the commit funnel regardless.
    pub fn is_derived(&self, path: &[Seg]) -> bool {
        matches!(path.first(), Some(Seg::Key(k)) if self.derived.contains(k))
    }

    /// The schema-declared top-level fields the document does **not** yet carry
    /// — what an "add field" affordance offers, so a declared field is reachable
    /// before it exists.
    ///
    /// Rows are projected from the *document*
    /// ([`build_rows`](crate::tree::build_rows)), so a field the schema declares
    /// but the document omits has no row and is otherwise unreachable: the user
    /// would have to know the key and type it exactly. This closes that gap —
    /// it is the schema's half of the row list, and the reason a declared type
    /// is worth writing down for a field that is empty.
    ///
    /// Only a rule addressing exactly one top-level key names an addable field:
    /// an each-item or subtree rule governs *within* a field rather than naming
    /// one. Hidden (managed) keys are never offered — the embedder reserves
    /// those. Order follows the schema's own rule order, so a caller can present
    /// them as declared.
    pub fn addable_fields(&self) -> Vec<&FieldRule> {
        let Some(schema) = &self.schema else {
            return Vec::new();
        };
        // Only a map root can take a top-level key at all.
        let Value::Map(entries) = &self.value else {
            return Vec::new();
        };
        let present: HashSet<&str> = entries
            .iter()
            .filter_map(|(k, _)| match k {
                Value::Str(s) => Some(s.as_str()),
                _ => None,
            })
            .collect();
        let mut seen = HashSet::new();
        schema
            .rules()
            .iter()
            .filter(|rule| {
                let [SegPat::Key(name)] = rule.at.0.as_slice() else {
                    return false;
                };
                !present.contains(name.as_str())
                    && !self.hidden.contains(name)
                    && seen.insert(name.as_str())
            })
            .collect()
    }

    /// The canonical serialized document — what the embedder writes on save.
    pub fn source_snapshot(&self) -> String {
        self.backend.source().unwrap_or_default()
    }

    /// The backend, for backend-specific reads (e.g. a prov backend's body).
    pub fn backend(&self) -> &B {
        &self.backend
    }

    /// The backend, for backend-specific operations that do **not** change the
    /// metadata tree flower renders (e.g. replacing a prov document's prose
    /// body). An op that *does* change the metadata leaves the view stale — go
    /// through the model's own edit methods for those.
    pub fn backend_mut(&mut self) -> &mut B {
        &mut self.backend
    }

    pub fn set_status(&mut self, s: impl Into<String>) {
        self.status = s.into();
    }

    /// Clear the dirty flag after the embedder has persisted the source.
    pub fn mark_saved(&mut self) {
        self.dirty = false;
    }

    // ── view derivation ───────────────────────────────────────────────────────

    /// Re-derive `value` + `rows` from the backend's current tree.
    fn reload(&mut self) -> Result<()> {
        self.value = self
            .backend
            .to_value()
            .map_err(|e| anyhow::anyhow!("reading value tree: {e}"))?;
        self.rebuild_rows();
        Ok(())
    }

    fn rebuild_rows(&mut self) {
        self.rows = tree::build_rows(&self.value, &self.collapsed, &self.hidden);
        if self.selected >= self.rows.len() {
            self.selected = self.rows.len().saturating_sub(1);
        }
    }

    fn selected_row(&self) -> Option<&Row> {
        self.rows.get(self.selected)
    }

    /// Re-anchor selection onto `path` after a rebuild, or clamp if it's gone.
    fn select_path(&mut self, path: &[Seg]) {
        if let Some(i) = self.rows.iter().position(|r| r.path == path) {
            self.selected = i;
        } else if self.selected >= self.rows.len() {
            self.selected = self.rows.len().saturating_sub(1);
        }
    }

    // ── navigation ────────────────────────────────────────────────────────────

    pub fn move_down(&mut self) {
        if self.selected + 1 < self.rows.len() {
            self.selected += 1;
        }
    }

    pub fn move_up(&mut self) {
        self.selected = self.selected.saturating_sub(1);
    }

    /// `l`: expand a collapsed container, else step into its first child.
    pub fn expand_or_enter(&mut self) {
        let Some(row) = self.selected_row() else {
            return;
        };
        if row.is_container() {
            if !row.expanded {
                let path = row.path.clone();
                self.collapsed.remove(&path);
                self.rebuild_rows();
                self.select_path(&path);
            } else if self.selected + 1 < self.rows.len()
                && self.rows[self.selected + 1].depth > row.depth
            {
                self.selected += 1;
            }
        }
    }

    /// `h`: collapse an expanded container, else step out to the parent row.
    pub fn collapse_or_leave(&mut self) {
        let Some(row) = self.selected_row() else {
            return;
        };
        if row.is_container() && row.expanded {
            let path = row.path.clone();
            self.collapsed.insert(path.clone());
            self.rebuild_rows();
            self.select_path(&path);
            return;
        }
        // Step out: the nearest earlier row at a shallower depth is the parent.
        let depth = row.depth;
        if depth == 0 {
            return;
        }
        for i in (0..self.selected).rev() {
            if self.rows[i].depth < depth {
                self.selected = i;
                return;
            }
        }
    }

    /// Whether the container at `path` is collapsed. Answers for a node with no
    /// row too (one nested inside another collapsed container), which
    /// [`Row::expanded`](crate::Row) cannot.
    pub fn is_collapsed(&self, path: &[Seg]) -> bool {
        self.collapsed.contains(path)
    }

    /// Collapse or expand the container at `path`, leaving the selection where the
    /// user put it — the by-path, non-interactive counterpart to
    /// [`activate`](Self::activate).
    ///
    /// `activate` folds *the selected row*, so driving it from a path means moving
    /// the selection first and putting it back after. This doesn't: it re-anchors
    /// onto whatever was selected before, and only falls back to `path` itself when
    /// the selection was a descendant that the fold just took off screen.
    ///
    /// A path naming a scalar (or nothing) is inert — see
    /// [`with_collapsed`](Self::with_collapsed).
    pub fn set_collapsed(&mut self, path: &[Seg], collapsed: bool) {
        let changed = if collapsed {
            self.collapsed.insert(path.to_vec())
        } else {
            self.collapsed.remove(path)
        };
        if !changed {
            return;
        }
        let was = self.selected_row().map(|r| r.path.clone());
        self.rebuild_rows();
        if let Some(was) = was {
            // A row swallowed by the fold has no path to return to; its nearest
            // surviving ancestor is the container the user just shut.
            if collapsed && was.len() > path.len() && was.starts_with(path) {
                self.select_path(path);
            } else {
                self.select_path(&was);
            }
        }
    }

    /// `Enter`/`Space`: toggle a container's expansion, or edit a scalar.
    pub fn activate(&mut self) {
        let Some(row) = self.selected_row() else {
            return;
        };
        if row.is_container() {
            let path = row.path.clone();
            if row.expanded {
                self.collapsed.insert(path.clone());
            } else {
                self.collapsed.remove(&path);
            }
            self.rebuild_rows();
            self.select_path(&path);
        } else {
            self.begin_edit();
        }
    }

    // ── editing ───────────────────────────────────────────────────────────────

    pub fn begin_edit(&mut self) {
        let Some(row) = self.selected_row() else {
            return;
        };
        if !row.is_scalar() {
            self.status = "can only edit scalar values".to_string();
            return;
        }
        let seed = self
            .value_at(&row.path)
            .map(tree::edit_seed)
            .unwrap_or_default();
        self.mode = Mode::Editing { buffer: seed };
    }

    pub fn edit_push(&mut self, c: char) {
        if let Mode::Editing { buffer } = &mut self.mode {
            buffer.push(c);
        }
    }

    pub fn edit_backspace(&mut self) {
        if let Mode::Editing { buffer } = &mut self.mode {
            buffer.pop();
        }
    }

    pub fn edit_cancel(&mut self) {
        self.mode = Mode::Normal;
        self.status = "edit cancelled".to_string();
    }

    pub fn edit_commit(&mut self) {
        let Mode::Editing { buffer } = &mut self.mode else {
            return;
        };
        let buffer = std::mem::take(buffer);
        self.mode = Mode::Normal;

        let Some(row) = self.selected_row() else {
            return;
        };
        let path = row.path.clone();
        let value = self.coerce_text(&path, &buffer);
        self.commit(
            EditOp::ReplaceValue {
                path: path.clone(),
                value,
            },
            path,
            "value updated",
        );
    }

    /// Programmatically replace the value at `path` (any depth), refreshing the
    /// view. The non-interactive counterpart to [`edit_commit`](Self::edit_commit)
    /// — for an embedder or FFI that edits by path rather than through the
    /// selection.
    pub fn set_value_at(&mut self, path: &[Seg], value: Value) {
        self.commit(
            EditOp::ReplaceValue {
                path: path.to_vec(),
                value,
            },
            path.to_vec(),
            "value updated",
        );
    }

    /// Set the scalar at `path` from an edit-buffer `text`, coercing by the
    /// schema's expected type when known (a `str` field keeps `"123"` a string)
    /// and otherwise guessing by literal shape — the by-path, schema-aware analog
    /// of [`edit_commit`](Self::edit_commit). Validation (closed-vocabulary
    /// rejection) still happens at the commit funnel.
    pub fn set_scalar_text(&mut self, path: &[Seg], text: &str) {
        let value = self.coerce_text(path, text);
        self.set_value_at(path, value);
    }

    /// Turn edit-buffer `text` into the value that belongs at `path`: the type the
    /// schema declares for that path when it declares one, and otherwise a guess
    /// from the literal's shape.
    ///
    /// The single rule behind [`edit_commit`](Self::edit_commit),
    /// [`set_scalar_text`](Self::set_scalar_text),
    /// [`insert_key_text`](Self::insert_key_text) and
    /// [`append_item_text`](Self::append_item_text). It is keyed on the path of the
    /// value being *written*, not of its container — that is what lets an
    /// each-item rule type a list's items independently of the list.
    fn coerce_text(&self, path: &[Seg], text: &str) -> Value {
        match self.rule_at(path).and_then(|r| r.ty) {
            Some(ty) => ty.coerce(text),
            None => tree::parse_scalar(text),
        }
    }

    /// Rename the mapping entry at `path` to `new_key`, keeping its value and
    /// re-anchoring the selection onto the renamed entry. A no-op (with a status
    /// hint) when `path` doesn't end in a key — a sequence item has no key. The
    /// backend rejects a name that collides with an existing sibling key.
    pub fn rename_key(&mut self, path: &[Seg], new_key: &str) {
        match path.last() {
            Some(Seg::Key(_)) => {
                let mut anchor = path[..path.len() - 1].to_vec();
                anchor.push(Seg::Key(new_key.to_string()));
                self.commit(
                    EditOp::RenameKey {
                        path: path.to_vec(),
                        new_key: new_key.to_string(),
                    },
                    anchor,
                    "renamed",
                );
            }
            _ => self.status = "only mapping keys can be renamed".to_string(),
        }
    }

    /// Insert `key = value` into the mapping at `map_path`, selecting the new
    /// entry. A frontend offers this on a map container; the backend rejects a
    /// duplicate key or a non-mapping target, leaving the document untouched.
    pub fn insert_key(&mut self, map_path: &[Seg], key: &str, value: Value) {
        let mut anchor = map_path.to_vec();
        anchor.push(Seg::Key(key.to_string()));
        self.commit(
            EditOp::InsertKey {
                map_path: map_path.to_vec(),
                key: key.to_string(),
                value,
            },
            anchor,
            "inserted",
        );
    }

    /// Insert `key = text` into the mapping at `map_path`, coercing `text` by the
    /// type the schema declares for the new entry and otherwise guessing by literal
    /// shape — the insert-shaped analog of
    /// [`set_scalar_text`](Self::set_scalar_text).
    ///
    /// Prefer this to [`insert_key`](Self::insert_key) whenever the value comes
    /// from a user's text: a caller that shape-guesses on its own writes `2026` as
    /// an integer into a field the schema declares `str`, and gets no say from the
    /// schema it is otherwise honoring everywhere else.
    pub fn insert_key_text(&mut self, map_path: &[Seg], key: &str, text: &str) {
        let mut target = map_path.to_vec();
        target.push(Seg::Key(key.to_string()));
        let value = self.coerce_text(&target, text);
        self.insert_key(map_path, key, value);
    }

    /// Append `value` to the sequence at `seq_path`, selecting the new item.
    pub fn append_item(&mut self, seq_path: &[Seg], value: Value) {
        let idx = self.seq_len(seq_path);
        let mut anchor = seq_path.to_vec();
        anchor.push(Seg::Index(idx));
        self.commit(
            EditOp::AppendItem {
                seq_path: seq_path.to_vec(),
                value,
            },
            anchor,
            "appended",
        );
    }

    /// Append `text` to the sequence at `seq_path`, coercing it by the type the
    /// schema declares for the sequence's *items* and otherwise guessing by literal
    /// shape — the append-shaped analog of
    /// [`set_scalar_text`](Self::set_scalar_text).
    ///
    /// The item's type comes from the rule matching the item path (an each-item or
    /// subtree rule), not from the rule on the list itself: `tags` is a `seq`, its
    /// items are `str`.
    pub fn append_item_text(&mut self, seq_path: &[Seg], text: &str) {
        let mut target = seq_path.to_vec();
        target.push(Seg::Index(self.seq_len(seq_path)));
        let value = self.coerce_text(&target, text);
        self.append_item(seq_path, value);
    }

    /// Move the selected row one place earlier among its siblings — a sequence
    /// item via fig's array-move, a mapping entry via a one-swap reorder.
    pub fn move_selected_up(&mut self) {
        self.reorder_selected(-1);
    }

    /// Move the selected row one place later among its siblings.
    pub fn move_selected_down(&mut self) {
        self.reorder_selected(1);
    }

    /// The shared body of [`move_selected_up`](Self::move_selected_up) /
    /// [`move_selected_down`](Self::move_selected_down): shift the selected row by
    /// `delta` positions within its parent container.
    fn reorder_selected(&mut self, delta: isize) {
        let Some(row) = self.selected_row() else {
            return;
        };
        let path = row.path.clone();
        let Some(last) = path.last().cloned() else {
            self.status = "cannot move the document root".to_string();
            return;
        };
        let parent = path[..path.len() - 1].to_vec();
        match last {
            Seg::Index(i) => {
                let len = self.seq_len(&parent);
                let to = i as isize + delta;
                if to < 0 || to as usize >= len {
                    self.status = "already at the edge".to_string();
                    return;
                }
                let to = to as usize;
                let mut anchor = parent.clone();
                anchor.push(Seg::Index(to));
                self.commit(
                    EditOp::MoveItem {
                        seq_path: parent,
                        from: i,
                        to,
                    },
                    anchor,
                    "moved",
                );
            }
            Seg::Key(k) => {
                let keys = self.map_keys(&parent);
                let Some(pos) = keys.iter().position(|x| *x == k) else {
                    return;
                };
                let target = pos as isize + delta;
                if target < 0 || target as usize >= keys.len() {
                    self.status = "already at the edge".to_string();
                    return;
                }
                let mut order = keys;
                order.swap(pos, target as usize);
                self.commit(
                    EditOp::ReorderKeys {
                        map_path: parent,
                        keys: order,
                    },
                    path,
                    "moved",
                );
            }
        }
    }

    /// The value the document currently holds at `path` (the whole tree for the
    /// empty path), or `None` when the path doesn't resolve — for a frontend
    /// reading a row's value without reaching for the backend.
    pub fn value_at(&self, path: &[Seg]) -> Option<&Value> {
        tree::value_at(&self.value, path)
    }

    /// The mapping keys at `path`, in document order (empty for a non-mapping).
    fn map_keys(&self, path: &[Seg]) -> Vec<String> {
        tree::map_keys(&self.value, path).unwrap_or_default()
    }

    /// The length of the sequence at `path` (0 for a non-sequence) — the index an
    /// append will land at.
    pub fn seq_len(&self, path: &[Seg]) -> usize {
        tree::seq_len(&self.value, path).unwrap_or(0)
    }

    /// `x`: delete the selected mapping entry or sequence item.
    pub fn delete_selected(&mut self) {
        let Some(row) = self.selected_row() else {
            return;
        };
        let path = row.path.clone();
        let (op, anchor) = match path.last() {
            Some(Seg::Index(i)) => {
                let seq_path = path[..path.len() - 1].to_vec();
                (
                    EditOp::RemoveItem {
                        seq_path: seq_path.clone(),
                        index: *i,
                    },
                    seq_path,
                )
            }
            Some(Seg::Key(_)) => (
                EditOp::DeleteKey { path: path.clone() },
                path[..path.len() - 1].to_vec(),
            ),
            None => {
                self.status = "cannot delete the document root".to_string();
                return;
            }
        };
        self.commit(op, anchor, "deleted");
    }

    /// Apply one edit through the backend, then refresh the view (or report the
    /// rollback). The single path every mutation funnels through — and the choke
    /// point where the schema validates values: a closed vocabulary rejects an
    /// unknown value here, before it reaches the backend; an open one applies but
    /// surfaces a soft warning. fig's reparse stays the last-resort backstop.
    fn commit(&mut self, op: EditOp, anchor: Vec<Seg>, msg: &str) {
        // A workspace-maintained field declines every mutation, not just a value
        // edit: renaming or deleting one would be undone on the next write just
        // as surely as retyping it.
        if let Some(key) = op_root_key(&op)
            && self.derived.contains(key)
        {
            self.status = format!("rejected: `{key}` is maintained by the workspace");
            return;
        }
        let mut warn: Option<Issue> = None;
        if let Some((path, value)) = op_target(&op)
            && let Some(rule) = self.rule_at(&path)
        {
            match rule.validate(value) {
                Validation::Reject(why) => {
                    self.status = format!("rejected: {why}");
                    return;
                }
                Validation::Warn(why) => warn = Some(why),
                Validation::Ok => {}
            }
        }
        match self.backend.apply(op) {
            Ok(()) => {
                self.after_edit(&anchor, msg);
                // A soft-warn overrides the success status so the user sees it.
                if let Some(why) = warn {
                    self.status = why.to_string();
                }
            }
            // The backend rolled back / declined; the document is untouched.
            Err(e) => self.status = format!("rejected: {e}"),
        }
    }

    /// Shared tail of a successful mutation: refresh the view, re-anchor
    /// selection, mark dirty, set the status line.
    fn after_edit(&mut self, anchor: &[Seg], msg: &str) {
        if let Err(e) = self.reload() {
            self.status = format!("view refresh failed: {e}");
            return;
        }
        self.select_path(anchor);
        self.dirty = true;
        self.status = msg.to_string();
    }
}

/// The (target path, value) a value-bearing [`EditOp`] writes — what schema
/// validation checks. An append's item index isn't known here, so a placeholder
/// `Index(0)` stands in; it only serves to match an `EachItem` rule pattern, which
/// is index-agnostic. Structural ops (delete, move, reorder, rename) carry no new
/// value and return `None`.
/// The top-level mapping key an op would change, if any — the unit at which a
/// document's managed fields are declared, so an edit anywhere beneath one
/// (an item of a managed list, a nested key) is caught along with the field
/// itself.
fn op_root_key(op: &EditOp) -> Option<&str> {
    fn first_key(path: &[Seg]) -> Option<&str> {
        match path.first() {
            Some(Seg::Key(k)) => Some(k.as_str()),
            _ => None,
        }
    }
    match op {
        EditOp::ReplaceValue { path, .. }
        | EditOp::DeleteKey { path }
        | EditOp::RenameKey { path, .. } => first_key(path),
        EditOp::RemoveItem { seq_path, .. }
        | EditOp::AppendItem { seq_path, .. }
        | EditOp::MoveItem { seq_path, .. } => first_key(seq_path),
        // An insert *at the root* names the new top-level key itself; deeper, the
        // container it lands in is what matters.
        EditOp::InsertKey { map_path, key, .. } => match map_path.first() {
            None => Some(key.as_str()),
            _ => first_key(map_path),
        },
        // Reordering the root's own keys moves no field's value.
        EditOp::ReorderKeys { map_path, .. } => first_key(map_path),
    }
}

fn op_target(op: &EditOp) -> Option<(Vec<Seg>, &Value)> {
    match op {
        EditOp::ReplaceValue { path, value } => Some((path.clone(), value)),
        EditOp::InsertKey {
            map_path,
            key,
            value,
        } => {
            let mut p = map_path.clone();
            p.push(Seg::Key(key.clone()));
            Some((p, value))
        }
        EditOp::AppendItem { seq_path, value } => {
            let mut p = seq_path.clone();
            p.push(Seg::Index(0));
            Some((p, value))
        }
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::backend::FigBackend;
    use fig::Format;

    const SAMPLE: &str = "\
# flower sample config — comments and formatting below should survive edits
title = \"flower\"
version = 1
enabled = true

# the server block
[server]
host = \"localhost\"
port = 8080
tags = [\"alpha\", \"beta\"]

[server.limits]
max_connections = 100
timeout = 30.5
";

    fn sample_model() -> Model<FigBackend> {
        let backend = FigBackend::open(SAMPLE.as_bytes(), Format::Toml).expect("open backend");
        Model::new(backend).expect("build model")
    }

    fn select(model: &mut Model<FigBackend>, path: &[Seg]) {
        model.selected = model
            .rows
            .iter()
            .position(|r| r.path == path)
            .unwrap_or_else(|| panic!("no row for {path:?}"));
    }

    fn type_value(model: &mut Model<FigBackend>, text: &str) {
        if let Mode::Editing { buffer } = &mut model.mode {
            buffer.clear();
        }
        for c in text.chars() {
            model.edit_push(c);
        }
        model.edit_commit();
    }

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

        select(&mut model, &[Seg::Key("version".into())]);
        model.begin_edit();
        type_value(&mut model, "2");

        let src = model.source_snapshot();
        assert!(src.contains("version = 2"), "value changed:\n{src}");
        assert!(src.contains("# the server block"), "comment preserved:\n{src}");
        assert!(
            src.contains("# flower sample config"),
            "header preserved:\n{src}"
        );
        assert!(model.dirty);
    }

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

        select(
            &mut model,
            &[Seg::Key("server".into()), Seg::Key("host".into())],
        );
        model.begin_edit();
        type_value(&mut model, "example.com");

        let src = model.source_snapshot();
        assert!(src.contains("host = \"example.com\""), "nested edit:\n{src}");
        assert!(src.contains("port = 8080"), "sibling untouched:\n{src}");
    }

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

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

        let src = model.source_snapshot();
        assert!(!src.contains("enabled = true"), "key removed:\n{src}");
        assert!(src.contains("title = \"flower\""), "siblings kept:\n{src}");
    }

    #[test]
    fn appends_a_sequence_item() {
        let mut model = sample_model();
        let tags = vec![Seg::Key("server".into()), Seg::Key("tags".into())];
        model.append_item(&tags, Value::Str("gamma".into()));

        let src = model.source_snapshot();
        assert!(src.contains("gamma"), "item appended:\n{src}");
        assert!(src.contains("alpha") && src.contains("beta"), "siblings kept");
        assert!(model.dirty);
    }

    #[test]
    fn inserts_a_mapping_key() {
        let mut model = sample_model();
        let server = vec![Seg::Key("server".into())];
        model.insert_key(&server, "scheme", Value::Str("https".into()));

        let src = model.source_snapshot();
        // fig may quote the inserted key (`"scheme" = …`); both are valid TOML.
        assert!(
            src.contains("scheme") && src.contains("= \"https\""),
            "key inserted:\n{src}"
        );
        assert!(src.contains("host = \"localhost\""), "siblings kept");
    }

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

        // Move the second tag ("beta", index 1) up to index 0.
        select(
            &mut model,
            &[
                Seg::Key("server".into()),
                Seg::Key("tags".into()),
                Seg::Index(1),
            ],
        );
        model.move_selected_up();
        let src = model.source_snapshot();
        let a = src.find("alpha").unwrap();
        let b = src.find("beta").unwrap();
        assert!(b < a, "beta now precedes alpha:\n{src}");

        // Move a top-level mapping entry down: title should follow version.
        select(&mut model, &[Seg::Key("title".into())]);
        model.move_selected_down();
        let src = model.source_snapshot();
        assert!(
            src.find("version").unwrap() < src.find("title").unwrap(),
            "version now precedes title:\n{src}"
        );
    }

    #[test]
    fn hidden_top_level_keys_are_projected_out_but_kept_lossless() {
        let backend = FigBackend::open(SAMPLE.as_bytes(), Format::Toml).expect("open");
        let mut model =
            Model::with_hidden(backend, vec!["title".into(), "enabled".into()]).expect("model");

        // Hidden keys produce no rows…
        assert!(!model.rows.iter().any(|r| r.path == [Seg::Key("title".into())]));
        assert!(!model.rows.iter().any(|r| r.path == [Seg::Key("enabled".into())]));
        // …but a visible sibling is still there,
        assert!(model.rows.iter().any(|r| r.path == [Seg::Key("version".into())]));
        // …and the hidden keys remain in the document bytes.
        assert!(model.source_snapshot().contains("title = \"flower\""));
        assert!(model.source_snapshot().contains("enabled = true"));

        // Editing a visible key doesn't disturb the hidden ones.
        select(&mut model, &[Seg::Key("version".into())]);
        model.begin_edit();
        type_value(&mut model, "9");
        let src = model.source_snapshot();
        assert!(src.contains("version = 9"));
        assert!(src.contains("title = \"flower\"") && src.contains("enabled = true"));
    }

    #[test]
    fn reorder_leaves_hidden_keys_in_place() {
        let backend = FigBackend::open(SAMPLE.as_bytes(), Format::Toml).expect("open");
        let mut model = Model::with_hidden(backend, vec!["title".into()]).expect("model");

        // Move a visible top-level key; the hidden `title` must keep its position.
        select(&mut model, &[Seg::Key("enabled".into())]);
        model.move_selected_up(); // enabled moves above version
        let src = model.source_snapshot();
        // title stays first (it was declared before version/enabled).
        let title = src.find("title").unwrap();
        let version = src.find("version").unwrap();
        let enabled = src.find("enabled").unwrap();
        assert!(title < version && title < enabled, "title stayed put:\n{src}");
        assert!(enabled < version, "enabled moved above version:\n{src}");
    }

    #[test]
    fn inserts_a_root_level_key() {
        let mut model = sample_model();
        model.insert_key(&[], "root_flag", Value::Bool(true));
        let src = model.source_snapshot();
        assert!(src.contains("root_flag"), "root key inserted:\n{src}");
        assert!(src.contains("title = \"flower\""), "existing kept");
    }

    #[test]
    fn renames_a_key_losslessly() {
        let mut model = sample_model();
        select(&mut model, &[Seg::Key("version".into())]);
        model.rename_key(&[Seg::Key("version".into())], "revision");
        let src = model.source_snapshot();
        // fig may quote the new key (`"revision" = 1`); both are valid TOML.
        assert!(
            src.contains("revision") && src.contains("= 1"),
            "renamed with value kept:\n{src}"
        );
        assert!(!src.contains("version = 1"), "old key gone");
        // Selection re-anchored onto the renamed entry.
        assert_eq!(model.rows[model.selected].path, [Seg::Key("revision".into())]);
    }

    #[test]
    fn rename_rejects_a_sequence_item() {
        let mut model = sample_model();
        model.rename_key(
            &[
                Seg::Key("server".into()),
                Seg::Key("tags".into()),
                Seg::Index(0),
            ],
            "nope",
        );
        assert!(model.status.contains("mapping keys"));
    }

    #[test]
    fn schema_closed_vocabulary_rejects_an_unknown_edit() {
        use crate::schema::{Constraint, FieldRule};
        use fig_schema::{FieldType, PathPat, Presentation, Term};
        let src = "audience = [\"public\"]\ntitle = \"note\"\n";
        let backend = FigBackend::open(src.as_bytes(), Format::Toml).expect("open");
        let mut model = Model::new(backend).expect("model");
        model.set_schema(crate::schema::Schema::new(vec![FieldRule {
            at: PathPat::each_item_of("audience"),
            ty: Some(FieldType::Str),
            constraint: Some(Constraint::Enum {
                values: vec![Term::value("public"), Term::value("private")],
                closed: true,
            }),
            present: Presentation::default(),
        }]));

        // An unknown value is rejected at the commit funnel; the document is
        // untouched (fig never sees the edit).
        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"),
            "document unchanged:\n{}",
            model.source_snapshot()
        );

        // A known value commits normally.
        model.begin_edit();
        type_value(&mut model, "private");
        let out = model.source_snapshot();
        assert!(out.contains("private"), "known value applied:\n{out}");
        assert!(!out.contains("public"), "old value replaced:\n{out}");
    }

    /// A declared field the document omits is otherwise unreachable — it has no
    /// row, because rows come from the document. This is what lets a frontend
    /// offer it.
    #[test]
    fn addable_fields_are_the_declared_keys_the_document_lacks() {
        use crate::schema::{Constraint, FieldRule};
        use fig_schema::{FieldType, PathPat, Presentation, Term};
        let src = "audience = [\"public\"]\ntitle = \"note\"\n";
        let backend = FigBackend::open(src.as_bytes(), Format::Toml).expect("open");
        let mut model =
            Model::with_hidden(backend, vec!["title".into(), "updated".into()]).expect("model");
        model.set_schema(crate::schema::Schema::new(vec![
            // Present in the document — already reachable, so never offered.
            FieldRule {
                at: PathPat::key("audience"),
                ty: Some(FieldType::Str),
                constraint: None,
                present: Presentation::default(),
            },
            // An each-item rule governs *within* a field; it names none.
            FieldRule {
                at: PathPat::each_item_of("audience"),
                ty: Some(FieldType::Str),
                constraint: Some(Constraint::Enum {
                    values: vec![Term::value("public")],
                    closed: true,
                }),
                present: Presentation::default(),
            },
            // Declared, absent, not managed — the one to offer.
            FieldRule {
                at: PathPat::key("created"),
                ty: Some(FieldType::Str),
                constraint: None,
                present: Presentation::default(),
            },
            // Declared and absent, but the embedder manages it.
            FieldRule {
                at: PathPat::key("updated"),
                ty: Some(FieldType::Str),
                constraint: None,
                present: Presentation::default(),
            },
        ]));

        let offered: Vec<_> = model
            .addable_fields()
            .iter()
            .map(|r| match r.at.0.as_slice() {
                [SegPat::Key(k)] => k.clone(),
                _ => unreachable!("only single-key rules are offered"),
            })
            .collect();
        assert_eq!(offered, vec!["created".to_string()]);

        // Once added it is a real row, so it stops being offered.
        model.insert_key(&[], "created", Value::Str("2026-07-24".into()));
        assert!(model.addable_fields().is_empty());
    }

    /// A derived field keeps its row — unlike a hidden one — but declines every
    /// mutation, because the workspace rewrites it on the next save regardless.
    #[test]
    fn a_derived_field_is_visible_but_declines_edits() {
        let src = "title = \"note\"\nupdated = \"2026-07-01\"\ncreated = \"2026-06-01\"\n";
        let backend = FigBackend::open(src.as_bytes(), Format::Toml).expect("open");
        let mut model =
            Model::with_managed(backend, vec!["title".into()], vec!["updated".into()])
                .expect("model");

        // Hidden means no row; derived means a row that is marked.
        let labels: Vec<&str> = model.rows.iter().map(|r| r.label.as_str()).collect();
        assert_eq!(labels, vec!["updated", "created"]);
        assert!(model.is_derived(&[Seg::Key("updated".into())]));
        assert!(!model.is_derived(&[Seg::Key("created".into())]));

        // Every shape of mutation is declined, and the document is untouched.
        model.set_scalar_text(&[Seg::Key("updated".into())], "2026-01-01");
        assert!(model.status.contains("maintained by the workspace"));
        model.rename_key(&[Seg::Key("updated".into())], "modified");
        assert!(model.status.contains("maintained by the workspace"));
        model.selected = 0;
        model.delete_selected();
        assert!(model.status.contains("maintained by the workspace"));
        let out = model.source_snapshot();
        assert!(out.contains("updated = \"2026-07-01\""), "unchanged:\n{out}");

        // A neighbouring ordinary field still edits normally.
        model.set_scalar_text(&[Seg::Key("created".into())], "2026-06-15");
        assert!(model.source_snapshot().contains("2026-06-15"));
    }

    /// Without a schema there is nothing to declare, so nothing is offered —
    /// a standalone config keeps the free-text add path.
    #[test]
    fn addable_fields_are_empty_without_a_schema() {
        let src = "title = \"note\"\n";
        let backend = FigBackend::open(src.as_bytes(), Format::Toml).expect("open");
        let model = Model::new(backend).expect("model");
        assert!(model.addable_fields().is_empty());
    }

    #[test]
    fn schema_typed_field_keeps_a_numeric_string_as_text() {
        use crate::schema::FieldRule;
        use fig_schema::{FieldType, PathPat, Presentation};
        let src = "code = \"x\"\n";
        let backend = FigBackend::open(src.as_bytes(), Format::Toml).expect("open");
        let mut model = Model::new(backend).expect("model");
        model.set_schema(crate::schema::Schema::new(vec![FieldRule {
            at: PathPat::key("code"),
            ty: Some(FieldType::Str),
            constraint: None,
            present: Presentation::default(),
        }]));

        select(&mut model, &[Seg::Key("code".into())]);
        model.begin_edit();
        type_value(&mut model, "123");
        // Schema says `str`, so the buffer stays a quoted string rather than being
        // coerced to an integer the way the shape-guessing heuristic would.
        let out = model.source_snapshot();
        assert!(out.contains("code = \"123\""), "kept as string:\n{out}");
    }

    /// The point of a default-collapsed set: the *opening* frame is already
    /// folded, without a toggle pass that walks the selection across the document.
    #[test]
    fn containers_can_arrive_collapsed() {
        let backend = FigBackend::open(SAMPLE.as_bytes(), Format::Toml).expect("open");
        let model = Model::with_collapsed(
            backend,
            Vec::new(),
            Vec::new(),
            vec![
                vec![Seg::Key("server".into())],
                // Naming a scalar is inert, not an error — a caller collapses the
                // keys it means to without first sorting containers from scalars.
                vec![Seg::Key("title".into())],
            ],
        )
        .expect("model");

        let server = model
            .rows
            .iter()
            .find(|r| r.path == [Seg::Key("server".into())])
            .expect("server row");
        assert!(!server.expanded, "collapsed before the first frame");
        assert!(
            !model.rows.iter().any(|r| r.path.len() > 1),
            "no descendant rows: {:?}",
            model.rows.iter().map(|r| &r.label).collect::<Vec<_>>()
        );
        // The inert scalar path didn't cost `title` its row.
        assert!(
            model
                .rows
                .iter()
                .any(|r| r.path == [Seg::Key("title".into())])
        );
        assert_eq!(model.selected, 0, "selection untouched");
    }

    /// Unlike `activate`, folding by path is not a selection move — that is the
    /// whole reason a caller reaches for it.
    #[test]
    fn set_collapsed_folds_by_path_without_moving_the_selection() {
        let mut model = sample_model();
        select(&mut model, &[Seg::Key("title".into())]);

        model.set_collapsed(&[Seg::Key("server".into())], true);
        assert!(model.is_collapsed(&[Seg::Key("server".into())]));
        assert!(
            !model.rows.iter().any(|r| r.path.len() > 1),
            "children hidden"
        );
        assert_eq!(
            model.rows[model.selected].path,
            [Seg::Key("title".into())],
            "selection stayed on title"
        );

        model.set_collapsed(&[Seg::Key("server".into())], false);
        assert!(!model.is_collapsed(&[Seg::Key("server".into())]));
        assert!(
            model
                .rows
                .iter()
                .any(|r| r.path == [Seg::Key("server".into()), Seg::Key("host".into())])
        );
        assert_eq!(model.rows[model.selected].path, [Seg::Key("title".into())]);
    }

    /// The one case where the selection *must* move: it was inside the fold.
    #[test]
    fn set_collapsed_reanchors_a_selection_it_swallowed() {
        let mut model = sample_model();
        select(
            &mut model,
            &[Seg::Key("server".into()), Seg::Key("host".into())],
        );
        model.set_collapsed(&[Seg::Key("server".into())], true);
        assert_eq!(
            model.rows[model.selected].path,
            [Seg::Key("server".into())],
            "landed on the container that swallowed it"
        );
    }

    /// The insert/append counterparts of the type-directed scalar edit: without
    /// them a caller shape-guesses, and `2026` lands in a `str` list as an integer.
    #[test]
    fn insert_and_append_are_type_directed_by_the_schema() {
        use crate::schema::FieldRule;
        use fig_schema::{FieldType, PathPat, Presentation};
        let src = "tags = [\"alpha\"]\n\n[meta]\nk = \"v\"\n";
        let backend = FigBackend::open(src.as_bytes(), Format::Toml).expect("open");
        let mut model = Model::new(backend).expect("model");
        model.set_schema(crate::schema::Schema::new(vec![
            // The *items* of `tags` are strings — the list itself is a seq.
            FieldRule {
                at: PathPat::each_item_of("tags"),
                ty: Some(FieldType::Str),
                constraint: None,
                present: Presentation::default(),
            },
            FieldRule {
                at: PathPat::key("year"),
                ty: Some(FieldType::Str),
                constraint: None,
                present: Presentation::default(),
            },
            FieldRule {
                at: PathPat(vec![
                    fig_schema::SegPat::Key("meta".into()),
                    fig_schema::SegPat::Key("code".into()),
                ]),
                ty: Some(FieldType::Str),
                constraint: None,
                present: Presentation::default(),
            },
        ]));

        model.append_item_text(&[Seg::Key("tags".into())], "2026");
        model.insert_key_text(&[], "year", "2026");
        // The nested case flower-ffi and Diaryx both shape-guessed.
        model.insert_key_text(&[Seg::Key("meta".into())], "code", "2026");

        let out = model.source_snapshot();
        assert!(
            !out.contains("2026,") && !out.contains("[2026]") && !out.contains("= 2026"),
            "no bare integers survived the schema:\n{out}"
        );
        assert_eq!(
            model.value_at(&[Seg::Key("tags".into()), Seg::Index(1)]),
            Some(&Value::Str("2026".into())),
            "list item took the each-item type:\n{out}"
        );
        assert_eq!(
            model.value_at(&[Seg::Key("year".into())]),
            Some(&Value::Str("2026".into()))
        );
        assert_eq!(
            model.value_at(&[Seg::Key("meta".into()), Seg::Key("code".into())]),
            Some(&Value::Str("2026".into()))
        );
    }

    /// With no rule to consult they fall back to the same shape-guessing the raw
    /// `insert_key`/`append_item` callers do today, so a standalone config is
    /// unaffected.
    #[test]
    fn insert_and_append_text_shape_guess_without_a_schema() {
        let mut model = sample_model();
        model.append_item_text(&[Seg::Key("server".into()), Seg::Key("tags".into())], "42");
        model.insert_key_text(&[], "count", "7");
        assert_eq!(
            model.value_at(&[
                Seg::Key("server".into()),
                Seg::Key("tags".into()),
                Seg::Index(2)
            ]),
            Some(&Value::Int(42))
        );
        assert_eq!(
            model.value_at(&[Seg::Key("count".into())]),
            Some(&Value::Int(7))
        );
    }

    /// The walkers a backend needs, over a plain `Value` — no `Model` in reach.
    #[test]
    fn tree_walkers_resolve_paths_and_reject_mismatches() {
        let model = sample_model();
        let root = model.value_at(&[]).expect("root");

        assert_eq!(
            tree::value_at(root, &[Seg::Key("server".into()), Seg::Key("port".into())]),
            Some(&Value::Int(8080))
        );
        assert_eq!(
            tree::seq_len(root, &[Seg::Key("server".into()), Seg::Key("tags".into())]),
            Some(2)
        );
        // Not a sequence, versus not there at all — both `None`, and neither is a
        // length of zero a caller could mistake for an empty list.
        assert_eq!(tree::seq_len(root, &[Seg::Key("title".into())]), None);
        assert_eq!(tree::seq_len(root, &[Seg::Key("absent".into())]), None);
        assert_eq!(
            tree::map_keys(root, &[Seg::Key("server".into())]),
            Some(vec![
                "host".to_string(),
                "port".to_string(),
                "tags".to_string(),
                "limits".to_string()
            ])
        );
        assert_eq!(tree::map_keys(root, &[Seg::Key("title".into())]), None);
        // A key step into a sequence resolves to nothing rather than guessing.
        assert_eq!(
            tree::value_at(
                root,
                &[
                    Seg::Key("server".into()),
                    Seg::Key("tags".into()),
                    Seg::Key("0".into())
                ]
            ),
            None
        );
    }

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

        select(&mut model, &[Seg::Key("server".into())]);
        model.collapse_or_leave();
        assert!(
            !model
                .rows
                .iter()
                .any(|r| r.path == [Seg::Key("server".into()), Seg::Key("host".into())]),
            "collapsed children hidden"
        );
        assert_eq!(model.rows[model.selected].path, [Seg::Key("server".into())]);
    }
}