sirno 0.0.6

Sirno gives project design a semantic intermediate representation.
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
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
//! Sirno entry model and Markdown frontmatter syntax.
//!
//! An entry is the Sirno Lake unit of Sirno design storage.
//! The prose body carries design content.
//! The metadata block carries structure that tools read exactly.

use std::collections::BTreeSet;

use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use serde_yaml::{Mapping, Value};
use thiserror::Error;

use crate::identifier::{EntryAddress, EntryAddressError};
use crate::meta::MetaRegistry;
use crate::structural::{StructuralEdgeDirection, StructuralTideSettings};

pub const NAME_FIELD: &str = "name";
pub const DESC_FIELD: &str = "desc";
pub const META_FIELD: &str = "meta";
pub const FROZEN_FIELD: &str = "frozen";
pub const META_TYPE_FIELD: &str = "meta.type";
pub const META_RIPPLE_LAKE_FIELD: &str = "meta.ripple.lake";
pub const META_RIPPLE_ANCHOR_FIELD: &str = "meta.ripple.anchor";
pub const STRUCTURAL_META_TYPE: &str = "structural";
pub const INTRINSIC_META_TYPE: &str = "intrinsic";

// sirno:witness:entry:begin
/// One Sirno entry.
///
/// Invariant: `id` is a valid entry address.
/// `metadata` contains typed entry metadata.
/// `body` is normal Markdown prose outside the metadata block.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Entry {
    /// Lookup path for this entry.
    pub id: EntryAddress,
    /// Typed metadata read from the YAML block.
    pub metadata: EntryMetadata,
    /// Markdown body after the metadata block.
    pub body: String,
}
// sirno:witness:entry:end

impl Entry {
    /// Construct an entry from already typed parts.
    // sirno:witness:entry:begin
    pub fn new(
        id: impl Into<EntryAddress>, metadata: EntryMetadata, body: impl Into<String>,
    ) -> Self {
        Self { id: id.into(), metadata, body: body.into() }
    }
    // sirno:witness:entry:end

    /// Parse an entry from Markdown source with LF or CRLF line endings.
    ///
    /// Sirno accepts mixed line endings so tooling can still inspect the file.
    /// Lake checks warn when one file mixes LF and CRLF.
    // sirno:witness:entry:begin
    pub fn from_markdown(
        id: impl Into<EntryAddress>, source: &str,
    ) -> Result<Self, EntryParseError> {
        Self::from_markdown_with_registry(id, source, &MetaRegistry::standard())
    }

    /// Parse an entry from Markdown source with a discovered meta registry.
    pub fn from_markdown_with_registry(
        id: impl Into<EntryAddress>, source: &str, registry: &MetaRegistry,
    ) -> Result<Self, EntryParseError> {
        RawEntry::from_markdown(id, source)?.into_entry(registry)
    }
    // sirno:witness:entry:end

    /// Render this entry to canonical Markdown source.
    // sirno:witness:entry:begin
    pub fn to_markdown(&self) -> Result<String, EntryRenderError> {
        Ok(format!("---\n{}---\n\n{}", self.metadata.to_yaml_source()?, self.body))
    }
    // sirno:witness:entry:end

    /// Replace the Markdown body in an existing entry source.
    ///
    /// The frontmatter region and its separator are preserved exactly.
    // sirno:witness:entry:begin
    pub fn replace_markdown_body(source: &str, body: &str) -> Result<String, EntryParseError> {
        let body_start = frontmatter_body_start(source)?;
        Ok(format!("{}{}", &source[..body_start], body))
    }
    // sirno:witness:entry:end

    /// Create the ordinary seed entries for a new Sirno Lake.
    ///
    /// The entries are normal entries.
    /// Later operations do not privilege them.
    pub fn default_seed_entries() -> Result<Vec<Self>, EntryParseError> {
        // sirno:witness:name:begin
        let mut name =
            EntryMetadata::new("Name", "The required plain-string title field for entries.")?;
        name.meta.entry_type = Some(EntryMetaType::Intrinsic);
        // sirno:witness:name:end

        // sirno:witness:desc:begin
        let mut desc = EntryMetadata::new(
            "Description",
            "The required plain-string summary field for entries.",
        )?;
        desc.meta.entry_type = Some(EntryMetaType::Intrinsic);
        // sirno:witness:desc:end

        // sirno:witness:category:begin
        let category =
            EntryMetadata::new("Category", "An entry that other entries can be categorized by.")?;
        // sirno:witness:category:end

        // sirno:witness:meta:begin
        let meta = EntryMetadata::new(
            "Meta",
            "An entry that defines the project's principles, vocabulary, and documentation method.",
        )?;
        // sirno:witness:meta:end

        // sirno:witness:concept:begin
        let concept =
            EntryMetadata::new("Concept", "A named idea that compresses project knowledge.")?;
        // sirno:witness:concept:end

        // sirno:witness:narrative:begin
        let narrative = EntryMetadata::new("Narrative", "A route through concepts for a reader.")?;
        // sirno:witness:narrative:end

        Ok(vec![
            Self::new(
                seed_id("name"),
                name,
                "The required `name` metadata field gives an entry its reader-facing title.\n",
            ),
            Self::new(
                seed_id("desc"),
                desc,
                "The required `desc` metadata field gives an entry its compact summary.\n",
            ),
            Self::new(
                seed_id("category"),
                category,
                "Categorize an entry by this entry to use it as a category target.\n",
            ),
            Self::new(
                seed_id("meta"),
                meta,
                "Defines how this project should be understood and developed.\n",
            ),
            Self::new(
                seed_id("concept"),
                concept,
                "A concept gives a stable name to compressed project knowledge.\n",
            ),
            Self::new(
                seed_id("narrative"),
                narrative,
                "A narrative records an order in which a reader can understand concepts.\n",
            ),
        ])
    }
}

/// Raw entry frontmatter and body before typed metadata resolution.
///
/// This form parses only the Markdown and YAML container shape.
/// It lets Sirno discover meta-level declarations before typed entry parsing.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RawEntry {
    /// Lookup path for this entry.
    pub id: EntryAddress,
    metadata: Mapping,
    /// Markdown body after the metadata block.
    pub body: String,
}

impl RawEntry {
    /// Parse raw entry frontmatter and body.
    pub fn from_markdown(
        id: impl Into<EntryAddress>, source: &str,
    ) -> Result<Self, EntryParseError> {
        let (metadata_source, body) = split_frontmatter(source)?;
        let metadata = parse_metadata_mapping(metadata_source)?;
        Ok(Self { id: id.into(), metadata, body })
    }

    /// Return the flat `meta.type` value when it is present and valid.
    pub fn meta_type(&self) -> Result<Option<EntryMetaType>, EntryParseError> {
        parse_flat_meta_type_value(self.metadata.get(Value::String(META_TYPE_FIELD.to_owned())))
    }

    /// Return Sirno-managed metadata without resolving intrinsic or structural fields.
    pub fn entry_meta(&self) -> Result<EntryMeta, EntryParseError> {
        let mut mapping = self.metadata.clone();
        if mapping.contains_key(Value::String(FROZEN_FIELD.to_owned())) {
            return Err(EntryParseError::TopLevelFrozenMarker);
        }
        let mut meta = take_entry_meta(&mut mapping)?;
        meta.entry_type = take_flat_meta_type(&mut mapping)?;
        meta.tide = take_flat_structural_tide_settings(&mut mapping, meta.entry_type)?;
        Ok(meta)
    }

    /// Convert this raw entry into typed entry data using discovered meta knowledge.
    pub fn into_entry(self, registry: &MetaRegistry) -> Result<Entry, EntryParseError> {
        let metadata = EntryMetadata::from_mapping(self.metadata, registry)?;
        Ok(Entry::new(self.id, metadata, self.body))
    }
}

/// Ordered structural link metadata for one entry.
pub type EntryStructuralFields = IndexMap<String, Vec<EntryAddress>>;

/// Ordered intrinsic metadata fields for one entry.
pub type EntryIntrinsicFields = IndexMap<String, String>;

/// Metadata for one Sirno entry.
///
/// Invariant: intrinsic values are single-line plain strings.
/// `meta` carries Sirno-managed optional metadata.
/// Structural links map relation names to entry-path targets.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EntryMetadata {
    /// Intrinsic metadata fields keyed by their Markdown field name.
    pub intrinsic: EntryIntrinsicFields,
    /// Sirno-managed metadata fields.
    pub meta: EntryMeta,
    // sirno:witness:structural:begin
    /// Structural link targets keyed by their Markdown metadata field name.
    ///
    /// Relation order follows the user-authored metadata order and is preserved when entries move
    /// through other storage forms.
    pub structural: EntryStructuralFields,
    // sirno:witness:structural:end
}

impl EntryMetadata {
    /// Construct metadata with required fields and no structural link values.
    // sirno:witness:metadata:begin
    pub fn new(name: impl Into<String>, desc: impl Into<String>) -> Result<Self, EntryParseError> {
        let name = name.into();
        let desc = desc.into();
        validate_plain_string(NAME_FIELD, &name)?;
        validate_plain_string(DESC_FIELD, &desc)?;
        let mut intrinsic = EntryIntrinsicFields::new();
        intrinsic.insert(NAME_FIELD.to_owned(), name);
        intrinsic.insert(DESC_FIELD.to_owned(), desc);
        Ok(Self { intrinsic, meta: EntryMeta::default(), structural: EntryStructuralFields::new() })
    }
    // sirno:witness:metadata:end

    /// Parse metadata from YAML source without surrounding `---` sentinels.
    // sirno:witness:metadata:begin
    pub fn from_yaml_source(source: &str) -> Result<Self, EntryParseError> {
        Self::from_yaml_source_with_registry(source, &MetaRegistry::standard())
    }

    /// Parse metadata from YAML source with a discovered meta registry.
    pub fn from_yaml_source_with_registry(
        source: &str, registry: &MetaRegistry,
    ) -> Result<Self, EntryParseError> {
        let mapping = parse_metadata_mapping(source)?;
        Self::from_mapping(mapping, registry)
    }

    pub(crate) fn from_mapping(
        mut mapping: Mapping, registry: &MetaRegistry,
    ) -> Result<Self, EntryParseError> {
        let mut intrinsic = EntryIntrinsicFields::new();
        for (field, _) in registry.intrinsic_fields() {
            let value = take_required_string(&mut mapping, field)?;
            validate_plain_string(field, &value)?;
            intrinsic.insert(field.to_owned(), value);
        }

        if mapping.contains_key(Value::String(FROZEN_FIELD.to_owned())) {
            return Err(EntryParseError::TopLevelFrozenMarker);
        }
        let mut meta = take_entry_meta(&mut mapping)?;
        meta.entry_type = take_flat_meta_type(&mut mapping)?;
        meta.tide = take_flat_structural_tide_settings(&mut mapping, meta.entry_type)?;
        let structural = take_structural_fields(mapping)?;

        Ok(Self { intrinsic, meta, structural })
    }
    // sirno:witness:metadata:end

    /// Render this metadata block to canonical YAML source.
    // sirno:witness:metadata:begin
    pub fn to_yaml_source(&self) -> Result<String, EntryRenderError> {
        for (field, value) in &self.intrinsic {
            validate_plain_string(field, value)?;
        }

        let mut out = String::new();
        for (field, value) in &self.intrinsic {
            out.push_str(&format!("{field}: {}\n", render_yaml_scalar(value)?));
        }
        render_entry_meta(&mut out, &self.meta);
        render_structural_fields(&mut out, &self.structural)?;
        Ok(out)
    }
    // sirno:witness:metadata:end

    /// Returns every entry address mentioned by structural links.
    // sirno:witness:metadata:begin
    pub fn structural_targets(&self) -> impl Iterator<Item = (&str, &EntryAddress)> {
        self.structural
            .iter()
            .flat_map(|(field, targets)| targets.iter().map(move |id| (field.as_str(), id)))
    }
    // sirno:witness:metadata:end

    /// Return link relation names and their targets in user-authored order.
    pub fn structural_fields(&self) -> impl Iterator<Item = (&str, &[EntryAddress])> {
        self.structural.iter().map(|(field, targets)| (field.as_str(), targets.as_slice()))
    }

    /// Return targets for one link relation.
    pub fn structural_targets_for(&self, field: &str) -> &[EntryAddress] {
        self.structural.get(field).map(Vec::as_slice).unwrap_or_default()
    }

    /// Return targets for one link relation while preserving field presence.
    ///
    /// `None` means the field is absent.
    /// `Some([])` means the field is present and has no targets.
    pub fn structural_field(&self, field: &str) -> Option<&[EntryAddress]> {
        self.structural.get(field).map(Vec::as_slice)
    }

    /// Return a mutable target list for one link relation.
    pub fn structural_targets_for_mut(
        &mut self, field: impl Into<String>,
    ) -> &mut Vec<EntryAddress> {
        self.structural.entry(field.into()).or_default()
    }

    /// Return one intrinsic metadata value.
    pub fn intrinsic_field(&self, field: &str) -> Option<&str> {
        self.intrinsic.get(field).map(String::as_str)
    }

    /// Iterate intrinsic metadata fields in stored order.
    pub fn intrinsic_fields(&self) -> impl Iterator<Item = (&str, &str)> {
        self.intrinsic.iter().map(|(field, value)| (field.as_str(), value.as_str()))
    }

    /// Human-readable entry name used by current Sirno surfaces.
    pub fn name(&self) -> &str {
        self.intrinsic_field(NAME_FIELD).unwrap_or("")
    }

    /// Short prose summary used by current Sirno surfaces.
    pub fn desc(&self) -> &str {
        self.intrinsic_field(DESC_FIELD).unwrap_or("")
    }

    /// Set the targets for one link relation.
    ///
    /// An empty target list records a present empty field.
    pub fn set_structural_targets(
        &mut self, field: impl Into<String>, targets: impl IntoIterator<Item = EntryAddress>,
    ) {
        self.structural.insert(field.into(), targets.into_iter().collect::<Vec<_>>());
    }

    /// Add one target to one link relation.
    pub fn push_structural_target(
        &mut self, field: impl Into<String>, target: impl Into<EntryAddress>,
    ) {
        self.structural_targets_for_mut(field).push(target.into());
    }

    /// Rename every structural link target that matches `old_id`.
    pub fn rename_structural_target(
        &mut self, old_id: &EntryAddress, new_id: &EntryAddress,
    ) -> bool {
        let mut changed = false;
        for targets in self.structural.values_mut() {
            for target in targets {
                if target == old_id {
                    *target = new_id.clone();
                    changed = true;
                }
            }
        }
        changed
    }

    /// Rename one structural link relation.
    ///
    /// The field stays in its original order position.
    pub fn rename_structural_field(
        &mut self, old_id: &EntryAddress, new_id: &EntryAddress,
    ) -> bool {
        let old_field = old_id.as_str();
        if !self.structural.contains_key(old_field) {
            return false;
        }

        let mut renamed = EntryStructuralFields::with_capacity(self.structural.len());
        for (field, targets) in std::mem::take(&mut self.structural) {
            if field == old_field {
                renamed.insert(new_id.as_str().to_owned(), targets);
            } else {
                renamed.insert(field, targets);
            }
        }
        self.structural = renamed;
        true
    }
}

/// Sirno-managed metadata for one entry.
///
/// Empty managed metadata is omitted from rendered entry frontmatter.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct EntryMeta {
    /// Freeze reasons declaring that this Sirno Lake entry file is protected.
    pub frozen: Option<FrozenMarker>,
    /// Entry role for Sirno-managed flat metadata.
    pub entry_type: Option<EntryMetaType>,
    /// Tide policy for a structural relation defined by this entry.
    pub tide: Option<StructuralTideSettings>,
}

impl EntryMeta {
    /// Return whether no managed metadata is set.
    pub fn is_empty(&self) -> bool {
        self.frozen.is_none() && self.entry_type.is_none() && self.tide.is_none()
    }

    /// Return true when this entry declares a structural-relation type.
    pub fn is_structural_relation(&self) -> bool {
        self.entry_type == Some(EntryMetaType::Structural)
    }

    /// Return true when this entry declares an intrinsic metadata-field type.
    pub fn is_intrinsic_field(&self) -> bool {
        self.entry_type == Some(EntryMetaType::Intrinsic)
    }
}

/// Sirno-managed entry type stored in the flat `meta.type` field.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum EntryMetaType {
    /// Entry defines one structural relation.
    Structural,
    /// Entry defines one intrinsic Sirno metadata field.
    Intrinsic,
}

/// Protection reasons stored in the canonical `meta.frozen` metadata field.
///
/// Invariant: the reason set is non-empty.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrozenMarker {
    reasons: BTreeSet<FrozenReason>,
}

impl FrozenMarker {
    /// Construct a marker for a reviewed entry.
    pub fn reviewed() -> Self {
        Self::from_reason(FrozenReason::Reviewed)
    }

    /// Construct a marker for a managed entry.
    pub fn managed() -> Self {
        Self::from_reason(FrozenReason::Managed)
    }

    /// Return whether this marker includes `reviewed`.
    pub fn is_reviewed(&self) -> bool {
        self.reasons.contains(&FrozenReason::Reviewed)
    }

    /// Return whether this marker includes `managed`.
    pub fn is_managed(&self) -> bool {
        self.reasons.contains(&FrozenReason::Managed)
    }

    /// Add `reviewed` to this marker.
    pub fn insert_reviewed(&mut self) {
        self.reasons.insert(FrozenReason::Reviewed);
    }

    /// Add `managed` to this marker.
    pub fn insert_managed(&mut self) {
        self.reasons.insert(FrozenReason::Managed);
    }

    /// Remove `reviewed` from this marker.
    ///
    /// Returns true when at least one protection reason remains.
    pub fn remove_reviewed(&mut self) -> bool {
        self.reasons.remove(&FrozenReason::Reviewed);
        !self.reasons.is_empty()
    }

    /// Iterate over reasons in canonical render order.
    pub fn reasons(&self) -> impl Iterator<Item = FrozenReason> + '_ {
        [FrozenReason::Reviewed, FrozenReason::Managed]
            .into_iter()
            .filter(|reason| self.reasons.contains(reason))
    }

    fn from_reason(reason: FrozenReason) -> Self {
        let mut reasons = BTreeSet::new();
        reasons.insert(reason);
        Self { reasons }
    }
}

/// One reason why a Sirno entry is protected.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum FrozenReason {
    /// The entry matches the accepted anchor.
    Reviewed,
    /// The entry is owned by crystallization.
    Managed,
}

fn seed_id(raw: &str) -> EntryAddress {
    EntryAddress::new(raw)
        .unwrap_or_else(|error| panic!("invalid built-in seed path `{raw}`: {error}"))
}

/// Byte ranges for one Markdown frontmatter block.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct FrontmatterBounds {
    /// First byte after the opening fence line.
    metadata_start: usize,
    /// First byte after metadata text, before the closing fence line.
    metadata_end: usize,
    /// First byte of the Markdown body after the optional blank separator.
    body_start: usize,
}

impl FrontmatterBounds {
    /// Locate the frontmatter block while preserving source byte offsets.
    fn parse(source: &str) -> Result<Self, EntryParseError> {
        let opening_line =
            source.split_inclusive('\n').next().ok_or(EntryParseError::MissingFrontmatter)?;
        if !opening_line.ends_with('\n') || line_text(opening_line) != "---" {
            return Err(EntryParseError::MissingFrontmatter);
        }

        let metadata_start = opening_line.len();
        let mut metadata_end = metadata_start;
        let mut cursor = metadata_start;

        for line in source[metadata_start..].split_inclusive('\n') {
            if line.ends_with('\n') && line_text(line) == "---" {
                let body_start =
                    cursor + line.len() + line_break_len_at(&source[cursor + line.len()..]);
                return Ok(Self { metadata_start, metadata_end, body_start });
            }

            if !line.ends_with('\n') {
                break;
            }

            metadata_end = cursor + line.len() - line_ending_len(line);
            cursor += line.len();
        }

        Err(EntryParseError::UnterminatedFrontmatter)
    }
}

fn split_frontmatter(source: &str) -> Result<(&str, String), EntryParseError> {
    let bounds = FrontmatterBounds::parse(source)?;
    Ok((bounds.metadata(source), bounds.body(source).to_owned()))
}

fn frontmatter_body_start(source: &str) -> Result<usize, EntryParseError> {
    Ok(FrontmatterBounds::parse(source)?.body_start)
}

impl FrontmatterBounds {
    fn metadata(self, source: &str) -> &str {
        &source[self.metadata_start..self.metadata_end]
    }

    fn body(self, source: &str) -> &str {
        &source[self.body_start..]
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum LineEnding {
    Lf,
    Crlf,
}

/// Return true when one source uses both LF-only and CRLF line endings.
pub(crate) fn has_mixed_line_endings(source: &str) -> bool {
    let mut first = None;
    for line in source.split_inclusive('\n') {
        let Some(ending) = line_ending(line) else {
            continue;
        };
        if let Some(first) = first {
            if first != ending {
                return true;
            }
        } else {
            first = Some(ending);
        }
    }
    false
}

fn line_text(line: &str) -> &str {
    match line_ending(line) {
        | Some(LineEnding::Crlf) => &line[..line.len() - "\r\n".len()],
        | Some(LineEnding::Lf) => &line[..line.len() - "\n".len()],
        | None => line,
    }
}

fn line_ending_len(line: &str) -> usize {
    match line_ending(line) {
        | Some(LineEnding::Crlf) => "\r\n".len(),
        | Some(LineEnding::Lf) => "\n".len(),
        | None => 0,
    }
}

fn line_break_len_at(source: &str) -> usize {
    if source.starts_with("\r\n") {
        "\r\n".len()
    } else if source.starts_with('\n') {
        "\n".len()
    } else {
        0
    }
}

fn line_ending(line: &str) -> Option<LineEnding> {
    if line.ends_with("\r\n") {
        Some(LineEnding::Crlf)
    } else if line.ends_with('\n') {
        Some(LineEnding::Lf)
    } else {
        None
    }
}

fn parse_metadata_mapping(source: &str) -> Result<Mapping, EntryParseError> {
    let value: Value = serde_yaml::from_str(source).map_err(EntryParseError::Yaml)?;
    match value {
        | Value::Mapping(mapping) => Ok(mapping),
        | _ => Err(EntryParseError::MetadataMustBeMapping),
    }
}

fn take_required_string(mapping: &mut Mapping, field: &str) -> Result<String, EntryParseError> {
    let value = mapping
        .shift_remove(Value::String(field.to_owned()))
        .ok_or_else(|| EntryParseError::MissingField(field.to_owned()))?;
    match value {
        | Value::String(value) => Ok(value),
        | _ => Err(EntryParseError::FieldMustBeString(field.to_owned())),
    }
}

fn take_structural_fields(mapping: Mapping) -> Result<EntryStructuralFields, EntryParseError> {
    let mut structural = EntryStructuralFields::new();
    for (key, value) in mapping {
        let Value::String(field) = key else {
            return Err(EntryParseError::MetadataKeyMustBeString);
        };
        structural.insert(field.clone(), parse_id_list(field, value)?);
    }
    Ok(structural)
}

fn take_entry_meta(mapping: &mut Mapping) -> Result<EntryMeta, EntryParseError> {
    let Some(value) = mapping.shift_remove(Value::String(META_FIELD.to_owned())) else {
        return Ok(EntryMeta::default());
    };
    let Value::Mapping(mut meta_mapping) = value else {
        return Err(EntryParseError::MetaMustBeMapping);
    };

    let frozen = take_meta_frozen_marker(&mut meta_mapping)?;
    if let Some((key, _)) = meta_mapping.into_iter().next() {
        let Value::String(field) = key else {
            return Err(EntryParseError::MetaKeyMustBeString);
        };
        return Err(EntryParseError::UnknownMetaField(field));
    }

    Ok(EntryMeta { frozen, entry_type: None, tide: None })
}

fn parse_id_list(field: String, value: Value) -> Result<Vec<EntryAddress>, EntryParseError> {
    let Value::Sequence(values) = value else {
        return Err(EntryParseError::FieldMustBeList(field));
    };

    values
        .into_iter()
        .map(|value| match value {
            | Value::String(raw) => EntryAddress::new(&raw).map_err(|source| {
                EntryParseError::InvalidStructuralId { field: field.clone(), value: raw, source }
            }),
            | _ => Err(EntryParseError::ListItemMustBeString(field.clone())),
        })
        .collect()
}

fn take_meta_frozen_marker(mapping: &mut Mapping) -> Result<Option<FrozenMarker>, EntryParseError> {
    let Some(value) = mapping.shift_remove(Value::String(FROZEN_FIELD.to_owned())) else {
        return Ok(None);
    };
    parse_frozen_marker_value(value).map(Some)
}

fn take_flat_meta_type(mapping: &mut Mapping) -> Result<Option<EntryMetaType>, EntryParseError> {
    let Some(value) = mapping.shift_remove(Value::String(META_TYPE_FIELD.to_owned())) else {
        return Ok(None);
    };
    parse_flat_meta_type_value(Some(&value))
}

fn parse_flat_meta_type_value(
    value: Option<&Value>,
) -> Result<Option<EntryMetaType>, EntryParseError> {
    match value {
        | None => Ok(None),
        | Some(Value::String(raw)) if raw == STRUCTURAL_META_TYPE => {
            Ok(Some(EntryMetaType::Structural))
        }
        | Some(Value::String(raw)) if raw == INTRINSIC_META_TYPE => {
            Ok(Some(EntryMetaType::Intrinsic))
        }
        | _ => Err(EntryParseError::InvalidMetaType),
    }
}

fn take_flat_structural_tide_settings(
    mapping: &mut Mapping, entry_type: Option<EntryMetaType>,
) -> Result<Option<StructuralTideSettings>, EntryParseError> {
    let keys = mapping
        .keys()
        .filter_map(|key| match key {
            | Value::String(field) if field.starts_with("meta.") => Some(field.clone()),
            | _ => None,
        })
        .collect::<Vec<_>>();
    let mut settings = None;
    for field in keys {
        let value = mapping
            .shift_remove(Value::String(field.clone()))
            .expect("metadata key was collected from this mapping");
        parse_flat_structural_tide_field(&mut settings, &field, value, entry_type)?;
    }
    Ok(settings)
}

fn parse_flat_structural_tide_field(
    settings: &mut Option<StructuralTideSettings>, field: &str, value: Value,
    entry_type: Option<EntryMetaType>,
) -> Result<(), EntryParseError> {
    let meta_field =
        field.strip_prefix("meta.").expect("flat structural tide field has meta prefix");
    let parts = meta_field.split('.').collect::<Vec<_>>();
    match parts.as_slice() {
        | ["ripple", line @ ("lake" | "anchor")] => {
            if entry_type != Some(EntryMetaType::Structural) {
                return Err(EntryParseError::StructuralTideWithoutType(field.to_owned()));
            }
            for direction in parse_tide_direction_list_field(field, value)? {
                set_structural_tide_setting(
                    settings.get_or_insert_with(StructuralTideSettings::default),
                    line,
                    direction,
                    true,
                );
            }
            settings.get_or_insert_with(StructuralTideSettings::default);
            Ok(())
        }
        | _ => Err(EntryParseError::UnknownMetaField(meta_field.to_owned())),
    }
}

fn parse_tide_direction_list_field(
    field: &str, value: Value,
) -> Result<Vec<StructuralEdgeDirection>, EntryParseError> {
    let Value::Sequence(values) = value else {
        return Err(EntryParseError::InvalidStructuralTideField(field.to_owned()));
    };
    let mut directions = Vec::new();
    for value in values {
        let Value::String(raw) = value else {
            return Err(EntryParseError::InvalidStructuralTideField(field.to_owned()));
        };
        let direction = raw
            .parse::<StructuralEdgeDirection>()
            .map_err(|_| EntryParseError::InvalidStructuralTideField(field.to_owned()))?;
        if directions.contains(&direction) {
            return Err(EntryParseError::InvalidStructuralTideField(field.to_owned()));
        }
        directions.push(direction);
    }
    Ok(directions)
}

fn set_structural_tide_setting(
    settings: &mut StructuralTideSettings, line: &str, direction: StructuralEdgeDirection,
    enabled: bool,
) {
    let ripple = match direction {
        | StructuralEdgeDirection::To => &mut settings.to,
        | StructuralEdgeDirection::From => &mut settings.from,
        | StructuralEdgeDirection::Clique => &mut settings.clique,
    };
    match line {
        | "lake" => ripple.lake = enabled,
        | "anchor" => ripple.anchor = enabled,
        | _ => unreachable!("line was parsed before setting tide value"),
    }
}

fn parse_frozen_marker_value(value: Value) -> Result<FrozenMarker, EntryParseError> {
    let Value::Sequence(values) = value else {
        return Err(EntryParseError::InvalidFrozenMarker);
    };
    if values.is_empty() {
        return Err(EntryParseError::InvalidFrozenMarker);
    }

    let mut reasons = BTreeSet::new();
    for value in values {
        let Value::String(raw) = value else {
            return Err(EntryParseError::InvalidFrozenMarker);
        };
        let reason = match raw.as_str() {
            | "reviewed" => FrozenReason::Reviewed,
            | "managed" => FrozenReason::Managed,
            | _ => return Err(EntryParseError::InvalidFrozenMarker),
        };
        if !reasons.insert(reason) {
            return Err(EntryParseError::InvalidFrozenMarker);
        }
    }
    Ok(FrozenMarker { reasons })
}

fn validate_plain_string(field: &str, value: &str) -> Result<(), EntryParseError> {
    if value.contains('\n') || value.contains('\r') {
        return Err(EntryParseError::FieldMustBePlainString(field.to_owned()));
    }
    Ok(())
}

fn render_id_list(
    out: &mut String, field: &str, values: &[EntryAddress],
) -> Result<(), EntryRenderError> {
    if values.is_empty() {
        out.push_str(field);
        out.push_str(": []\n");
        return Ok(());
    }
    out.push_str(field);
    out.push_str(":\n");
    for id in values {
        out.push_str("  - ");
        out.push_str(&render_yaml_scalar(id.as_str())?);
        out.push('\n');
    }
    Ok(())
}

fn render_structural_fields(
    out: &mut String, structural: &EntryStructuralFields,
) -> Result<(), EntryRenderError> {
    for (field, values) in structural {
        render_id_list(out, field, values)?;
    }
    Ok(())
}

fn render_entry_meta(out: &mut String, meta: &EntryMeta) {
    if meta.is_empty() {
        return;
    }

    if let Some(marker) = &meta.frozen {
        out.push_str("meta:\n");
        render_meta_frozen_marker(out, marker);
    }
    if let Some(entry_type) = meta.entry_type {
        render_flat_meta_type(out, entry_type);
    }
    if let Some(tide) = &meta.tide {
        render_flat_structural_tide_settings(out, tide);
    }
}

fn render_meta_frozen_marker(out: &mut String, marker: &FrozenMarker) {
    out.push_str("  frozen:\n");
    for reason in marker.reasons() {
        out.push_str("    - ");
        out.push_str(match reason {
            | FrozenReason::Reviewed => "reviewed",
            | FrozenReason::Managed => "managed",
        });
        out.push('\n');
    }
}

fn render_flat_meta_type(out: &mut String, entry_type: EntryMetaType) {
    out.push_str(META_TYPE_FIELD);
    out.push_str(": ");
    out.push_str(match entry_type {
        | EntryMetaType::Structural => "\"structural\"",
        | EntryMetaType::Intrinsic => "\"intrinsic\"",
    });
    out.push('\n');
}

fn render_flat_structural_tide_settings(out: &mut String, settings: &StructuralTideSettings) {
    render_flat_structural_tide_line(
        out,
        "lake",
        settings.to.lake,
        settings.from.lake,
        settings.clique.lake,
    );
    render_flat_structural_tide_line(
        out,
        "anchor",
        settings.to.anchor,
        settings.from.anchor,
        settings.clique.anchor,
    );
}

fn render_flat_structural_tide_line(
    out: &mut String, line: &str, to: bool, from: bool, clique: bool,
) {
    out.push_str("meta.ripple.");
    out.push_str(line);
    out.push_str(": [");
    let mut first = true;
    for (direction, enabled) in [("to", to), ("from", from), ("clique", clique)] {
        if enabled {
            if !first {
                out.push_str(", ");
            }
            first = false;
            out.push('"');
            out.push_str(direction);
            out.push('"');
        }
    }
    out.push_str("]\n");
}

fn render_yaml_scalar(value: &str) -> Result<String, EntryRenderError> {
    let mut rendered = serde_yaml::to_string(value).map_err(EntryRenderError::Yaml)?;
    if let Some(stripped) = rendered.strip_suffix("\n...\n") {
        rendered = stripped.to_owned();
    }
    Ok(rendered.trim_end_matches('\n').to_owned())
}

/// Error raised when entry Markdown cannot be parsed into the Sirno model.
#[derive(Debug, Error)]
pub enum EntryParseError {
    /// The entry source does not start with a frontmatter block.
    #[error("entry is missing a YAML metadata block")]
    MissingFrontmatter,
    /// The entry source has an opening metadata block without a closing sentinel.
    #[error("entry metadata block is not closed")]
    UnterminatedFrontmatter,
    /// YAML metadata failed to parse.
    #[error("invalid YAML metadata: {0}")]
    Yaml(serde_yaml::Error),
    /// The YAML metadata root must be a mapping.
    #[error("entry metadata must be a mapping")]
    MetadataMustBeMapping,
    /// Metadata keys must be strings.
    #[error("entry metadata keys must be strings")]
    MetadataKeyMustBeString,
    /// The managed meta field must be a YAML mapping.
    #[error("metadata field `meta` must be a mapping")]
    MetaMustBeMapping,
    /// Managed meta keys must be strings.
    #[error("metadata field `meta` keys must be strings")]
    MetaKeyMustBeString,
    /// A managed meta field is not supported.
    #[error("unknown Sirno-managed metadata field `meta.{0}`")]
    UnknownMetaField(String),
    /// The flat meta type field has an invalid value.
    #[error("metadata field `meta.type` must be \"structural\" or \"intrinsic\"")]
    InvalidMetaType,
    /// Structural tide metadata requires the structural meta type.
    #[error("metadata field `{0}` requires `meta.type: \"structural\"`")]
    StructuralTideWithoutType(String),
    /// A required field is absent.
    #[error("missing required metadata field `{0}`")]
    MissingField(String),
    /// A required string field has another YAML type.
    #[error("metadata field `{0}` must be a string")]
    FieldMustBeString(String),
    /// A string field is not a single-line plain string.
    #[error("metadata field `{0}` must be a single-line plain string")]
    FieldMustBePlainString(String),
    /// A structural link relation is not a YAML list.
    #[error("metadata field `{0}` must be a list")]
    FieldMustBeList(String),
    /// A structural list item is not a string.
    #[error("items in metadata field `{0}` must be strings")]
    ListItemMustBeString(String),
    /// A structural link target is not a valid entry address.
    #[error("metadata field `{field}` contains invalid entry address `{value}`")]
    InvalidStructuralId {
        /// Link relation containing the invalid path.
        field: String,
        /// Invalid raw path.
        value: String,
        /// Entry address validation error.
        #[source]
        source: EntryAddressError,
    },
    /// The frozen field is present with invalid protection reasons.
    #[error("metadata field `meta.frozen` must be a non-empty list of reviewed or managed reasons")]
    InvalidFrozenMarker,
    /// A flat tide metadata field has an invalid value.
    #[error("metadata field `{0}` must be a list of to, from, and clique tide directions")]
    InvalidStructuralTideField(String),
    /// The old top-level frozen field is no longer valid.
    #[error("metadata field `frozen` moved to `meta.frozen`")]
    TopLevelFrozenMarker,
}

/// Error raised when typed entry data cannot be rendered.
#[derive(Debug, Error)]
pub enum EntryRenderError {
    /// The entry metadata violates a plain-string invariant.
    #[error(transparent)]
    InvalidMetadata(#[from] EntryParseError),
    /// YAML scalar rendering failed.
    #[error("failed to render YAML scalar: {0}")]
    Yaml(serde_yaml::Error),
}

#[cfg(test)]
mod tests {
    use super::*;

    fn entry_id() -> EntryAddress {
        EntryAddress::new("witness").unwrap()
    }

    #[test]
    fn parses_canonical_entry_metadata() {
        let source = "\
---
name: Witness
desc: An entry whose claim is evidenced by repository artifacts.
topic:
  - concept
---

Body.
";

        let entry = Entry::from_markdown(entry_id(), source).unwrap();
        assert_eq!(entry.metadata.name(), "Witness");
        assert_eq!(
            entry.metadata.structural_targets_for("topic"),
            &[EntryAddress::new("concept").unwrap()]
        );
        assert_eq!(entry.body, "Body.\n");
    }

    #[test]
    fn parses_crlf_entry_metadata() {
        let source = concat!(
            "---\r\n",
            "name: Witness\r\n",
            "desc: An entry whose claim is evidenced by repository artifacts.\r\n",
            "topic:\r\n",
            "  - concept\r\n",
            "---\r\n",
            "\r\n",
            "Body.\r\n",
        );

        let entry = Entry::from_markdown(entry_id(), source).unwrap();

        assert_eq!(entry.metadata.name(), "Witness");
        assert_eq!(
            entry.metadata.structural_targets_for("topic"),
            &[EntryAddress::new("concept").unwrap()]
        );
        assert_eq!(entry.body, "Body.\r\n");
    }

    #[test]
    fn rejects_scalar_structural_link_relation() {
        let source = "\
---
name: Bad
desc: Bad structural metadata.
topic: concept
---
";

        let error = Entry::from_markdown(entry_id(), source).unwrap_err();
        assert!(matches!(error, EntryParseError::FieldMustBeList(field) if field == "topic"));
    }

    #[test]
    fn parses_extra_list_metadata_as_structural_link_relation() {
        let source = "\
---
name: Evidence
desc: Metadata with a project-defined structural link relation.
witness:
  - repository-evidence
---
";

        let entry = Entry::from_markdown(entry_id(), source).unwrap();

        assert_eq!(
            entry.metadata.structural_targets_for("witness"),
            &[EntryAddress::new("repository-evidence").unwrap()]
        );
    }

    #[test]
    fn preserves_structural_link_relation_order_when_rendering() {
        let source = "\
---
name: Ordered
desc: Metadata with user-authored structural link relation order.
zeta:
  - concept
alpha:
  - meta
---

Body.
";

        let entry = Entry::from_markdown(entry_id(), source).unwrap();
        let fields = entry.metadata.structural_fields().map(|(field, _)| field).collect::<Vec<_>>();
        let rendered = entry.to_markdown().unwrap();

        assert_eq!(fields, ["zeta", "alpha"]);
        assert!(rendered.find("zeta:\n").unwrap() < rendered.find("alpha:\n").unwrap());
    }

    #[test]
    fn preserves_present_empty_structural_link_relation_when_rendering() {
        let source = "\
---
name: Empty Field
desc: Metadata with a present empty structural link relation.
topic: []
---

Body.
";

        let entry = Entry::from_markdown(entry_id(), source).unwrap();
        let rendered = entry.to_markdown().unwrap();
        let reparsed = Entry::from_markdown(entry_id(), &rendered).unwrap();

        assert!(
            matches!(entry.metadata.structural_field("topic"), Some(targets) if targets.is_empty())
        );
        assert!(
            matches!(reparsed.metadata.structural_field("topic"), Some(targets) if targets.is_empty())
        );
        assert!(rendered.contains("topic: []\n"));
    }

    #[test]
    fn renders_structural_ids_as_yaml_scalars() {
        let target = EntryAddress::new("Design Note #1").unwrap();
        let mut metadata =
            EntryMetadata::new("Evidence", "Metadata with a quoted target.").unwrap();
        metadata.push_structural_target("witness", target.clone());
        let entry = Entry::new(entry_id(), metadata, "Body.\n");

        let rendered = entry.to_markdown().unwrap();
        let reparsed = Entry::from_markdown(entry_id(), &rendered).unwrap();

        assert_eq!(reparsed.metadata.structural_targets_for("witness"), &[target]);
    }

    #[test]
    fn renames_structural_targets() {
        let old_id = EntryAddress::new("old-entry").unwrap();
        let new_id = EntryAddress::new("new-entry").unwrap();
        let mut metadata = EntryMetadata::new("Concept", "A named idea.").unwrap();
        metadata.push_structural_target("belongs", old_id.clone());
        metadata.push_structural_target("belongs", EntryAddress::new("other-entry").unwrap());
        metadata.push_structural_target("refines", old_id.clone());

        assert!(metadata.rename_structural_target(&old_id, &new_id));

        assert_eq!(
            metadata.structural_targets_for("belongs"),
            &[new_id.clone(), EntryAddress::new("other-entry").unwrap()]
        );
        assert_eq!(metadata.structural_targets_for("refines"), &[new_id]);
    }

    #[test]
    fn renames_structural_fields() {
        let old_id = EntryAddress::new("refines").unwrap();
        let new_id = EntryAddress::new("prerequisite").unwrap();
        let mut metadata = EntryMetadata::new("Concept", "A named idea.").unwrap();
        metadata.push_structural_target("category", EntryAddress::new("concept").unwrap());
        metadata.push_structural_target("refines", EntryAddress::new("broader").unwrap());
        metadata.push_structural_target("belongs", EntryAddress::new("area").unwrap());

        assert!(metadata.rename_structural_field(&old_id, &new_id));

        let fields = metadata.structural_fields().map(|(field, _)| field).collect::<Vec<_>>();
        assert_eq!(fields, ["category", "prerequisite", "belongs"]);
        assert_eq!(
            metadata.structural_targets_for("prerequisite"),
            &[EntryAddress::new("broader").unwrap()]
        );
        assert!(metadata.structural_field("refines").is_none());
    }

    #[test]
    fn parses_canonical_frozen_marker() {
        let source = "\
---
name: Frozen
desc: A protected entry.
meta:
  frozen:
    - reviewed
---

Body.
";

        let entry = Entry::from_markdown(entry_id(), source).unwrap();

        assert_eq!(entry.metadata.meta.frozen, Some(FrozenMarker::reviewed()));
        assert!(entry.metadata.meta.frozen.as_ref().unwrap().is_reviewed());
    }

    #[test]
    fn parses_entry_without_managed_meta() {
        let source = "\
---
name: Plain
desc: No managed metadata.
topic:
  - concept
---

Body.
";

        let entry = Entry::from_markdown(entry_id(), source).unwrap();

        assert!(entry.metadata.meta.is_empty());
        assert_eq!(
            entry.metadata.structural_targets_for("topic"),
            &[EntryAddress::new("concept").unwrap()]
        );
    }

    #[test]
    fn rejects_top_level_frozen_marker() {
        let source = "\
---
name: Old
desc: Old frozen marker.
frozen:
  - reviewed
---
";

        let error = Entry::from_markdown(entry_id(), source).unwrap_err();

        assert!(matches!(error, EntryParseError::TopLevelFrozenMarker));
    }

    #[test]
    fn rejects_noncanonical_frozen_value() {
        let source = "\
---
name: Bad
desc: Bad frozen marker.
meta:
  frozen: true
---
";

        let error = Entry::from_markdown(entry_id(), source).unwrap_err();

        assert!(matches!(error, EntryParseError::InvalidFrozenMarker));
    }

    #[test]
    fn rejects_explicit_null_frozen_value() {
        let source = "\
---
name: Bad
desc: Bad frozen marker.
meta:
  frozen: null
---
";

        let error = Entry::from_markdown(entry_id(), source).unwrap_err();

        assert!(matches!(error, EntryParseError::InvalidFrozenMarker));
    }

    #[test]
    fn parses_managed_frozen_reason() {
        let source = "\
---
name: Managed
desc: A managed entry.
meta:
  frozen:
    - reviewed
    - managed
---

Body.
";

        let entry = Entry::from_markdown(entry_id(), source).unwrap();
        let frozen = entry.metadata.meta.frozen.as_ref().unwrap();

        assert!(frozen.is_reviewed());
        assert!(frozen.is_managed());
    }

    #[test]
    fn parses_structural_tide_settings() {
        let source = "\
---
name: Belongs
desc: A structural relation.
meta.type: \"structural\"
meta.ripple.lake: [\"to\", \"from\", \"clique\"]
meta.ripple.anchor: [\"from\"]
---

Body.
";

        let entry = Entry::from_markdown(entry_id(), source).unwrap();
        let structural = entry.metadata.meta.tide.unwrap();

        assert_eq!(
            structural,
            StructuralTideSettings::new(
                crate::structural::StructuralRippleSettings::new(true, false),
                crate::structural::StructuralRippleSettings::new(true, true),
                crate::structural::StructuralRippleSettings::new(true, false),
            )
        );
    }

    #[test]
    fn renders_empty_structural_tide_settings() {
        let mut metadata = EntryMetadata::new("Category", "A structural relation.").unwrap();
        metadata.meta.entry_type = Some(EntryMetaType::Structural);
        metadata.meta.tide = Some(StructuralTideSettings::default());
        let entry = Entry::new(entry_id(), metadata, "Body.\n");

        let rendered = entry.to_markdown().unwrap();
        let reparsed = Entry::from_markdown(entry_id(), &rendered).unwrap();

        assert!(
            rendered.contains(
                "meta.type: \"structural\"\nmeta.ripple.lake: []\nmeta.ripple.anchor: []\n"
            )
        );
        assert_eq!(reparsed.metadata.meta.tide, Some(StructuralTideSettings::default()));
    }

    #[test]
    fn parses_structural_type_without_tide_settings() {
        let source = "\
---
name: Category
desc: A structural relation.
meta.type: \"structural\"
---

Body.
";

        let entry = Entry::from_markdown(entry_id(), source).unwrap();

        assert_eq!(entry.metadata.meta.entry_type, Some(EntryMetaType::Structural));
        assert_eq!(entry.metadata.meta.tide, None);
    }

    #[test]
    fn parses_intrinsic_meta_type() {
        let source = "\
---
name: Name
desc: A required metadata field.
meta.type: \"intrinsic\"
---

Body.
";

        let entry = Entry::from_markdown(entry_id(), source).unwrap();

        assert_eq!(entry.metadata.meta.entry_type, Some(EntryMetaType::Intrinsic));
        assert!(entry.metadata.meta.is_intrinsic_field());
        assert_eq!(entry.metadata.meta.tide, None);
    }

    #[test]
    fn renders_intrinsic_meta_type() {
        let mut metadata = EntryMetadata::new("Name", "A required metadata field.").unwrap();
        metadata.meta.entry_type = Some(EntryMetaType::Intrinsic);
        let entry = Entry::new(entry_id(), metadata, "Body.\n");

        let rendered = entry.to_markdown().unwrap();

        assert!(rendered.contains("meta.type: \"intrinsic\"\n"));
    }

    #[test]
    fn renders_structural_tide_settings() {
        let mut metadata = EntryMetadata::new("Belongs", "A structural relation.").unwrap();
        metadata.meta.entry_type = Some(EntryMetaType::Structural);
        metadata.meta.tide = Some(StructuralTideSettings::new(
            crate::structural::StructuralRippleSettings::new(true, false),
            crate::structural::StructuralRippleSettings::new(true, true),
            crate::structural::StructuralRippleSettings::new(true, false),
        ));
        let entry = Entry::new(entry_id(), metadata, "Body.\n");

        let rendered = entry.to_markdown().unwrap();

        assert!(rendered.contains(
            "\
meta.ripple.lake: [\"to\", \"from\", \"clique\"]
meta.ripple.anchor: [\"from\"]
"
        ));
    }

    #[test]
    fn renders_canonical_frozen_marker() {
        let mut metadata = EntryMetadata::new("Frozen", "Protected entry.").unwrap();
        metadata.meta.frozen = Some(FrozenMarker::reviewed());
        let entry = Entry::new(entry_id(), metadata, "Body.\n");

        let rendered = entry.to_markdown().unwrap();

        assert!(rendered.contains("meta:\n  frozen:\n    - reviewed\n"));
        assert!(
            rendered.find("desc: Protected entry.\n").unwrap() < rendered.find("meta:\n").unwrap()
        );
        assert!(!rendered.contains("frozen: null"));
        assert!(!rendered.contains("frozen: true"));
    }

    #[test]
    fn omits_empty_managed_meta_when_rendering() {
        let metadata = EntryMetadata::new("Plain", "No managed metadata.").unwrap();
        let entry = Entry::new(entry_id(), metadata, "Body.\n");

        let rendered = entry.to_markdown().unwrap();

        assert!(!rendered.contains("meta:\n"));
    }

    #[test]
    fn rejects_non_mapping_meta() {
        let source = "\
---
name: Bad
desc: Bad meta.
meta: true
---
";

        let error = Entry::from_markdown(entry_id(), source).unwrap_err();

        assert!(matches!(error, EntryParseError::MetaMustBeMapping));
    }

    #[test]
    fn rejects_unknown_meta_field() {
        let source = "\
---
name: Bad
desc: Bad meta.
meta:
  owner: sirno
---
";

        let error = Entry::from_markdown(entry_id(), source).unwrap_err();

        assert!(matches!(error, EntryParseError::UnknownMetaField(field) if field == "owner"));
    }

    #[test]
    fn rejects_old_structural_tide_block() {
        let source = "\
---
name: Bad
desc: Bad tide metadata.
meta:
  structural: {}
---
";

        let error = Entry::from_markdown(entry_id(), source).unwrap_err();

        assert!(matches!(error, EntryParseError::UnknownMetaField(field) if field == "structural"));
    }

    #[test]
    fn rejects_old_dotted_tide_field() {
        let source = "\
---
name: Bad
desc: Bad tide metadata.
meta.ripple.lake.to: true
---
";

        let error = Entry::from_markdown(entry_id(), source).unwrap_err();

        assert!(
            matches!(error, EntryParseError::UnknownMetaField(field) if field == "ripple.lake.to")
        );
    }

    #[test]
    fn rejects_old_flat_tide_field() {
        let source = "\
---
name: Bad
desc: Bad tide metadata.
meta.type: \"structural\"
meta.lake: [\"to\"]
---
";

        let error = Entry::from_markdown(entry_id(), source).unwrap_err();

        assert!(matches!(error, EntryParseError::UnknownMetaField(field) if field == "lake"));
    }

    #[test]
    fn rejects_non_list_flat_tide_field() {
        let source = "\
---
name: Bad
desc: Bad tide metadata.
meta.type: \"structural\"
meta.ripple.lake: true
---
";

        let error = Entry::from_markdown(entry_id(), source).unwrap_err();

        assert!(
            matches!(error, EntryParseError::InvalidStructuralTideField(field) if field == "meta.ripple.lake")
        );
    }

    #[test]
    fn rejects_unknown_flat_tide_direction() {
        let source = "\
---
name: Bad
desc: Bad tide metadata.
meta.type: \"structural\"
meta.ripple.lake: [\"around\"]
---
";

        let error = Entry::from_markdown(entry_id(), source).unwrap_err();

        assert!(
            matches!(error, EntryParseError::InvalidStructuralTideField(field) if field == "meta.ripple.lake")
        );
    }

    #[test]
    fn rejects_tide_field_without_structural_type() {
        let source = "\
---
name: Bad
desc: Bad tide metadata.
meta.ripple.lake: [\"to\"]
---
";

        let error = Entry::from_markdown(entry_id(), source).unwrap_err();

        assert!(
            matches!(error, EntryParseError::StructuralTideWithoutType(field) if field == "meta.ripple.lake")
        );
    }

    #[test]
    fn rejects_tide_field_with_intrinsic_type() {
        let source = "\
---
name: Bad
desc: Bad tide metadata.
meta.type: \"intrinsic\"
meta.ripple.lake: [\"to\"]
---
";

        let error = Entry::from_markdown(entry_id(), source).unwrap_err();

        assert!(
            matches!(error, EntryParseError::StructuralTideWithoutType(field) if field == "meta.ripple.lake")
        );
    }

    #[test]
    fn rejects_unknown_flat_meta_type() {
        let source = "\
---
name: Bad
desc: Bad type metadata.
meta.type: \"concept\"
---
";

        let error = Entry::from_markdown(entry_id(), source).unwrap_err();

        assert!(matches!(error, EntryParseError::InvalidMetaType));
    }

    #[test]
    fn replaces_body_without_rewriting_frontmatter() {
        let source = "\
---
name: Old
desc: Existing desc.
---

Old body.
";

        let replaced = Entry::replace_markdown_body(source, "New body.\n").unwrap();

        assert!(replaced.starts_with("---\nname: Old\ndesc: Existing desc.\n---\n\n"));
        assert!(replaced.ends_with("New body.\n"));
        assert!(!replaced.contains("Old body."));
    }

    #[test]
    fn replaces_crlf_body_without_rewriting_frontmatter() {
        let source = "---\r\nname: Old\r\ndesc: Existing desc.\r\n---\r\n\r\nOld body.\r\n";

        let replaced = Entry::replace_markdown_body(source, "New body.\n").unwrap();

        assert!(replaced.starts_with("---\r\nname: Old\r\ndesc: Existing desc.\r\n---\r\n\r\n"));
        assert!(replaced.ends_with("New body.\n"));
        assert!(!replaced.contains("Old body."));
    }

    #[test]
    fn detects_mixed_line_endings() {
        assert!(!has_mixed_line_endings("---\nname: Entry\n---\n"));
        assert!(!has_mixed_line_endings("---\r\nname: Entry\r\n---\r\n"));
        assert!(has_mixed_line_endings("---\r\nname: Entry\n---\r\n"));
    }
}