nereid 0.9.0

Source-available noncommercial terminal diagram TUI and MCP server for Mermaid-backed sessions
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
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
// SPDX-FileCopyrightText: 2026 Bruno Meilick
// SPDX-License-Identifier: LicenseRef-Nereid-FreeUse-NoCopy-NoDerivatives
//
// All rights reserved.
//
// This file is part of Nereid and is proprietary software.
// Unauthorized copying, modification, or distribution is prohibited.

//! Filesystem adapter for a single session directory (`SessionFolder`).
//!
//! Coordinates meta commit, per-diagram Mermaid + sidecar writes, walkthrough files, async
//! text exports, and cross-process write locking. Prefer `begin_session_update` / `commit`
//! when MCP and TUI cohabit. Atomic writes revalidate paths against symlink TOCTOU; GC cancels
//! pending ascii exports by both `*.wt.json` and `*.ascii.txt` keys.

use std::collections::hash_map::Entry;
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
use std::fmt;
use std::fs;
use std::fs::OpenOptions;
use std::io;
use std::io::Seek;
use std::io::SeekFrom;
use std::io::Write;
use std::path::{Component, Path, PathBuf};
use std::sync::{Arc, Condvar, Mutex, OnceLock};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use fs2::FileExt;
use serde::{Deserialize, Serialize};

use crate::format::mermaid::{
    export_class_diagram, export_er_diagram, export_flowchart, export_gantt_diagram,
    export_sequence_diagram, parse_class_diagram, parse_er_diagram, parse_flowchart,
    parse_gantt_diagram, parse_sequence_diagram, MermaidClassExportError, MermaidClassParseError,
    MermaidErExportError, MermaidErParseError, MermaidFlowchartExportError,
    MermaidFlowchartParseError, MermaidGanttExportError, MermaidGanttParseError,
    MermaidSequenceExportError, MermaidSequenceParseError,
};
use crate::layout::{layout_flowchart, layout_sequence, FlowchartLayoutError, SequenceLayoutError};
use crate::model::seq_ast::{SequenceBlock, SequenceBlockKind, SequenceSectionKind};
use crate::model::{
    ClassRelationKind, Diagram, DiagramAst, DiagramAstKindMismatch, DiagramId, DiagramKind,
    ErCardinality, ErStroke, FlowNode, FlowchartAst, IdError, ObjectId, ObjectRef,
    ParseObjectRefError, SequenceAst, SequenceMessageKind, Session, SessionId, SymbolAnchor,
    SymbolAnchorError, Walkthrough, WalkthroughEdge, WalkthroughId, WalkthroughNode,
    WalkthroughNodeId, XRef, XRefId, XRefStatus as ModelXRefStatus,
};
use crate::render::{
    render_flowchart_unicode, render_sequence_unicode, render_walkthrough_unicode,
    FlowchartRenderError, SequenceRenderError, WalkthroughRenderError,
};

const SESSION_META_FILENAME: &str = "nereid-session.meta.json";
const LEGACY_SESSION_META_FILENAME: &str = "session.meta.json";
const SESSION_WRITE_LOCK_FILENAME: &str = ".nereid-session.write.lock";

fn migrate_legacy_gantt_lane_ref(session: &Session, object_ref: ObjectRef) -> ObjectRef {
    let [left, right] = object_ref.category().segments() else {
        return object_ref;
    };
    if left != "gantt" || right != "lane" {
        return object_ref;
    }
    let Some(day) = object_ref
        .object_id()
        .as_str()
        .strip_prefix("lane:")
        .filter(|suffix| suffix.len() == 4 && suffix.chars().all(|ch| ch.is_ascii_digit()))
        .and_then(|suffix| suffix.parse::<u32>().ok())
    else {
        return object_ref;
    };
    let Some(DiagramAst::Gantt(ast)) =
        session.diagrams().get(object_ref.diagram_id()).map(Diagram::ast)
    else {
        return object_ref;
    };
    let Some(lane_id) = ast.lane_id_for_relative_day(day) else {
        return object_ref;
    };
    ObjectRef::new(object_ref.diagram_id().clone(), object_ref.category().clone(), lane_id)
}

fn migrate_legacy_gantt_lane_walkthrough_refs(session: &Session, walkthrough: &mut Walkthrough) {
    for node in walkthrough.nodes_mut() {
        for object_ref in node.refs_mut() {
            *object_ref = migrate_legacy_gantt_lane_ref(session, object_ref.clone());
        }
    }
}
const SESSION_WRITE_LOCK_RETRY_DELAY: Duration = Duration::from_millis(10);
const SESSION_WRITE_LOCK_TIMEOUT: Duration = Duration::from_secs(30);

mod reconcile;

use reconcile::{reconcile_diagram_ast, stable_id_map_from_ast};

#[derive(Debug)]
enum AsciiExportTask {
    Diagram {
        session_dir: PathBuf,
        mmd_path: PathBuf,
        text_path: PathBuf,
        durability: WriteDurability,
        ast: DiagramAst,
    },
    Walkthrough {
        session_dir: PathBuf,
        json_path: PathBuf,
        text_path: PathBuf,
        durability: WriteDurability,
        walkthrough: Walkthrough,
    },
}

impl AsciiExportTask {
    fn output_path(&self) -> &Path {
        match self {
            Self::Diagram { text_path, .. } | Self::Walkthrough { text_path, .. } => text_path,
        }
    }

    fn session_dir(&self) -> &Path {
        match self {
            Self::Diagram { session_dir, .. } | Self::Walkthrough { session_dir, .. } => {
                session_dir
            }
        }
    }
}

#[derive(Debug, Default)]
struct AsciiExportState {
    pending: HashMap<PathBuf, AsciiExportTask>,
    queue: VecDeque<PathBuf>,
    in_flight_session_dir: Option<PathBuf>,
}

#[derive(Debug)]
struct AsciiExportInner {
    state: Mutex<AsciiExportState>,
    cv: Condvar,
}

#[derive(Debug)]
struct AsciiExportManager {
    inner: Arc<AsciiExportInner>,
}

impl AsciiExportManager {
    fn new() -> Self {
        let inner = Arc::new(AsciiExportInner {
            state: Mutex::new(AsciiExportState::default()),
            cv: Condvar::new(),
        });

        std::thread::Builder::new()
            .name("nereid-ascii-export".to_owned())
            .spawn({
                let inner = inner.clone();
                move || Self::run_worker(inner)
            })
            .expect("spawn ascii export worker thread");

        Self { inner }
    }

    fn schedule(&self, task: AsciiExportTask) {
        let output_path = task.output_path().to_path_buf();

        let mut state = self.inner.state.lock().expect("ascii export lock poisoned");
        match state.pending.entry(output_path.clone()) {
            Entry::Occupied(mut entry) => {
                entry.insert(task);
                return;
            }
            Entry::Vacant(entry) => {
                entry.insert(task);
            }
        }
        state.queue.push_back(output_path);
        self.inner.cv.notify_one();
    }

    fn cancel(&self, output_path: &Path) {
        let mut state = self.inner.state.lock().expect("ascii export lock poisoned");
        state.pending.remove(output_path);
    }

    fn flush_session_dir(&self, session_dir: &Path) {
        let mut state = self.inner.state.lock().expect("ascii export lock poisoned");
        while state.in_flight_session_dir.as_deref().is_some_and(|active| active == session_dir)
            || state.pending.values().any(|task| task.session_dir() == session_dir)
        {
            state = self.inner.cv.wait(state).expect("ascii export cv poisoned");
        }
    }

    fn run_worker(inner: Arc<AsciiExportInner>) {
        loop {
            let task = {
                let mut state = inner.state.lock().expect("ascii export lock poisoned");

                loop {
                    if let Some(output_path) = state.queue.pop_front() {
                        if let Some(task) = state.pending.remove(&output_path) {
                            state.in_flight_session_dir = Some(task.session_dir().to_path_buf());
                            break task;
                        }
                    }

                    state = inner.cv.wait(state).expect("ascii export cv poisoned");
                }
            };

            match task {
                AsciiExportTask::Diagram { session_dir, mmd_path, text_path, durability, ast } => {
                    if !mmd_path.is_file() {
                        // Likely removed or cleaned up; avoid resurrecting temp session dirs.
                    } else if let Some(mut text) = match ast {
                        DiagramAst::Sequence(ast) => match layout_sequence(&ast) {
                            Ok(layout) => render_sequence_unicode(&ast, &layout).ok(),
                            Err(_) => None,
                        },
                        DiagramAst::Flowchart(ast) => match layout_flowchart(&ast) {
                            Ok(layout) => render_flowchart_unicode(&ast, &layout).ok(),
                            Err(_) => None,
                        },
                        DiagramAst::Class(ast) => {
                            use crate::render::{
                                lower_class, render_class_unicode_with_options, RenderOptions,
                            };
                            let model = lower_class(&ast);
                            render_class_unicode_with_options(&model, RenderOptions::default()).ok()
                        }
                        DiagramAst::Er(ast) => {
                            use crate::render::{
                                lower_er, render_er_unicode_with_options, RenderOptions,
                            };
                            let model = lower_er(&ast);
                            render_er_unicode_with_options(&model, RenderOptions::default()).ok()
                        }
                        DiagramAst::Gantt(ast) => crate::render::track_paint::render_gantt_unicode(
                            &ast,
                            crate::render::RenderOptions::default(),
                        )
                        .ok(),
                    } {
                        if !text.ends_with('\n') {
                            text.push('\n');
                        }
                        let _ = write_atomic_in_session_if_session_dir_exists(
                            &session_dir,
                            &text_path,
                            text.as_bytes(),
                            durability,
                        );
                    }
                }
                AsciiExportTask::Walkthrough {
                    session_dir,
                    json_path,
                    text_path,
                    durability,
                    walkthrough,
                } => {
                    if !json_path.is_file() {
                        // Walkthrough was likely deleted/garbage-collected.
                    } else if let Ok(mut text) = render_walkthrough_unicode(&walkthrough) {
                        if !text.ends_with('\n') {
                            text.push('\n');
                        }
                        // Re-check after render: GC may have cancelled/deleted while we
                        // were working. Avoid resurrecting orphan `*.ascii.txt` sidecars.
                        if json_path.is_file() {
                            let _ = write_atomic_in_session_if_session_dir_exists(
                                &session_dir,
                                &text_path,
                                text.as_bytes(),
                                durability,
                            );
                        }
                    }
                }
            }

            let mut state = inner.state.lock().expect("ascii export lock poisoned");
            state.in_flight_session_dir = None;
            inner.cv.notify_all();
        }
    }
}

static ASCII_EXPORTS: OnceLock<AsciiExportManager> = OnceLock::new();

fn ascii_exports() -> &'static AsciiExportManager {
    ASCII_EXPORTS.get_or_init(AsciiExportManager::new)
}

/// Filesystem, parse, layout/render, and validation errors from session persistence.
#[derive(Debug)]
pub enum StoreError {
    Io {
        path: PathBuf,
        source: io::Error,
    },
    Json {
        path: PathBuf,
        source: serde_json::Error,
    },
    MermaidSequenceParse {
        diagram_id: DiagramId,
        path: PathBuf,
        source: Box<MermaidSequenceParseError>,
    },
    MermaidFlowchartParse {
        diagram_id: DiagramId,
        path: PathBuf,
        source: Box<MermaidFlowchartParseError>,
    },
    MermaidSequenceExport {
        diagram_id: DiagramId,
        path: PathBuf,
        source: Box<MermaidSequenceExportError>,
    },
    MermaidFlowchartExport {
        diagram_id: DiagramId,
        path: PathBuf,
        source: Box<MermaidFlowchartExportError>,
    },
    MermaidClassParse {
        diagram_id: DiagramId,
        path: PathBuf,
        source: Box<MermaidClassParseError>,
    },
    MermaidClassExport {
        diagram_id: DiagramId,
        path: PathBuf,
        source: Box<MermaidClassExportError>,
    },
    MermaidErParse {
        diagram_id: DiagramId,
        path: PathBuf,
        source: Box<MermaidErParseError>,
    },
    MermaidErExport {
        diagram_id: DiagramId,
        path: PathBuf,
        source: Box<MermaidErExportError>,
    },
    MermaidGanttParse {
        diagram_id: DiagramId,
        path: PathBuf,
        source: Box<MermaidGanttParseError>,
    },
    MermaidGanttExport {
        diagram_id: DiagramId,
        path: PathBuf,
        source: Box<MermaidGanttExportError>,
    },
    SequenceLayout {
        diagram_id: DiagramId,
        path: PathBuf,
        source: Box<SequenceLayoutError>,
    },
    SequenceRender {
        diagram_id: DiagramId,
        path: PathBuf,
        source: Box<SequenceRenderError>,
    },
    FlowchartLayout {
        diagram_id: DiagramId,
        path: PathBuf,
        source: Box<FlowchartLayoutError>,
    },
    FlowchartRender {
        diagram_id: DiagramId,
        path: PathBuf,
        source: Box<FlowchartRenderError>,
    },
    WalkthroughRender {
        walkthrough_id: WalkthroughId,
        path: PathBuf,
        source: Box<WalkthroughRenderError>,
    },
    InvalidId {
        field: &'static str,
        value: String,
        source: Box<IdError>,
    },
    InvalidObjectRef {
        field: &'static str,
        value: String,
        source: Box<ParseObjectRefError>,
    },
    InvalidSymbolAnchor {
        field: &'static str,
        value: String,
        source: Box<SymbolAnchorError>,
    },
    /// Relative path escapes the session root or contains disallowed components (`..`, absolute).
    InvalidRelativePath {
        field: &'static str,
        value: PathBuf,
    },
    /// Resolved path is not under the session directory (after canonicalize).
    PathOutsideSession {
        session_dir: PathBuf,
        path: PathBuf,
    },
    /// Refusing to follow or write through a symlink inside the session tree.
    SymlinkRefused {
        path: PathBuf,
    },
    /// Timed out acquiring `.nereid-session.write.lock` (cross-process exclusive).
    SessionWriteLockTimeout {
        path: PathBuf,
    },
    /// Meta missing but `diagrams/` has content — refuse to seed and orphan existing files.
    MetaMissingWithExistingDiagrams {
        meta_path: PathBuf,
        diagrams_dir: PathBuf,
    },
    /// Meta missing but `walkthroughs/` has content — refuse to seed and orphan existing files.
    MetaMissingWithExistingWalkthroughs {
        meta_path: PathBuf,
        walkthroughs_dir: PathBuf,
    },
    WalkthroughIdMismatch {
        path: PathBuf,
        expected: WalkthroughId,
        found: WalkthroughId,
    },
}

impl fmt::Display for StoreError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Io { path, source } => write!(f, "io error at {path:?}: {source}"),
            Self::Json { path, source } => write!(f, "json error at {path:?}: {source}"),
            Self::MermaidSequenceParse {
                diagram_id,
                path,
                source,
            } => write!(
                f,
                "cannot parse Mermaid sequence diagram {diagram_id} from {path:?}: {source}"
            ),
            Self::MermaidFlowchartParse {
                diagram_id,
                path,
                source,
            } => write!(
                f,
                "cannot parse Mermaid flowchart diagram {diagram_id} from {path:?}: {source}"
            ),
            Self::MermaidSequenceExport {
                diagram_id,
                path,
                source,
            } => write!(
                f,
                "cannot export Mermaid sequence diagram {diagram_id} to {path:?}: {source}"
            ),
            Self::MermaidFlowchartExport {
                diagram_id,
                path,
                source,
            } => write!(
                f,
                "cannot export Mermaid flowchart diagram {diagram_id} to {path:?}: {source}"
            ),
            Self::MermaidClassParse {
                diagram_id,
                path,
                source,
            } => write!(
                f,
                "cannot parse Mermaid class diagram {diagram_id} from {path:?}: {source}"
            ),
            Self::MermaidClassExport {
                diagram_id,
                path,
                source,
            } => write!(
                f,
                "cannot export Mermaid class diagram {diagram_id} to {path:?}: {source}"
            ),
            Self::MermaidErParse {
                diagram_id,
                path,
                source,
            } => write!(
                f,
                "cannot parse Mermaid er diagram {diagram_id} from {path:?}: {source}"
            ),
            Self::MermaidErExport {
                diagram_id,
                path,
                source,
            } => write!(
                f,
                "cannot export Mermaid er diagram {diagram_id} to {path:?}: {source}"
            ),
            Self::MermaidGanttParse {
                diagram_id,
                path,
                source,
            } => write!(
                f,
                "cannot parse Mermaid gantt diagram {diagram_id} from {path:?}: {source}"
            ),
            Self::MermaidGanttExport {
                diagram_id,
                path,
                source,
            } => write!(
                f,
                "cannot export Mermaid gantt diagram {diagram_id} to {path:?}: {source}"
            ),
            Self::SequenceLayout {
                diagram_id,
                path,
                source,
            } => write!(
                f,
                "cannot layout sequence diagram {diagram_id} for unicode export to {path:?}: {source}"
            ),
            Self::SequenceRender {
                diagram_id,
                path,
                source,
            } => write!(
                f,
                "cannot render sequence diagram {diagram_id} for unicode export to {path:?}: {source}"
            ),
            Self::FlowchartLayout {
                diagram_id,
                path,
                source,
            } => write!(
                f,
                "cannot layout flowchart diagram {diagram_id} for unicode export to {path:?}: {source}"
            ),
            Self::FlowchartRender {
                diagram_id,
                path,
                source,
            } => write!(
                f,
                "cannot render flowchart diagram {diagram_id} for unicode export to {path:?}: {source}"
            ),
            Self::WalkthroughRender {
                walkthrough_id,
                path,
                source,
            } => write!(
                f,
                "cannot render walkthrough {walkthrough_id} for unicode export to {path:?}: {source}"
            ),
            Self::InvalidId {
                field,
                value,
                source,
            } => write!(f, "invalid id for {field}: {value:?}: {source}"),
            Self::InvalidObjectRef {
                field,
                value,
                source,
            } => write!(f, "invalid object ref for {field}: {value:?}: {source}"),
            Self::InvalidSymbolAnchor {
                field,
                value,
                source,
            } => write!(f, "invalid symbol anchor for {field}: {value:?}: {source}"),
            Self::InvalidRelativePath { field, value } => {
                write!(f, "invalid relative path for {field}: {value:?}")
            }
            Self::PathOutsideSession { session_dir, path } => write!(
                f,
                "path is outside session dir: session_dir={session_dir:?} path={path:?}"
            ),
            Self::SymlinkRefused { path } => {
                write!(f, "refusing to write through symlink at {path:?}")
            }
            Self::SessionWriteLockTimeout { path } => {
                write!(f, "timed out waiting for session write lock at {path:?}")
            }
            Self::MetaMissingWithExistingDiagrams { meta_path, diagrams_dir } => write!(
                f,
                "session meta {meta_path:?} is missing but diagram files exist in {diagrams_dir:?}; \
                 refusing to seed a fresh session and orphan them (restore the meta index to repair)"
            ),
            Self::MetaMissingWithExistingWalkthroughs { meta_path, walkthroughs_dir } => write!(
                f,
                "session meta {meta_path:?} is missing but walkthrough files exist in {walkthroughs_dir:?}; \
                 refusing to seed a fresh session and orphan them (restore the meta index to repair)"
            ),
            Self::WalkthroughIdMismatch {
                path,
                expected,
                found,
            } => write!(
                f,
                "walkthrough id mismatch at {path:?}: expected {expected}, found {found}"
            ),
        }
    }
}

impl std::error::Error for StoreError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io { source, .. } => Some(source),
            Self::Json { source, .. } => Some(source),
            Self::MermaidSequenceParse { source, .. } => Some(source),
            Self::MermaidFlowchartParse { source, .. } => Some(source),
            Self::MermaidSequenceExport { source, .. } => Some(source),
            Self::MermaidFlowchartExport { source, .. } => Some(source),
            Self::MermaidClassParse { source, .. } => Some(source),
            Self::MermaidClassExport { source, .. } => Some(source),
            Self::MermaidErParse { source, .. } => Some(source),
            Self::MermaidErExport { source, .. } => Some(source),
            Self::MermaidGanttParse { source, .. } => Some(source),
            Self::MermaidGanttExport { source, .. } => Some(source),
            Self::SequenceLayout { source, .. } => Some(source),
            Self::SequenceRender { source, .. } => Some(source),
            Self::FlowchartLayout { source, .. } => Some(source),
            Self::FlowchartRender { source, .. } => Some(source),
            Self::WalkthroughRender { source, .. } => Some(source),
            Self::InvalidId { source, .. } => Some(source),
            Self::InvalidObjectRef { source, .. } => Some(source),
            Self::InvalidSymbolAnchor { source, .. } => Some(source),
            Self::InvalidRelativePath { .. } => None,
            Self::PathOutsideSession { .. } => None,
            Self::SymlinkRefused { .. } => None,
            Self::SessionWriteLockTimeout { .. } => None,
            Self::MetaMissingWithExistingDiagrams { .. } => None,
            Self::MetaMissingWithExistingWalkthroughs { .. } => None,
            Self::WalkthroughIdMismatch { .. } => None,
        }
    }
}

/// On-disk session catalog: active ids, diagram index, xrefs, and selection.
///
/// Written as `nereid-session.meta.json` at the session folder root.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionMeta {
    pub session_id: SessionId,
    pub active_diagram_id: Option<DiagramId>,
    pub active_walkthrough_id: Option<WalkthroughId>,
    pub walkthrough_ids: Option<Vec<WalkthroughId>>,
    pub diagrams: Vec<SessionMetaDiagram>,
    pub xrefs: Vec<SessionXRef>,
    pub selected_object_refs: Vec<ObjectRef>,
}

/// One diagram row in session meta (id, kind, relative `.mmd` path, revision).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionMetaDiagram {
    pub diagram_id: DiagramId,
    pub name: String,
    pub kind: DiagramKind,
    pub mmd_path: PathBuf,
    pub rev: u64,
}

/// Cross-diagram link persisted in session meta with resolved status.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionXRef {
    pub xref_id: XRefId,
    pub from: ObjectRef,
    pub to: ObjectRef,
    pub kind: String,
    pub label: Option<String>,
    pub status: ModelXRefStatus,
}

/// Per-diagram sidecar payload: stable ids, structure fingerprints, notes, symbols.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiagramMeta {
    pub diagram_id: DiagramId,
    pub mmd_path: PathBuf,
    pub stable_id_map: DiagramStableIdMap,
    pub xrefs: Vec<DiagramXRef>,
    pub flow_edges: Vec<DiagramFlowEdgeMeta>,
    pub class_relations: Vec<DiagramClassRelationMeta>,
    pub er_relationships: Vec<DiagramErRelationshipMeta>,
    pub gantt_sections: Vec<DiagramGanttSectionMeta>,
    pub sequence_messages: Vec<DiagramSequenceMessageMeta>,
    pub sequence_blocks: Vec<DiagramSequenceBlockMeta>,
    pub default_symbol_repository_id: Option<String>,
    pub flow_node_notes: BTreeMap<ObjectId, String>,
    pub sequence_participant_notes: BTreeMap<ObjectId, String>,
    pub class_node_notes: BTreeMap<ObjectId, String>,
    pub er_entity_notes: BTreeMap<ObjectId, String>,
    pub gantt_task_notes: BTreeMap<ObjectId, String>,
    pub gantt_lane_notes: BTreeMap<ObjectId, String>,
    pub flow_node_symbols: BTreeMap<ObjectId, SymbolAnchor>,
    pub sequence_participant_symbols: BTreeMap<ObjectId, SymbolAnchor>,
}

/// Maps Mermaid surface keys → stable `ObjectId` strings for reconcile on load/replace.
///
/// `by_mermaid_id` (flow nodes / gantt tags), `by_name` (participants, classes, entities),
/// and `by_fingerprint` (messages, edges, relations, untagged gantt tasks) cover identity
/// when the textual Mermaid is rewritten.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DiagramStableIdMap {
    pub by_mermaid_id: BTreeMap<String, String>,
    pub by_name: BTreeMap<String, String>,
    /// Semantic fingerprints for objects without an explicit Mermaid id/tag.
    pub by_fingerprint: BTreeMap<String, String>,
}

/// XRef row stored in a diagram sidecar (stringified refs for JSON durability).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiagramXRef {
    pub xref_id: String,
    pub from: String,
    pub to: String,
    pub kind: String,
    pub label: Option<String>,
    pub status: XRefStatus,
}

/// Flow edge fingerprint for load-time id reconciliation.
///
/// Match key: `(from, to, label, normalized connector)`; `style` restores with the matched id.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiagramFlowEdgeMeta {
    pub edge_id: ObjectId,
    pub from_node_id: ObjectId,
    pub to_node_id: ObjectId,
    pub label: Option<String>,
    /// Normalized Mermaid connector; `None` means default solid `-->`.
    pub connector: Option<String>,
    pub style: Option<String>,
}

/// Class relation fingerprint for load-time id reconciliation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiagramClassRelationMeta {
    pub relation_id: ObjectId,
    pub from_class_id: ObjectId,
    pub to_class_id: ObjectId,
    pub kind: ClassRelationKind,
    pub label: Option<String>,
    pub raw_connector: Option<String>,
}

/// ER relationship fingerprint for load-time id reconciliation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiagramErRelationshipMeta {
    pub relationship_id: ObjectId,
    pub from_entity_id: ObjectId,
    pub to_entity_id: ObjectId,
    pub from_card: ErCardinality,
    pub to_card: ErCardinality,
    pub stroke: ErStroke,
    pub label: Option<String>,
}

/// Gantt section fingerprint for load-time id reconciliation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiagramGanttSectionMeta {
    pub section_id: ObjectId,
    pub name: String,
    pub task_ids: Vec<ObjectId>,
}

/// Sequence message fingerprint for load-time id reconciliation.
///
/// Match key: `(from, to, kind, text)` — order_key is not part of the fingerprint.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiagramSequenceMessageMeta {
    pub message_id: ObjectId,
    pub from_participant_id: ObjectId,
    pub to_participant_id: ObjectId,
    pub kind: SequenceMessageKind,
    pub text: String,
}

/// Sequence block tree fingerprint (parent + sections + membership).
///
/// Match key: kind, header, parent stable id, and per-section kind/header/message membership.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiagramSequenceBlockMeta {
    pub block_id: ObjectId,
    pub kind: SequenceBlockKind,
    pub header: Option<String>,
    pub parent_block_id: Option<ObjectId>,
    pub sections: Vec<DiagramSequenceSectionMeta>,
}

/// Section within a sequence block fingerprint.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiagramSequenceSectionMeta {
    pub section_id: ObjectId,
    pub kind: SequenceSectionKind,
    pub header: Option<String>,
    pub message_ids: Vec<ObjectId>,
}

/// Flatten sequence blocks with parent ids for sidecar persistence.
pub(crate) fn sequence_blocks_meta_from_ast(ast: &SequenceAst) -> Vec<DiagramSequenceBlockMeta> {
    fn walk(
        blocks: &[SequenceBlock],
        parent_block_id: Option<&ObjectId>,
        out: &mut Vec<DiagramSequenceBlockMeta>,
    ) {
        for block in blocks {
            out.push(DiagramSequenceBlockMeta {
                block_id: block.block_id().clone(),
                kind: block.kind(),
                header: block.header().map(ToOwned::to_owned),
                parent_block_id: parent_block_id.cloned(),
                sections: block
                    .sections()
                    .iter()
                    .map(|section| DiagramSequenceSectionMeta {
                        section_id: section.section_id().clone(),
                        kind: section.kind(),
                        header: section.header().map(ToOwned::to_owned),
                        message_ids: section.message_ids().to_vec(),
                    })
                    .collect(),
            });
            walk(block.blocks(), Some(block.block_id()), out);
        }
    }

    let mut out = Vec::new();
    walk(ast.blocks(), None, &mut out);
    out
}

fn class_relations_meta_from_ast(ast: &crate::model::ClassAst) -> Vec<DiagramClassRelationMeta> {
    ast.relations()
        .iter()
        .map(|(relation_id, relation)| DiagramClassRelationMeta {
            relation_id: relation_id.clone(),
            from_class_id: relation.from_class_id().clone(),
            to_class_id: relation.to_class_id().clone(),
            kind: relation.kind(),
            label: relation.label().map(ToOwned::to_owned),
            raw_connector: relation.raw_connector().map(ToOwned::to_owned),
        })
        .collect()
}

fn er_relationships_meta_from_ast(ast: &crate::model::ErAst) -> Vec<DiagramErRelationshipMeta> {
    ast.relationships()
        .iter()
        .map(|(relationship_id, relationship)| DiagramErRelationshipMeta {
            relationship_id: relationship_id.clone(),
            from_entity_id: relationship.from_entity_id().clone(),
            to_entity_id: relationship.to_entity_id().clone(),
            from_card: relationship.from_card(),
            to_card: relationship.to_card(),
            stroke: relationship.stroke(),
            label: relationship.label().map(ToOwned::to_owned),
        })
        .collect()
}

fn gantt_sections_meta_from_ast(ast: &crate::model::GanttAst) -> Vec<DiagramGanttSectionMeta> {
    ast.sections()
        .iter()
        .map(|section| DiagramGanttSectionMeta {
            section_id: section.section_id().clone(),
            name: section.name().to_owned(),
            task_ids: section.task_ids().to_vec(),
        })
        .collect()
}

/// Endpoint validity of an xref after reconcile (ok or which side is missing).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum XRefStatus {
    Ok,
    DanglingFrom,
    DanglingTo,
    DanglingBoth,
}

/// Filesystem adapter for the session folder format under a single root directory.
///
/// Coordinates meta JSON, per-diagram Mermaid + sidecars, walkthrough JSON, ASCII exports,
/// and cross-process write locking. In-process writers also take `meta_lock` before the
/// file lock so process-local critical sections nest in a fixed order.
#[derive(Debug, Clone)]
pub struct SessionFolder {
    root: PathBuf,
    durability: WriteDurability,
    meta_lock: Arc<Mutex<()>>,
}

#[derive(Debug)]
struct DiagramArtifactsSnapshot {
    mmd_path: PathBuf,
    meta_path: PathBuf,
    mmd_contents: Option<Vec<u8>>,
    meta_contents: Option<Vec<u8>>,
}

#[derive(Debug)]
struct WalkthroughArtifactsSnapshot {
    json_path: PathBuf,
    ascii_path: PathBuf,
    json_contents: Option<Vec<u8>>,
    ascii_contents: Option<Vec<u8>>,
}

/// Scoped session mutation guarded by the folder write lock; commit persists atomically.
///
/// Created by [`SessionFolder::begin_session_update`] (lock + reload). Drop without commit
/// discards in-memory edits and releases the write lock. Diagram-level OCC still uses
/// `base_rev` via `ops::apply_ops` inside the update body.
#[derive(Debug)]
pub struct SessionUpdate<'a> {
    folder: &'a SessionFolder,
    _guard: SessionWriteGuard<'a>,
    session: Option<Session>,
}

impl<'a> SessionUpdate<'a> {
    /// Borrow the in-memory session (panics after commit).
    pub fn session(&self) -> &Session {
        self.session.as_ref().expect("session update is committed")
    }

    /// Mutably borrow the in-memory session (panics after commit).
    pub fn session_mut(&mut self) -> &mut Session {
        self.session.as_mut().expect("session update is committed")
    }

    /// Write the session to disk and release the update (single-use).
    pub fn commit(mut self) -> Result<Session, StoreError> {
        let session = self.session.take().expect("session update is committed once");
        self.folder.save_session_locked(&session)?;
        Ok(session)
    }
}

/// Holds process-local `meta_lock` then exclusive `.nereid-session.write.lock` (order: mutex → file).
#[derive(Debug)]
struct SessionWriteGuard<'a> {
    _meta_guard: std::sync::MutexGuard<'a, ()>,
    lock_path: PathBuf,
    lock_file: fs::File,
}

impl Drop for SessionWriteGuard<'_> {
    fn drop(&mut self) {
        if self.lock_file.set_len(0).is_err() {
            let _ = &self.lock_path;
        }
        let _ = FileExt::unlock(&self.lock_file);
    }
}

fn try_lock_session_file(file: &fs::File, path: &Path) -> Result<bool, StoreError> {
    file.try_lock_exclusive().map(|()| true).or_else(|source| {
        if source.kind() == io::ErrorKind::WouldBlock {
            Ok(false)
        } else {
            Err(StoreError::Io { path: path.to_path_buf(), source })
        }
    })
}

/// How aggressively atomic session writes fsync before/after rename.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum WriteDurability {
    /// Fast, best-effort persistence.
    ///
    /// - Writes a temp file and renames atomically into place.
    /// - Does not perform per-file fsync/sync.
    #[default]
    BestEffort,

    /// Slower, best-effort durability.
    ///
    /// Attempts to flush written file contents and rename operations to stable storage where
    /// possible. Exact guarantees are platform/filesystem-dependent.
    Durable,
}

fn encode_persisted_id_segment(segment: &str) -> String {
    if !needs_windows_safe_filename_segment_encoding(segment) {
        return segment.to_owned();
    }

    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut out = String::with_capacity(1 + segment.len().saturating_mul(2));
    out.push('~');
    for &b in segment.as_bytes() {
        out.push(HEX[(b >> 4) as usize] as char);
        out.push(HEX[(b & 0x0f) as usize] as char);
    }
    out
}

fn validate_legacy_persisted_id_segment(
    field: &'static str,
    segment: &str,
) -> Result<(), StoreError> {
    if segment.contains('/') || segment.contains('\\') {
        return Err(StoreError::InvalidRelativePath { field, value: PathBuf::from(segment) });
    }

    Ok(())
}

fn needs_windows_safe_filename_segment_encoding(segment: &str) -> bool {
    if segment.starts_with('~') {
        return true;
    }
    if segment == "." || segment == ".." {
        return true;
    }
    if segment.ends_with(' ') || segment.ends_with('.') {
        return true;
    }

    let trimmed = segment.trim_end_matches([' ', '.']);
    let base = trimmed.split('.').next().unwrap_or(trimmed);
    if is_windows_device_name(base) {
        return true;
    }

    for ch in segment.chars() {
        if matches!(ch, '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*') {
            return true;
        }
        if ch <= '\u{1f}' || ch == '\u{7f}' {
            return true;
        }
    }

    false
}

fn is_windows_device_name(base: &str) -> bool {
    let base = base.to_ascii_uppercase();
    match base.as_str() {
        "CON" | "PRN" | "AUX" | "NUL" => true,
        _ => {
            if let Some(num) = base.strip_prefix("COM") {
                matches!(num, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9")
            } else if let Some(num) = base.strip_prefix("LPT") {
                matches!(num, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9")
            } else {
                false
            }
        }
    }
}

impl SessionFolder {
    /// Open a session folder at `root` (does not create or load until save/load is called).
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self {
            root: root.into(),
            durability: WriteDurability::default(),
            meta_lock: Arc::new(Mutex::new(())),
        }
    }

    fn lock_meta(&self) -> std::sync::MutexGuard<'_, ()> {
        self.meta_lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    fn session_write_lock_path(&self) -> PathBuf {
        self.root.join(SESSION_WRITE_LOCK_FILENAME)
    }

    fn lock_session_write(&self) -> Result<SessionWriteGuard<'_>, StoreError> {
        // Lock order: process-local meta_lock, then exclusive file lock (never reverse).
        let meta_guard = self.lock_meta();
        fs::create_dir_all(&self.root)
            .map_err(|source| StoreError::Io { path: self.root.clone(), source })?;

        let lock_path = self.session_write_lock_path();
        let mut lock_file = OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(false)
            .open(&lock_path)
            .map_err(|source| StoreError::Io { path: lock_path.clone(), source })?;
        let started = Instant::now();
        loop {
            match try_lock_session_file(&lock_file, &lock_path) {
                Ok(true) => {
                    lock_file
                        .set_len(0)
                        .map_err(|source| StoreError::Io { path: lock_path.clone(), source })?;
                    lock_file
                        .seek(SeekFrom::Start(0))
                        .map_err(|source| StoreError::Io { path: lock_path.clone(), source })?;
                    writeln!(
                        lock_file,
                        "pid={} acquired_unix_ms={}",
                        std::process::id(),
                        SystemTime::now()
                            .duration_since(UNIX_EPOCH)
                            .map(|d| d.as_millis())
                            .unwrap_or(0)
                    )
                    .map_err(|source| StoreError::Io { path: lock_path.clone(), source })?;
                    return Ok(SessionWriteGuard { _meta_guard: meta_guard, lock_path, lock_file });
                }
                Ok(false) => {
                    if started.elapsed() >= SESSION_WRITE_LOCK_TIMEOUT {
                        return Err(StoreError::SessionWriteLockTimeout { path: lock_path });
                    }
                    std::thread::sleep(SESSION_WRITE_LOCK_RETRY_DELAY);
                }
                Err(err) => return Err(err),
            }
        }
    }

    /// Builder: choose best-effort vs fsync-oriented write durability for disk commits.
    pub fn with_durability(mut self, durability: WriteDurability) -> Self {
        self.durability = durability;
        self
    }

    pub fn durability(&self) -> WriteDurability {
        self.durability
    }

    pub fn root(&self) -> &Path {
        &self.root
    }

    /// Path to `nereid-session.meta.json` under this session folder root.
    pub fn meta_path(&self) -> PathBuf {
        self.root.join(SESSION_META_FILENAME)
    }

    fn legacy_meta_path(&self) -> PathBuf {
        self.root.join(LEGACY_SESSION_META_FILENAME)
    }

    /// Canonical relative Mermaid path for a diagram id (`diagrams/<id>.mmd`).
    pub fn default_diagram_mmd_path(&self, diagram_id: &DiagramId) -> PathBuf {
        let file_stem = encode_persisted_id_segment(diagram_id.as_str());
        self.root.join("diagrams").join(format!("{file_stem}.mmd"))
    }

    /// Returns the path for the deterministic text render export.
    ///
    /// Note: The `.ascii.txt` extension is a legacy filename; the contents may include Unicode.
    ///
    /// This file is generated asynchronously as a best-effort export. It may lag behind `.mmd`
    /// updates during rapid edits.
    pub fn diagram_ascii_path(&self, mmd_path: &Path) -> Result<PathBuf, StoreError> {
        let relative_mmd_path = to_relative_path(self.root(), mmd_path, "mmd_path")?;
        let relative_ascii_path = relative_mmd_path.with_extension("ascii.txt");
        Ok(self.root.join(relative_ascii_path))
    }

    /// Sidecar path sibling to a diagram `.mmd` (`*.meta.json` with stable ids and notes).
    pub fn diagram_meta_path(&self, mmd_path: &Path) -> Result<PathBuf, StoreError> {
        let relative_mmd_path = to_relative_path(self.root(), mmd_path, "mmd_path")?;
        let relative_meta_path = relative_mmd_path.with_extension("meta.json");
        Ok(self.root.join(relative_meta_path))
    }

    /// Canonical walkthrough JSON path (`walkthroughs/<id>.wt.json`).
    pub fn walkthrough_json_path(&self, walkthrough_id: &WalkthroughId) -> PathBuf {
        let file_stem = encode_persisted_id_segment(walkthrough_id.as_str());
        self.root.join("walkthroughs").join(format!("{file_stem}.wt.json"))
    }

    fn legacy_walkthrough_json_path(
        &self,
        walkthrough_id: &WalkthroughId,
    ) -> Result<PathBuf, StoreError> {
        validate_legacy_persisted_id_segment("walkthrough_id", walkthrough_id.as_str())?;
        Ok(self.root.join("walkthroughs").join(format!("{}.wt.json", walkthrough_id.as_str())))
    }

    /// Returns the path for the deterministic text render export.
    ///
    /// Note: The `.ascii.txt` extension is a legacy filename; the contents may include Unicode.
    ///
    /// This file is generated asynchronously as a best-effort export. It may lag behind `.wt.json`
    /// updates during rapid edits.
    pub fn walkthrough_ascii_path(&self, walkthrough_id: &WalkthroughId) -> PathBuf {
        let file_stem = encode_persisted_id_segment(walkthrough_id.as_str());
        self.root.join("walkthroughs").join(format!("{file_stem}.ascii.txt"))
    }

    /// Block until async Unicode text exports for this session folder finish writing.
    pub fn flush_ascii_exports(&self) {
        ascii_exports().flush_session_dir(self.root());
    }

    fn initial_session_id(&self) -> SessionId {
        let candidate = self
            .root
            .file_name()
            .and_then(|name| name.to_str())
            .filter(|name| !name.is_empty())
            .map(|name| format!("s:{name}"))
            .unwrap_or_else(|| "s:session".to_owned());

        SessionId::new(candidate).unwrap_or_else(|_| {
            SessionId::new("s:session").expect("hard-coded fallback session id is valid")
        })
    }

    fn initial_session(&self) -> Session {
        let mut session = Session::new(self.initial_session_id());
        let diagram_id = DiagramId::new("flow").expect("hard-coded initial diagram id is valid");
        let node_id = ObjectId::new("n:hello").expect("hard-coded initial node id is valid");

        let mut ast = FlowchartAst::default();
        ast.nodes_mut().insert(node_id, FlowNode::new("Hello"));

        let diagram = Diagram::new(diagram_id.clone(), "Flow", DiagramAst::Flowchart(ast));
        session.diagrams_mut().insert(diagram_id.clone(), diagram);
        session.set_active_diagram_id(Some(diagram_id));
        session
    }

    /// Load an existing session, or seed a default flowchart when the folder is empty.
    ///
    /// Refuses to invent meta if `diagrams/*.mmd` or `walkthroughs/*.wt.json` already exists
    /// without session meta (so seeding + GC cannot wipe durable artifacts).
    pub fn load_or_init_session(&self) -> Result<Session, StoreError> {
        match self.load_session() {
            Ok(session) => Ok(session),
            Err(StoreError::Io { path, source })
                if source.kind() == io::ErrorKind::NotFound && path == self.meta_path() =>
            {
                if self.has_existing_diagram_files()? {
                    return Err(StoreError::MetaMissingWithExistingDiagrams {
                        meta_path: self.meta_path(),
                        diagrams_dir: self.root.join("diagrams"),
                    });
                }
                if self.has_existing_walkthrough_files()? {
                    return Err(StoreError::MetaMissingWithExistingWalkthroughs {
                        meta_path: self.meta_path(),
                        walkthroughs_dir: self.root.join("walkthroughs"),
                    });
                }
                let session = self.initial_session();
                self.save_session(&session)?;
                Ok(session)
            }
            Err(err) => Err(err),
        }
    }

    fn has_existing_diagram_files(&self) -> Result<bool, StoreError> {
        let diagrams_dir = self.root.join("diagrams");
        let entries = match fs::read_dir(&diagrams_dir) {
            Ok(entries) => entries,
            Err(source) if source.kind() == io::ErrorKind::NotFound => return Ok(false),
            Err(source) => return Err(StoreError::Io { path: diagrams_dir, source }),
        };
        for entry in entries {
            let entry =
                entry.map_err(|source| StoreError::Io { path: diagrams_dir.clone(), source })?;
            let path = entry.path();
            if path.extension().and_then(|ext| ext.to_str()) == Some("mmd") && path.is_file() {
                return Ok(true);
            }
        }
        Ok(false)
    }

    fn has_existing_walkthrough_files(&self) -> Result<bool, StoreError> {
        let walkthroughs_dir = self.root.join("walkthroughs");
        let entries = match fs::read_dir(&walkthroughs_dir) {
            Ok(entries) => entries,
            Err(source) if source.kind() == io::ErrorKind::NotFound => return Ok(false),
            Err(source) => return Err(StoreError::Io { path: walkthroughs_dir, source }),
        };
        for entry in entries {
            let entry = entry
                .map_err(|source| StoreError::Io { path: walkthroughs_dir.clone(), source })?;
            let path = entry.path();
            let is_wt_json = path
                .file_name()
                .and_then(|name| name.to_str())
                .is_some_and(|name| name.ends_with(".wt.json"));
            if is_wt_json && path.is_file() {
                return Ok(true);
            }
        }
        Ok(false)
    }

    /// Persist the full session under the write lock (diagrams, walkthroughs, meta).
    pub fn save_session(&self, session: &Session) -> Result<(), StoreError> {
        let _guard = self.lock_session_write()?;
        self.save_session_locked(session)
    }

    /// Lock, reload from disk, and return a [`SessionUpdate`] for concurrent-safe mutation.
    pub fn begin_session_update(&self) -> Result<SessionUpdate<'_>, StoreError> {
        let guard = self.lock_session_write()?;
        let session = self.load_session()?;
        Ok(SessionUpdate { folder: self, _guard: guard, session: Some(session) })
    }

    fn read_file_snapshot(path: &Path) -> Result<Option<Vec<u8>>, StoreError> {
        match fs::read(path) {
            Ok(contents) => Ok(Some(contents)),
            Err(source) if source.kind() == io::ErrorKind::NotFound => Ok(None),
            Err(source) => Err(StoreError::Io { path: path.to_path_buf(), source }),
        }
    }

    fn snapshot_diagram_artifacts(
        &self,
        mmd_path: &Path,
        meta_path: &Path,
    ) -> Result<DiagramArtifactsSnapshot, StoreError> {
        Ok(DiagramArtifactsSnapshot {
            mmd_path: mmd_path.to_path_buf(),
            meta_path: meta_path.to_path_buf(),
            mmd_contents: Self::read_file_snapshot(mmd_path)?,
            meta_contents: Self::read_file_snapshot(meta_path)?,
        })
    }

    fn snapshot_walkthrough_artifacts(
        &self,
        walkthrough_id: &WalkthroughId,
    ) -> Result<WalkthroughArtifactsSnapshot, StoreError> {
        let json_path = self.walkthrough_json_path(walkthrough_id);
        let ascii_path = self.walkthrough_ascii_path(walkthrough_id);
        Ok(WalkthroughArtifactsSnapshot {
            json_path: json_path.clone(),
            ascii_path: ascii_path.clone(),
            json_contents: Self::read_file_snapshot(&json_path)?,
            ascii_contents: Self::read_file_snapshot(&ascii_path)?,
        })
    }

    fn restore_file_snapshot(
        &self,
        path: &Path,
        contents: &Option<Vec<u8>>,
    ) -> Result<(), StoreError> {
        match contents {
            Some(contents) => {
                write_atomic_in_session(self.root(), path, contents, self.durability)?;
            }
            None => match fs::remove_file(path) {
                Ok(()) => {}
                Err(source) if source.kind() == io::ErrorKind::NotFound => {}
                Err(source) => return Err(StoreError::Io { path: path.to_path_buf(), source }),
            },
        }
        Ok(())
    }

    fn restore_file_snapshot_unless_symlink(
        &self,
        path: &Path,
        contents: &Option<Vec<u8>>,
    ) -> Result<(), StoreError> {
        match fs::symlink_metadata(path) {
            Ok(metadata) if metadata.file_type().is_symlink() => Ok(()),
            Ok(_) | Err(_) => self.restore_file_snapshot(path, contents),
        }
    }

    fn restore_diagram_artifacts(
        &self,
        snapshot: &DiagramArtifactsSnapshot,
    ) -> Result<(), StoreError> {
        self.restore_file_snapshot(&snapshot.mmd_path, &snapshot.mmd_contents)?;
        self.restore_file_snapshot(&snapshot.meta_path, &snapshot.meta_contents)?;
        Ok(())
    }

    fn restore_walkthrough_artifacts(
        &self,
        snapshot: &WalkthroughArtifactsSnapshot,
    ) -> Result<(), StoreError> {
        self.restore_file_snapshot(&snapshot.json_path, &snapshot.json_contents)?;
        self.restore_file_snapshot(&snapshot.ascii_path, &snapshot.ascii_contents)?;
        Ok(())
    }

    fn rollback_diagram_artifacts(
        &self,
        snapshots: &[DiagramArtifactsSnapshot],
    ) -> Result<(), StoreError> {
        for snapshot in snapshots.iter().rev() {
            self.restore_diagram_artifacts(snapshot)?;
        }
        Ok(())
    }

    fn rollback_session_artifacts(
        &self,
        diagram_snapshots: &[DiagramArtifactsSnapshot],
        walkthrough_snapshots: &[WalkthroughArtifactsSnapshot],
    ) -> Result<(), StoreError> {
        self.rollback_diagram_artifacts(diagram_snapshots)?;
        for snapshot in walkthrough_snapshots.iter().rev() {
            self.restore_walkthrough_artifacts(snapshot)?;
        }
        Ok(())
    }

    fn rollback_session_artifacts_then<T>(
        &self,
        diagram_snapshots: &[DiagramArtifactsSnapshot],
        walkthrough_snapshots: &[WalkthroughArtifactsSnapshot],
        err: StoreError,
    ) -> Result<T, StoreError> {
        self.rollback_session_artifacts(diagram_snapshots, walkthrough_snapshots)?;
        Err(err)
    }

    fn save_diagram_artifacts(
        &self,
        diagram: &Diagram,
        mmd_path: &Path,
        meta_path: &Path,
        diagram_meta: &DiagramMeta,
    ) -> Result<DiagramArtifactsSnapshot, StoreError> {
        let snapshot = self.snapshot_diagram_artifacts(mmd_path, meta_path)?;

        self.save_diagram_meta(diagram_meta)?;

        if let Err(err) = export_diagram_mmd(self, diagram, mmd_path) {
            self.restore_file_snapshot(&snapshot.meta_path, &snapshot.meta_contents)?;
            self.restore_file_snapshot_unless_symlink(&snapshot.mmd_path, &snapshot.mmd_contents)?;
            return Err(err);
        }

        Ok(snapshot)
    }

    fn save_session_locked(&self, session: &Session) -> Result<(), StoreError> {
        #[derive(Debug, Deserialize)]
        struct WalkthroughRevJson {
            #[serde(default)]
            rev: u64,
        }

        let existing_meta = match self.load_meta() {
            Ok(meta) => Some(meta),
            Err(StoreError::Io { source, .. }) if source.kind() == io::ErrorKind::NotFound => None,
            Err(err) => return Err(err),
        };

        let mut existing_diagram_revs = BTreeMap::<DiagramId, u64>::new();
        let mut existing_walkthrough_id_set = Option::<BTreeSet<WalkthroughId>>::None;

        if let Some(meta) = existing_meta.as_ref() {
            for diagram in &meta.diagrams {
                existing_diagram_revs.insert(diagram.diagram_id.clone(), diagram.rev);
            }
            if let Some(ids) = meta.walkthrough_ids.as_ref() {
                existing_walkthrough_id_set = Some(ids.iter().cloned().collect());
            }
        }

        let read_walkthrough_rev = |path: &Path| -> Option<u64> {
            let wt_str = fs::read_to_string(path).ok()?;
            let wt_rev: WalkthroughRevJson = serde_json::from_str(&wt_str).ok()?;
            Some(wt_rev.rev)
        };

        let mut meta = SessionMeta {
            session_id: session.session_id().clone(),
            active_diagram_id: session.active_diagram_id().cloned(),
            active_walkthrough_id: session.active_walkthrough_id().cloned(),
            walkthrough_ids: Some(Vec::new()),
            diagrams: Vec::new(),
            xrefs: Vec::new(),
            selected_object_refs: session.selected_object_refs().iter().cloned().collect(),
        };
        let mut changed_diagram_artifacts = Vec::new();
        let mut changed_walkthrough_artifacts = Vec::new();
        let mut pending_diagram_ascii_exports = Vec::new();
        let mut pending_walkthrough_ascii_exports = Vec::new();

        for (diagram_id, diagram) in session.diagrams() {
            let mmd_path = self.default_diagram_mmd_path(diagram_id);
            let ascii_path = match self.diagram_ascii_path(&mmd_path) {
                Ok(path) => path,
                Err(err) => {
                    return self.rollback_session_artifacts_then(
                        &changed_diagram_artifacts,
                        &changed_walkthrough_artifacts,
                        err,
                    );
                }
            };
            let meta_path = match self.diagram_meta_path(&mmd_path) {
                Ok(path) => path,
                Err(err) => {
                    return self.rollback_session_artifacts_then(
                        &changed_diagram_artifacts,
                        &changed_walkthrough_artifacts,
                        err,
                    );
                }
            };

            let diagram_rev_unchanged = existing_diagram_revs
                .get(diagram_id)
                .copied()
                .is_some_and(|rev| rev == diagram.rev())
                && mmd_path.is_file()
                && meta_path.is_file();

            if !diagram_rev_unchanged {
                let flow_edges = match diagram.ast() {
                    DiagramAst::Flowchart(ast) => ast
                        .edges()
                        .iter()
                        .map(|(edge_id, edge)| DiagramFlowEdgeMeta {
                            edge_id: edge_id.clone(),
                            from_node_id: edge.from_node_id().clone(),
                            to_node_id: edge.to_node_id().clone(),
                            label: edge.label().map(ToOwned::to_owned),
                            connector: edge.connector().map(ToOwned::to_owned),
                            style: edge.style().map(ToOwned::to_owned),
                        })
                        .collect(),
                    DiagramAst::Sequence(_)
                    | DiagramAst::Class(_)
                    | DiagramAst::Er(_)
                    | DiagramAst::Gantt(_) => Vec::new(),
                };

                let class_relations = match diagram.ast() {
                    DiagramAst::Class(ast) => class_relations_meta_from_ast(ast),
                    DiagramAst::Sequence(_)
                    | DiagramAst::Flowchart(_)
                    | DiagramAst::Er(_)
                    | DiagramAst::Gantt(_) => Vec::new(),
                };

                let er_relationships = match diagram.ast() {
                    DiagramAst::Er(ast) => er_relationships_meta_from_ast(ast),
                    DiagramAst::Sequence(_)
                    | DiagramAst::Flowchart(_)
                    | DiagramAst::Class(_)
                    | DiagramAst::Gantt(_) => Vec::new(),
                };

                let gantt_sections = match diagram.ast() {
                    DiagramAst::Gantt(ast) => gantt_sections_meta_from_ast(ast),
                    DiagramAst::Sequence(_)
                    | DiagramAst::Flowchart(_)
                    | DiagramAst::Class(_)
                    | DiagramAst::Er(_) => Vec::new(),
                };

                let sequence_messages = match diagram.ast() {
                    DiagramAst::Sequence(ast) => ast
                        .messages_in_order()
                        .into_iter()
                        .map(|msg| DiagramSequenceMessageMeta {
                            message_id: msg.message_id().clone(),
                            from_participant_id: msg.from_participant_id().clone(),
                            to_participant_id: msg.to_participant_id().clone(),
                            kind: msg.kind(),
                            text: msg.text().to_owned(),
                        })
                        .collect(),
                    DiagramAst::Flowchart(_)
                    | DiagramAst::Class(_)
                    | DiagramAst::Er(_)
                    | DiagramAst::Gantt(_) => Vec::new(),
                };

                let sequence_blocks = match diagram.ast() {
                    DiagramAst::Sequence(ast) => sequence_blocks_meta_from_ast(ast),
                    DiagramAst::Flowchart(_)
                    | DiagramAst::Class(_)
                    | DiagramAst::Er(_)
                    | DiagramAst::Gantt(_) => Vec::new(),
                };

                let flow_node_notes = match diagram.ast() {
                    DiagramAst::Flowchart(ast) => ast
                        .nodes()
                        .iter()
                        .filter_map(|(node_id, node)| {
                            node.note().map(|note| (node_id.clone(), note.to_owned()))
                        })
                        .collect(),
                    DiagramAst::Sequence(_)
                    | DiagramAst::Class(_)
                    | DiagramAst::Er(_)
                    | DiagramAst::Gantt(_) => BTreeMap::new(),
                };

                let sequence_participant_notes = match diagram.ast() {
                    DiagramAst::Sequence(ast) => ast
                        .participants()
                        .iter()
                        .filter_map(|(participant_id, participant)| {
                            participant.note().map(|note| (participant_id.clone(), note.to_owned()))
                        })
                        .collect(),
                    DiagramAst::Flowchart(_)
                    | DiagramAst::Class(_)
                    | DiagramAst::Er(_)
                    | DiagramAst::Gantt(_) => BTreeMap::new(),
                };

                let class_node_notes = match diagram.ast() {
                    DiagramAst::Class(ast) => ast
                        .classes()
                        .iter()
                        .filter_map(|(class_id, class)| {
                            class.note().map(|note| (class_id.clone(), note.to_owned()))
                        })
                        .collect(),
                    DiagramAst::Sequence(_)
                    | DiagramAst::Flowchart(_)
                    | DiagramAst::Er(_)
                    | DiagramAst::Gantt(_) => BTreeMap::new(),
                };

                let er_entity_notes = match diagram.ast() {
                    DiagramAst::Er(ast) => ast
                        .entities()
                        .iter()
                        .filter_map(|(entity_id, entity)| {
                            entity.note().map(|note| (entity_id.clone(), note.to_owned()))
                        })
                        .collect(),
                    DiagramAst::Sequence(_)
                    | DiagramAst::Flowchart(_)
                    | DiagramAst::Class(_)
                    | DiagramAst::Gantt(_) => BTreeMap::new(),
                };

                let gantt_task_notes = match diagram.ast() {
                    DiagramAst::Gantt(ast) => ast
                        .tasks()
                        .iter()
                        .filter_map(|(task_id, task)| {
                            task.note().map(|note| (task_id.clone(), note.to_owned()))
                        })
                        .collect(),
                    DiagramAst::Sequence(_)
                    | DiagramAst::Flowchart(_)
                    | DiagramAst::Class(_)
                    | DiagramAst::Er(_) => BTreeMap::new(),
                };

                let gantt_lane_notes = match diagram.ast() {
                    DiagramAst::Gantt(ast) => ast.lane_notes().clone(),
                    DiagramAst::Sequence(_)
                    | DiagramAst::Flowchart(_)
                    | DiagramAst::Class(_)
                    | DiagramAst::Er(_) => BTreeMap::new(),
                };

                let flow_node_symbols = match diagram.ast() {
                    DiagramAst::Flowchart(ast) => ast
                        .nodes()
                        .iter()
                        .filter_map(|(node_id, node)| {
                            node.symbol().map(|symbol| (node_id.clone(), symbol.clone()))
                        })
                        .collect(),
                    DiagramAst::Sequence(_)
                    | DiagramAst::Class(_)
                    | DiagramAst::Er(_)
                    | DiagramAst::Gantt(_) => BTreeMap::new(),
                };

                let sequence_participant_symbols = match diagram.ast() {
                    DiagramAst::Sequence(ast) => ast
                        .participants()
                        .iter()
                        .filter_map(|(participant_id, participant)| {
                            participant
                                .symbol()
                                .map(|symbol| (participant_id.clone(), symbol.clone()))
                        })
                        .collect(),
                    DiagramAst::Flowchart(_)
                    | DiagramAst::Class(_)
                    | DiagramAst::Er(_)
                    | DiagramAst::Gantt(_) => BTreeMap::new(),
                };

                let diagram_meta = DiagramMeta {
                    diagram_id: diagram_id.clone(),
                    mmd_path: mmd_path.clone(),
                    stable_id_map: stable_id_map_from_ast(diagram.ast()),
                    xrefs: Vec::new(),
                    flow_edges,
                    class_relations,
                    er_relationships,
                    gantt_sections,
                    sequence_messages,
                    sequence_blocks,
                    default_symbol_repository_id: diagram
                        .default_symbol_repository_id()
                        .map(ToOwned::to_owned),
                    flow_node_notes,
                    sequence_participant_notes,
                    class_node_notes,
                    er_entity_notes,
                    gantt_task_notes,
                    gantt_lane_notes,
                    flow_node_symbols,
                    sequence_participant_symbols,
                };

                match self.save_diagram_artifacts(diagram, &mmd_path, &meta_path, &diagram_meta) {
                    Ok(snapshot) => changed_diagram_artifacts.push(snapshot),
                    Err(err) => {
                        return self.rollback_session_artifacts_then(
                            &changed_diagram_artifacts,
                            &changed_walkthrough_artifacts,
                            err,
                        );
                    }
                }
            }

            if !diagram_rev_unchanged || !ascii_path.is_file() {
                pending_diagram_ascii_exports.push((mmd_path.clone(), diagram.clone()));
            }

            meta.diagrams.push(SessionMetaDiagram {
                diagram_id: diagram_id.clone(),
                name: diagram.name().to_owned(),
                kind: diagram.kind(),
                mmd_path,
                rev: diagram.rev(),
            });
        }

        for (xref_id, xref) in session.xrefs() {
            meta.xrefs.push(SessionXRef {
                xref_id: xref_id.clone(),
                from: xref.from().clone(),
                to: xref.to().clone(),
                kind: xref.kind().to_owned(),
                label: xref.label().map(ToOwned::to_owned),
                status: xref.status(),
            });
        }

        let mut walkthrough_ids = session.walkthroughs().keys().cloned().collect::<Vec<_>>();
        walkthrough_ids.sort();
        let current_walkthrough_id_set: BTreeSet<_> = walkthrough_ids.iter().cloned().collect();
        let skip_walkthrough_gc = existing_walkthrough_id_set
            .as_ref()
            .is_some_and(|prev| prev == &current_walkthrough_id_set);
        meta.walkthrough_ids = Some(walkthrough_ids.clone());

        for walkthrough_id in walkthrough_ids {
            let walkthrough = session
                .walkthroughs()
                .get(&walkthrough_id)
                .expect("walkthrough id listed in walkthrough_ids");
            let json_path = self.walkthrough_json_path(&walkthrough_id);
            let ascii_path = self.walkthrough_ascii_path(&walkthrough_id);
            let rev_matches = json_path.is_file()
                && read_walkthrough_rev(&json_path).is_some_and(|rev| rev == walkthrough.rev());

            if !rev_matches {
                let snapshot =
                    match self.snapshot_walkthrough_artifacts(walkthrough.walkthrough_id()) {
                        Ok(snapshot) => snapshot,
                        Err(err) => {
                            return self.rollback_session_artifacts_then(
                                &changed_diagram_artifacts,
                                &changed_walkthrough_artifacts,
                                err,
                            );
                        }
                    };
                changed_walkthrough_artifacts.push(snapshot);
                if let Err(err) = self.save_walkthrough_json(walkthrough) {
                    return self.rollback_session_artifacts_then(
                        &changed_diagram_artifacts,
                        &changed_walkthrough_artifacts,
                        err,
                    );
                }
                pending_walkthrough_ascii_exports.push(walkthrough.clone());
            } else if !ascii_path.is_file() {
                pending_walkthrough_ascii_exports.push(walkthrough.clone());
            }
        }

        if let Err(err) = self.save_meta(&meta) {
            return self.rollback_session_artifacts_then(
                &changed_diagram_artifacts,
                &changed_walkthrough_artifacts,
                err,
            );
        }

        for (mmd_path, diagram) in pending_diagram_ascii_exports {
            self.schedule_diagram_ascii_export(&mmd_path, &diagram)?;
        }
        for walkthrough in pending_walkthrough_ascii_exports {
            self.schedule_walkthrough_ascii_export(&walkthrough)?;
        }

        if !skip_walkthrough_gc {
            if let Some(walkthrough_ids) = meta.walkthrough_ids.as_deref() {
                self.garbage_collect_walkthrough_files(walkthrough_ids)?;
            }
        }

        Ok(())
    }

    fn garbage_collect_walkthrough_files(
        &self,
        walkthrough_ids: &[WalkthroughId],
    ) -> Result<(), StoreError> {
        let mut keep_stems = std::collections::BTreeSet::<String>::new();
        for id in walkthrough_ids {
            keep_stems.insert(id.to_string());
            keep_stems.insert(encode_persisted_id_segment(id.as_str()));
        }

        let walkthroughs_dir = self.root.join("walkthroughs");
        let walkthroughs_metadata = match fs::symlink_metadata(&walkthroughs_dir) {
            Ok(metadata) => metadata,
            Err(source) if source.kind() == io::ErrorKind::NotFound => return Ok(()),
            Err(source) => {
                return Err(StoreError::Io { path: walkthroughs_dir, source });
            }
        };
        if walkthroughs_metadata.file_type().is_symlink() {
            return Err(StoreError::SymlinkRefused { path: walkthroughs_dir });
        }
        if !walkthroughs_metadata.is_dir() {
            return Err(StoreError::Io {
                path: walkthroughs_dir,
                source: io::Error::new(io::ErrorKind::AlreadyExists, "expected directory"),
            });
        }

        let canonical_walkthroughs_dir = fs::canonicalize(&walkthroughs_dir)
            .map_err(|source| StoreError::Io { path: walkthroughs_dir.clone(), source })?;
        let entries = match fs::read_dir(&walkthroughs_dir) {
            Ok(entries) => entries,
            Err(source) if source.kind() == io::ErrorKind::NotFound => return Ok(()),
            Err(source) => {
                return Err(StoreError::Io { path: walkthroughs_dir, source });
            }
        };

        for entry in entries {
            let entry = entry
                .map_err(|source| StoreError::Io { path: walkthroughs_dir.clone(), source })?;
            let path = entry.path();
            let file_type = entry
                .file_type()
                .map_err(|source| StoreError::Io { path: path.clone(), source })?;
            if !file_type.is_file() {
                continue;
            }
            let Some(file_name) = path.file_name().and_then(|s| s.to_str()) else {
                continue;
            };

            let Some(walkthrough_id) =
                file_name.strip_suffix(".wt.json").or_else(|| file_name.strip_suffix(".ascii.txt"))
            else {
                continue;
            };

            if keep_stems.contains(walkthrough_id) {
                continue;
            }

            let canonical_path = fs::canonicalize(&path)
                .map_err(|source| StoreError::Io { path: path.clone(), source })?;
            if !canonical_path.starts_with(&canonical_walkthroughs_dir) {
                return Err(StoreError::PathOutsideSession {
                    session_dir: canonical_walkthroughs_dir.clone(),
                    path: canonical_path,
                });
            }

            // Pending walkthrough ascii exports are keyed by text path (`*.ascii.txt`).
            // Cancel both sibling keys so GC works whether we encounter the json or ascii
            // entry first (cancel by directory-entry path alone misses the scheduled key).
            let json_path = walkthroughs_dir.join(format!("{walkthrough_id}.wt.json"));
            let ascii_path = walkthroughs_dir.join(format!("{walkthrough_id}.ascii.txt"));
            ascii_exports().cancel(&json_path);
            ascii_exports().cancel(&ascii_path);

            match fs::remove_file(&path) {
                Ok(()) => {}
                Err(source) if source.kind() == io::ErrorKind::NotFound => {}
                Err(source) => {
                    return Err(StoreError::Io { path, source });
                }
            }
        }

        Ok(())
    }

    /// Load meta + diagrams (parse Mermaid, reconcile sidecars) + walkthroughs into memory.
    pub fn load_session(&self) -> Result<Session, StoreError> {
        let meta = self.load_meta()?;

        let mut session = Session::new(meta.session_id);
        session.set_active_diagram_id(meta.active_diagram_id);
        session.set_active_walkthrough_id(meta.active_walkthrough_id);
        let selected_object_refs = meta.selected_object_refs;
        let walkthrough_ids = meta.walkthrough_ids.clone();

        for diagram_meta in meta.diagrams {
            let diagram_id = diagram_meta.diagram_id;
            let mmd_path = diagram_meta.mmd_path;
            let mmd = fs::read_to_string(&mmd_path)
                .map_err(|source| StoreError::Io { path: mmd_path.clone(), source })?;

            let sidecar = match self.load_diagram_meta(&mmd_path) {
                Ok(sidecar) => Some(sidecar),
                Err(StoreError::Io { source, .. }) if source.kind() == io::ErrorKind::NotFound => {
                    None
                }
                Err(err) => return Err(err),
            };

            let mut ast = match diagram_meta.kind {
                DiagramKind::Sequence => {
                    DiagramAst::Sequence(parse_sequence_diagram(&mmd).map_err(|source| {
                        StoreError::MermaidSequenceParse {
                            diagram_id: diagram_id.clone(),
                            path: mmd_path.clone(),
                            source: Box::new(source),
                        }
                    })?)
                }
                DiagramKind::Flowchart => {
                    DiagramAst::Flowchart(parse_flowchart(&mmd).map_err(|source| {
                        StoreError::MermaidFlowchartParse {
                            diagram_id: diagram_id.clone(),
                            path: mmd_path.clone(),
                            source: Box::new(source),
                        }
                    })?)
                }
                DiagramKind::Class => {
                    DiagramAst::Class(parse_class_diagram(&mmd).map_err(|source| {
                        StoreError::MermaidClassParse {
                            diagram_id: diagram_id.clone(),
                            path: mmd_path.clone(),
                            source: Box::new(source),
                        }
                    })?)
                }
                DiagramKind::Er => DiagramAst::Er(parse_er_diagram(&mmd).map_err(|source| {
                    StoreError::MermaidErParse {
                        diagram_id: diagram_id.clone(),
                        path: mmd_path.clone(),
                        source: Box::new(source),
                    }
                })?),
                DiagramKind::Gantt => {
                    DiagramAst::Gantt(parse_gantt_diagram(&mmd).map_err(|source| {
                        StoreError::MermaidGanttParse {
                            diagram_id: diagram_id.clone(),
                            path: mmd_path.clone(),
                            source: Box::new(source),
                        }
                    })?)
                }
            };

            if let Some(sidecar) = sidecar.as_ref() {
                reconcile_diagram_ast(&mut ast, sidecar);
            }

            let mut diagram = Diagram::new(diagram_id.clone(), diagram_meta.name, ast);
            diagram.set_rev(diagram_meta.rev);
            if let Some(sidecar) = sidecar.as_ref() {
                diagram
                    .set_default_symbol_repository_id(sidecar.default_symbol_repository_id.clone());
            }
            session.diagrams_mut().insert(diagram_id, diagram);
        }

        session.set_selected_object_refs(
            selected_object_refs
                .into_iter()
                .map(|object_ref| migrate_legacy_gantt_lane_ref(&session, object_ref))
                .collect(),
        );

        for xref_meta in meta.xrefs {
            let from = migrate_legacy_gantt_lane_ref(&session, xref_meta.from);
            let to = migrate_legacy_gantt_lane_ref(&session, xref_meta.to);
            let mut xref = XRef::new(from, to, xref_meta.kind, xref_meta.status);
            xref.set_label(xref_meta.label);
            session.xrefs_mut().insert(xref_meta.xref_id, xref);
        }
        refresh_xref_statuses(&mut session);

        match walkthrough_ids {
            Some(walkthrough_ids) => {
                for walkthrough_id in walkthrough_ids {
                    let mut walkthrough = self.load_walkthrough(&walkthrough_id)?;
                    migrate_legacy_gantt_lane_walkthrough_refs(&session, &mut walkthrough);
                    session.walkthroughs_mut().insert(walkthrough_id, walkthrough);
                }
            }
            None => {
                let walkthroughs_dir = self.root.join("walkthroughs");
                match fs::read_dir(&walkthroughs_dir) {
                    Ok(entries) => {
                        let mut wt_paths = entries
                            .filter_map(|entry| entry.ok())
                            .map(|entry| entry.path())
                            .filter(|path| path.is_file())
                            .filter(|path| path.to_string_lossy().ends_with(".wt.json"))
                            .collect::<Vec<_>>();
                        wt_paths.sort();

                        for wt_path in wt_paths {
                            let wt_str = fs::read_to_string(&wt_path).map_err(|source| {
                                StoreError::Io { path: wt_path.clone(), source }
                            })?;

                            let wt_json: WalkthroughJson =
                                serde_json::from_str(&wt_str).map_err(|source| {
                                    StoreError::Json { path: wt_path.clone(), source }
                                })?;

                            let mut walkthrough = walkthrough_from_json(wt_json)?;
                            migrate_legacy_gantt_lane_walkthrough_refs(&session, &mut walkthrough);
                            session
                                .walkthroughs_mut()
                                .insert(walkthrough.walkthrough_id().clone(), walkthrough);
                        }
                    }
                    Err(source) if source.kind() == io::ErrorKind::NotFound => {}
                    Err(source) => {
                        return Err(StoreError::Io { path: walkthroughs_dir, source });
                    }
                }
            }
        }

        Ok(session)
    }

    /// Read and decode `nereid-session.meta.json` (falls back to legacy `session.meta.json`).
    pub fn load_meta(&self) -> Result<SessionMeta, StoreError> {
        let meta_path = self.meta_path();
        let (meta_path, meta_str) = match fs::read_to_string(&meta_path) {
            Ok(meta_str) => (meta_path, meta_str),
            Err(source) if source.kind() == io::ErrorKind::NotFound => {
                let legacy_path = self.legacy_meta_path();
                match fs::read_to_string(&legacy_path) {
                    Ok(meta_str) => (legacy_path, meta_str),
                    Err(legacy_source) if legacy_source.kind() == io::ErrorKind::NotFound => {
                        return Err(StoreError::Io { path: meta_path, source });
                    }
                    Err(legacy_source) => {
                        return Err(StoreError::Io { path: legacy_path, source: legacy_source });
                    }
                }
            }
            Err(source) => {
                return Err(StoreError::Io { path: meta_path.clone(), source });
            }
        };

        let meta_json: SessionMetaJson = serde_json::from_str(&meta_str)
            .map_err(|source| StoreError::Json { path: meta_path.clone(), source })?;

        session_meta_from_json(self.root(), meta_json)
    }

    /// Atomically write session meta JSON under the configured write durability.
    pub fn save_meta(&self, meta: &SessionMeta) -> Result<(), StoreError> {
        fs::create_dir_all(self.root())
            .map_err(|source| StoreError::Io { path: self.root.clone(), source })?;

        let meta_path = self.meta_path();
        let meta_json = session_meta_to_json(self.root(), meta)?;
        let meta_str = serde_json::to_string_pretty(&meta_json)
            .map_err(|source| StoreError::Json { path: meta_path.clone(), source })?;

        write_atomic_in_session(
            self.root(),
            &meta_path,
            format!("{meta_str}\n").as_bytes(),
            self.durability,
        )?;

        let legacy_path = self.legacy_meta_path();
        if legacy_path != meta_path {
            match fs::remove_file(&legacy_path) {
                Ok(()) => {}
                Err(source) if source.kind() == io::ErrorKind::NotFound => {}
                Err(_source) => {}
            }
        }

        Ok(())
    }

    /// Patch selection into session meta under the write lock (full save if meta missing).
    pub fn save_selected_object_refs(&self, session: &Session) -> Result<(), StoreError> {
        let _guard = self.lock_session_write()?;
        match self.load_meta() {
            Ok(mut meta) => {
                meta.selected_object_refs =
                    session.selected_object_refs().iter().cloned().collect();
                self.save_meta(&meta)?;
                Ok(())
            }
            Err(StoreError::Io { source, .. }) if source.kind() == io::ErrorKind::NotFound => {
                self.save_session_locked(session)
            }
            Err(err) => Err(err),
        }
    }

    /// Patch active diagram id into session meta under the write lock.
    pub fn save_active_diagram_id(&self, session: &Session) -> Result<(), StoreError> {
        let _guard = self.lock_session_write()?;
        match self.load_meta() {
            Ok(mut meta) => {
                meta.active_diagram_id = session.active_diagram_id().cloned();
                self.save_meta(&meta)?;
                Ok(())
            }
            Err(StoreError::Io { source, .. }) if source.kind() == io::ErrorKind::NotFound => {
                self.save_session_locked(session)
            }
            Err(err) => Err(err),
        }
    }

    /// Load one walkthrough JSON by id (checks id match; falls back to legacy path).
    pub fn load_walkthrough(
        &self,
        walkthrough_id: &WalkthroughId,
    ) -> Result<Walkthrough, StoreError> {
        let wt_path = self.walkthrough_json_path(walkthrough_id);
        let (wt_path, wt_str) = match fs::read_to_string(&wt_path) {
            Ok(wt_str) => (wt_path, wt_str),
            Err(source) if source.kind() == io::ErrorKind::NotFound => {
                let legacy_path = self.legacy_walkthrough_json_path(walkthrough_id)?;
                let wt_str = fs::read_to_string(&legacy_path)
                    .map_err(|source| StoreError::Io { path: legacy_path.clone(), source })?;
                (legacy_path, wt_str)
            }
            Err(source) => {
                return Err(StoreError::Io { path: wt_path.clone(), source });
            }
        };

        let wt_json: WalkthroughJson = serde_json::from_str(&wt_str)
            .map_err(|source| StoreError::Json { path: wt_path.clone(), source })?;

        let walkthrough = walkthrough_from_json(wt_json)?;
        if walkthrough.walkthrough_id() != walkthrough_id {
            return Err(StoreError::WalkthroughIdMismatch {
                path: wt_path,
                expected: walkthrough_id.clone(),
                found: walkthrough.walkthrough_id().clone(),
            });
        }
        Ok(walkthrough)
    }

    /// Persist walkthrough JSON and schedule a best-effort Unicode text export.
    pub fn save_walkthrough(&self, walkthrough: &Walkthrough) -> Result<(), StoreError> {
        self.save_walkthrough_json(walkthrough)?;
        self.schedule_walkthrough_ascii_export(walkthrough)?;

        Ok(())
    }

    fn save_walkthrough_json(&self, walkthrough: &Walkthrough) -> Result<(), StoreError> {
        let wt_path = self.walkthrough_json_path(walkthrough.walkthrough_id());

        let wt_json = walkthrough_to_json(walkthrough);
        let wt_str = serde_json::to_string_pretty(&wt_json)
            .map_err(|source| StoreError::Json { path: wt_path.clone(), source })?;

        write_atomic_in_session(
            self.root(),
            &wt_path,
            format!("{wt_str}\n").as_bytes(),
            self.durability,
        )?;

        Ok(())
    }

    fn schedule_diagram_ascii_export(
        &self,
        mmd_path: &Path,
        diagram: &Diagram,
    ) -> Result<(), StoreError> {
        let text_path = self.diagram_ascii_path(mmd_path)?;

        ascii_exports().schedule(AsciiExportTask::Diagram {
            session_dir: self.root.clone(),
            mmd_path: mmd_path.to_path_buf(),
            text_path,
            durability: self.durability,
            ast: diagram.ast().clone(),
        });

        Ok(())
    }

    fn schedule_walkthrough_ascii_export(
        &self,
        walkthrough: &Walkthrough,
    ) -> Result<(), StoreError> {
        let json_path = self.walkthrough_json_path(walkthrough.walkthrough_id());
        let text_path = self.walkthrough_ascii_path(walkthrough.walkthrough_id());

        ascii_exports().schedule(AsciiExportTask::Walkthrough {
            session_dir: self.root.clone(),
            json_path,
            text_path,
            durability: self.durability,
            walkthrough: walkthrough.clone(),
        });

        Ok(())
    }

    /// Load a diagram sidecar (stable ids, fingerprints, notes, symbols) for reconcile on load.
    pub fn load_diagram_meta(&self, mmd_path: &Path) -> Result<DiagramMeta, StoreError> {
        let meta_path = self.diagram_meta_path(mmd_path)?;
        let meta_str = fs::read_to_string(&meta_path)
            .map_err(|source| StoreError::Io { path: meta_path.clone(), source })?;

        let meta_json: DiagramMetaJson = serde_json::from_str(&meta_str)
            .map_err(|source| StoreError::Json { path: meta_path.clone(), source })?;

        diagram_meta_from_json(self.root(), meta_json)
    }

    /// Atomically write a diagram sidecar next to its `.mmd` source.
    pub fn save_diagram_meta(&self, meta: &DiagramMeta) -> Result<(), StoreError> {
        let meta_path = self.diagram_meta_path(&meta.mmd_path)?;

        let meta_json = diagram_meta_to_json(self.root(), meta)?;
        let meta_str = serde_json::to_string_pretty(&meta_json)
            .map_err(|source| StoreError::Json { path: meta_path.clone(), source })?;

        write_atomic_in_session(
            self.root(),
            &meta_path,
            format!("{meta_str}\n").as_bytes(),
            self.durability,
        )?;

        Ok(())
    }
}

include!("session_folder/helpers.rs");

#[cfg(test)]
mod tests;

/// Object-id sets before/after a Mermaid replace (for identity / MCP reporting).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiagramMermaidReplaceResult {
    pub new_rev: u64,
    pub previous_object_ids: BTreeSet<String>,
    pub next_object_ids: BTreeSet<String>,
}

/// Failures from [`replace_diagram_from_mermaid`] (kind, parse, or AST set mismatch).
#[derive(Debug)]
pub enum DiagramMermaidReplaceError {
    /// Source Mermaid kind does not match the target diagram.
    KindMismatch {
        expected: DiagramKind,
        found: DiagramKind,
    },
    /// First non-empty content line is not a recognized diagram header.
    MissingOrUnknownKind {
        first_line: Option<String>,
    },
    ParseSequence(Box<MermaidSequenceParseError>),
    ParseFlowchart(Box<MermaidFlowchartParseError>),
    ParseClass(Box<MermaidClassParseError>),
    ParseEr(Box<MermaidErParseError>),
    ParseGantt(Box<MermaidGanttParseError>),
    AstKindMismatch(DiagramAstKindMismatch),
}

impl fmt::Display for DiagramMermaidReplaceError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::KindMismatch { expected, found } => {
                write!(f, "mermaid kind mismatch (expected {expected:?}, found {found:?})")
            }
            Self::MissingOrUnknownKind { first_line: None } => f.write_str(
                "expected 'flowchart'/'graph', 'sequenceDiagram', 'classDiagram', 'erDiagram', or 'gantt' as the first non-empty line",
            ),
            Self::MissingOrUnknownKind {
                first_line: Some(line),
            } => write!(
                f,
                "expected 'flowchart'/'graph', 'sequenceDiagram', 'classDiagram', 'erDiagram', or 'gantt' as the first non-empty line, found: {line}"
            ),
            Self::ParseSequence(err) => write!(f, "cannot parse Mermaid sequence diagram: {err}"),
            Self::ParseFlowchart(err) => write!(f, "cannot parse Mermaid flowchart diagram: {err}"),
            Self::ParseClass(err) => write!(f, "cannot parse Mermaid class diagram: {err}"),
            Self::ParseEr(err) => write!(f, "cannot parse Mermaid er diagram: {err}"),
            Self::ParseGantt(err) => write!(f, "cannot parse Mermaid gantt diagram: {err}"),
            Self::AstKindMismatch(err) => write!(f, "{err}"),
        }
    }
}

impl std::error::Error for DiagramMermaidReplaceError {}

fn collect_stable_object_ids(ast: &DiagramAst) -> BTreeSet<String> {
    let mut ids = BTreeSet::new();
    match ast {
        DiagramAst::Sequence(seq) => {
            for id in seq.participants().keys() {
                ids.insert(id.to_string());
            }
            for msg in seq.messages() {
                ids.insert(msg.message_id().to_string());
            }
            for id in seq.collect_block_ids() {
                ids.insert(id.to_string());
            }
            for id in seq.collect_section_ids() {
                ids.insert(id.to_string());
            }
        }
        DiagramAst::Flowchart(flow) => {
            for id in flow.nodes().keys() {
                ids.insert(id.to_string());
            }
            for id in flow.edges().keys() {
                ids.insert(id.to_string());
            }
        }
        DiagramAst::Class(class) => {
            for id in class.classes().keys() {
                ids.insert(id.to_string());
            }
            for id in class.relations().keys() {
                ids.insert(id.to_string());
            }
        }
        DiagramAst::Er(er) => {
            for id in er.entities().keys() {
                ids.insert(id.to_string());
            }
            for id in er.relationships().keys() {
                ids.insert(id.to_string());
            }
        }
        DiagramAst::Gantt(gantt) => {
            for id in gantt.tasks().keys() {
                ids.insert(id.to_string());
            }
            for sec in gantt.sections() {
                ids.insert(sec.section_id().to_string());
            }
        }
    }
    ids
}

/// Parse Mermaid into the same diagram kind, reconciling stable ids from the current AST.
///
/// Builds an identity sidecar from the live diagram, parses source, runs reconcile (name /
/// mermaid-id / fingerprint match), installs the AST, and bumps revision. Kind must match;
/// does not touch disk — callers persist via `SessionFolder` / `SessionUpdate`.
pub fn replace_diagram_from_mermaid(
    diagram: &mut Diagram,
    mermaid: &str,
) -> Result<DiagramMermaidReplaceResult, DiagramMermaidReplaceError> {
    let mut first_content_line: Option<String> = None;
    let detected = {
        let mut found = None;
        for raw_line in mermaid.lines() {
            let trimmed = raw_line.trim();
            if trimmed.is_empty() || trimmed.starts_with("%%") {
                continue;
            }
            first_content_line = Some(trimmed.to_owned());
            if trimmed.starts_with("sequenceDiagram") {
                found = Some(DiagramKind::Sequence);
            } else if trimmed.starts_with("flowchart") || trimmed.starts_with("graph") {
                found = Some(DiagramKind::Flowchart);
            } else if trimmed.starts_with("classDiagram") {
                found = Some(DiagramKind::Class);
            } else if trimmed.starts_with("erDiagram") {
                found = Some(DiagramKind::Er);
            } else if trimmed.starts_with("gantt") {
                found = Some(DiagramKind::Gantt);
            }
            break;
        }
        found
    };

    let Some(found_kind) = detected else {
        return Err(DiagramMermaidReplaceError::MissingOrUnknownKind {
            first_line: first_content_line,
        });
    };
    if found_kind != diagram.kind() {
        return Err(DiagramMermaidReplaceError::KindMismatch {
            expected: diagram.kind(),
            found: found_kind,
        });
    }

    let previous_object_ids = collect_stable_object_ids(diagram.ast());
    let sidecar = reconcile::identity_sidecar_from_diagram(diagram);

    let mut ast = match found_kind {
        DiagramKind::Sequence => DiagramAst::Sequence(
            parse_sequence_diagram(mermaid)
                .map_err(|err| DiagramMermaidReplaceError::ParseSequence(Box::new(err)))?,
        ),
        DiagramKind::Flowchart => DiagramAst::Flowchart(
            parse_flowchart(mermaid)
                .map_err(|err| DiagramMermaidReplaceError::ParseFlowchart(Box::new(err)))?,
        ),
        DiagramKind::Class => DiagramAst::Class(
            parse_class_diagram(mermaid)
                .map_err(|err| DiagramMermaidReplaceError::ParseClass(Box::new(err)))?,
        ),
        DiagramKind::Er => DiagramAst::Er(
            parse_er_diagram(mermaid)
                .map_err(|err| DiagramMermaidReplaceError::ParseEr(Box::new(err)))?,
        ),
        DiagramKind::Gantt => DiagramAst::Gantt(
            parse_gantt_diagram(mermaid)
                .map_err(|err| DiagramMermaidReplaceError::ParseGantt(Box::new(err)))?,
        ),
    };

    reconcile::reconcile_diagram_ast(&mut ast, &sidecar);
    diagram.set_ast(ast).map_err(DiagramMermaidReplaceError::AstKindMismatch)?;
    diagram.bump_rev();

    Ok(DiagramMermaidReplaceResult {
        new_rev: diagram.rev(),
        previous_object_ids,
        next_object_ids: collect_stable_object_ids(diagram.ast()),
    })
}