adrs-core 0.7.3

Core library for managing Architecture Decision Records
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
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
//! Repository operations for managing ADRs.

use crate::{
    Adr, AdrLink, AdrStatus, Config, ConfigMode, Error, LinkKind, Parser, Result, Template,
    TemplateEngine, TemplateFormat, TemplateVariant,
};
use fuzzy_matcher::FuzzyMatcher;
use fuzzy_matcher::skim::SkimMatcherV2;
use regex::Regex;
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;
use walkdir::WalkDir;

/// Regex for matching the status line in YAML frontmatter.
static FM_STATUS_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?m)^status:\s*.*$").unwrap());

/// Regex for matching the links block in YAML frontmatter (multi-line).
static FM_LINKS_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?m)^links:\n(?:(?:  .+\n)*)").unwrap());

/// Regex for matching the tags block in YAML frontmatter (multi-line).
static FM_TAGS_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?m)^tags:\n(?:(?:  .+\n)*)").unwrap());

/// A repository of Architecture Decision Records.
#[derive(Debug)]
pub struct Repository {
    /// The root directory of the project.
    root: PathBuf,

    /// Configuration for this repository.
    config: Config,

    /// Parser for reading ADRs.
    parser: Parser,

    /// Template engine for creating ADRs.
    template_engine: TemplateEngine,
}

impl Repository {
    /// Open an existing repository at the given root.
    pub fn open(root: impl Into<PathBuf>) -> Result<Self> {
        let root = root.into();
        let config = Config::load(&root)?;
        let template_engine = Self::engine_from_config(&config);

        Ok(Self {
            root,
            config,
            parser: Parser::new(),
            template_engine,
        })
    }

    /// Open a repository, or create default config if not found.
    pub fn open_or_default(root: impl Into<PathBuf>) -> Self {
        let root = root.into();
        let config = Config::load_or_default(&root);
        let template_engine = Self::engine_from_config(&config);

        Self {
            root,
            config,
            parser: Parser::new(),
            template_engine,
        }
    }

    /// Initialize a new repository at the given root.
    pub fn init(root: impl Into<PathBuf>, adr_dir: Option<PathBuf>, ng: bool) -> Result<Self> {
        let root = root.into();
        let adr_dir = adr_dir.unwrap_or_else(|| PathBuf::from(crate::config::DEFAULT_ADR_DIR));
        let adr_path = root.join(&adr_dir);

        // Check if directory exists and count existing ADRs
        let existing_adrs = if adr_path.exists() {
            count_existing_adrs(&adr_path)
        } else {
            // Create the directory
            fs::create_dir_all(&adr_path)?;
            0
        };

        // Create config
        let config = Config {
            adr_dir,
            mode: if ng {
                ConfigMode::NextGen
            } else {
                ConfigMode::Compatible
            },
            ..Default::default()
        };
        config.save(&root)?;

        let template_engine = Self::engine_from_config(&config);

        let repo = Self {
            root,
            config,
            parser: Parser::new(),
            template_engine,
        };

        // Only create initial ADR if no ADRs exist
        if existing_adrs == 0 {
            let mut adr = Adr::new(1, "Record architecture decisions");
            adr.status = AdrStatus::Accepted;
            adr.context =
                "We need to record the architectural decisions made on this project.".into();
            adr.decision = "We will use Architecture Decision Records, as described by Michael Nygard in his article \"Documenting Architecture Decisions\".".into();
            adr.consequences = "See Michael Nygard's article, linked above. For a lightweight ADR toolset, see Nat Pryce's adr-tools.".into();
            repo.create(&adr)?;
        }

        Ok(repo)
    }

    /// Get the repository root path.
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// Get the configuration.
    pub fn config(&self) -> &Config {
        &self.config
    }

    /// Get the full path to the ADR directory.
    pub fn adr_path(&self) -> PathBuf {
        self.config.adr_path(&self.root)
    }

    /// Build a template engine that respects the config's template format.
    fn engine_from_config(config: &Config) -> TemplateEngine {
        let mut engine = TemplateEngine::new();
        if let Some(ref fmt) = config.templates.format
            && let Ok(format) = fmt.parse::<TemplateFormat>()
        {
            engine = engine.with_format(format);
        }
        engine
    }

    /// Set the template format.
    pub fn with_template_format(mut self, format: TemplateFormat) -> Self {
        self.template_engine = self.template_engine.with_format(format);
        self
    }

    /// Set the template variant.
    pub fn with_template_variant(mut self, variant: TemplateVariant) -> Self {
        self.template_engine = self.template_engine.with_variant(variant);
        self
    }

    /// Set a custom template.
    pub fn with_custom_template(mut self, template: Template) -> Self {
        self.template_engine = self.template_engine.with_custom_template(template);
        self
    }

    /// List all ADRs in the repository.
    pub fn list(&self) -> Result<Vec<Adr>> {
        let adr_path = self.adr_path();
        if !adr_path.exists() {
            return Err(Error::AdrDirNotFound);
        }

        let mut adrs: Vec<Adr> = WalkDir::new(&adr_path)
            .max_depth(1)
            .into_iter()
            .filter_map(|e| e.ok())
            .filter(|e| {
                e.path().extension().is_some_and(|ext| ext == "md")
                    && e.path()
                        .file_name()
                        .and_then(|n| n.to_str())
                        .is_some_and(|n| n.chars().next().is_some_and(|c| c.is_ascii_digit()))
            })
            .filter_map(|e| self.parser.parse_file(e.path()).ok())
            .collect();

        adrs.sort_by_key(|a| a.number);
        Ok(adrs)
    }

    /// Get the next available ADR number.
    pub fn next_number(&self) -> Result<u32> {
        let adrs = self.list()?;
        Ok(adrs.last().map(|a| a.number + 1).unwrap_or(1))
    }

    /// Find an ADR by number.
    pub fn get(&self, number: u32) -> Result<Adr> {
        let adrs = self.list()?;
        adrs.into_iter()
            .find(|a| a.number == number)
            .ok_or_else(|| Error::AdrNotFound(number.to_string()))
    }

    /// Find an ADR by query (number or fuzzy title match).
    pub fn find(&self, query: &str) -> Result<Adr> {
        // Try parsing as number first
        if let Ok(number) = query.parse::<u32>() {
            return self.get(number);
        }

        // Fuzzy match on title
        let adrs = self.list()?;
        let matcher = SkimMatcherV2::default();

        let mut matches: Vec<_> = adrs
            .into_iter()
            .filter_map(|adr| {
                let score = matcher.fuzzy_match(&adr.title, query)?;
                Some((adr, score))
            })
            .collect();

        matches.sort_by(|a, b| b.1.cmp(&a.1));

        match matches.len() {
            0 => Err(Error::AdrNotFound(query.to_string())),
            1 => Ok(matches.remove(0).0),
            _ => {
                // If top match is significantly better, use it
                if matches[0].1 > matches[1].1 * 2 {
                    Ok(matches.remove(0).0)
                } else {
                    Err(Error::AmbiguousAdr {
                        query: query.to_string(),
                        matches: matches
                            .iter()
                            .take(5)
                            .map(|(a, _)| a.title.clone())
                            .collect(),
                    })
                }
            }
        }
    }

    /// Resolve link target titles and filenames for an ADR's links.
    fn resolve_link_titles(&self, adr: &Adr) -> HashMap<u32, (String, String)> {
        let mut map = HashMap::new();
        for link in &adr.links {
            if map.contains_key(&link.target) {
                continue;
            }
            if let Ok(target_adr) = self.get(link.target) {
                map.insert(
                    link.target,
                    (target_adr.title.clone(), target_adr.filename()),
                );
            }
        }
        map
    }

    /// Create a new ADR.
    pub fn create(&self, adr: &Adr) -> Result<PathBuf> {
        let path = self.adr_path().join(adr.filename());

        let link_titles = self.resolve_link_titles(adr);
        let content = self
            .template_engine
            .render(adr, &self.config, &link_titles)?;
        fs::write(&path, content)?;

        Ok(path)
    }

    /// Create a new ADR with the given title.
    pub fn new_adr(&self, title: impl Into<String>) -> Result<(Adr, PathBuf)> {
        let number = self.next_number()?;
        let adr = Adr::new(number, title);
        let path = self.create(&adr)?;
        Ok((adr, path))
    }

    /// Create a new ADR that supersedes another.
    pub fn supersede(&self, title: impl Into<String>, superseded: u32) -> Result<(Adr, PathBuf)> {
        let number = self.next_number()?;
        let mut adr = Adr::new(number, title);
        adr.add_link(AdrLink::new(superseded, LinkKind::Supersedes));

        // Create the new ADR first so its file exists on disk when
        // the old ADR's "Superseded by" link is resolved.
        let path = self.create(&adr)?;

        // Now update the superseded ADR — the new ADR is on disk so
        // its title and filename can be resolved for the link.
        let mut old_adr = self.get(superseded)?;
        old_adr.status = AdrStatus::Superseded;
        old_adr.add_link(AdrLink::new(number, LinkKind::SupersededBy));
        self.update_metadata(&old_adr)?;

        Ok((adr, path))
    }

    /// Change the status of an ADR.
    ///
    /// If the new status is `Superseded` and `superseded_by` is provided,
    /// a superseded-by link will be added automatically.
    pub fn set_status(
        &self,
        number: u32,
        status: AdrStatus,
        superseded_by: Option<u32>,
    ) -> Result<PathBuf> {
        let mut adr = self.get(number)?;
        adr.status = status.clone();

        // If superseded by another ADR, add the link
        if let (AdrStatus::Superseded, Some(by)) = (&status, superseded_by) {
            // Check that the superseding ADR exists
            let _ = self.get(by)?;

            // Add superseded-by link if not already present
            if !adr
                .links
                .iter()
                .any(|l| matches!(l.kind, LinkKind::SupersededBy) && l.target == by)
            {
                adr.add_link(AdrLink::new(by, LinkKind::SupersededBy));
            }
        }

        self.update_metadata(&adr)
    }

    /// Link two ADRs together.
    pub fn link(
        &self,
        source: u32,
        target: u32,
        source_kind: LinkKind,
        target_kind: LinkKind,
    ) -> Result<()> {
        let mut source_adr = self.get(source)?;
        let mut target_adr = self.get(target)?;

        source_adr.add_link(AdrLink::new(target, source_kind));
        target_adr.add_link(AdrLink::new(source, target_kind));

        self.update_metadata(&source_adr)?;
        self.update_metadata(&target_adr)?;

        Ok(())
    }

    /// Update an existing ADR.
    pub fn update(&self, adr: &Adr) -> Result<PathBuf> {
        let path = adr
            .path
            .clone()
            .unwrap_or_else(|| self.adr_path().join(adr.filename()));

        let link_titles = self.resolve_link_titles(adr);
        let content = self
            .template_engine
            .render(adr, &self.config, &link_titles)?;
        fs::write(&path, content)?;

        Ok(path)
    }

    /// Read the content of an ADR file.
    pub fn read_content(&self, adr: &Adr) -> Result<String> {
        let path = adr
            .path
            .as_ref()
            .cloned()
            .unwrap_or_else(|| self.adr_path().join(adr.filename()));

        Ok(fs::read_to_string(path)?)
    }

    /// Write content to an ADR file.
    pub fn write_content(&self, adr: &Adr, content: &str) -> Result<PathBuf> {
        let path = adr
            .path
            .as_ref()
            .cloned()
            .unwrap_or_else(|| self.adr_path().join(adr.filename()));

        fs::write(&path, content)?;
        Ok(path)
    }

    /// Update only the metadata (status, links, tags) of an existing ADR file,
    /// preserving all other content byte-for-byte.
    pub fn update_metadata(&self, adr: &Adr) -> Result<PathBuf> {
        let path = adr
            .path
            .clone()
            .unwrap_or_else(|| self.adr_path().join(adr.filename()));

        let content = fs::read_to_string(&path)?;

        let updated = if content.starts_with("---\n") {
            self.update_frontmatter_metadata(adr, &content)?
        } else {
            self.update_legacy_metadata(adr, &content)?
        };

        fs::write(&path, updated)?;
        Ok(path)
    }

    /// Surgically update metadata fields in a YAML frontmatter file.
    ///
    /// Replaces only `status:`, `links:`, and `tags:` blocks in the frontmatter.
    /// YAML comments (e.g., SPDX headers), unknown fields, and the entire
    /// markdown body are preserved untouched.
    fn update_frontmatter_metadata(&self, adr: &Adr, content: &str) -> Result<String> {
        // Split into frontmatter and body at the closing `---`
        let Some(rest) = content.strip_prefix("---\n") else {
            return Err(Error::InvalidFormat {
                path: Default::default(),
                reason: "Missing opening frontmatter delimiter".into(),
            });
        };

        let Some(end_idx) = rest.find("\n---\n").or_else(|| {
            // Handle case where closing delimiter is at end of file with no trailing newline
            if rest.ends_with("\n---") {
                Some(rest.len() - 3)
            } else {
                None
            }
        }) else {
            return Err(Error::InvalidFormat {
                path: Default::default(),
                reason: "Missing closing frontmatter delimiter".into(),
            });
        };

        let yaml_block = &rest[..end_idx + 1]; // include trailing \n
        let after_yaml = &rest[end_idx..]; // starts with \n---\n...

        // 1. Replace status line
        let new_status = format!("status: {}", adr.status.to_string().to_lowercase());
        let yaml_block = FM_STATUS_RE.replace(yaml_block, new_status.as_str());

        // 2. Replace or remove links block
        let links_yaml = Self::format_links_yaml(&adr.links);
        let yaml_block = if FM_LINKS_RE.is_match(&yaml_block) {
            FM_LINKS_RE
                .replace(&yaml_block, links_yaml.as_str())
                .into_owned()
        } else if !links_yaml.is_empty() {
            // Append links before end of frontmatter
            let mut s = yaml_block.into_owned();
            if !s.ends_with('\n') {
                s.push('\n');
            }
            s.push_str(&links_yaml);
            s
        } else {
            yaml_block.into_owned()
        };

        // 3. Replace or remove tags block
        let tags_yaml = Self::format_tags_yaml(&adr.tags);
        let yaml_block = if FM_TAGS_RE.is_match(&yaml_block) {
            FM_TAGS_RE
                .replace(&yaml_block, tags_yaml.as_str())
                .into_owned()
        } else if !tags_yaml.is_empty() {
            let mut s = yaml_block;
            if !s.ends_with('\n') {
                s.push('\n');
            }
            s.push_str(&tags_yaml);
            s
        } else {
            yaml_block
        };

        let yaml_block = yaml_block.trim_end_matches('\n');
        Ok(format!("---\n{}{}", yaml_block, after_yaml))
    }

    /// Surgically update metadata in a legacy (no-frontmatter) ADR file.
    ///
    /// Replaces the content between `## Status` and the next `## ` heading
    /// with the new status and link lines. All other sections pass through untouched.
    fn update_legacy_metadata(&self, adr: &Adr, content: &str) -> Result<String> {
        let lines: Vec<&str> = content.lines().collect();
        let mut result = String::with_capacity(content.len());

        // Find the ## Status section
        let status_idx = lines.iter().position(|l| {
            l.trim().eq_ignore_ascii_case("## Status") || l.trim().eq_ignore_ascii_case("## STATUS")
        });

        let Some(status_idx) = status_idx else {
            // No status section found -- just return content unchanged
            return Ok(content.to_string());
        };

        // Find the next ## heading after status
        let next_heading_idx = lines[status_idx + 1..]
            .iter()
            .position(|l| l.starts_with("## "))
            .map(|i| i + status_idx + 1);

        // Write everything before the status section (including the ## Status line)
        for line in &lines[..=status_idx] {
            result.push_str(line);
            result.push('\n');
        }

        // Write new status content
        result.push('\n');
        result.push_str(&adr.status.to_string());
        result.push('\n');

        // Write link lines with resolved titles
        let link_titles = self.resolve_link_titles(adr);
        for link in &adr.links {
            result.push('\n');
            if let Some((title, filename)) = link_titles.get(&link.target) {
                result.push_str(&format!(
                    "{} [{}. {}]({})",
                    link.kind, link.target, title, filename
                ));
            } else {
                result.push_str(&format!(
                    "{} [{}. ...]({:04}-....md)",
                    link.kind, link.target, link.target
                ));
            }
            result.push('\n');
        }

        // Write everything from the next heading onward
        if let Some(next_idx) = next_heading_idx {
            result.push('\n');
            for (i, line) in lines[next_idx..].iter().enumerate() {
                result.push_str(line);
                // Preserve trailing newline behavior
                if next_idx + i < lines.len() - 1 || content.ends_with('\n') {
                    result.push('\n');
                }
            }
        } else if content.ends_with('\n') {
            // No next heading, but original ended with newline
        }

        Ok(result)
    }

    /// Format links as YAML block for frontmatter insertion.
    fn format_links_yaml(links: &[AdrLink]) -> String {
        if links.is_empty() {
            return String::new();
        }
        let mut s = String::from("links:\n");
        for link in links {
            let kind_str = match &link.kind {
                LinkKind::Supersedes => "supersedes",
                LinkKind::SupersededBy => "supersededby",
                LinkKind::Amends => "amends",
                LinkKind::AmendedBy => "amendedby",
                LinkKind::RelatesTo => "relatesto",
                LinkKind::Custom(c) => c.as_str(),
            };
            s.push_str(&format!(
                "  - target: {}\n    kind: {}\n",
                link.target, kind_str
            ));
        }
        s
    }

    /// Format tags as YAML block for frontmatter insertion.
    fn format_tags_yaml(tags: &[String]) -> String {
        if tags.is_empty() {
            return String::new();
        }
        let mut s = String::from("tags:\n");
        for tag in tags {
            s.push_str(&format!("  - {}\n", tag));
        }
        s
    }
}

/// Count existing ADR files in a directory.
fn count_existing_adrs(path: &Path) -> usize {
    if !path.is_dir() {
        return 0;
    }

    fs::read_dir(path)
        .map(|entries| {
            entries
                .filter_map(|e| e.ok())
                .filter(|e| {
                    let path = e.path();
                    path.is_file()
                        && path.extension().is_some_and(|ext| ext == "md")
                        && path.file_name().and_then(|n| n.to_str()).is_some_and(|n| {
                            // Match NNNN-*.md pattern (adr-tools style)
                            n.len() > 5 && n[..4].chars().all(|c| c.is_ascii_digit())
                        })
                })
                .count()
        })
        .unwrap_or(0)
}

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

    // ========== Initialization Tests ==========

    #[test]
    fn test_init_repository() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();

        assert!(repo.adr_path().exists());
        assert!(temp.path().join(".adr-dir").exists());

        let adrs = repo.list().unwrap();
        assert_eq!(adrs.len(), 1);
        assert_eq!(adrs[0].number, 1);
        assert_eq!(adrs[0].title, "Record architecture decisions");
    }

    #[test]
    fn test_init_repository_ng() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, true).unwrap();

        assert!(temp.path().join("adrs.toml").exists());
        assert!(repo.config().is_next_gen());
    }

    #[test]
    fn test_init_repository_custom_dir() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), Some("decisions".into()), false).unwrap();

        assert!(temp.path().join("decisions").exists());
        assert_eq!(repo.config().adr_dir, PathBuf::from("decisions"));
    }

    #[test]
    fn test_init_repository_nested_dir() {
        let temp = TempDir::new().unwrap();
        let _repo =
            Repository::init(temp.path(), Some("docs/architecture/adr".into()), false).unwrap();

        assert!(temp.path().join("docs/architecture/adr").exists());
    }

    #[test]
    fn test_init_repository_already_exists_skips_initial_adr() {
        let temp = TempDir::new().unwrap();
        Repository::init(temp.path(), None, false).unwrap();

        // Re-init should succeed but not create another ADR
        let repo = Repository::init(temp.path(), None, false).unwrap();
        let adrs = repo.list().unwrap();
        assert_eq!(adrs.len(), 1); // Still just the original initial ADR
    }

    #[test]
    fn test_init_with_existing_adrs_skips_initial() {
        let temp = TempDir::new().unwrap();
        let adr_dir = temp.path().join("doc/adr");
        fs::create_dir_all(&adr_dir).unwrap();

        // Create some existing ADR files
        fs::write(
            adr_dir.join("0001-existing-decision.md"),
            "# 1. Existing Decision\n\nDate: 2024-01-01\n\n## Status\n\nAccepted\n\n## Context\n\nTest\n\n## Decision\n\nTest\n\n## Consequences\n\nTest\n",
        )
        .unwrap();
        fs::write(
            adr_dir.join("0002-another-decision.md"),
            "# 2. Another Decision\n\nDate: 2024-01-02\n\n## Status\n\nAccepted\n\n## Context\n\nTest\n\n## Decision\n\nTest\n\n## Consequences\n\nTest\n",
        )
        .unwrap();

        // Init should succeed and NOT create initial ADR
        let repo = Repository::init(temp.path(), None, false).unwrap();
        let adrs = repo.list().unwrap();
        assert_eq!(adrs.len(), 2); // Only the existing ADRs, no "Record architecture decisions"
        assert_eq!(adrs[0].title, "Existing Decision");
        assert_eq!(adrs[1].title, "Another Decision");
    }

    #[test]
    fn test_init_creates_first_adr() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();

        let adr = repo.get(1).unwrap();
        assert_eq!(adr.title, "Record architecture decisions");
        assert_eq!(adr.status, AdrStatus::Accepted);
        assert!(!adr.context.is_empty());
        assert!(!adr.decision.is_empty());
        assert!(!adr.consequences.is_empty());
    }

    // ========== Open Tests ==========

    #[test]
    fn test_open_repository() {
        let temp = TempDir::new().unwrap();
        Repository::init(temp.path(), None, false).unwrap();

        let repo = Repository::open(temp.path()).unwrap();
        assert_eq!(repo.list().unwrap().len(), 1);
    }

    #[test]
    fn test_open_repository_not_found() {
        let temp = TempDir::new().unwrap();
        let result = Repository::open(temp.path());
        assert!(result.is_err());
    }

    #[test]
    fn test_open_or_default() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::open_or_default(temp.path());
        assert_eq!(repo.config().adr_dir, PathBuf::from("doc/adr"));
    }

    #[test]
    fn test_open_or_default_existing() {
        let temp = TempDir::new().unwrap();
        Repository::init(temp.path(), Some("custom".into()), false).unwrap();

        let repo = Repository::open_or_default(temp.path());
        assert_eq!(repo.config().adr_dir, PathBuf::from("custom"));
    }

    // ========== Create and List Tests ==========

    #[test]
    fn test_create_and_list() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();

        let (adr, _) = repo.new_adr("Use Rust").unwrap();
        assert_eq!(adr.number, 2);

        let adrs = repo.list().unwrap();
        assert_eq!(adrs.len(), 2);
    }

    #[test]
    fn test_create_multiple() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();

        repo.new_adr("Second").unwrap();
        repo.new_adr("Third").unwrap();
        repo.new_adr("Fourth").unwrap();

        let adrs = repo.list().unwrap();
        assert_eq!(adrs.len(), 4);
        assert_eq!(adrs[0].number, 1);
        assert_eq!(adrs[1].number, 2);
        assert_eq!(adrs[2].number, 3);
        assert_eq!(adrs[3].number, 4);
    }

    #[test]
    fn test_list_sorted_by_number() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();

        repo.new_adr("B").unwrap();
        repo.new_adr("A").unwrap();
        repo.new_adr("C").unwrap();

        let adrs = repo.list().unwrap();
        assert!(adrs.windows(2).all(|w| w[0].number < w[1].number));
    }

    #[test]
    fn test_next_number() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();

        assert_eq!(repo.next_number().unwrap(), 2);

        repo.new_adr("Second").unwrap();
        assert_eq!(repo.next_number().unwrap(), 3);
    }

    #[test]
    fn test_create_file_exists() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();

        let (_, path) = repo.new_adr("Test ADR").unwrap();
        assert!(path.exists());
        assert!(path.to_string_lossy().contains("0002-test-adr.md"));
    }

    // ========== Get and Find Tests ==========

    #[test]
    fn test_get_by_number() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();
        repo.new_adr("Second").unwrap();

        let adr = repo.get(2).unwrap();
        assert_eq!(adr.title, "Second");
    }

    #[test]
    fn test_get_not_found() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();

        let result = repo.get(99);
        assert!(result.is_err());
    }

    #[test]
    fn test_find_by_number() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();

        let adr = repo.find("1").unwrap();
        assert_eq!(adr.number, 1);
    }

    #[test]
    fn test_find_by_title() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();

        let adr = repo.find("architecture").unwrap();
        assert_eq!(adr.number, 1);
    }

    #[test]
    fn test_find_fuzzy_match() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();
        repo.new_adr("Use PostgreSQL for database").unwrap();
        repo.new_adr("Use Redis for caching").unwrap();

        let adr = repo.find("postgres").unwrap();
        assert!(adr.title.contains("PostgreSQL"));
    }

    #[test]
    fn test_find_not_found() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();

        let result = repo.find("nonexistent");
        assert!(result.is_err());
    }

    // ========== Supersede Tests ==========

    #[test]
    fn test_supersede() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();

        let (new_adr, _) = repo.supersede("New approach", 1).unwrap();
        assert_eq!(new_adr.number, 2);
        assert_eq!(new_adr.links.len(), 1);
        assert_eq!(new_adr.links[0].kind, LinkKind::Supersedes);

        let old_adr = repo.get(1).unwrap();
        assert_eq!(old_adr.status, AdrStatus::Superseded);
    }

    #[test]
    fn test_supersede_creates_bidirectional_links() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();

        repo.supersede("New approach", 1).unwrap();

        let old_adr = repo.get(1).unwrap();
        assert_eq!(old_adr.links.len(), 1);
        assert_eq!(old_adr.links[0].target, 2);
        assert_eq!(old_adr.links[0].kind, LinkKind::SupersededBy);

        let new_adr = repo.get(2).unwrap();
        assert_eq!(new_adr.links.len(), 1);
        assert_eq!(new_adr.links[0].target, 1);
        assert_eq!(new_adr.links[0].kind, LinkKind::Supersedes);
    }

    #[test]
    fn test_supersede_not_found() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();

        let result = repo.supersede("New", 99);
        assert!(result.is_err());
    }

    // ========== Link Resolution Tests (Issue #180) ==========

    #[test]
    fn test_supersede_generates_functional_links() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();

        // Create ADR 2, then supersede it with ADR 3
        repo.new_adr("Use MySQL for persistence").unwrap();
        repo.supersede("Use PostgreSQL instead", 2).unwrap();

        // Check the new ADR (3) has a functional "Supersedes" link to ADR 2
        let new_content =
            fs::read_to_string(repo.adr_path().join("0003-use-postgresql-instead.md")).unwrap();
        assert!(
            new_content.contains(
                "Supersedes [2. Use MySQL for persistence](0002-use-mysql-for-persistence.md)"
            ),
            "New ADR should have functional Supersedes link. Got:\n{new_content}"
        );

        // Check the old ADR (2) has a functional "Superseded by" link to ADR 3
        let old_content =
            fs::read_to_string(repo.adr_path().join("0002-use-mysql-for-persistence.md")).unwrap();
        assert!(
            old_content.contains(
                "Superseded by [3. Use PostgreSQL instead](0003-use-postgresql-instead.md)"
            ),
            "Old ADR should have functional Superseded by link. Got:\n{old_content}"
        );
    }

    #[test]
    fn test_link_generates_functional_links() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();

        repo.new_adr("Use REST API").unwrap();
        repo.new_adr("Use JSON for API responses").unwrap();

        repo.link(3, 2, LinkKind::Amends, LinkKind::AmendedBy)
            .unwrap();

        // Check source ADR has functional link
        let source_content =
            fs::read_to_string(repo.adr_path().join("0003-use-json-for-api-responses.md")).unwrap();
        assert!(
            source_content.contains("Amends [2. Use REST API](0002-use-rest-api.md)"),
            "Source ADR should have functional Amends link. Got:\n{source_content}"
        );

        // Check target ADR has functional reverse link
        let target_content =
            fs::read_to_string(repo.adr_path().join("0002-use-rest-api.md")).unwrap();
        assert!(
            target_content.contains(
                "Amended by [3. Use JSON for API responses](0003-use-json-for-api-responses.md)"
            ),
            "Target ADR should have functional Amended by link. Got:\n{target_content}"
        );
    }

    #[test]
    fn test_set_status_superseded_generates_functional_link() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();

        repo.new_adr("First Decision").unwrap();
        repo.new_adr("Second Decision").unwrap();

        repo.set_status(2, AdrStatus::Superseded, Some(3)).unwrap();

        let content = fs::read_to_string(repo.adr_path().join("0002-first-decision.md")).unwrap();
        assert!(
            content.contains("Superseded by [3. Second Decision](0003-second-decision.md)"),
            "ADR should have functional Superseded by link. Got:\n{content}"
        );
    }

    #[test]
    fn test_supersede_chain_generates_functional_links() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();

        // ADR 1 is "Record architecture decisions" (from init)
        // Create ADR 2
        repo.new_adr("Use SQLite").unwrap();
        // ADR 3 supersedes ADR 2
        repo.supersede("Use PostgreSQL", 2).unwrap();
        // ADR 4 supersedes ADR 3
        repo.supersede("Use CockroachDB", 3).unwrap();

        // Check ADR 3 has both directions
        let adr3_content =
            fs::read_to_string(repo.adr_path().join("0003-use-postgresql.md")).unwrap();
        assert!(
            adr3_content.contains("Supersedes [2. Use SQLite](0002-use-sqlite.md)"),
            "ADR 3 should supersede ADR 2. Got:\n{adr3_content}"
        );
        assert!(
            adr3_content.contains("Superseded by [4. Use CockroachDB](0004-use-cockroachdb.md)"),
            "ADR 3 should be superseded by ADR 4. Got:\n{adr3_content}"
        );
    }

    #[test]
    fn test_ng_mode_supersede_generates_functional_links() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, true).unwrap();

        repo.new_adr("Use MySQL").unwrap();
        repo.supersede("Use PostgreSQL", 2).unwrap();

        // Check the new ADR has functional links in both frontmatter and body
        let new_content =
            fs::read_to_string(repo.adr_path().join("0003-use-postgresql.md")).unwrap();

        // Body should have functional markdown link
        assert!(
            new_content.contains("Supersedes [2. Use MySQL](0002-use-mysql.md)"),
            "NG mode should have functional link in body. Got:\n{new_content}"
        );
        // Frontmatter should have structured link
        assert!(new_content.contains("links:"));
        assert!(new_content.contains("target: 2"));
    }

    // ========== Set Status Tests ==========

    #[test]
    fn test_set_status_accepted() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();
        repo.new_adr("Test Decision").unwrap();

        repo.set_status(2, AdrStatus::Accepted, None).unwrap();

        let adr = repo.get(2).unwrap();
        assert_eq!(adr.status, AdrStatus::Accepted);
    }

    #[test]
    fn test_set_status_deprecated() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();
        repo.new_adr("Old Decision").unwrap();

        repo.set_status(2, AdrStatus::Deprecated, None).unwrap();

        let adr = repo.get(2).unwrap();
        assert_eq!(adr.status, AdrStatus::Deprecated);
    }

    #[test]
    fn test_set_status_superseded_with_link() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();
        repo.new_adr("First Decision").unwrap();
        repo.new_adr("Second Decision").unwrap();

        repo.set_status(2, AdrStatus::Superseded, Some(3)).unwrap();

        let adr = repo.get(2).unwrap();
        assert_eq!(adr.status, AdrStatus::Superseded);
        assert_eq!(adr.links.len(), 1);
        assert_eq!(adr.links[0].target, 3);
        assert_eq!(adr.links[0].kind, LinkKind::SupersededBy);
    }

    #[test]
    fn test_set_status_superseded_without_link() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();
        repo.new_adr("Decision").unwrap();

        repo.set_status(2, AdrStatus::Superseded, None).unwrap();

        let adr = repo.get(2).unwrap();
        assert_eq!(adr.status, AdrStatus::Superseded);
        assert_eq!(adr.links.len(), 0);
    }

    #[test]
    fn test_set_status_custom() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();
        repo.new_adr("Test Decision").unwrap();

        repo.set_status(2, AdrStatus::Custom("Draft".into()), None)
            .unwrap();

        let adr = repo.get(2).unwrap();
        assert_eq!(adr.status, AdrStatus::Custom("Draft".into()));
    }

    #[test]
    fn test_set_status_adr_not_found() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();

        let result = repo.set_status(99, AdrStatus::Accepted, None);
        assert!(result.is_err());
    }

    #[test]
    fn test_set_status_superseded_by_not_found() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();
        repo.new_adr("Decision").unwrap();

        let result = repo.set_status(2, AdrStatus::Superseded, Some(99));
        assert!(result.is_err());
    }

    // ========== Link Tests ==========

    #[test]
    fn test_link_adrs() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();
        repo.new_adr("Second").unwrap();

        repo.link(1, 2, LinkKind::Amends, LinkKind::AmendedBy)
            .unwrap();

        let adr1 = repo.get(1).unwrap();
        assert_eq!(adr1.links.len(), 1);
        assert_eq!(adr1.links[0].target, 2);
        assert_eq!(adr1.links[0].kind, LinkKind::Amends);

        let adr2 = repo.get(2).unwrap();
        assert_eq!(adr2.links.len(), 1);
        assert_eq!(adr2.links[0].target, 1);
        assert_eq!(adr2.links[0].kind, LinkKind::AmendedBy);
    }

    #[test]
    fn test_link_relates_to() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();
        repo.new_adr("Second").unwrap();

        repo.link(1, 2, LinkKind::RelatesTo, LinkKind::RelatesTo)
            .unwrap();

        let adr1 = repo.get(1).unwrap();
        assert_eq!(adr1.links[0].kind, LinkKind::RelatesTo);

        let adr2 = repo.get(2).unwrap();
        assert_eq!(adr2.links[0].kind, LinkKind::RelatesTo);
    }

    // ========== Update Tests ==========

    #[test]
    fn test_update_adr() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();

        let mut adr = repo.get(1).unwrap();
        adr.status = AdrStatus::Deprecated;

        repo.update(&adr).unwrap();

        let updated = repo.get(1).unwrap();
        assert_eq!(updated.status, AdrStatus::Deprecated);
    }

    #[test]
    fn test_update_preserves_content() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();

        let mut adr = repo.get(1).unwrap();
        let original_title = adr.title.clone();
        adr.status = AdrStatus::Deprecated;

        repo.update(&adr).unwrap();

        let updated = repo.get(1).unwrap();
        assert_eq!(updated.title, original_title);
    }

    // ========== Read/Write Content Tests ==========

    #[test]
    fn test_read_content() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();

        let adr = repo.get(1).unwrap();
        let content = repo.read_content(&adr).unwrap();

        assert!(content.contains("Record architecture decisions"));
        assert!(content.contains("## Status"));
    }

    #[test]
    fn test_write_content() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();

        let adr = repo.get(1).unwrap();
        let new_content = "# 1. Modified\n\n## Status\n\nAccepted\n";

        repo.write_content(&adr, new_content).unwrap();

        let content = repo.read_content(&adr).unwrap();
        assert!(content.contains("Modified"));
    }

    // ========== Template Configuration Tests ==========

    #[test]
    fn test_with_template_format() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false)
            .unwrap()
            .with_template_format(TemplateFormat::Madr);

        let (_, path) = repo.new_adr("MADR Test").unwrap();
        let content = fs::read_to_string(path).unwrap();

        assert!(content.contains("Context and Problem Statement"));
    }

    #[test]
    fn test_with_custom_template() {
        let temp = TempDir::new().unwrap();
        let custom = Template::from_string("custom", "# ADR {{ number }}: {{ title }}");
        let repo = Repository::init(temp.path(), None, false)
            .unwrap()
            .with_custom_template(custom);

        let (_, path) = repo.new_adr("Custom Test").unwrap();
        let content = fs::read_to_string(path).unwrap();

        assert_eq!(content, "# ADR 2: Custom Test");
    }

    // ========== Accessor Tests ==========

    #[test]
    fn test_root() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();

        assert_eq!(repo.root(), temp.path());
    }

    #[test]
    fn test_config() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), Some("custom".into()), true).unwrap();

        assert_eq!(repo.config().adr_dir, PathBuf::from("custom"));
        assert!(repo.config().is_next_gen());
    }

    #[test]
    fn test_adr_path() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), Some("my/adrs".into()), false).unwrap();

        assert_eq!(repo.adr_path(), temp.path().join("my/adrs"));
    }

    // ========== NextGen Mode Tests ==========

    #[test]
    fn test_ng_mode_creates_frontmatter() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, true).unwrap();

        let (_, path) = repo.new_adr("NG Test").unwrap();
        let content = fs::read_to_string(path).unwrap();

        assert!(content.starts_with("---"));
        assert!(content.contains("number: 2"));
        assert!(content.contains("title: NG Test"));
    }

    #[test]
    fn test_ng_mode_parses_frontmatter() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, true).unwrap();

        repo.new_adr("NG ADR").unwrap();

        let adr = repo.get(2).unwrap();
        assert_eq!(adr.title, "NG ADR");
        assert_eq!(adr.number, 2);
    }

    // ========== Edge Cases ==========

    #[test]
    fn test_list_empty_after_init_removal() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();

        // Remove the initial ADR
        fs::remove_file(
            repo.adr_path()
                .join("0001-record-architecture-decisions.md"),
        )
        .unwrap();

        let adrs = repo.list().unwrap();
        assert!(adrs.is_empty());
    }

    #[test]
    fn test_list_ignores_non_adr_files() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();

        // Create non-ADR files
        fs::write(repo.adr_path().join("README.md"), "# README").unwrap();
        fs::write(repo.adr_path().join("notes.txt"), "Notes").unwrap();

        let adrs = repo.list().unwrap();
        assert_eq!(adrs.len(), 1); // Only the initial ADR
    }

    #[test]
    fn test_special_characters_in_title() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();

        let (adr, path) = repo.new_adr("Use C++ & Rust!").unwrap();
        assert!(path.exists());
        assert_eq!(adr.title, "Use C++ & Rust!");
    }

    // ========== Metadata Preservation Tests (issue #187) ==========

    #[test]
    fn test_set_status_preserves_madr_body() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, true).unwrap();

        let madr_content = r#"---
number: 2
title: Use Redis for caching
date: 2026-01-15
status: proposed
---

# Use Redis for caching

## Context and Problem Statement

We need a **fast** caching layer for our [API](https://api.example.com).

## Considered Options

* Redis
* Memcached
* In-memory cache

## Decision Outcome

Chosen option: "Redis", because it supports data structures beyond simple key-value.

### Consequences

* Good, because it provides pub/sub
* Bad, because it adds operational complexity

## Pros and Cons of the Options

### Redis

* Good, because it supports complex data types
* Bad, because it requires a separate server

### Memcached

* Good, because it's simpler
* Bad, because it only supports strings
"#;
        let adr_path = repo.adr_path().join("0002-use-redis-for-caching.md");
        fs::write(&adr_path, madr_content).unwrap();

        // Change status
        repo.set_status(2, AdrStatus::Accepted, None).unwrap();

        let result = fs::read_to_string(&adr_path).unwrap();

        // Status should be updated
        assert!(result.contains("status: accepted"));
        assert!(!result.contains("status: proposed"));

        // Body should be completely preserved
        let body_start = result.find("\n# Use Redis").unwrap();
        let original_body_start = madr_content.find("\n# Use Redis").unwrap();
        assert_eq!(
            &result[body_start..],
            &madr_content[original_body_start..],
            "Body content was modified"
        );
    }

    #[test]
    fn test_set_status_preserves_yaml_comments() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, true).unwrap();

        let content_with_comments = r#"---
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: 2026 Example Corp
number: 2
title: Use MADR format
date: 2026-01-15
status: proposed
---

## Context and Problem Statement

We need a standard ADR format.

## Decision Outcome

Use MADR 4.0.0.
"#;
        let adr_path = repo.adr_path().join("0002-use-madr-format.md");
        fs::write(&adr_path, content_with_comments).unwrap();

        repo.set_status(2, AdrStatus::Accepted, None).unwrap();

        let result = fs::read_to_string(&adr_path).unwrap();

        // YAML comments must be preserved
        assert!(
            result.contains("# SPDX-License-Identifier: MIT"),
            "SPDX comment was destroyed"
        );
        assert!(
            result.contains("# SPDX-FileCopyrightText: 2026 Example Corp"),
            "Copyright comment was destroyed"
        );
        assert!(result.contains("status: accepted"));
    }

    #[test]
    fn test_set_status_preserves_markdown_links() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, true).unwrap();

        let content = r#"---
number: 2
title: Use PostgreSQL
date: 2026-01-15
status: proposed
---

## Context

See the [PostgreSQL docs](https://www.postgresql.org/docs/) for details.

Also see [RFC 7159](https://tools.ietf.org/html/rfc7159) and `inline code`.

## Decision

We will use **PostgreSQL** version `16.x`.

## Consequences

- [Monitoring guide](https://example.com/monitoring)
- Performance benchmarks in [this report](./benchmarks.md)
"#;
        let adr_path = repo.adr_path().join("0002-use-postgresql.md");
        fs::write(&adr_path, content).unwrap();

        repo.set_status(2, AdrStatus::Accepted, None).unwrap();

        let result = fs::read_to_string(&adr_path).unwrap();

        assert!(result.contains("[PostgreSQL docs](https://www.postgresql.org/docs/)"));
        assert!(result.contains("[RFC 7159](https://tools.ietf.org/html/rfc7159)"));
        assert!(result.contains("`inline code`"));
        assert!(result.contains("**PostgreSQL**"));
        assert!(result.contains("[Monitoring guide](https://example.com/monitoring)"));
        assert!(result.contains("[this report](./benchmarks.md)"));
    }

    #[test]
    fn test_link_preserves_body_content() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, true).unwrap();

        let content_1 = r#"---
number: 2
title: First decision
date: 2026-01-15
status: accepted
---

## Context

Custom context with **bold** and [links](https://example.com).

## Decision

A detailed decision paragraph.

## Consequences

- Important consequence 1
- Important consequence 2
"#;
        let content_2 = r#"---
number: 3
title: Second decision
date: 2026-01-16
status: accepted
---

## Context

Different context entirely.

## Decision

Another decision.

## Consequences

None significant.
"#;
        fs::write(repo.adr_path().join("0002-first-decision.md"), content_1).unwrap();
        fs::write(repo.adr_path().join("0003-second-decision.md"), content_2).unwrap();

        repo.link(2, 3, LinkKind::Amends, LinkKind::AmendedBy)
            .unwrap();

        let result_1 = fs::read_to_string(repo.adr_path().join("0002-first-decision.md")).unwrap();
        let result_2 = fs::read_to_string(repo.adr_path().join("0003-second-decision.md")).unwrap();

        // Bodies must be intact
        assert!(result_1.contains("Custom context with **bold** and [links](https://example.com)"));
        assert!(result_1.contains("A detailed decision paragraph."));
        assert!(result_2.contains("Different context entirely."));
        assert!(result_2.contains("None significant."));

        // Links must be present in frontmatter
        assert!(result_1.contains("links:"));
        assert!(result_1.contains("target: 3"));
        assert!(result_2.contains("links:"));
        assert!(result_2.contains("target: 2"));
    }

    #[test]
    fn test_supersede_preserves_old_adr_body() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, true).unwrap();

        let rich_content = r#"---
number: 2
title: Original approach
date: 2026-01-15
status: accepted
---

## Context and Problem Statement

This has **rich** markdown with [links](https://example.com).

```rust
fn important_code() -> bool {
    true
}
```

## Decision Outcome

We chose the original approach.

| Criteria | Score |
|----------|-------|
| Speed    | 9/10  |
| Safety   | 8/10  |
"#;
        fs::write(
            repo.adr_path().join("0002-original-approach.md"),
            rich_content,
        )
        .unwrap();

        repo.supersede("Better approach", 2).unwrap();

        let old_content =
            fs::read_to_string(repo.adr_path().join("0002-original-approach.md")).unwrap();

        // Old ADR body must be preserved
        assert!(old_content.contains("```rust"));
        assert!(old_content.contains("fn important_code()"));
        assert!(old_content.contains("| Criteria | Score |"));
        assert!(old_content.contains("[links](https://example.com)"));

        // Status and links must be updated
        assert!(old_content.contains("status: superseded"));
        assert!(old_content.contains("target: 3"));
    }

    #[test]
    fn test_set_status_legacy_preserves_sections() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, false).unwrap();

        let legacy_content = r#"# 2. Use Rust for backend

Date: 2026-01-15

## Status

Proposed

## Context

We need a fast, safe language for our backend services.

See the [Rust book](https://doc.rust-lang.org/book/) for details.

## Decision

We will use **Rust** with the `tokio` runtime.

```toml
[dependencies]
tokio = { version = "1", features = ["full"] }
```

## Consequences

- Type safety prevents many bugs at compile time
- Learning curve for team members
"#;
        let adr_path = repo.adr_path().join("0002-use-rust-for-backend.md");
        fs::write(&adr_path, legacy_content).unwrap();

        repo.set_status(2, AdrStatus::Accepted, None).unwrap();

        let result = fs::read_to_string(&adr_path).unwrap();

        // Status should change
        assert!(result.contains("Accepted"));

        // Other sections must be preserved exactly
        assert!(result.contains("[Rust book](https://doc.rust-lang.org/book/)"));
        assert!(result.contains("**Rust**"));
        assert!(result.contains("`tokio`"));
        assert!(result.contains("```toml"));
        assert!(result.contains("tokio = { version = \"1\", features = [\"full\"] }"));
        assert!(result.contains("Type safety prevents many bugs"));
    }

    #[test]
    fn test_set_status_frontmatter_with_existing_links() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, true).unwrap();

        let content = r#"---
number: 2
title: Updated approach
date: 2026-01-15
status: proposed
links:
  - target: 1
    kind: amends
---

## Context

Context.

## Decision

Decision.
"#;
        let adr_path = repo.adr_path().join("0002-updated-approach.md");
        fs::write(&adr_path, content).unwrap();

        // Just change status, links should be preserved
        repo.set_status(2, AdrStatus::Accepted, None).unwrap();

        let result = fs::read_to_string(&adr_path).unwrap();
        assert!(result.contains("status: accepted"));
        assert!(result.contains("links:"));
        assert!(result.contains("target: 1"));
        assert!(result.contains("kind: amends"));
        // No extra blank line before closing ---
        assert!(
            !result.contains("\n\n---"),
            "Should not have extra blank line before closing ---: {:?}",
            result
        );
    }

    #[test]
    fn test_set_status_no_extra_newline_before_separator() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, true).unwrap();

        let content = "---\nnumber: 2\ntitle: Test\ndate: 2026-01-15\nstatus: proposed\n---\n\n## Context\n\nContext.\n";
        let adr_path = repo.adr_path().join("0002-test.md");
        fs::write(&adr_path, content).unwrap();

        repo.set_status(2, AdrStatus::Accepted, None).unwrap();

        let result = fs::read_to_string(&adr_path).unwrap();
        assert!(result.contains("status: accepted"));
        // Frontmatter should close cleanly without extra blank line (#192)
        assert!(
            result.contains("\n---\n"),
            "Should have clean closing separator: {:?}",
            result
        );
        assert!(
            !result.contains("\n\n---"),
            "Should not have extra blank line before closing ---: {:?}",
            result
        );
    }

    #[test]
    fn test_update_metadata_adds_tags_to_frontmatter() {
        let temp = TempDir::new().unwrap();
        let repo = Repository::init(temp.path(), None, true).unwrap();

        let content = r#"---
number: 2
title: Tagged ADR
date: 2026-01-15
status: proposed
---

## Context

Context.
"#;
        let adr_path = repo.adr_path().join("0002-tagged-adr.md");
        fs::write(&adr_path, content).unwrap();

        let mut adr = repo.get(2).unwrap();
        adr.set_tags(vec!["security".into(), "api".into()]);
        repo.update_metadata(&adr).unwrap();

        let result = fs::read_to_string(&adr_path).unwrap();
        assert!(result.contains("tags:"));
        assert!(result.contains("  - security"));
        assert!(result.contains("  - api"));
        // Body preserved
        assert!(result.contains("## Context\n\nContext."));
    }
}