sirno 0.0.1

Sirno gives project design a semantic intermediate representation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
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
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
//! Command-line interface for Sirno.

use std::env;
use std::ffi::OsString;
use std::fs;
use std::io::{self, ErrorKind, Write};
use std::path::{Path, PathBuf};
use std::process::{Command as ProcessCommand, ExitCode, ExitStatus};
use std::str::FromStr;
use std::time::{SystemTime, UNIX_EPOCH};

use clap::{CommandFactory, Parser, Subcommand, ValueEnum};
use clap_complete::{Shell, generate};
use indexmap::IndexMap;
use serde::ser::SerializeMap;
use sirno::{
    CONFIG_FILE_NAME, CheckMode, ConfigError, Entry, EntryDirectory, EntryDirectoryCheckSettings,
    EntryDirectoryError, EntryDirectoryReport, EntryDirectoryWritePolicy, EntryId, EntryIdError,
    EntryMetadata, EntryParseError, EntryQuery, Eterator, FrostError, FrostLockStatus,
    GenLinkDirectoryReport, GeneratedLinkBody, GeneratedLinkError, LockError, SirnoConfig,
    SirnoFrost, SirnoLock, StructuralSettings, VagueEntryQuery, WitnessCheckSettings, WitnessError,
    WitnessRecord,
};
use thiserror::Error;

const RG_PREPROCESSOR_ARGV0_PREFIX: &str = "sirno-rg-preprocess-";

/// Sirno command-line entry point.
#[derive(Debug, Parser)]
#[command(name = "sirno")]
#[command(about = "Manage Sirno design entries")]
struct Cli {
    /// Sirno project config file.
    #[arg(short = 'C', long, global = true)]
    config: Option<PathBuf>,
    /// Public Markdown lake path override.
    #[arg(short = 'L', long = "lake-path", global = true)]
    lake_path: Option<PathBuf>,
    #[command(subcommand)]
    command: Command,
}

/// Supported Sirno commands.
#[derive(Debug, Subcommand)]
enum Command {
    /// Run a lake operation at the top level.
    // sirno:witness:interfaces:begin
    #[command(flatten)]
    TopLevelLake(LakeCommand),
    /// Run an entry operation at the top level.
    #[command(flatten)]
    TopLevelEntry(EntryCommand),
    /// Manage public Markdown lake storage.
    Lake {
        /// Lake command.
        #[command(subcommand)]
        command: LakeCommand,
    },
    /// Manage public Markdown lake entries.
    Entry {
        /// Entry command.
        #[command(subcommand)]
        command: GroupedEntryCommand,
    },
    // sirno:witness:interfaces:end
    /// Manage optional Sirno Frost snapshots.
    // sirno:witness:interfaces:begin
    Frost {
        /// Frost command.
        #[command(subcommand)]
        command: FrostCommand,
    },
    // sirno:witness:interfaces:end
    /// Utility commands.
    // sirno:witness:interfaces:begin
    Util {
        /// Utility command.
        #[command(subcommand)]
        command: UtilCommand,
    },
    // sirno:witness:interfaces:end
}

/// Supported public lake commands.
#[derive(Debug, Subcommand)]
enum LakeCommand {
    /// Create a Sirno config and ordinary seed entries.
    // sirno:witness:interfaces:begin
    Init {
        /// Monograph path written to Sirno.toml.
        #[arg(long)]
        mono: Option<PathBuf>,
        /// Public Markdown entry lake path written to Sirno.toml.
        #[arg(long)]
        lake: Option<PathBuf>,
    },
    /// Move the configured public Markdown entry lake.
    #[command(visible_alias = "mv")]
    Move {
        /// New public Markdown entry lake path written to Sirno.toml.
        lake: PathBuf,
    },
    // sirno:witness:interfaces:end
    /// Check current entry structure.
    // sirno:witness:interfaces:begin
    Check {
        /// Sirno Frost path.
        #[arg(long = "frost-path", conflicts_with = "lake_path")]
        frost_path: Option<PathBuf>,
        /// Check boundary.
        #[arg(short = 'm', long, value_enum)]
        mode: Option<CliCheckMode>,
    },
    // sirno:witness:interfaces:end
    /// Generate Markdown links in entry footers.
    // sirno:witness:interfaces:begin
    #[command(name = "gen-link")]
    GenLink {
        /// Report generated-link changes without writing files.
        #[arg(short = 'n', long, visible_alias = "dry-run")]
        dry: bool,
        /// Generated-link command.
        #[command(subcommand)]
        command: Option<GenLinkCommand>,
    },
    // sirno:witness:interfaces:end
    /// Show the current Sirno project status.
    // sirno:witness:interfaces:begin
    #[command(visible_alias = "st")]
    Status,
    // sirno:witness:interfaces:end
}

/// Supported public entry commands.
#[derive(Debug, Subcommand)]
enum EntryCommand {
    /// Create one Markdown entry.
    // sirno:witness:interfaces:begin
    New {
        /// Entry id and filename stem.
        id: String,
        /// Human-readable entry name.
        #[arg(short = 'n', long)]
        name: Option<String>,
        /// Short entry desc.
        #[arg(short = 'd', long)]
        desc: String,
        /// Structural metadata target as FIELD=ENTRY_ID.
        #[arg(long = "structural", value_name = "FIELD=ENTRY_ID")]
        structural: Vec<CliStructuralPredicate>,
        /// Initial Markdown body.
        #[arg(short = 'b', long)]
        body: Option<String>,
    },
    // sirno:witness:interfaces:end
    /// Rename one entry id and its Sirno references.
    // sirno:witness:interfaces:begin
    Rename {
        /// Existing entry id.
        old_id: String,
        /// New entry id.
        new_id: String,
    },
    // sirno:witness:interfaces:end
    /// Freeze one public Markdown entry and make its file read-only.
    // sirno:witness:interfaces:begin
    Freeze {
        /// Entry id to freeze.
        id: String,
    },
    // sirno:witness:interfaces:end
    /// Melt one public Markdown entry and make its file writable.
    // sirno:witness:interfaces:begin
    #[command(visible_alias = "unfreeze")]
    Melt {
        /// Entry id to melt.
        id: String,
    },
    // sirno:witness:interfaces:end
    /// Query public Markdown entries.
    // sirno:witness:interfaces:begin
    #[command(visible_alias = "q")]
    Query {
        /// Vague text terms matched against entries and structural target summaries.
        terms: Vec<String>,
        /// Exact text term matched against id, name, desc, and body.
        #[arg(long = "exact-term")]
        exact_terms: Vec<String>,
        /// Exact structural predicate as FIELD=ENTRY_ID.
        #[arg(short = 'x', long, value_name = "FIELD=ENTRY_ID")]
        exact: Vec<CliStructuralPredicate>,
        /// Comma-separated output fields: id, name, path, desc.
        #[arg(short = 'f', long, value_name = "FIELDS")]
        fields: Option<CliQueryFields>,
        /// Output format.
        #[arg(short = 'o', long, value_enum)]
        format: Option<CliQueryOutputFormat>,
    },
    // sirno:witness:interfaces:end
    /// Run ripgrep in the configured public Markdown lake.
    // sirno:witness:interfaces:begin
    Rg {
        /// Include Sirno-owned generated-footer regions in the search.
        #[arg(long = "with-generated-footer")]
        with_generated_footer: bool,
        /// Arguments forwarded to ripgrep before the lake path.
        #[arg(required = true, trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<OsString>,
    },
    // sirno:witness:interfaces:end
    /// Show repository witness blocks for one entry id.
    // sirno:witness:interfaces:begin
    #[command(visible_aliases = ["w", "wit"])]
    Witness {
        /// Entry id used as the witness query key.
        id: String,
        /// Print full witness regions instead of only their locations.
        #[arg(short = 'f', long)]
        full: bool,
    },
    // sirno:witness:interfaces:end
}

/// Supported grouped public entry commands.
#[derive(Debug, Subcommand)]
enum GroupedEntryCommand {
    /// Create one Markdown entry.
    New {
        /// Entry id and filename stem.
        id: String,
        /// Human-readable entry name.
        #[arg(short = 'n', long)]
        name: Option<String>,
        /// Short entry desc.
        #[arg(short = 'd', long)]
        desc: String,
        /// Structural metadata target as FIELD=ENTRY_ID.
        #[arg(long = "structural", value_name = "FIELD=ENTRY_ID")]
        structural: Vec<CliStructuralPredicate>,
        /// Initial Markdown body.
        #[arg(short = 'b', long)]
        body: Option<String>,
    },
    /// Rename one entry id and its Sirno references.
    #[command(visible_aliases = ["mv", "move"])]
    Rename {
        /// Existing entry id.
        old_id: String,
        /// New entry id.
        new_id: String,
    },
    /// Freeze one public Markdown entry and make its file read-only.
    Freeze {
        /// Entry id to freeze.
        id: String,
    },
    /// Melt one public Markdown entry and make its file writable.
    #[command(visible_alias = "unfreeze")]
    Melt {
        /// Entry id to melt.
        id: String,
    },
    /// Query public Markdown entries.
    #[command(visible_alias = "q")]
    Query {
        /// Vague text terms matched against entries and structural target summaries.
        terms: Vec<String>,
        /// Exact text term matched against id, name, desc, and body.
        #[arg(long = "exact-term")]
        exact_terms: Vec<String>,
        /// Exact structural predicate as FIELD=ENTRY_ID.
        #[arg(short = 'x', long, value_name = "FIELD=ENTRY_ID")]
        exact: Vec<CliStructuralPredicate>,
        /// Comma-separated output fields: id, name, path, desc.
        #[arg(short = 'f', long, value_name = "FIELDS")]
        fields: Option<CliQueryFields>,
        /// Output format.
        #[arg(short = 'o', long, value_enum)]
        format: Option<CliQueryOutputFormat>,
    },
    /// Run ripgrep in the configured public Markdown lake.
    Rg {
        /// Include Sirno-owned generated-footer regions in the search.
        #[arg(long = "with-generated-footer")]
        with_generated_footer: bool,
        /// Arguments forwarded to ripgrep before the lake path.
        #[arg(required = true, trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<OsString>,
    },
    /// Show repository witness blocks for one entry id.
    #[command(visible_aliases = ["w", "wit"])]
    Witness {
        /// Entry id used as the witness query key.
        id: String,
        /// Print full witness regions instead of only their locations.
        #[arg(short = 'f', long)]
        full: bool,
    },
}

/// CLI representation of check boundaries.
#[derive(Clone, Copy, Debug, ValueEnum)]
enum CliCheckMode {
    /// Editing boundary: dangling references are warnings.
    Edit,
    /// Review boundary: dangling references are errors.
    Review,
}

/// CLI query output renderer.
#[derive(Clone, Copy, Debug, ValueEnum)]
enum CliQueryOutputFormat {
    /// Print a JSON array of objects.
    Json,
    /// Print an aligned table.
    Human,
}

/// CLI query output field list.
#[derive(Clone, Debug, PartialEq, Eq)]
struct CliQueryFields {
    fields: Vec<CliQueryField>,
}

impl Default for CliQueryFields {
    fn default() -> Self {
        Self { fields: vec![CliQueryField::Id, CliQueryField::Path, CliQueryField::Name] }
    }
}

impl FromStr for CliQueryFields {
    type Err = CliQueryFieldsParseError;

    fn from_str(raw: &str) -> Result<Self, Self::Err> {
        if raw.trim().is_empty() {
            return Err(CliQueryFieldsParseError::Empty);
        }

        let mut fields = Vec::new();
        for raw_field in raw.split(',') {
            let field = raw_field.trim();
            if field.is_empty() {
                return Err(CliQueryFieldsParseError::EmptyField);
            }
            fields.push(field.parse()?);
        }

        Ok(Self { fields })
    }
}

/// One field printable by `sirno query`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum CliQueryField {
    /// Entry id.
    Id,
    /// Human-readable entry name.
    Name,
    /// Markdown path.
    Path,
    /// Short entry desc.
    Desc,
}

impl FromStr for CliQueryField {
    type Err = CliQueryFieldsParseError;

    fn from_str(raw: &str) -> Result<Self, Self::Err> {
        match raw {
            | "id" => Ok(Self::Id),
            | "name" => Ok(Self::Name),
            | "path" => Ok(Self::Path),
            | "desc" => Ok(Self::Desc),
            | field => Err(CliQueryFieldsParseError::UnknownField(field.to_owned())),
        }
    }
}

impl CliQueryField {
    fn label(self) -> &'static str {
        match self {
            | Self::Id => "id",
            | Self::Name => "name",
            | Self::Path => "path",
            | Self::Desc => "desc",
        }
    }
}

/// Error raised while parsing one `--fields` field list.
#[derive(Debug, Error)]
enum CliQueryFieldsParseError {
    /// The list contains no fields.
    #[error("query fields must include at least one field")]
    Empty,
    /// The list contains a separator without a field.
    #[error("query fields contain an empty field")]
    EmptyField,
    /// The list contains an unknown output field.
    #[error("unknown query field `{0}`; expected id, name, path, or desc")]
    UnknownField(String),
}

/// Structural metadata predicate parsed from `FIELD=ENTRY_ID`.
#[derive(Clone, Debug, PartialEq, Eq)]
struct CliStructuralPredicate {
    field: String,
    target: EntryId,
}

impl FromStr for CliStructuralPredicate {
    type Err = CliStructuralPredicateParseError;

    fn from_str(raw: &str) -> Result<Self, Self::Err> {
        let Some((field, target)) = raw.split_once('=') else {
            return Err(CliStructuralPredicateParseError::MissingEquals);
        };
        if field.is_empty() {
            return Err(CliStructuralPredicateParseError::EmptyField);
        }
        let target = EntryId::new(target)?;
        Ok(Self { field: field.to_owned(), target })
    }
}

/// Error raised while parsing one structural `FIELD=ENTRY_ID` argument.
#[derive(Debug, Error)]
enum CliStructuralPredicateParseError {
    /// The argument does not contain the field-target separator.
    #[error("expected FIELD=ENTRY_ID")]
    MissingEquals,
    /// The structural field name is empty.
    #[error("structural field name must not be empty")]
    EmptyField,
    /// The target entry id is invalid.
    #[error(transparent)]
    EntryId(#[from] EntryIdError),
}

/// CLI shell target for completion generation.
#[derive(Clone, Copy, Debug, ValueEnum)]
enum CliCompletionShell {
    /// Bash completion script.
    Bash,
    /// Elvish completion script.
    Elvish,
    /// Fish completion script.
    Fish,
    /// PowerShell completion script.
    #[value(name = "powershell", alias = "power-shell")]
    PowerShell,
    /// Zsh completion script.
    Zsh,
}

/// Supported utility commands.
#[derive(Debug, Subcommand)]
enum UtilCommand {
    /// Generate a shell completion script.
    Completion {
        /// Shell whose completion script should be generated.
        #[arg(value_enum)]
        shell: CliCompletionShell,
    },
}

/// Supported Sirno Frost commands.
#[derive(Debug, Subcommand)]
enum FrostCommand {
    /// Configure Sirno Frost and freeze the current public Markdown lake.
    Init {
        /// Sirno Frost path written to Sirno.toml.
        #[arg(long = "frost-path")]
        frost_path: Option<PathBuf>,
    },
    /// Move the configured Sirno Frost path.
    #[command(visible_alias = "mv")]
    Move {
        /// New Sirno Frost path written to Sirno.toml.
        frost: PathBuf,
    },
    /// Freeze the current public Markdown lake.
    Commit,
    /// Check out Frost entries into the public Markdown lake.
    #[command(visible_alias = "defrost")]
    Checkout {
        /// Version coordinate to materialize in the current Frost generation.
        #[arg(required_unless_present = "latest", conflicts_with = "latest")]
        version: Option<u64>,
        /// Check out the latest Frost version as the mutable current lake.
        #[arg(long, conflicts_with = "unsafe_mutable")]
        latest: bool,
        /// Leave an explicit version checkout writable.
        #[arg(long)]
        unsafe_mutable: bool,
    },
}

/// Supported generated-link commands.
#[derive(Debug, Subcommand)]
enum GenLinkCommand {
    /// Delete generated Markdown link footers.
    Delete,
}

impl From<CliCheckMode> for CheckMode {
    fn from(value: CliCheckMode) -> Self {
        match value {
            | CliCheckMode::Edit => CheckMode::Edit,
            | CliCheckMode::Review => CheckMode::Review,
        }
    }
}

impl From<CliCompletionShell> for Shell {
    fn from(value: CliCompletionShell) -> Self {
        match value {
            | CliCompletionShell::Bash => Shell::Bash,
            | CliCompletionShell::Elvish => Shell::Elvish,
            | CliCompletionShell::Fish => Shell::Fish,
            | CliCompletionShell::PowerShell => Shell::PowerShell,
            | CliCompletionShell::Zsh => Shell::Zsh,
        }
    }
}

fn main() -> ExitCode {
    if is_rg_preprocessor_invocation() {
        return match run_rg_preprocessor_from_env() {
            | Ok(code) => code,
            | Err(error) => {
                eprintln!("sirno: {error}");
                ExitCode::FAILURE
            }
        };
    }

    match Cli::parse().run() {
        | Ok(code) => code,
        | Err(error) => {
            eprintln!("sirno: {error}");
            ExitCode::FAILURE
        }
    }
}

impl Cli {
    fn run(self) -> Result<ExitCode, CliError> {
        let config_path = self.config.unwrap_or_else(default_config_path);
        let lake_path = self.lake_path;
        match self.command {
            | Command::TopLevelLake(command) | Command::Lake { command } => {
                command.run(&config_path, lake_path.as_deref())
            }
            | Command::TopLevelEntry(command) => command.run(&config_path, lake_path.as_deref()),
            | Command::Entry { command } => {
                EntryCommand::from(command).run(&config_path, lake_path.as_deref())
            }
            | Command::Frost { command } => command.run(&config_path, lake_path.as_deref()),
            | Command::Util { command } => command.run(),
        }
    }
}

impl From<GroupedEntryCommand> for EntryCommand {
    fn from(command: GroupedEntryCommand) -> Self {
        match command {
            | GroupedEntryCommand::New { id, name, desc, structural, body } => {
                Self::New { id, name, desc, structural, body }
            }
            | GroupedEntryCommand::Rename { old_id, new_id } => Self::Rename { old_id, new_id },
            | GroupedEntryCommand::Freeze { id } => Self::Freeze { id },
            | GroupedEntryCommand::Melt { id } => Self::Melt { id },
            | GroupedEntryCommand::Query { terms, exact_terms, exact, fields, format } => {
                Self::Query { terms, exact_terms, exact, fields, format }
            }
            | GroupedEntryCommand::Rg { with_generated_footer, args } => {
                Self::Rg { with_generated_footer, args }
            }
            | GroupedEntryCommand::Witness { id, full } => Self::Witness { id, full },
        }
    }
}

impl LakeCommand {
    fn run(self, config_path: &Path, lake_path: Option<&Path>) -> Result<ExitCode, CliError> {
        match self {
            | LakeCommand::Init { mono, lake } => {
                let mut config = SirnoConfig::new(
                    lake.or_else(|| lake_path.map(Path::to_path_buf))
                        .unwrap_or_else(default_lake_path),
                );
                if let Some(mono) = mono {
                    config = config.with_mono(mono);
                }
                let lake_path = config.resolve_lake(config_path);
                config.write_new(config_path)?;
                let paths = EntryDirectory::new(&lake_path).init()?;
                println!(
                    "initialized {} with {} entries in {}",
                    config_path.display(),
                    paths.len(),
                    lake_path.display()
                );
                Ok(ExitCode::SUCCESS)
            }
            | LakeCommand::Move { lake } => {
                let config = SirnoConfig::from_file(config_path)?;
                let old_lake = config.resolve_lake(config_path);
                let config = config.with_lake(lake);
                config.validate_for_file(config_path)?;
                let new_lake = config.resolve_lake(config_path);
                move_configured_path_and_write_config(&old_lake, &new_lake, &config, config_path)?;
                println!("moved lake {} to {}", old_lake.display(), new_lake.display());
                Ok(ExitCode::SUCCESS)
            }
            | LakeCommand::Check { frost_path, mode } => {
                if lake_path.is_some() && frost_path.is_some() {
                    return Err(CliError::LakePathWithFrostPath);
                }
                let mode = mode.unwrap_or(CliCheckMode::Review);
                if lake_path.is_some() {
                    let (lake, settings) = resolve_lake_directory(lake_path, config_path)?;
                    let report =
                        EntryDirectory::new(lake).check_with_settings(mode.into(), &settings)?;
                    print_entry_directory_report(&report);
                    return if report.has_errors() {
                        Ok(ExitCode::FAILURE)
                    } else {
                        Ok(ExitCode::SUCCESS)
                    };
                }

                let Some(frost_path) = frost_path else {
                    let config = SirnoConfig::from_file(config_path)?;
                    let report = EntryDirectory::new(config.resolve_lake(config_path))
                        .check_with_settings(
                            mode.into(),
                            &entry_directory_check_settings(config_path, &config),
                        )?;
                    print_entry_directory_report(&report);
                    return if report.has_errors() {
                        Ok(ExitCode::FAILURE)
                    } else {
                        Ok(ExitCode::SUCCESS)
                    };
                };

                let frost = SirnoFrost::open(frost_path)?;
                let report = frost.check_current(mode.into())?;
                if report.is_clean() {
                    println!("ok: {}", frost.root().display());
                    return Ok(ExitCode::SUCCESS);
                }

                for diagnostic in report.diagnostics() {
                    println!("{}: {}", diagnostic.severity.label(), diagnostic.message());
                }

                if report.has_errors() { Ok(ExitCode::FAILURE) } else { Ok(ExitCode::SUCCESS) }
            }
            | LakeCommand::GenLink { command, dry } => match command {
                | None => {
                    let (lake, mut settings) = resolve_lake_directory(lake_path, config_path)?;
                    settings.link = false;
                    settings.witness = None;

                    let directory = EntryDirectory::new(&lake);
                    let check = directory.check_with_settings(CheckMode::Review, &settings)?;
                    if check.has_errors() {
                        print_entry_directory_report(&check);
                        return Ok(ExitCode::FAILURE);
                    }

                    if dry {
                        let report = directory.check_generated_links_with_ignored_paths(
                            &settings.structural,
                            settings.ignore.clone(),
                        )?;
                        print_gen_link_report(&report);
                        return Ok(ExitCode::SUCCESS);
                    }

                    let report = directory.generate_links_with_ignored_paths(
                        &settings.structural,
                        settings.ignore.clone(),
                    )?;
                    print_gen_link_report(&report);
                    Ok(ExitCode::SUCCESS)
                }
                | Some(GenLinkCommand::Delete) => {
                    if dry {
                        return Err(CliError::DryWithGenLinkSubcommand);
                    }
                    let (lake, mut settings) = resolve_lake_directory(lake_path, config_path)?;
                    settings.witness = None;

                    let report = EntryDirectory::new(&lake)
                        .delete_generated_links_with_ignored_paths(settings.ignore)?;
                    print_gen_link_report(&report);
                    Ok(ExitCode::SUCCESS)
                }
            },
            | LakeCommand::Status => {
                let config = SirnoConfig::from_file(config_path)?;
                let mono = config.resolve_mono(config_path);
                let frost = config.resolve_frost(config_path);
                let lock_path = SirnoLock::path_for_config(config_path);
                let lock = if frost.is_some() {
                    SirnoLock::from_file_if_exists(&lock_path)?
                } else {
                    None
                };
                let (lake, settings) = resolve_lake_directory(lake_path, config_path)?;
                let report =
                    EntryDirectory::new(&lake).check_with_settings(CheckMode::Review, &settings)?;
                print_status(
                    config_path,
                    mono.as_deref(),
                    frost.as_deref(),
                    lock.as_ref(),
                    &config,
                    &report,
                );
                if report.has_errors() { Ok(ExitCode::FAILURE) } else { Ok(ExitCode::SUCCESS) }
            }
        }
    }
}

impl EntryCommand {
    fn run(self, config_path: &Path, lake_path: Option<&Path>) -> Result<ExitCode, CliError> {
        match self {
            | EntryCommand::New { id, name, desc, structural, body } => {
                let (lake, settings) = resolve_lake_directory(lake_path, config_path)?;
                let id = EntryId::new(&id)?;
                let mut metadata =
                    EntryMetadata::new(name.unwrap_or_else(|| title_name_from_id(&id)), desc)?;
                for (field, targets) in
                    structural_targets_by_field(structural, &settings.structural)?
                {
                    metadata.set_structural_targets(field, targets);
                }

                let entry = Entry::new(id, metadata, body.unwrap_or_default());
                let path = EntryDirectory::new(&lake).create_entry(&entry)?;
                println!("created {}", path.display());
                Ok(ExitCode::SUCCESS)
            }
            | EntryCommand::Rename { old_id, new_id } => {
                let (lake, settings) = resolve_lake_directory(lake_path, config_path)?;
                let old_id = EntryId::new(&old_id)?;
                let new_id = EntryId::new(&new_id)?;
                let report =
                    EntryDirectory::new(&lake).rename_entry(&old_id, &new_id, &settings)?;
                let mut changed_paths = report.changed_paths().to_vec();
                if let Some(witness) = &settings.witness {
                    changed_paths.extend(witness.rename_entry_references(&old_id, &new_id)?);
                }
                changed_paths.sort();
                changed_paths.dedup();
                println!("renamed entry {old_id} to {new_id}");
                println!("updated {} paths", changed_paths.len());
                Ok(ExitCode::SUCCESS)
            }
            | EntryCommand::Freeze { id } => {
                let (lake, _) = resolve_lake_directory(lake_path, config_path)?;
                let id = EntryId::new(&id)?;
                let path = EntryDirectory::new(&lake).freeze_entry(&id)?;
                println!("froze entry {id} at {}", path.display());
                Ok(ExitCode::SUCCESS)
            }
            | EntryCommand::Melt { id } => {
                let (lake, _) = resolve_lake_directory(lake_path, config_path)?;
                let id = EntryId::new(&id)?;
                let path = EntryDirectory::new(&lake).melt_entry(&id)?;
                println!("melted entry {id} at {}", path.display());
                Ok(ExitCode::SUCCESS)
            }
            | EntryCommand::Query { terms, exact_terms, exact, fields, format } => {
                let (lake, mut settings) = resolve_lake_directory(lake_path, config_path)?;
                settings.link = false;
                settings.witness = None;
                let report =
                    EntryDirectory::new(&lake).check_with_settings(CheckMode::Edit, &settings)?;
                if report.has_errors() {
                    print_entry_directory_report(&report);
                    return Ok(ExitCode::FAILURE);
                }

                let vague_query = VagueEntryQuery::new().with_text_terms(terms);
                let exact_query = exact_query_from_predicates(
                    EntryQuery::new().with_text_terms(exact_terms),
                    exact,
                    &settings.structural,
                )?;
                let vague_matches = vague_query.select_entries(report.entries());
                let matches = exact_query.select_entries(vague_matches);
                let fields = fields.unwrap_or_default();
                let format = format.unwrap_or(CliQueryOutputFormat::Json);
                print_query_results(&report, &matches, &fields, format)?;
                Ok(ExitCode::SUCCESS)
            }
            | EntryCommand::Rg { with_generated_footer, args } => {
                run_rg_command(lake_path, config_path, with_generated_footer, args)
            }
            | EntryCommand::Witness { id, full } => {
                run_witness_command(config_path, lake_path, &id, full)
            }
        }
    }
}

impl FrostCommand {
    fn run(
        self, config_path: &std::path::Path, lake_path: Option<&Path>,
    ) -> Result<ExitCode, CliError> {
        match self {
            | FrostCommand::Init { frost_path } => {
                let config = SirnoConfig::from_file(config_path)?;
                let existing_frost = config.frost.as_ref().map(|settings| settings.path.clone());
                let frost_path = frost_path
                    .or_else(|| existing_frost.clone())
                    .unwrap_or_else(default_frost_path);
                if let Some(existing_frost) = existing_frost
                    && existing_frost != frost_path
                {
                    return Err(CliError::FrostAlreadyConfigured(existing_frost));
                }

                let needs_config_write = config.frost.is_none();
                let config =
                    if needs_config_write { config.with_frost(frost_path) } else { config };
                config.validate_for_file(config_path)?;

                let frost_path =
                    config.resolve_frost(config_path).expect("frost path configured by init");
                let frost = SirnoFrost::open(&frost_path)?;
                let version = frost.current_snapshot()?;
                if needs_config_write {
                    config.write(config_path)?;
                }
                SirnoLock::current(version).write(SirnoLock::path_for_config(config_path))?;
                println!(
                    "initialized frost {} at version {}",
                    frost_path.display(),
                    version.version(),
                );
                Ok(ExitCode::SUCCESS)
            }
            | FrostCommand::Move { frost } => {
                let config = SirnoConfig::from_file(config_path)?;
                let Some(old_frost) = config.resolve_frost(config_path) else {
                    return Err(CliError::FrostNotConfigured);
                };
                let config = config.with_frost(frost);
                config.validate_for_file(config_path)?;
                let new_frost =
                    config.resolve_frost(config_path).expect("frost path configured by move");
                move_configured_path_and_write_config(
                    &old_frost,
                    &new_frost,
                    &config,
                    config_path,
                )?;
                println!("moved frost {} to {}", old_frost.display(), new_frost.display());
                Ok(ExitCode::SUCCESS)
            }
            | FrostCommand::Commit => {
                let context = FrostContext::load(config_path, lake_path)?;
                context.reject_immutable_checkout()?;
                let mut frost = SirnoFrost::open(&context.frost_path)?;
                let version =
                    frost.commit_entry_directory(&context.lake_path, &context.settings)?;
                context.lake().set_writable(&context.settings)?;
                SirnoLock::current(version).write(&context.lock_path)?;
                println!(
                    "froze version {} from {}",
                    version.version(),
                    context.lake_path.display()
                );
                Ok(ExitCode::SUCCESS)
            }
            | FrostCommand::Checkout { version, latest, unsafe_mutable } => {
                let context = FrostContext::load(config_path, lake_path)?;
                let frost = SirnoFrost::open(&context.frost_path)?;
                let snapshot = if latest {
                    frost.current_snapshot()?
                } else {
                    frost.snapshot_for_version(frost_version(
                        version.expect("clap requires VERSION unless --latest is present"),
                    )?)?
                };
                if snapshot.version() == Eterator::EMPTY.version() {
                    return Err(CliError::InvalidFrostVersion(snapshot.version()));
                }
                let paths = frost.checkout_entry_directory(
                    snapshot,
                    &context.lake_path,
                    EntryDirectoryWritePolicy::ReplaceDirectory {
                        ignore: context.settings.ignore.clone(),
                    },
                )?;
                if latest || unsafe_mutable {
                    context.lake().set_writable(&context.settings)?;
                } else {
                    context.lake().add_readonly_checkout_warnings(&paths)?;
                    context.lake().set_readonly(&context.settings)?;
                }
                if latest {
                    SirnoLock::current(snapshot).write(&context.lock_path)?;
                } else {
                    SirnoLock::checked_out(snapshot, unsafe_mutable).write(&context.lock_path)?;
                }
                println!(
                    "checked out {}frost version {} into {} ({} entries, {})",
                    if latest { "latest " } else { "" },
                    snapshot.version(),
                    context.lake_path.display(),
                    paths.len(),
                    if latest {
                        "mutable"
                    } else if unsafe_mutable {
                        "unsafe mutable"
                    } else {
                        "immutable"
                    }
                );
                Ok(ExitCode::SUCCESS)
            }
        }
    }
}

fn move_configured_path_and_write_config(
    source: &Path, destination: &Path, config: &SirnoConfig, config_path: &Path,
) -> Result<(), CliError> {
    let moved = move_configured_path(source, destination)?;
    if let Err(config_error) = config.write(config_path) {
        if moved && let Err(rollback) = fs::rename(destination, source) {
            return Err(CliError::MoveConfigWriteRollback {
                source_path: source.to_path_buf(),
                destination_path: destination.to_path_buf(),
                source: Box::new(config_error),
                rollback,
            });
        }
        return Err(CliError::Config(config_error));
    }
    Ok(())
}

fn move_configured_path(source: &Path, destination: &Path) -> Result<bool, CliError> {
    if source == destination {
        return Ok(false);
    }
    match fs::symlink_metadata(destination) {
        | Ok(_) => return Err(CliError::MoveDestinationExists(destination.to_path_buf())),
        | Err(source) if source.kind() == ErrorKind::NotFound => {}
        | Err(source) => {
            return Err(CliError::ReadMoveDestination { path: destination.to_path_buf(), source });
        }
    }
    fs::rename(source, destination).map_err(|error| CliError::MovePath {
        source_path: source.to_path_buf(),
        destination_path: destination.to_path_buf(),
        source: error,
    })?;
    Ok(true)
}

struct FrostContext {
    frost_path: PathBuf,
    lock_path: PathBuf,
    settings: EntryDirectoryCheckSettings,
    lake_path: PathBuf,
}

impl FrostContext {
    fn load(config_path: &Path, lake_path: Option<&Path>) -> Result<Self, CliError> {
        let config = SirnoConfig::from_file(config_path)?;
        let Some(frost_path) = config.resolve_frost(config_path) else {
            return Err(CliError::FrostNotConfigured);
        };
        Ok(Self {
            frost_path,
            lock_path: SirnoLock::path_for_config(config_path),
            settings: entry_directory_check_settings(config_path, &config),
            lake_path: resolve_lake_path(lake_path, config_path, &config),
        })
    }

    fn lake(&self) -> EntryDirectory {
        EntryDirectory::new(&self.lake_path)
    }

    fn reject_immutable_checkout(&self) -> Result<(), CliError> {
        let Some(lock) = SirnoLock::from_file_if_exists(&self.lock_path)? else {
            return Ok(());
        };
        if lock.frost.is_checked_out() && !lock.frost.is_unsafe_mutable_checkout() {
            return Err(CliError::ImmutableFrostCheckout(lock.frost.version));
        }
        Ok(())
    }
}

fn frost_version(version: u64) -> Result<Eterator, CliError> {
    if version == Eterator::EMPTY.version() {
        return Err(CliError::InvalidFrostVersion(version));
    }
    Ok(Eterator(version))
}

fn run_witness_command(
    config_path: &Path, lake_path: Option<&Path>, raw_id: &str, full: bool,
) -> Result<ExitCode, CliError> {
    let config = SirnoConfig::from_file(config_path)?;
    let id = EntryId::new(raw_id)?;
    let lake = resolve_lake_path(lake_path, config_path, &config);
    if !EntryDirectory::new(&lake).entry_exists(&id)? {
        return Err(CliError::MissingWitnessEntry(id));
    }
    let Some(settings) = witness_check_settings(config_path, &config) else {
        return Err(CliError::RepoMembersNotConfigured);
    };
    let index = settings.scan()?;
    let records = index.records_for(&id);
    if records.is_empty() {
        println!("no witness found for {id}");
        return Ok(ExitCode::FAILURE);
    }
    print_witness_records(records, full);
    Ok(ExitCode::SUCCESS)
}

fn print_witness_records(records: &[WitnessRecord], full: bool) {
    print!("{}", format_witness_records(records, full));
}

fn run_rg_command(
    lake_path: Option<&Path>, config_path: &Path, with_generated_footer: bool, args: Vec<OsString>,
) -> Result<ExitCode, CliError> {
    if !with_generated_footer && rg_args_include_preprocessor(&args) {
        return Err(CliError::RgPreprocessorConflict);
    }

    let lake = resolve_lake_path_for_rg(lake_path, config_path)?;
    let preprocessor =
        if with_generated_footer { None } else { Some(RgPreprocessorLink::create()?) };

    let mut command = ProcessCommand::new("rg");
    if let Some(preprocessor) = &preprocessor {
        command.arg("--pre").arg(preprocessor.path()).arg("--pre-glob").arg("*.md");
    }
    let status = command.args(args).arg(lake).status().map_err(CliError::RunRg)?;
    Ok(exit_code_from_status(status))
}

fn rg_args_include_preprocessor(args: &[OsString]) -> bool {
    args.iter()
        .filter_map(|arg| arg.to_str())
        .any(|arg| arg == "--pre" || arg.starts_with("--pre="))
}

fn resolve_lake_path_for_rg(
    lake_path: Option<&Path>, config_path: &Path,
) -> Result<PathBuf, CliError> {
    if let Some(lake_path) = lake_path {
        return Ok(lake_path.to_path_buf());
    }

    let config = SirnoConfig::from_file(config_path)?;
    Ok(config.resolve_lake(config_path))
}

fn exit_code_from_status(status: ExitStatus) -> ExitCode {
    if let Some(code) = status.code().and_then(|code| u8::try_from(code).ok()) {
        return ExitCode::from(code);
    }

    ExitCode::FAILURE
}

fn is_rg_preprocessor_invocation() -> bool {
    env::args_os()
        .next()
        .and_then(|arg| PathBuf::from(arg).file_name().map(|name| name.to_os_string()))
        .is_some_and(|name| name.to_string_lossy().starts_with(RG_PREPROCESSOR_ARGV0_PREFIX))
}

fn run_rg_preprocessor_from_env() -> Result<ExitCode, CliError> {
    let mut args = env::args_os().skip(1);
    let Some(path) = args.next() else {
        return Err(CliError::RgPreprocessorArgumentCount);
    };
    if args.next().is_some() {
        return Err(CliError::RgPreprocessorArgumentCount);
    }

    run_rg_preprocessor(&PathBuf::from(path))
}

fn run_rg_preprocessor(path: &Path) -> Result<ExitCode, CliError> {
    let body = fs::read_to_string(path)
        .map_err(|source| CliError::ReadRgPreprocessorInput { path: path.to_path_buf(), source })?;
    let masked = GeneratedLinkBody::new(&body).mask()?;
    io::stdout().write_all(masked.as_bytes()).map_err(CliError::WriteRgPreprocessorOutput)?;
    Ok(ExitCode::SUCCESS)
}

#[derive(Debug)]
struct RgPreprocessorLink {
    path: PathBuf,
}

impl RgPreprocessorLink {
    fn create() -> Result<Self, CliError> {
        let current_exe = env::current_exe().map_err(CliError::LocateCurrentExe)?;
        let mut path = env::temp_dir();
        path.push(format!(
            "{RG_PREPROCESSOR_ARGV0_PREFIX}{}-{}",
            std::process::id(),
            current_time_nanos()
        ));
        #[cfg(not(unix))]
        if let Some(extension) = current_exe.extension() {
            path.set_extension(extension);
        }

        create_rg_preprocessor_invoker(&current_exe, &path).map_err(|source| {
            CliError::CreateRgPreprocessorInvoker { path: path.clone(), source }
        })?;
        Ok(Self { path })
    }

    fn path(&self) -> &Path {
        &self.path
    }
}

impl Drop for RgPreprocessorLink {
    fn drop(&mut self) {
        let _ = fs::remove_file(&self.path);
    }
}

fn current_time_nanos() -> u128 {
    SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_nanos()
}

#[cfg(unix)]
fn create_rg_preprocessor_invoker(current_exe: &Path, path: &Path) -> io::Result<()> {
    std::os::unix::fs::symlink(current_exe, path)
}

#[cfg(not(unix))]
fn create_rg_preprocessor_invoker(current_exe: &Path, path: &Path) -> io::Result<()> {
    fs::copy(current_exe, path).map(|_| ())
}

fn format_witness_records(records: &[WitnessRecord], full: bool) -> String {
    let mut out = String::new();
    for (index, record) in records.iter().enumerate() {
        if full && index > 0 {
            out.push_str("---\n\n");
        }
        out.push_str(&format_witness_record(record, full));
    }
    out
}

fn format_witness_record(record: &WitnessRecord, full: bool) -> String {
    let range = format_witness_summary(record);
    if !full {
        let marker =
            record.body.lines().next().map(str::to_owned).unwrap_or_else(|| record.marker.clone());
        return format!("{range}\t{marker}\n");
    }

    let mut out = format!("{range}\n\n");
    out.push_str(&record.body);
    if !record.body.ends_with('\n') {
        out.push('\n');
    }
    out.push('\n');
    out
}

fn format_witness_summary(record: &WitnessRecord) -> String {
    format!(
        "{}:{}:{}-{} :: {}:{}-{}",
        record.path.display(),
        record.opening.start_line,
        record.opening.start_column,
        record.opening.end_column,
        record.closing.start_line,
        record.closing.start_column,
        record.closing.end_column
    )
}

impl UtilCommand {
    fn run(self) -> Result<ExitCode, CliError> {
        match self {
            | UtilCommand::Completion { shell } => {
                let shell = Shell::from(shell);
                let mut command = Cli::command();
                let mut stdout = std::io::stdout();
                generate(shell, &mut command, "sirno", &mut stdout);
                Ok(ExitCode::SUCCESS)
            }
        }
    }
}

fn default_config_path() -> PathBuf {
    PathBuf::from(CONFIG_FILE_NAME)
}

fn default_lake_path() -> PathBuf {
    PathBuf::from("docs")
}

fn default_frost_path() -> PathBuf {
    PathBuf::from("sirno-frost")
}

fn explicit_lake_check_settings(
    config_path: &std::path::Path,
) -> Result<EntryDirectoryCheckSettings, CliError> {
    if config_path.exists() {
        let config = SirnoConfig::from_file(config_path)?;
        Ok(entry_directory_check_settings(config_path, &config))
    } else {
        Ok(EntryDirectoryCheckSettings::default())
    }
}

fn entry_directory_check_settings(
    config_path: &Path, config: &SirnoConfig,
) -> EntryDirectoryCheckSettings {
    EntryDirectoryCheckSettings {
        link: config.check.link,
        structural: config.structural.clone(),
        ignore: config.lake.ignore.clone(),
        witness: witness_check_settings(config_path, config),
    }
}

fn witness_check_settings(
    config_path: &Path, config: &SirnoConfig,
) -> Option<WitnessCheckSettings> {
    let repo = config.repo.as_ref()?;
    if repo.members.is_empty() {
        return None;
    }
    Some(WitnessCheckSettings::new(
        config_path.parent().unwrap_or_else(|| Path::new(".")),
        repo.members.clone(),
        config.witness.clone(),
    ))
}

fn resolve_lake_path(
    lake_path: Option<&Path>, config_path: &Path, config: &SirnoConfig,
) -> PathBuf {
    lake_path.map(Path::to_path_buf).unwrap_or_else(|| config.resolve_lake(config_path))
}

fn resolve_lake_directory(
    lake_path: Option<&Path>, config_path: &std::path::Path,
) -> Result<(PathBuf, EntryDirectoryCheckSettings), CliError> {
    if let Some(lake_path) = lake_path {
        return Ok((lake_path.to_path_buf(), explicit_lake_check_settings(config_path)?));
    }

    let config = SirnoConfig::from_file(config_path)?;
    Ok((config.resolve_lake(config_path), entry_directory_check_settings(config_path, &config)))
}

fn exact_query_from_predicates(
    mut query: EntryQuery, predicates: Vec<CliStructuralPredicate>, structural: &StructuralSettings,
) -> Result<EntryQuery, CliError> {
    for (field, targets) in structural_targets_by_field(predicates, structural)? {
        query = query.with_structural_targets(field, targets);
    }
    Ok(query)
}

fn structural_targets_by_field(
    predicates: Vec<CliStructuralPredicate>, structural: &StructuralSettings,
) -> Result<IndexMap<String, Vec<EntryId>>, CliError> {
    let mut targets_by_field = IndexMap::<String, Vec<EntryId>>::new();
    for predicate in predicates {
        if !structural.contains_field(&predicate.field) {
            return Err(CliError::UnconfiguredStructuralField(predicate.field));
        }
        targets_by_field.entry(predicate.field).or_default().push(predicate.target);
    }
    Ok(targets_by_field)
}

fn title_name_from_id(id: &EntryId) -> String {
    id.as_str()
        .split('-')
        .map(|segment| {
            let mut chars = segment.chars();
            let Some(first) = chars.next() else {
                return String::new();
            };
            let mut word = first.to_uppercase().to_string();
            word.push_str(chars.as_str());
            word
        })
        .collect::<Vec<_>>()
        .join(" ")
}

fn print_status(
    config_path: &std::path::Path, mono: Option<&std::path::Path>, frost: Option<&std::path::Path>,
    lock: Option<&SirnoLock>, config: &SirnoConfig, report: &EntryDirectoryReport,
) {
    println!("config: {}", config_path.display());
    if let Some(mono) = mono {
        println!("mono: {}", mono.display());
    } else {
        println!("mono: (not configured)");
    }
    println!("lake: {}", report.root().display());
    if let Some(frost) = frost {
        println!("frost: {}", frost.display());
        println!("frost-state: {}", frost_state_label(lock));
    } else {
        println!("frost: (not configured)");
    }
    println!("entries: {}", report.entries().len());
    println!("checks:");
    println!("  link: {}", config.check.link);
    println!("structural:");
    for (field, settings) in config.structural.fields() {
        println!("  {field}.link: {}", settings.link);
    }
    if report.has_errors() {
        println!("check: failed");
        print_entry_directory_report(report);
    } else {
        println!("check: ok");
    }
}

fn frost_state_label(lock: Option<&SirnoLock>) -> String {
    let Some(lock) = lock else {
        return "(unlocked)".to_owned();
    };
    match lock.frost.status {
        | FrostLockStatus::Current => {
            format!(
                "current version {} (generation {}, mutable)",
                lock.frost.version, lock.frost.generation
            )
        }
        | FrostLockStatus::CheckedOut if lock.frost.mutable => {
            format!(
                "checked-out version {} (generation {}, unsafe mutable)",
                lock.frost.version, lock.frost.generation
            )
        }
        | FrostLockStatus::CheckedOut => {
            format!(
                "checked-out version {} (generation {}, immutable)",
                lock.frost.version, lock.frost.generation
            )
        }
    }
}

fn print_gen_link_report(report: &GenLinkDirectoryReport) {
    println!(
        "{}",
        format_gen_link_report(report.root(), report.entry_count(), report.changed_paths())
    );
}

fn format_gen_link_report(root: &Path, entry_count: usize, changed_paths: &[PathBuf]) -> String {
    if changed_paths.is_empty() {
        return format!("No changes in {}", root.display());
    }

    let mut report = format!("Changes in {}:", root.display());
    for path in changed_paths {
        report.push_str("\n- ");
        report.push_str(&path.display().to_string());
    }
    report.push_str("\nTotal changes: ");
    report.push_str(&changed_paths.len().to_string());
    report.push('/');
    report.push_str(&entry_count.to_string());
    report
}

fn print_query_results(
    report: &EntryDirectoryReport, entries: &[&Entry], fields: &CliQueryFields,
    format: CliQueryOutputFormat,
) -> Result<(), CliError> {
    let rows = query_result_rows(report, entries, fields)?;
    match format {
        | CliQueryOutputFormat::Json => {
            println!("{}", format_query_json(fields, &rows)?);
        }
        | CliQueryOutputFormat::Human => {
            print!("{}", format_query_table(fields, &rows));
        }
    }
    Ok(())
}

fn query_result_rows(
    report: &EntryDirectoryReport, entries: &[&Entry], fields: &CliQueryFields,
) -> Result<Vec<Vec<String>>, CliError> {
    entries
        .iter()
        .map(|entry| {
            fields
                .fields
                .iter()
                .map(|field| format_query_field(report, entry, *field))
                .collect::<Result<Vec<_>, _>>()
        })
        .collect()
}

fn format_query_field(
    report: &EntryDirectoryReport, entry: &Entry, field: CliQueryField,
) -> Result<String, CliError> {
    match field {
        | CliQueryField::Id => Ok(entry.id.to_string()),
        | CliQueryField::Name => Ok(entry.metadata.name.clone()),
        | CliQueryField::Path => {
            let path = report
                .entry_path(&entry.id)
                .ok_or_else(|| EntryDirectoryError::MissingEntryPath(entry.id.clone()))?;
            Ok(path.display().to_string())
        }
        | CliQueryField::Desc => Ok(entry.metadata.desc.clone()),
    }
}

fn format_query_json(fields: &CliQueryFields, rows: &[Vec<String>]) -> Result<String, CliError> {
    let records = rows.iter().map(|row| QueryJsonRecord { fields, row }).collect::<Vec<_>>();
    Ok(serde_json::to_string_pretty(&records)?)
}

struct QueryJsonRecord<'a> {
    fields: &'a CliQueryFields,
    row: &'a [String],
}

impl serde::Serialize for QueryJsonRecord<'_> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let mut map = serializer.serialize_map(Some(self.fields.fields.len()))?;
        for (field, value) in self.fields.fields.iter().zip(self.row) {
            map.serialize_entry(field.label(), value)?;
        }
        map.end()
    }
}

fn format_query_table(fields: &CliQueryFields, rows: &[Vec<String>]) -> String {
    let headers = fields.fields.iter().map(|field| field.label()).collect::<Vec<_>>();
    let mut widths = headers.iter().map(|header| cell_width(header)).collect::<Vec<_>>();
    for row in rows {
        for (index, cell) in row.iter().enumerate() {
            widths[index] = widths[index].max(cell_width(cell));
        }
    }

    let mut table = String::new();
    push_query_table_row(&mut table, headers.iter().copied(), &widths);
    push_query_table_separator(&mut table, &widths);
    for row in rows {
        push_query_table_row(&mut table, row.iter().map(String::as_str), &widths);
    }
    table
}

fn push_query_table_row<'a>(
    table: &mut String, cells: impl IntoIterator<Item = &'a str>, widths: &[usize],
) {
    table.push('|');
    for (cell, width) in cells.into_iter().zip(widths) {
        table.push(' ');
        table.push_str(cell);
        table.push_str(&" ".repeat(width.saturating_sub(cell_width(cell))));
        table.push_str(" |");
    }
    table.push('\n');
}

fn push_query_table_separator(table: &mut String, widths: &[usize]) {
    table.push('|');
    for width in widths {
        table.push(' ');
        table.push_str(&"-".repeat(*width));
        table.push_str(" |");
    }
    table.push('\n');
}

fn cell_width(cell: &str) -> usize {
    cell.chars().count()
}

fn print_entry_directory_report(report: &EntryDirectoryReport) {
    if report.is_clean() {
        println!("ok: {}", report.root().display());
        return;
    }

    for diagnostic in report.file_diagnostics() {
        println!(
            "{}: {}: {}",
            diagnostic.severity.label(),
            diagnostic.path.display(),
            diagnostic.message
        );
    }

    for diagnostic in report.structural_report().diagnostics() {
        if let Some(path) = report.entry_path(&diagnostic.entry) {
            println!(
                "{}: {}: {}",
                diagnostic.severity.label(),
                path.display(),
                diagnostic.message()
            );
        } else {
            println!("{}: {}", diagnostic.severity.label(), diagnostic.message());
        }
    }
}

/// Error raised while running the CLI.
#[derive(Debug, Error)]
enum CliError {
    /// Sirno Frost has already been configured at another path.
    #[error("frost is already configured at {0}")]
    FrostAlreadyConfigured(PathBuf),
    /// Sirno Frost is required for a frost command but is not configured.
    #[error("frost is not configured; run `sirno frost init` first")]
    FrostNotConfigured,
    /// Immutable Frost checkouts cannot be committed.
    #[error("frost version {0} is checked out immutably; use checkout --unsafe-mutable first")]
    ImmutableFrostCheckout(u64),
    /// Empty Frost cannot be checked out as a version.
    #[error("frost version {0} is not a check-outable snapshot")]
    InvalidFrostVersion(u64),
    /// A configured lake move cannot replace an existing destination.
    #[error("move destination already exists: {0}")]
    MoveDestinationExists(PathBuf),
    /// A configured lake move could not inspect its destination.
    #[error("failed to inspect move destination {path}")]
    ReadMoveDestination {
        /// Destination path that could not be inspected.
        path: PathBuf,
        /// Underlying I/O error.
        #[source]
        source: std::io::Error,
    },
    /// A configured lake path could not be moved.
    #[error("failed to move {source_path} to {destination_path}")]
    MovePath {
        /// Source path configured before the move.
        source_path: PathBuf,
        /// Destination path configured by the move.
        destination_path: PathBuf,
        /// Underlying I/O error.
        #[source]
        source: std::io::Error,
    },
    /// A config write failed after a configured path was moved, and the rollback also failed.
    #[error(
        "failed to write config after moving {source_path} to {destination_path}; rollback failed: {rollback}"
    )]
    MoveConfigWriteRollback {
        /// Source path configured before the move.
        source_path: PathBuf,
        /// Destination path already moved into place.
        destination_path: PathBuf,
        /// Config write error.
        #[source]
        source: Box<ConfigError>,
        /// Rollback rename error.
        rollback: std::io::Error,
    },
    /// Witness lookup requires configured repo members.
    #[error("repo members are not configured; add [repo].members to Sirno.toml")]
    RepoMembersNotConfigured,
    /// Witness lookup requires an existing entry id.
    #[error("entry `{0}` does not exist")]
    MissingWitnessEntry(EntryId),
    /// Lake path override does not apply to checking a Frost path directly.
    #[error("`--lake-path` cannot be used with `check --frost-path`")]
    LakePathWithFrostPath,
    /// Dry-run mode applies only to generated-link writing.
    #[error("`--dry` only applies to `sirno gen-link` without a subcommand")]
    DryWithGenLinkSubcommand,
    /// A command named a structural field not configured for this project.
    #[error("structural field `{0}` is not configured; add it under [structural] in Sirno.toml")]
    UnconfiguredStructuralField(String),
    /// Generated-footer masking cannot compose with another ripgrep preprocessor.
    #[error(
        "generated-footer filtering cannot be combined with `rg --pre`; use `--with-generated-footer`"
    )]
    RgPreprocessorConflict,
    /// Ripgrep generated-footer preprocessor received an unexpected argument shape.
    #[error("rg generated-footer preprocessor expects one path argument")]
    RgPreprocessorArgumentCount,
    /// The current executable path could not be resolved.
    #[error("failed to locate current executable for rg preprocessor")]
    LocateCurrentExe(#[source] std::io::Error),
    /// A temporary ripgrep preprocessor invoker could not be created.
    #[error("failed to create rg preprocessor invoker at {path}")]
    CreateRgPreprocessorInvoker {
        /// Invoker path that could not be created.
        path: PathBuf,
        /// Underlying I/O error.
        #[source]
        source: std::io::Error,
    },
    /// The generated-footer preprocessor could not read one file.
    #[error("failed to read rg preprocessor input {path}")]
    ReadRgPreprocessorInput {
        /// Path passed by ripgrep.
        path: PathBuf,
        /// Underlying I/O error.
        #[source]
        source: std::io::Error,
    },
    /// The generated-footer preprocessor could not write masked output.
    #[error("failed to write rg preprocessor output")]
    WriteRgPreprocessorOutput(#[source] std::io::Error),
    /// Config-backed command failed.
    #[error(transparent)]
    Config(#[from] ConfigError),
    /// Lock-backed command failed.
    #[error(transparent)]
    Lock(#[from] LockError),
    /// Sirno-Frost-backed command failed.
    #[error(transparent)]
    Frost(#[from] FrostError),
    /// Witness lookup failed.
    #[error(transparent)]
    Witness(#[from] WitnessError),
    /// Public Markdown entry directory command failed.
    #[error(transparent)]
    EntryDirectory(#[from] EntryDirectoryError),
    /// Entry id parsing failed.
    #[error(transparent)]
    EntryId(#[from] EntryIdError),
    /// Entry metadata construction failed.
    #[error(transparent)]
    EntryParse(#[from] EntryParseError),
    /// Generated-link footer handling failed.
    #[error(transparent)]
    GeneratedLink(#[from] GeneratedLinkError),
    /// Ripgrep could not be started.
    #[error("failed to run rg")]
    RunRg(#[source] std::io::Error),
    /// Query JSON rendering failed.
    #[error(transparent)]
    Json(#[from] serde_json::Error),
}

#[cfg(test)]
mod tests {
    use std::ffi::OsString;
    use std::fs;
    use std::path::{Path, PathBuf};

    use clap::Parser;

    use sirno::{
        CONFIG_FILE_NAME, Entry, EntryId, EntryMetadata, EntryQuery, Eterator, FrostLockStatus,
        FrostSettings, LOCK_FILE_NAME, RepoMember, RepoSettings, SirnoConfig, SirnoFrost,
        SirnoLock, StructuralFieldSettings, StructuralSettings, WitnessRecord, WitnessSpan,
    };

    use crate::{
        Cli, CliCheckMode, CliError, CliQueryField, CliQueryFields, CliQueryOutputFormat,
        CliStructuralPredicate, Command, EntryCommand, FrostCommand, GroupedEntryCommand,
        LakeCommand, exact_query_from_predicates, format_gen_link_report, format_query_json,
        format_query_table, format_witness_record, format_witness_records,
        rg_args_include_preprocessor,
    };

    fn assert_before(source: &str, before: &str, after: &str) {
        assert!(source.find(before).unwrap() < source.find(after).unwrap());
    }

    #[test]
    fn init_does_not_accept_frost_path() {
        let error =
            Cli::try_parse_from(["sirno", "init", "--frost-path", "sirno-frost"]).unwrap_err();

        assert!(error.to_string().contains("unexpected argument"));
    }

    #[test]
    fn init_uses_global_lake_path() {
        let temp = tempfile::tempdir().unwrap();
        let config_path = temp.path().join(CONFIG_FILE_NAME);
        let docs = temp.path().join("sirno-docs");

        Cli::parse_from([
            "sirno",
            "--config",
            config_path.to_str().unwrap(),
            "--lake-path",
            "sirno-docs",
            "init",
        ])
        .run()
        .unwrap();

        let config = SirnoConfig::from_file(&config_path).unwrap();
        assert_eq!(config.lake.path, PathBuf::from("sirno-docs"));
        assert!(docs.join("concept.md").exists());
    }

    #[test]
    fn short_config_matches_global_config() {
        let cli = Cli::parse_from(["sirno", "-C", "Sirno.alt.toml", "status"]);

        assert_eq!(cli.config, Some(PathBuf::from("Sirno.alt.toml")));
        assert!(matches!(cli.command, Command::TopLevelLake(LakeCommand::Status)));
    }

    #[test]
    fn short_lake_path_matches_global_lake_path() {
        let cli = Cli::parse_from(["sirno", "-L", "scratch-docs", "status"]);

        assert_eq!(cli.lake_path.as_deref(), Some(Path::new("scratch-docs")));
        assert!(matches!(cli.command, Command::TopLevelLake(LakeCommand::Status)));
    }

    #[test]
    fn frost_init_accepts_frost_path() {
        let cli = Cli::parse_from(["sirno", "frost", "init", "--frost-path", "sirno-frost"]);

        assert!(matches!(
            cli.command,
            Command::Frost { command: FrostCommand::Init { frost_path: Some(_) } }
        ));
    }

    #[test]
    fn frost_init_rejects_old_frost_flag() {
        let error =
            Cli::try_parse_from(["sirno", "frost", "init", "--frost", "sirno-frost"]).unwrap_err();

        assert_eq!(error.kind(), clap::error::ErrorKind::UnknownArgument);
    }

    #[test]
    fn frost_init_creates_empty_version_zero_store() {
        let temp = tempfile::tempdir().unwrap();
        let config_path = temp.path().join(CONFIG_FILE_NAME);
        let docs = temp.path().join("docs");
        let frost_path = temp.path().join("sirno-frost");
        SirnoConfig::new("docs").write_new(&config_path).unwrap();
        fs::create_dir(&docs).unwrap();
        fs::write(
            docs.join("alpha.md"),
            "\
---
name: Alpha
desc: Alpha entry.
---

Body.
",
        )
        .unwrap();

        Cli::parse_from(["sirno", "--config", config_path.to_str().unwrap(), "frost", "init"])
            .run()
            .unwrap();

        let config = SirnoConfig::from_file(&config_path).unwrap();
        let lock = SirnoLock::from_file(temp.path().join(LOCK_FILE_NAME)).unwrap();
        let frost = SirnoFrost::open(&frost_path).unwrap();
        let mut frost_paths = fs::read_dir(&frost_path)
            .unwrap()
            .map(|entry| entry.unwrap().file_name())
            .collect::<Vec<_>>();
        frost_paths.sort();

        assert_eq!(config.frost, Some(FrostSettings { path: PathBuf::from("sirno-frost") }));
        assert_eq!(lock.frost.status, FrostLockStatus::Current);
        assert_eq!(lock.frost.version, Eterator::EMPTY.version());
        assert_eq!(frost.current_version().unwrap(), Eterator::EMPTY);
        assert!(frost.read_all_entries().unwrap().is_empty());
        assert_eq!(frost_paths, [OsString::from("Eter.lock.toml")]);
    }

    #[test]
    fn frost_checkout_latest_writes_mutable_current_lake() {
        let temp = tempfile::tempdir().unwrap();
        let config_path = temp.path().join(CONFIG_FILE_NAME);
        let docs = temp.path().join("docs");
        SirnoConfig::new("docs").with_frost("sirno-frost").write_new(&config_path).unwrap();
        fs::create_dir(&docs).unwrap();
        fs::write(
            docs.join("alpha.md"),
            "\
---
name: Alpha
desc: Alpha entry.
---

Body.
",
        )
        .unwrap();

        Cli::parse_from(["sirno", "--config", config_path.to_str().unwrap(), "frost", "commit"])
            .run()
            .unwrap();
        Cli::parse_from([
            "sirno",
            "--config",
            config_path.to_str().unwrap(),
            "frost",
            "checkout",
            "1",
        ])
        .run()
        .unwrap();
        assert!(fs::metadata(docs.join("alpha.md")).unwrap().permissions().readonly());

        Cli::parse_from([
            "sirno",
            "--config",
            config_path.to_str().unwrap(),
            "frost",
            "checkout",
            "--latest",
        ])
        .run()
        .unwrap();

        let lock = SirnoLock::from_file(temp.path().join(LOCK_FILE_NAME)).unwrap();
        let source = fs::read_to_string(docs.join("alpha.md")).unwrap();
        assert_eq!(lock.frost.status, FrostLockStatus::Current);
        assert_eq!(lock.frost.version, 1);
        assert!(!lock.frost.mutable);
        assert!(!source.contains("read-only Sirno Frost checkout"));
        assert!(!fs::metadata(&docs).unwrap().permissions().readonly());
        assert!(!fs::metadata(docs.join("alpha.md")).unwrap().permissions().readonly());
    }

    #[test]
    fn move_accepts_lake_path() {
        let cli = Cli::parse_from(["sirno", "move", "sirno-docs"]);

        assert!(matches!(
            cli.command,
            Command::TopLevelLake(LakeCommand::Move { lake }) if lake == Path::new("sirno-docs")
        ));
    }

    #[test]
    fn mv_alias_accepts_lake_path() {
        let cli = Cli::parse_from(["sirno", "mv", "sirno-docs"]);

        assert!(matches!(
            cli.command,
            Command::TopLevelLake(LakeCommand::Move { lake }) if lake == Path::new("sirno-docs")
        ));
    }

    #[test]
    fn lake_move_accepts_mv_alias() {
        let cli = Cli::parse_from(["sirno", "lake", "mv", "sirno-docs"]);

        assert!(matches!(
            cli.command,
            Command::Lake { command: LakeCommand::Move { lake } }
                if lake == Path::new("sirno-docs")
        ));
    }

    #[test]
    fn frost_move_accepts_frost_path() {
        let cli = Cli::parse_from(["sirno", "frost", "move", "sirno-frost-2"]);

        assert!(matches!(
            cli.command,
            Command::Frost { command: FrostCommand::Move { frost } }
                if frost == Path::new("sirno-frost-2")
        ));
    }

    #[test]
    fn frost_mv_alias_accepts_frost_path() {
        let cli = Cli::parse_from(["sirno", "frost", "mv", "sirno-frost-2"]);

        assert!(matches!(
            cli.command,
            Command::Frost { command: FrostCommand::Move { frost } }
                if frost == Path::new("sirno-frost-2")
        ));
    }

    #[test]
    fn frost_checkout_accepts_unsafe_mutable_flag() {
        let cli = Cli::parse_from(["sirno", "frost", "checkout", "3", "--unsafe-mutable"]);

        assert!(matches!(
            cli.command,
            Command::Frost {
                command: FrostCommand::Checkout {
                    version: Some(3),
                    latest: false,
                    unsafe_mutable: true
                }
            }
        ));
    }

    #[test]
    fn frost_checkout_accepts_latest_flag() {
        let cli = Cli::parse_from(["sirno", "frost", "checkout", "--latest"]);

        assert!(matches!(
            cli.command,
            Command::Frost {
                command: FrostCommand::Checkout {
                    version: None,
                    latest: true,
                    unsafe_mutable: false
                }
            }
        ));
    }

    #[test]
    fn frost_defrost_alias_accepts_latest_flag() {
        let cli = Cli::parse_from(["sirno", "frost", "defrost", "--latest"]);

        assert!(matches!(
            cli.command,
            Command::Frost {
                command: FrostCommand::Checkout {
                    version: None,
                    latest: true,
                    unsafe_mutable: false
                }
            }
        ));
    }

    #[test]
    fn frost_checkout_rejects_latest_with_version() {
        let error =
            Cli::try_parse_from(["sirno", "frost", "checkout", "3", "--latest"]).unwrap_err();

        assert_eq!(error.kind(), clap::error::ErrorKind::ArgumentConflict);
    }

    #[test]
    fn frost_checkout_rejects_latest_with_unsafe_mutable() {
        let error =
            Cli::try_parse_from(["sirno", "frost", "checkout", "--latest", "--unsafe-mutable"])
                .unwrap_err();

        assert_eq!(error.kind(), clap::error::ErrorKind::ArgumentConflict);
    }

    #[test]
    fn freeze_accepts_entry_id() {
        let cli = Cli::parse_from(["sirno", "freeze", "alpha"]);

        assert!(matches!(
            cli.command,
            Command::TopLevelEntry(EntryCommand::Freeze { id, .. }) if id == "alpha"
        ));
    }

    #[test]
    fn new_accepts_short_metadata_flags() {
        let cli = Cli::parse_from([
            "sirno",
            "new",
            "alpha",
            "-n",
            "Alpha",
            "-d",
            "Alpha desc.",
            "-b",
            "Alpha body.",
        ]);

        assert!(matches!(
            cli.command,
            Command::TopLevelEntry(EntryCommand::New {
                id,
                name: Some(name),
                desc,
                body: Some(body),
                ..
            })
                if id == "alpha"
                    && name == "Alpha"
                    && desc == "Alpha desc."
                    && body == "Alpha body."
        ));
    }

    #[test]
    fn new_accepts_structural_targets() {
        let cli = Cli::parse_from([
            "sirno",
            "new",
            "alpha",
            "-d",
            "Alpha desc.",
            "--structural",
            "topic=concept",
            "--structural",
            "topic=methodology",
        ]);

        assert!(matches!(
            cli.command,
            Command::TopLevelEntry(EntryCommand::New { structural, .. })
                if structural == vec![
                    CliStructuralPredicate {
                        field: "topic".to_owned(),
                        target: EntryId::new("concept").unwrap(),
                    },
                    CliStructuralPredicate {
                        field: "topic".to_owned(),
                        target: EntryId::new("methodology").unwrap(),
                    },
            ]
        ));
    }

    #[test]
    fn rename_accepts_entry_ids_and_aliases() {
        let top_level = Cli::parse_from(["sirno", "rename", "old-entry", "new-entry"]);
        let grouped = Cli::parse_from(["sirno", "entry", "rename", "old-entry", "new-entry"]);
        let short = Cli::parse_from(["sirno", "entry", "mv", "old-entry", "new-entry"]);
        let mnemonic = Cli::parse_from(["sirno", "entry", "move", "old-entry", "new-entry"]);

        assert!(matches!(
            top_level.command,
            Command::TopLevelEntry(EntryCommand::Rename { old_id, new_id })
                if old_id == "old-entry" && new_id == "new-entry"
        ));
        assert!(matches!(
            grouped.command,
            Command::Entry { command: GroupedEntryCommand::Rename { old_id, new_id } }
                if old_id == "old-entry" && new_id == "new-entry"
        ));
        assert!(matches!(
            short.command,
            Command::Entry { command: GroupedEntryCommand::Rename { old_id, new_id } }
                if old_id == "old-entry" && new_id == "new-entry"
        ));
        assert!(matches!(
            mnemonic.command,
            Command::Entry { command: GroupedEntryCommand::Rename { old_id, new_id } }
                if old_id == "old-entry" && new_id == "new-entry"
        ));
    }

    #[test]
    fn entry_new_creates_entry() {
        let temp = tempfile::tempdir().unwrap();
        let config_path = temp.path().join(CONFIG_FILE_NAME);
        let docs = temp.path().join("docs");
        SirnoConfig::new("docs").write_new(&config_path).unwrap();
        fs::create_dir(&docs).unwrap();

        Cli::parse_from([
            "sirno",
            "--config",
            config_path.to_str().unwrap(),
            "entry",
            "new",
            "alpha",
            "--desc",
            "Alpha entry.",
        ])
        .run()
        .unwrap();

        assert!(docs.join("alpha.md").exists());
    }

    #[test]
    fn new_rejects_exact_short_alias() {
        let error = Cli::try_parse_from([
            "sirno",
            "new",
            "alpha",
            "-d",
            "Alpha desc.",
            "-x",
            "topic=concept",
        ])
        .unwrap_err();

        assert_eq!(error.kind(), clap::error::ErrorKind::UnknownArgument);
    }

    #[test]
    fn lake_path_is_global() {
        let cli = Cli::parse_from(["sirno", "freeze", "alpha", "--lake-path", "scratch-docs"]);

        assert_eq!(cli.lake_path.as_deref(), Some(Path::new("scratch-docs")));
        assert!(matches!(
            cli.command,
            Command::TopLevelEntry(EntryCommand::Freeze { id }) if id == "alpha"
        ));
    }

    #[test]
    fn lake_path_conflicts_with_frost_path_check() {
        let error = Cli::parse_from([
            "sirno",
            "--lake-path",
            "scratch-docs",
            "check",
            "--frost-path",
            "sirno-frost",
        ])
        .run()
        .unwrap_err();

        assert!(matches!(error, CliError::LakePathWithFrostPath));
    }

    #[test]
    fn check_rejects_old_frost_root_flag() {
        let error =
            Cli::try_parse_from(["sirno", "check", "--frost-root", "sirno-frost"]).unwrap_err();

        assert_eq!(error.kind(), clap::error::ErrorKind::UnknownArgument);
    }

    #[test]
    fn query_accepts_exact_structural_predicate() {
        let cli = Cli::parse_from(["sirno", "query", "--exact", "topic=concept"]);

        assert!(matches!(
            cli.command,
            Command::TopLevelEntry(EntryCommand::Query { exact, .. })
                if exact == vec![CliStructuralPredicate {
                    field: "topic".to_owned(),
                    target: EntryId::new("concept").unwrap(),
                }]
        ));
    }

    #[test]
    fn query_accepts_short_alias_and_options() {
        let cli =
            Cli::parse_from(["sirno", "q", "-x", "topic=concept", "-f", "id,path", "-o", "human"]);
        let Command::TopLevelEntry(EntryCommand::Query {
            exact,
            fields: Some(fields),
            format: Some(format),
            ..
        }) = cli.command
        else {
            panic!("expected query command with short options");
        };

        assert_eq!(
            exact,
            vec![CliStructuralPredicate {
                field: "topic".to_owned(),
                target: EntryId::new("concept").unwrap(),
            }]
        );
        assert_eq!(fields.fields, vec![CliQueryField::Id, CliQueryField::Path]);
        assert!(matches!(format, CliQueryOutputFormat::Human));
    }

    #[test]
    fn entry_query_accepts_short_alias_and_options() {
        let cli = Cli::parse_from([
            "sirno",
            "entry",
            "q",
            "-x",
            "topic=concept",
            "-f",
            "id,path",
            "-o",
            "human",
        ]);
        let Command::Entry {
            command:
                GroupedEntryCommand::Query { exact, fields: Some(fields), format: Some(format), .. },
        } = cli.command
        else {
            panic!("expected grouped query command with short options");
        };

        assert_eq!(
            exact,
            vec![CliStructuralPredicate {
                field: "topic".to_owned(),
                target: EntryId::new("concept").unwrap(),
            }]
        );
        assert_eq!(fields.fields, vec![CliQueryField::Id, CliQueryField::Path]);
        assert!(matches!(format, CliQueryOutputFormat::Human));
    }

    #[test]
    fn query_accepts_comma_separated_fields() {
        let cli = Cli::parse_from(["sirno", "query", "--fields", "id,name,path,desc"]);
        let Command::TopLevelEntry(EntryCommand::Query { fields: Some(fields), .. }) = cli.command
        else {
            panic!("expected query command with fields");
        };

        assert_eq!(
            fields.fields,
            vec![CliQueryField::Id, CliQueryField::Name, CliQueryField::Path, CliQueryField::Desc,]
        );
    }

    #[test]
    fn query_accepts_json_format() {
        let cli = Cli::parse_from(["sirno", "query", "--format", "json"]);

        assert!(matches!(
            cli.command,
            Command::TopLevelEntry(EntryCommand::Query {
                format: Some(CliQueryOutputFormat::Json),
                ..
            })
        ));
    }

    #[test]
    fn query_accepts_human_format() {
        let cli = Cli::parse_from(["sirno", "query", "--format", "human"]);

        assert!(matches!(
            cli.command,
            Command::TopLevelEntry(EntryCommand::Query {
                format: Some(CliQueryOutputFormat::Human),
                ..
            })
        ));
    }

    #[test]
    fn query_rejects_old_human_flag() {
        let error = Cli::try_parse_from(["sirno", "query", "--human"]).unwrap_err();

        assert_eq!(error.kind(), clap::error::ErrorKind::UnknownArgument);
    }

    #[test]
    fn query_rejects_old_format_field_list() {
        let error = Cli::try_parse_from(["sirno", "query", "--format", "id,desc"]).unwrap_err();

        assert_eq!(error.kind(), clap::error::ErrorKind::InvalidValue);
    }

    #[test]
    fn query_rejects_unknown_field() {
        let error = Cli::try_parse_from(["sirno", "query", "--fields", "id,summary"]).unwrap_err();

        assert_eq!(error.kind(), clap::error::ErrorKind::ValueValidation);
    }

    #[test]
    fn query_rejects_empty_field() {
        let error = Cli::try_parse_from(["sirno", "query", "--fields", "id,,desc"]).unwrap_err();

        assert_eq!(error.kind(), clap::error::ErrorKind::ValueValidation);
    }

    #[test]
    fn query_json_uses_selected_field_names() {
        let fields = "id,desc".parse::<CliQueryFields>().unwrap();
        let json = format_query_json(&fields, &[vec!["query".to_owned(), "Selection".to_owned()]])
            .unwrap();
        let parsed = serde_json::from_str::<serde_json::Value>(&json).unwrap();

        assert_eq!(
            json,
            "\
[
  {
    \"id\": \"query\",
    \"desc\": \"Selection\"
  }
]"
        );
        assert_eq!(parsed, serde_json::json!([{ "id": "query", "desc": "Selection" }]));
    }

    #[test]
    fn query_table_uses_selected_field_headers_and_widths() {
        let fields = "id,desc".parse::<CliQueryFields>().unwrap();
        let table =
            format_query_table(&fields, &[vec!["query".to_owned(), "Selection".to_owned()]]);

        assert_eq!(
            table,
            "\
| id    | desc      |
| ----- | --------- |
| query | Selection |
"
        );
    }

    #[test]
    fn query_rejects_old_exact_structural_flags() {
        let error =
            Cli::try_parse_from(["sirno", "query", "--exact-topic", "concept"]).unwrap_err();

        assert_eq!(error.kind(), clap::error::ErrorKind::UnknownArgument);
    }

    #[test]
    fn check_accepts_short_mode() {
        let cli = Cli::parse_from(["sirno", "check", "-m", "review"]);

        assert!(matches!(
            cli.command,
            Command::TopLevelLake(LakeCommand::Check { mode: Some(CliCheckMode::Review), .. })
        ));
    }

    #[test]
    fn rg_accepts_forwarded_arguments() {
        let cli = Cli::parse_from(["sirno", "rg", "--json", "metadata"]);

        assert!(matches!(
            cli.command,
            Command::TopLevelEntry(EntryCommand::Rg { with_generated_footer: false, args })
                if args == vec![OsString::from("--json"), OsString::from("metadata")]
        ));
    }

    #[test]
    fn rg_accepts_generated_footer_inclusion_flag() {
        let cli = Cli::parse_from(["sirno", "rg", "--with-generated-footer", "metadata"]);

        assert!(matches!(
            cli.command,
            Command::TopLevelEntry(EntryCommand::Rg { with_generated_footer: true, args })
                if args == vec![OsString::from("metadata")]
        ));
    }

    #[test]
    fn rg_detects_forwarded_preprocessor_arguments() {
        assert!(rg_args_include_preprocessor(&[OsString::from("--pre"), OsString::from("cat")]));
        assert!(rg_args_include_preprocessor(&[OsString::from("--pre=cat")]));
        assert!(!rg_args_include_preprocessor(&[
            OsString::from("--pre-glob"),
            OsString::from("*.md")
        ]));
    }

    #[test]
    fn rg_requires_forwarded_arguments() {
        let error = Cli::try_parse_from(["sirno", "rg"]).unwrap_err();

        assert_eq!(error.kind(), clap::error::ErrorKind::MissingRequiredArgument);
    }

    #[test]
    fn exact_query_rejects_unconfigured_structural_field() {
        let error = exact_query_from_predicates(
            EntryQuery::new(),
            vec!["topic=concept".parse::<CliStructuralPredicate>().unwrap()],
            &StructuralSettings::default(),
        )
        .unwrap_err();

        assert!(matches!(error, CliError::UnconfiguredStructuralField(field) if field == "topic"));
    }

    #[test]
    fn exact_query_keeps_repeated_field_targets_disjunctive() {
        let mut metadata = EntryMetadata::new("Concept", "A named idea.").unwrap();
        metadata.push_structural_target("topic", EntryId::new("meta").unwrap());
        let entry = Entry::new(EntryId::new("concept").unwrap(), metadata, "");
        let settings =
            StructuralSettings::from_fields([("topic", StructuralFieldSettings::default())]);
        let query = exact_query_from_predicates(
            EntryQuery::new(),
            vec![
                "topic=concept".parse::<CliStructuralPredicate>().unwrap(),
                "topic=meta".parse::<CliStructuralPredicate>().unwrap(),
            ],
            &settings,
        )
        .unwrap();

        assert!(query.matches(&entry));
    }

    #[test]
    fn subcommands_reject_entries_flag() {
        let error = Cli::try_parse_from(["sirno", "freeze", "alpha", "--entries", "scratch-docs"])
            .unwrap_err();

        assert_eq!(error.kind(), clap::error::ErrorKind::UnknownArgument);
    }

    #[test]
    fn melt_accepts_entry_id_and_unfreeze_alias() {
        let melt = Cli::parse_from(["sirno", "melt", "alpha"]);
        let unfreeze = Cli::parse_from(["sirno", "unfreeze", "alpha"]);

        assert!(matches!(
            melt.command,
            Command::TopLevelEntry(EntryCommand::Melt { id, .. }) if id == "alpha"
        ));
        assert!(matches!(
            unfreeze.command,
            Command::TopLevelEntry(EntryCommand::Melt { id, .. }) if id == "alpha"
        ));
    }

    #[test]
    fn move_moves_lake_and_rewrites_config() {
        let temp = tempfile::tempdir().unwrap();
        let config_path = temp.path().join(CONFIG_FILE_NAME);
        let old_lake = temp.path().join("docs");
        let new_lake = temp.path().join("sirno-docs");
        let config = SirnoConfig {
            structural: StructuralSettings::from_fields([
                ("zeta", StructuralFieldSettings::default()),
                ("area", StructuralFieldSettings::default()),
            ]),
            ..SirnoConfig::new("docs")
        };
        config.write_new(&config_path).unwrap();
        fs::create_dir(&old_lake).unwrap();
        fs::write(old_lake.join("entry.md"), "entry").unwrap();

        Cli::parse_from(["sirno", "--config", config_path.to_str().unwrap(), "move", "sirno-docs"])
            .run()
            .unwrap();

        let config = SirnoConfig::from_file(&config_path).unwrap();
        let source = fs::read_to_string(&config_path).unwrap();
        assert_eq!(config.lake.path, PathBuf::from("sirno-docs"));
        assert_before(&source, "zeta = ", "area = ");
        assert!(!old_lake.exists());
        assert!(new_lake.join("entry.md").exists());
    }

    #[test]
    fn move_refuses_existing_destination() {
        let temp = tempfile::tempdir().unwrap();
        let config_path = temp.path().join(CONFIG_FILE_NAME);
        let old_lake = temp.path().join("docs");
        let new_lake = temp.path().join("sirno-docs");
        SirnoConfig::new("docs").write_new(&config_path).unwrap();
        fs::create_dir(&old_lake).unwrap();
        fs::create_dir(&new_lake).unwrap();

        let error = Cli::parse_from([
            "sirno",
            "--config",
            config_path.to_str().unwrap(),
            "move",
            "sirno-docs",
        ])
        .run()
        .unwrap_err();

        assert!(matches!(error, CliError::MoveDestinationExists(_)));
        let config = SirnoConfig::from_file(&config_path).unwrap();
        assert_eq!(config.lake.path, PathBuf::from("docs"));
        assert!(old_lake.exists());
    }

    #[test]
    fn frost_move_moves_frost_and_rewrites_config() {
        let temp = tempfile::tempdir().unwrap();
        let config_path = temp.path().join(CONFIG_FILE_NAME);
        let old_frost = temp.path().join("sirno-frost");
        let new_frost = temp.path().join("frost");
        let config = SirnoConfig {
            structural: StructuralSettings::from_fields([
                ("zeta", StructuralFieldSettings::default()),
                ("area", StructuralFieldSettings::default()),
            ]),
            ..SirnoConfig::new("docs").with_frost("sirno-frost")
        };
        config.write_new(&config_path).unwrap();
        fs::create_dir(&old_frost).unwrap();
        fs::write(old_frost.join("row"), "frost").unwrap();

        Cli::parse_from([
            "sirno",
            "--config",
            config_path.to_str().unwrap(),
            "frost",
            "move",
            "frost",
        ])
        .run()
        .unwrap();

        let config = SirnoConfig::from_file(&config_path).unwrap();
        let source = fs::read_to_string(&config_path).unwrap();
        assert_eq!(config.frost, Some(FrostSettings { path: PathBuf::from("frost") }));
        assert_before(&source, "zeta = ", "area = ");
        assert!(!old_frost.exists());
        assert!(new_frost.join("row").exists());
    }

    #[test]
    fn freeze_and_melt_commands_toggle_marker_and_permissions() {
        let temp = tempfile::tempdir().unwrap();
        let config_path = temp.path().join(CONFIG_FILE_NAME);
        let docs = temp.path().join("docs");
        SirnoConfig::new("docs").write_new(&config_path).unwrap();
        fs::create_dir(&docs).unwrap();
        fs::write(
            docs.join("alpha.md"),
            "\
---
name: Alpha
desc: Alpha entry.
---

Body.
",
        )
        .unwrap();

        Cli::parse_from(["sirno", "--config", config_path.to_str().unwrap(), "freeze", "alpha"])
            .run()
            .unwrap();
        let source = fs::read_to_string(docs.join("alpha.md")).unwrap();
        assert!(source.contains("frozen:\n"));
        assert!(fs::metadata(docs.join("alpha.md")).unwrap().permissions().readonly());

        Cli::parse_from(["sirno", "--config", config_path.to_str().unwrap(), "melt", "alpha"])
            .run()
            .unwrap();
        let source = fs::read_to_string(docs.join("alpha.md")).unwrap();
        assert!(!source.contains("frozen:\n"));
        assert!(!fs::metadata(docs.join("alpha.md")).unwrap().permissions().readonly());
    }

    #[test]
    fn rename_command_updates_lake_and_witness_references() {
        let temp = tempfile::tempdir().unwrap();
        let config_path = temp.path().join(CONFIG_FILE_NAME);
        let docs = temp.path().join("docs");
        let src = temp.path().join("src");
        SirnoConfig {
            repo: Some(RepoSettings { members: vec![RepoMember::new("src").unwrap()] }),
            structural: StructuralSettings::from_fields([(
                "area",
                StructuralFieldSettings::default(),
            )]),
            ..SirnoConfig::new("docs")
        }
        .write_new(&config_path)
        .unwrap();
        fs::create_dir(&docs).unwrap();
        fs::create_dir(&src).unwrap();
        fs::write(
            docs.join("old-entry.md"),
            "\
---
name: Old
desc: Old entry.
---

Body.
",
        )
        .unwrap();
        fs::write(
            docs.join("reader.md"),
            "\
---
name: Reader
desc: Reader entry.
area:
  - old-entry
---

Body.
",
        )
        .unwrap();
        let witness_source = format!(
            "\
// sirno{}old-entry:begin
fn sample() {{}}
// sirno{}old-entry:end
",
            ":witness:", ":witness:"
        );
        fs::write(src.join("lib.rs"), witness_source).unwrap();

        Cli::parse_from([
            "sirno",
            "--config",
            config_path.to_str().unwrap(),
            "entry",
            "rename",
            "old-entry",
            "new-entry",
        ])
        .run()
        .unwrap();

        let reader_source = fs::read_to_string(docs.join("reader.md")).unwrap();
        let witness_source = fs::read_to_string(src.join("lib.rs")).unwrap();
        assert!(!docs.join("old-entry.md").exists());
        assert!(docs.join("new-entry.md").exists());
        assert!(reader_source.contains("area:\n  - new-entry\n"));
        assert!(witness_source.contains("sirno:witness:new-entry:begin"));
        assert!(witness_source.contains("sirno:witness:new-entry:end"));
    }

    #[test]
    fn lake_path_override_targets_public_lake_commands() {
        let temp = tempfile::tempdir().unwrap();
        let config_path = temp.path().join(CONFIG_FILE_NAME);
        let configured_docs = temp.path().join("docs");
        let override_docs = temp.path().join("scratch-docs");
        SirnoConfig::new("docs").write_new(&config_path).unwrap();
        fs::create_dir(&configured_docs).unwrap();
        fs::create_dir(&override_docs).unwrap();
        let entry = "\
---
name: Alpha
desc: Alpha entry.
---

Body.
";
        fs::write(configured_docs.join("alpha.md"), entry).unwrap();
        fs::write(override_docs.join("alpha.md"), entry).unwrap();

        Cli::parse_from([
            "sirno",
            "--config",
            config_path.to_str().unwrap(),
            "freeze",
            "alpha",
            "--lake-path",
            override_docs.to_str().unwrap(),
        ])
        .run()
        .unwrap();

        assert!(!fs::read_to_string(configured_docs.join("alpha.md")).unwrap().contains("frozen:"));
        assert!(fs::read_to_string(override_docs.join("alpha.md")).unwrap().contains("frozen:"));
    }

    #[test]
    fn new_rejects_witness_flag() {
        let error = Cli::try_parse_from(["sirno", "new", "alpha", "--desc", "Alpha.", "--witness"])
            .unwrap_err();

        assert_eq!(error.kind(), clap::error::ErrorKind::UnknownArgument);
    }

    #[test]
    fn new_rejects_old_description_flag() {
        let error =
            Cli::try_parse_from(["sirno", "new", "alpha", "--description", "Alpha."]).unwrap_err();

        assert_eq!(error.kind(), clap::error::ErrorKind::UnknownArgument);
    }

    #[test]
    fn witness_accepts_entry_id() {
        let cli = Cli::parse_from(["sirno", "witness", "witness"]);

        assert!(matches!(
            cli.command,
            Command::TopLevelEntry(EntryCommand::Witness { id, full: false }) if id == "witness"
        ));
    }

    #[test]
    fn status_accepts_short_alias() {
        let cli = Cli::parse_from(["sirno", "st"]);

        assert!(matches!(cli.command, Command::TopLevelLake(LakeCommand::Status)));
    }

    #[test]
    fn witness_accepts_short_aliases() {
        let short = Cli::parse_from(["sirno", "w", "alpha"]);
        let mnemonic = Cli::parse_from(["sirno", "wit", "beta"]);

        assert!(matches!(
            short.command,
            Command::TopLevelEntry(EntryCommand::Witness { id, full: false }) if id == "alpha"
        ));
        assert!(matches!(
            mnemonic.command,
            Command::TopLevelEntry(EntryCommand::Witness { id, full: false }) if id == "beta"
        ));
    }

    #[test]
    fn lake_subcommand_accepts_status_alias() {
        let status = Cli::parse_from(["sirno", "lake", "st"]);

        assert!(matches!(status.command, Command::Lake { command: LakeCommand::Status }));
    }

    #[test]
    fn lake_subcommand_rejects_entry_aliases() {
        let error = Cli::try_parse_from(["sirno", "lake", "q"]).unwrap_err();

        assert_eq!(error.kind(), clap::error::ErrorKind::InvalidSubcommand);
    }

    #[test]
    fn entry_subcommand_accepts_common_aliases() {
        let short_query = Cli::parse_from(["sirno", "entry", "q", "alpha"]);
        let short_witness = Cli::parse_from(["sirno", "entry", "w", "alpha"]);
        let mnemonic_witness = Cli::parse_from(["sirno", "entry", "wit", "beta"]);

        assert!(matches!(
            short_query.command,
            Command::Entry { command: GroupedEntryCommand::Query { terms, .. } }
                if terms == vec!["alpha"]
        ));
        assert!(matches!(
            short_witness.command,
            Command::Entry { command: GroupedEntryCommand::Witness { id, full: false } }
                if id == "alpha"
        ));
        assert!(matches!(
            mnemonic_witness.command,
            Command::Entry { command: GroupedEntryCommand::Witness { id, full: false } }
                if id == "beta"
        ));
    }

    #[test]
    fn witness_accepts_full_flag() {
        let cli = Cli::parse_from(["sirno", "witness", "witness", "--full"]);

        assert!(matches!(
            cli.command,
            Command::TopLevelEntry(EntryCommand::Witness { id, full: true }) if id == "witness"
        ));
    }

    #[test]
    fn witness_accepts_short_full_flag() {
        let cli = Cli::parse_from(["sirno", "witness", "witness", "-f"]);

        assert!(matches!(
            cli.command,
            Command::TopLevelEntry(EntryCommand::Witness { id, full: true }) if id == "witness"
        ));
    }

    #[test]
    fn witness_rejects_missing_entry_before_repo_scan() {
        let temp = tempfile::tempdir().unwrap();
        let config_path = temp.path().join(CONFIG_FILE_NAME);
        fs::create_dir(temp.path().join("docs")).unwrap();
        SirnoConfig {
            repo: Some(RepoSettings { members: vec![RepoMember::new("missing-src").unwrap()] }),
            ..SirnoConfig::new("docs")
        }
        .write_new(&config_path)
        .unwrap();

        let error = Cli::parse_from([
            "sirno",
            "--config",
            config_path.to_str().unwrap(),
            "witness",
            "missing-entry",
        ])
        .run()
        .unwrap_err();

        assert!(
            matches!(error, CliError::MissingWitnessEntry(id) if id.as_str() == "missing-entry")
        );
    }

    // sirno:witness:witness-fixture-isolation:begin
    #[test]
    fn format_witness_record_prints_range_and_preserves_body() {
        let record = WitnessRecord {
            entry: EntryId::new("entry").unwrap(),
            path: PathBuf::from("src/lib.rs"),
            region: witness_span(10, 5, 14, 25),
            opening: witness_span(10, 5, 10, 33),
            closing: witness_span(14, 5, 14, 25),
            marker: "    // sample:start entry".to_owned(),
            body: concat!(
                "    // sample:start entry\n",
                "        fn main() {}\n",
                "    // sample:end"
            )
            .to_owned(),
        };

        assert_eq!(
            format_witness_record(&record, false),
            "src/lib.rs:10:5-33 :: 14:5-25\t    // sample:start entry\n"
        );
        assert_eq!(
            format_witness_record(&record, true),
            concat!(
                "src/lib.rs:10:5-33 :: 14:5-25\n",
                "\n",
                "    // sample:start entry\n",
                "        fn main() {}\n",
                "    // sample:end\n",
                "\n",
            )
        );
    }

    #[test]
    fn format_witness_records_adds_full_region_spacing() {
        let first = WitnessRecord {
            entry: EntryId::new("entry").unwrap(),
            path: PathBuf::from("src/lib.rs"),
            region: witness_span(10, 5, 14, 25),
            opening: witness_span(10, 5, 10, 33),
            closing: witness_span(14, 5, 14, 25),
            marker: "    // sample:start entry".to_owned(),
            body: concat!(
                "    // sample:start entry\n",
                "        fn main() {}\n",
                "    // sample:end"
            )
            .to_owned(),
        };
        let mut second = first.clone();
        second.region = witness_span(20, 5, 24, 25);
        second.opening = witness_span(20, 5, 20, 33);
        second.closing = witness_span(24, 5, 24, 25);

        assert!(format_witness_records(&[first, second], true).contains(concat!(
            "    // sample:end\n",
            "\n",
            "---\n",
            "\n",
            "src/lib.rs:20:5-33 :: 24:5-25\n",
        )));
    }
    // sirno:witness:witness-fixture-isolation:end

    fn witness_span(
        start_line: usize, start_column: usize, end_line: usize, end_column: usize,
    ) -> WitnessSpan {
        WitnessSpan { start_line, start_column, end_line, end_column }
    }

    #[test]
    fn gen_link_rejects_no_check_flag() {
        let error = Cli::try_parse_from(["sirno", "gen-link", "--no-check"]).unwrap_err();

        assert!(error.to_string().contains("unexpected argument"));
    }

    #[test]
    fn gen_link_accepts_dry_flag() {
        let cli = Cli::parse_from(["sirno", "gen-link", "--dry"]);

        assert!(matches!(
            cli.command,
            Command::TopLevelLake(LakeCommand::GenLink { dry: true, command: None, .. })
        ));
    }

    #[test]
    fn gen_link_accepts_dry_run_aliases() {
        let short = Cli::parse_from(["sirno", "gen-link", "-n"]);
        let long = Cli::parse_from(["sirno", "gen-link", "--dry-run"]);

        assert!(matches!(
            short.command,
            Command::TopLevelLake(LakeCommand::GenLink { dry: true, command: None, .. })
        ));
        assert!(matches!(
            long.command,
            Command::TopLevelLake(LakeCommand::GenLink { dry: true, command: None, .. })
        ));
    }

    #[test]
    fn format_gen_link_report_lists_changed_paths() {
        let report = format_gen_link_report(
            Path::new("sirno-docs"),
            31,
            &[PathBuf::from("sirno-docs/concept.md"), PathBuf::from("sirno-docs/entry.md")],
        );

        assert_eq!(
            report,
            "Changes in sirno-docs:\n- sirno-docs/concept.md\n- sirno-docs/entry.md\nTotal changes: 2/31"
        );
    }

    #[test]
    fn format_gen_link_report_summarizes_no_changes() {
        let report = format_gen_link_report(Path::new("sirno-docs"), 31, &[]);

        assert_eq!(report, "No changes in sirno-docs");
    }
}