enprot 0.4.1

Engyon Protected Text (EPT) — confidentiality processor and capability ledger
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
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
// Copyright (c) 2018-2026 [Ribose Inc](https://www.ribose.com).
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

//! CLI dispatch layer — gated behind the `cli` feature. Contains
//! all clap-dependent types (CommonArgs, Command, *Subcmd structs)
//! and the `app_main` entry point. Library-only consumers build
//! with `--no-default-features` and get the crypto / parsing /
//! capability / ledger modules without pulling in clap.

use std::collections::HashMap;
use std::ffi::OsString;
use std::fs;
use std::fs::File;
use std::io::{BufRead, BufReader, BufWriter, Write};
use std::path::{Path, PathBuf};

use clap::builder::PossibleValuesParser;
use clap::{Args, CommandFactory, Parser, Subcommand};

use crate::etree::ParseOps;
use crate::{
    Error, Result, capability, cappolicy, cas, cipher, config, consts, crypto, etree, ledger,
    merge, output, pbkdf, pki, prot, provenance, resolve, scm,
};

fn make_policy(name: &str) -> Box<dyn crypto::CryptoPolicy> {
    // Invariant: callers route `name` through clap's `VALID_POLICIES`
    // value_parser, so only "default" or "nist" reach here. Returning
    // an `Err` would be incorrect — this function is infallible by
    // contract; an unknown name indicates a programming error in the
    // caller, not user input.
    match name {
        "default" => Box::new(crypto::CryptoPolicyDefault {}),
        "nist" => Box::new(crypto::CryptoPolicyNIST {}),
        other => panic!(
            "make_policy: unknown policy '{}' (callers must validate via VALID_POLICIES)",
            other
        ),
    }
}

/// Top-level CLI. Every invocation picks one subcommand.
#[derive(Parser)]
#[command(
    name = "enprot",
    version,
    about = "Engyon Protected Text (EPT) confidentiality processor"
)]
pub struct Cli {
    /// Common arguments accepted in any position (before or after the
    /// subcommand name). Each field has `global = true` so clap recognises
    /// it at top-level or inside any subcommand.
    #[command(flatten)]
    pub common: CommonArgs,

    #[command(subcommand)]
    pub command: Command,
}

#[derive(Subcommand)]
pub enum Command {
    /// Encrypt WORD segments in the input file(s).
    Encrypt(EncryptSubcmd),
    /// Decrypt WORD segments in the input file(s).
    Decrypt(OperationSubcmd),
    /// Store (unencrypted) WORD segments to CAS.
    Store(OperationSubcmd),
    /// Fetch (unencrypted) WORD segments from CAS.
    Fetch(OperationSubcmd),
    /// Encrypt and store WORD segments (shorthand for `encrypt` plus store mode).
    EncryptStore(EncryptSubcmd),
    /// Parse and re-write each input without applying any transform.
    /// Useful for validating markup or measuring parse performance.
    Passthrough(OperationSubcmd),
    /// Verify file integrity: check markup structure, CAS pointers,
    /// and extfield format without decrypting.
    Verify(OperationSubcmd),
    /// List all WORD segments in the input file(s).
    List(OperationSubcmd),
    /// Print shell completion script to stdout.
    ///
    /// Install with: enprot completions bash > /etc/bash_completion.d/enprot
    Completions {
        /// Target shell.
        #[arg(value_enum)]
        shell: clap_complete::Shell,
    },
    /// Generate a keypair (e.g. Ed25519) and write the PEM-encoded
    /// halves to `--out-priv` / `--out-pub`.
    Keygen(KeygenSubcmd),
    /// Sign FILE (or stdin) with `--key` and write a detached signature
    /// to `--out` (default: `<FILE>.sig`).
    Sign(SignSubcmd),
    /// Verify a detached signature (`SIG`, default `<FILE>.sig`)
    /// against FILE using `--key`. Named `verify-sig` to avoid clashing
    /// with the existing `verify` subcommand, which checks EPT markup.
    VerifySig(VerifySigSubcmd),
    /// Compute and print the SHA3-256 fingerprint of a PEM-encoded
    /// pubkey. Useful for building `trust_roots` lists in policy
    /// files (TODO.finalize/26) and for visually comparing two keys
    /// for equality.
    Fingerprint(FingerprintSubcmd),
    /// Walk the chain anchor DAG in FILE(s): check that every CHAIN
    /// block's signature validates against the named signer's pubkey,
    /// that parent references resolve to earlier anchors, and that
    /// There are no cycles. Exit non-zero on any failure (CI-friendly).
    VerifyChain(VerifyChainSubcmd),
    /// Append-only signed audit log. Each line on stdin becomes a
    /// signed chain anchor in FILE — `tail -f` for cryptographic
    /// logs. Verify later with `enprot verify-chain --trust-root`.
    AuditLog(AuditLogSubcmd),
    /// Print the current chain head hash of FILE. The head is the
    /// AnchorHash of the last CHAIN block (or a full-file SHA3-256
    /// if the file has no anchors). Publish the hash out-of-band;
    /// later verify with `enprot pin`.
    Snapshot(SnapshotSubcmd),
    /// Verify that FILE's chain head hash matches EXPECTED-HASH.
    /// Exit non-zero on mismatch. Use after `enprot snapshot` to
    /// detect retroactive modification against a published pin.
    Pin(PinSubcmd),
    /// Print the capability set implied by the current flags (passwords,
    /// CAS dir, key files) and exit. No file transformation occurs.
    /// Useful for verifying "what would I be able to do?" before running
    /// a real command. Output is one capability per line.
    Capabilities,
    /// Write a commented TOML template to `.enprot.toml` (or, with
    /// `--global`, to `~/.config/enprot/config.toml`). Refuses to
    /// overwrite an existing file. See TODO.roadmap/40.
    Init(InitSubcmd),
    /// Git merge-driver contract: `enprot merge-driver %O %A %B %P`
    /// (TODO.roadmap/43). Performs a three-way WORD-aware merge and
    /// writes the result back into `%A` (the "ours" path). Emits
    /// CONFLICT markers when both sides modified the same WORD region
    /// differently.
    MergeDriver(MergeDriverSubcmd),
    /// Walk CONFLICT blocks in FILE and replace each one with the
    /// chosen resolution (TODO.roadmap/44). The default mode is
    /// `--interactive`; pass `--ours`/`--theirs`/`--both`/`--skip`
    /// for non-interactive runs (e.g., CI).
    Resolve(ResolveSubcmd),
    /// Walk CONFLICT blocks in FILE and print one summary line per
    /// conflict (TODO.roadmap/49). Exit non-zero if any conflicts
    /// remain — CI-friendly as a gate after a merge-driver step.
    Conflicts(ConflictsSubcmd),
    /// Combined diagnostic: show structure + integrity + capabilities
    /// in one pass (TODO.finalize/42). Useful for debugging
    /// "what is this file and what can I do with it?".
    Inspect(InspectSubcmd),
    /// Git `clean` filter (TODO.roadmap/45): read plaintext from
    /// stdin, write ciphertext to stdout. Used by `.gitattributes`
    /// `filter=enprot`. Defaults to `aes-256-gcm-siv-det` so the
    /// ciphertext is deterministic and diffs are stable.
    Clean(SmudgeCleanSubcmd),
    /// Git `smudge` filter: read ciphertext from stdin, write
    /// plaintext to stdout. Inverse of `clean`. Requires the WORD
    /// password (from `-k` or `ENPROPT_KEY`).
    Smudge(SmudgeCleanSubcmd),
    /// Git `textconv` for readable diffs (alias for `smudge`).
    Textconv(SmudgeCleanSubcmd),
    /// Build a provenance manifest for a directory (TODO.roadmap/51):
    /// walk the tree, store each file in CAS, emit INCLUDE per file.
    /// Output is an EPT file ready for `enprot attest`.
    Manifest(ManifestSubcmd),
    /// Append a signed chain anchor to a provenance manifest
    /// (TODO.roadmap/51). The anchor commits to the manifest's full
    /// state — any later tampering invalidates the signature.
    Attest(AttestSubcmd),
    /// Supply-chain manifest operations (TODO.roadmap/52). Wraps
    /// provenance with dependency parsing, structural diff, and a
    /// customer-side verify entry point. Subcommand form:
    /// `enprot scm {init,add,deps,attest,verify,diff}`.
    Scm(ScmSubcmd),
}

/// `init` subcommand: scaffold a commented TOML config the user can
/// edit in place. With `--git`, also writes a `.gitattributes` file
/// that wires `enprot` into git's `clean` / `smudge` / `textconv`
/// filter chain.
#[derive(Args)]
pub struct InitSubcmd {
    /// Write to `~/.config/enprot/config.toml` instead of `./.enprot.toml`.
    #[arg(long)]
    pub global: bool,

    /// Overwrite an existing file. Off by default to prevent stomping
    /// hand-edited config.
    #[arg(long)]
    pub force: bool,

    /// Also write `.gitattributes` and print the `.git/config` snippet
    /// for the enprot filter (TODO.roadmap/45). The config snippet
    /// goes to stdout so the user can review before pasting — enprot
    /// doesn't write to `.git/config` directly to avoid stomping
    /// unrelated entries.
    #[arg(long)]
    pub git: bool,
}

/// `merge-driver` subcommand: invoked by git with four positional
/// arguments — the ancestor version, our version, their version,
/// and the path of the file in the working tree. Output goes back
/// into the "ours" path (the second argument). Exits non-zero on
/// parse errors; exits zero even when conflicts are emitted (the
/// presence of CONFLICT markers in the output is the merge's signal).
#[derive(Args)]
pub struct MergeDriverSubcmd {
    /// Common ancestor version (`%O` in git's contract).
    pub base: PathBuf,
    /// Our version (`%A`); the merge result is written here.
    pub ours: PathBuf,
    /// Their version (`%B`).
    pub theirs: PathBuf,
    /// Working-tree path (`%P`); informational.
    #[arg(value_name = "PATH")]
    pub path: Option<PathBuf>,
}

/// `resolve` subcommand: clear CONFLICT markers by replacing each one
/// with the chosen side. Modes: `--ours`, `--theirs`, `--both`,
/// `--skip`, or `--interactive` (default). Per-WORD overrides via
/// `--word WORD:MODE` (TODO.roadmap/56).
#[derive(Args)]
pub struct ResolveSubcmd {
    /// Resolution mode. One of: ours, theirs, both, skip, interactive.
    /// Default: interactive. Used for any CONFLICT not covered by an
    /// explicit `--word` override.
    #[arg(long, short = 'm', value_name = "MODE", default_value = "interactive")]
    pub mode: String,

    /// Per-WORD resolution override. Repeatable. Format: `WORD:MODE`
    /// where MODE is one of ours/theirs/both/skip. Takes precedence
    /// over `--mode` for the named WORD. Unknown WORDs are silently
    /// skipped (the file may have changed between listing conflicts
    /// and resolving them).
    #[arg(long = "word", value_name = "WORD:MODE", value_delimiter = ',')]
    pub word: Vec<String>,

    /// Input file. Resolved output is written back here in-place.
    #[arg(value_name = "FILE")]
    pub file: PathBuf,
}

/// `conflicts` subcommand (TODO.roadmap/49): walk CONFLICT blocks
/// in FILE and print one summary per conflict. Exits non-zero if
/// any conflicts remain.
#[derive(Args)]
pub struct ConflictsSubcmd {
    /// Output format: text (default) or json (enveloped versioned
    /// schema, same shape as `capabilities --format json`).
    #[arg(long, value_enum, default_value_t = output::OutputFormat::Text)]
    pub format: output::OutputFormat,

    /// Input file.
    #[arg(value_name = "FILE")]
    pub file: PathBuf,
}

/// `inspect` subcommand (TODO.finalize/42): combined diagnostic.
/// Shows file structure, chain anchor integrity, and the
/// capabilities the current call context has over the file.
/// Exits non-zero if the file fails integrity checks.
#[derive(Args)]
pub struct InspectSubcmd {
    /// Output format: text (default) or json.
    #[arg(long, value_enum, default_value_t = output::OutputFormat::Text)]
    pub format: output::OutputFormat,

    /// Input file (use stdin if omitted).
    #[arg(value_name = "FILE")]
    pub file: Option<PathBuf>,
}

/// Shared args for the git `clean` / `smudge` / `textconv` filters
/// (TODO.roadmap/45). All three operate as stdin → stdout pipes; the
/// WORD password comes from the global `-k WORD=password` flag or
/// `ENPROPT_KEY=WORD=password` env var.
#[derive(Args)]
pub struct SmudgeCleanSubcmd {
    /// WORD whose password unlocks the file. Required.
    #[arg(short = 'w', long = "word", value_name = "WORD")]
    pub word: String,

    /// Override the cipher algorithm (clean only). Default:
    /// `aes-256-gcm-siv-det` for diff-stable ciphertext.
    #[arg(long, value_name = "ALG")]
    pub cipher: Option<String>,

    /// Override the PBKDF algorithm (clean only). For diff-stable
    /// output across runs, pair `aes-256-gcm-siv-det` with `legacy`
    /// (no random salt). Default: argon2 with auto-tuned params.
    #[arg(long, value_name = "ALG")]
    pub pbkdf: Option<String>,
}

/// `manifest` subcommand (TODO.roadmap/51): build a provenance
/// manifest for a project tree. Walks the directory, stores each
/// file in CAS, emits an EPT file with one INCLUDE per source file.
#[derive(Args)]
pub struct ManifestSubcmd {
    /// Project root to walk.
    #[arg(value_name = "DIR")]
    pub dir: PathBuf,

    /// CAS directory (default: `./cas` if it exists, else `.`).
    #[arg(short = 'c', long, value_name = "DIR")]
    pub casdir: Option<PathBuf>,

    /// Output manifest path (default: stdout).
    #[arg(short = 'o', long, value_name = "FILE")]
    pub output: Option<PathBuf>,
}

/// `attest` subcommand (TODO.roadmap/51): append a signed chain
/// anchor to a manifest, signing the file's current state.
#[derive(Args)]
pub struct AttestSubcmd {
    /// Builder's private key (PEM).
    #[arg(long, value_name = "PRIV.pem")]
    pub signer: PathBuf,

    /// Manifest file. Modified in-place.
    #[arg(value_name = "FILE")]
    pub file: PathBuf,
}

/// `scm` subcommand (TODO.roadmap/52). The subcommand selects the
/// operation; common args (CAS dir, signer, etc.) are flat fields.
/// Re-uses `provenance::attest` and the existing `verify-chain` so
/// the wire format is identical to TODO.roadmap/51.
#[derive(Args)]
pub struct ScmSubcmd {
    #[command(subcommand)]
    pub command: ScmCommand,

    /// CAS directory. Default: `./cas` if it exists, else `.`.
    #[arg(short = 'c', long, global = true)]
    pub casdir: Option<PathBuf>,
}

#[derive(Subcommand)]
pub enum ScmCommand {
    /// Create an empty manifest at MANIFEST.
    Init {
        #[arg(value_name = "MANIFEST")]
        manifest: PathBuf,
    },
    /// Append PATH (file or directory) to MANIFEST.
    Add {
        #[arg(value_name = "MANIFEST")]
        manifest: PathBuf,
        #[arg(value_name = "PATH")]
        path: PathBuf,
    },
    /// Parse Cargo.toml at MANIFEST_FILE and append each `[dependencies]`
    /// entry as an INCLUDE. (npm + pyproject parsers are stubbed.)
    Deps {
        #[arg(value_name = "MANIFEST")]
        manifest: PathBuf,
        #[arg(value_name = "Cargo.toml")]
        cargo_toml: PathBuf,
    },
    /// Sign MANIFEST with --signer (delegates to provenance::attest).
    Attest {
        #[arg(long, value_name = "PRIV.pem")]
        signer: PathBuf,
        #[arg(value_name = "MANIFEST")]
        manifest: PathBuf,
    },
    /// Verify MANIFEST with --trust-root (delegates to verify-chain).
    Verify {
        #[arg(long, value_name = "PUB.pem")]
        trust_root: PathBuf,
        #[arg(value_name = "MANIFEST")]
        manifest: PathBuf,
    },
    /// Structural diff between OLD and NEW manifests.
    Diff {
        #[arg(value_name = "OLD")]
        old: PathBuf,
        #[arg(value_name = "NEW")]
        new: PathBuf,
    },
}

/// Encrypt subcommand: encrypt-specific options plus the shared output
/// wiring.
#[derive(Args)]
pub struct EncryptSubcmd {
    #[command(flatten)]
    pub encrypt: EncryptOpts,

    #[command(flatten)]
    pub output: OutputArgs,

    /// Recipient pubkey (PEM). Repeatable. When supplied, the
    /// transform uses ML-KEM encapsulation instead of PBKDF
    /// (TODO.roadmap/60). Any one matching privkey can decrypt.
    #[arg(long = "recipient", value_name = "PUB.pem")]
    pub recipients: Vec<PathBuf>,
}

/// Decrypt/Store/Fetch/Passthrough subcommand: just the shared output
/// wiring (no crypto knobs).
#[derive(Args)]
pub struct OperationSubcmd {
    #[command(flatten)]
    pub output: OutputArgs,

    /// Private key (PEM) for KEM-mode decryption (TODO.roadmap/60).
    /// When the Encrypted block has a `recipients:` extfield, this
    /// privkey is used for ML-KEM decapsulation. Ignored for
    /// password-mode blocks.
    #[arg(long = "key-file", value_name = "PRIV.pem")]
    pub key_files: Vec<PathBuf>,
}

/// `keygen` subcommand: emit a fresh keypair.
#[derive(Args)]
pub struct KeygenSubcmd {
    /// Signature algorithm.
    #[arg(value_parser = clap::builder::PossibleValuesParser::new(
        pki::SigAlgKind::ALL.iter().map(|k| k.name()).collect::<Vec<_>>()
    ))]
    pub alg: String,

    /// Write private key to PATH (PEM). Default: stdout.
    #[arg(long = "out-priv", value_name = "PATH")]
    pub out_priv: Option<PathBuf>,

    /// Write public key to PATH (PEM). Default: stdout.
    #[arg(long = "out-pub", value_name = "PATH")]
    pub out_pub: Option<PathBuf>,
}

/// `sign` subcommand: produce a detached signature. When
/// `--key-file` is supplied multiple times (TODO.roadmap/59),
/// produces a multi-signature bundle file; single `--key-file`
/// produces raw signature bytes (backwards compat).
#[derive(Args)]
pub struct SignSubcmd {
    /// Signature algorithm (must match the key type).
    #[arg(long, value_parser = clap::builder::PossibleValuesParser::new(
        pki::SigAlgKind::ALL.iter().map(|k| k.name()).collect::<Vec<_>>()
    ))]
    pub alg: String,

    /// Private key (PEM) to sign with. Repeatable for multi-sig
    /// bundles. Named `--key-file` because the global `-k/--key`
    /// already means a symmetric WORD=PASSWORD pair.
    #[arg(long = "key-file", value_name = "PRIV.pem")]
    pub key: Vec<PathBuf>,

    /// Input file (omit to read stdin).
    #[arg(value_name = "FILE")]
    pub input: Option<PathBuf>,

    /// Write signature to PATH. Default: `<FILE>.sig`, or stdout when
    /// reading from stdin.
    #[arg(short = 'o', long = "out", value_name = "PATH")]
    pub out: Option<PathBuf>,
}

/// `verify-sig` subcommand: verify a detached signature. When
/// `--key-file` is supplied multiple times (TODO.roadmap/59), the
/// signature file is treated as a multi-sig bundle and every entry
/// must verify against its corresponding pubkey.
#[derive(Args)]
pub struct VerifySigSubcmd {
    /// Signature algorithm (must match the key type).
    #[arg(long, value_parser = clap::builder::PossibleValuesParser::new(
        pki::SigAlgKind::ALL.iter().map(|k| k.name()).collect::<Vec<_>>()
    ))]
    pub alg: String,

    /// Public key (PEM) to verify against. Repeatable for multi-sig
    /// bundles.
    #[arg(long = "key-file", value_name = "PUB.pem")]
    pub key: Vec<PathBuf>,

    /// Signature file. Default: `<FILE>.sig`. Required when reading
    /// the message from stdin.
    #[arg(long = "sig-file", value_name = "SIG")]
    pub sig: Option<PathBuf>,

    /// Input file (omit to read stdin).
    #[arg(value_name = "FILE")]
    pub input: Option<PathBuf>,
}

/// `fingerprint` subcommand: print the SHA3-256 fingerprint of a
/// PEM-encoded pubkey. Used to populate `trust_roots` lists in
/// policy files (TODO.finalize/26) and to compare two keys for
/// equality without parsing the full PEM.
#[derive(Args)]
pub struct FingerprintSubcmd {
    /// Public key (PEM) to fingerprint.
    #[arg(value_name = "PUB.pem")]
    pub key: PathBuf,
}

/// `verify-chain` subcommand: walk a file's CHAIN anchors and verify
/// signatures + DAG structure. Repeatable `--trust-root` flags form
/// a whitelist; if non-empty, anchors signed by anything else fail.
#[derive(Args)]
pub struct VerifyChainSubcmd {
    /// Public key (PEM) whose fingerprint must match a CHAIN's
    /// `signer:` field. Repeatable; if non-empty, forms a trust
    /// whitelist. If empty, every anchor is checked against the
    /// pubkey whose fingerprint matches — and fails if no key
    /// matches.
    #[arg(long = "trust-root", value_name = "PUB.pem")]
    pub trust_roots: Vec<PathBuf>,

    /// Input file(s). Each is verified independently.
    #[arg(value_name = "FILE")]
    pub files: Vec<String>,
}

/// `audit-log` subcommand: stream lines from stdin into FILE as
/// signed chain anchors. Each line becomes one Plain node + one
/// CHAIN node appended to the file. Produces a linear, tamper-evident
/// log with O(1) verification per anchor.
#[derive(Args)]
pub struct AuditLogSubcmd {
    /// Private key (PEM) to sign each anchor. The pubkey is derived
    /// automatically; pass it to `verify-chain --trust-root` later.
    #[arg(long = "signer", value_name = "PRIV.pem")]
    pub signer: PathBuf,

    /// Log file. Appended to if it exists; created if not. Each
    /// invocation reads the existing content into memory, appends
    /// new anchors, and writes the result back atomically.
    #[arg(value_name = "FILE")]
    pub file: String,
}

/// `snapshot` subcommand: print the chain head hash.
#[derive(Args)]
pub struct SnapshotSubcmd {
    #[arg(value_name = "FILE")]
    pub file: String,
}

/// `pin` subcommand: verify the chain head hash matches EXPECTED.
#[derive(Args)]
pub struct PinSubcmd {
    /// Expected chain head hash (64 hex chars).
    #[arg(value_name = "EXPECTED-HASH")]
    pub expected: String,

    #[arg(value_name = "FILE")]
    pub file: String,
}

/// Crypto-policy, separators, RNG source, password store. Defined at
/// top-level with `global = true` on every field, so clap accepts these
/// flags before or after the subcommand name.
#[derive(Args, Clone)]
pub struct CommonArgs {
    /// Produce more verbose output.
    #[arg(short = 'v', long, global = true)]
    pub verbose: bool,

    /// Suppress unnecessary output.
    #[arg(short = 'q', long, global = true)]
    pub quiet: bool,

    /// Maximum recursion depth (0 = infinite).
    #[arg(long, global = true, default_value_t = consts::DEFAULT_MAX_DEPTH)]
    pub max_depth: usize,

    /// Specify left separator in parsing.
    #[arg(short = 'l', long, global = true, default_value = consts::DEFAULT_LEFT_SEP)]
    pub left_separator: String,

    /// Specify right separator in parsing.
    #[arg(short = 'r', long, global = true, default_value = consts::DEFAULT_RIGHT_SEP)]
    pub right_separator: String,

    /// Specify a secret PASSWORD for WORD (format: WORD=PASSWORD).
    ///
    /// One pair per occurrence; passwords containing commas are accepted
    /// verbatim. Use multiple `-k` flags for multiple pairs.
    #[arg(short = 'k', long = "key", global = true, value_name = "WORD=PASSWORD", value_parser = parse_word_password)]
    pub password: Vec<(String, String)>,

    /// Directory for CAS files (default "cas" if it exists, else ".").
    #[arg(short = 'c', long, global = true, value_name = "DIRECTORY", value_parser = parse_casdir)]
    pub casdir: Option<PathBuf>,

    /// Set the policy to restrict cryptographic algorithms.
    #[arg(long, global = true, value_parser = PossibleValuesParser::new(consts::VALID_POLICIES.to_vec()))]
    pub policy: Option<String>,

    /// Load settings from POLICY, but do not enforce the policy.
    #[arg(long, global = true, value_parser = PossibleValuesParser::new(consts::VALID_POLICIES.to_vec()))]
    pub defaults: Option<String>,

    /// Select and enforce the use of FIPS-compliant algorithms (implies --policy=nist).
    #[arg(long, global = true)]
    pub fips: bool,

    /// Preset left/right separators for the host language.
    /// Overrides the default (`// <(` … `)>`). Explicit `-l`/`-r` flags
    /// take precedence over `--lang`.
    #[arg(long, global = true, value_parser = PossibleValuesParser::new(consts::LANG_SEPARATORS.iter().map(|(n, _, _)| *n).collect::<Vec<_>>()))]
    pub lang: Option<String>,

    /// Disable the PBKDF cache mechanism. Affects both encrypt (key
    /// derivation) and decrypt (same derivation, repeated per file).
    #[arg(long = "pbkdf-disable-cache", global = true)]
    pub pbkdf_disable_cache: bool,

    /// After running the transform, append a CHAIN block to the
    /// output that signs the new file state. Requires `--signer`.
    /// The resulting anchor can be verified later with
    /// `enprot verify-chain --trust-root <pubkey>`.
    ///
    /// Mutually exclusive with `passthrough` (which by definition
    /// performs no transformation and thus has nothing to anchor).
    #[arg(long, global = true)]
    pub anchor: bool,

    /// Private key (PEM) used to sign chain anchors when `--anchor`
    /// is set. The corresponding pubkey is derived automatically;
    /// pass it to `verify-chain --trust-root` later.
    #[arg(long, global = true, value_name = "PRIV.pem")]
    pub signer: Option<PathBuf>,

    /// Output format for inspection subcommands (`capabilities`,
    /// `list`, `verify-chain`). `text` is the default; `json` emits a
    /// versioned envelope (`$schema: enprot/v1`) suitable for
    /// machine consumption.
    #[arg(long, global = true, value_enum, default_value_t = output::OutputFormat::Text)]
    pub format: output::OutputFormat,

    /// Emit inline `DATA` blocks on encrypt instead of the default
    /// CAS-referenced `STORED ct <hash>` (TODO.roadmap/42). Restores
    /// the pre-42 behavior; useful when CAS isn't available or for
    /// self-contained single-file output.
    #[arg(long, global = true)]
    pub inline: bool,

    /// Path to a capability policy TOML file (TODO.roadmap/46). When
    /// set, `verify-chain` checks trust roots and timestamp
    /// monotonicity, and `encrypt` refuses to write blocks for a WORD
    /// whose required capability the caller doesn't hold.
    #[arg(long, global = true, value_name = "PATH")]
    pub policy_file: Option<PathBuf>,
}

impl CommonArgs {
    /// Construct a CommonArgs with only the filter-context fields
    /// populated. Used by subcommands that don't take the full CLI
    /// surface (e.g., `scm verify`, which delegates to
    /// `verify_chain_files`). Producing this in one place keeps the
    /// filter-dispatch paths DRY: any new CommonArgs field added
    /// downstream doesn't need to be wired through every call site.
    pub fn for_filter(casdir: Option<PathBuf>) -> Self {
        CommonArgs {
            verbose: false,
            quiet: false,
            max_depth: consts::DEFAULT_MAX_DEPTH,
            left_separator: consts::DEFAULT_LEFT_SEP.to_string(),
            right_separator: consts::DEFAULT_RIGHT_SEP.to_string(),
            password: Vec::new(),
            casdir,
            policy: None,
            defaults: None,
            fips: false,
            lang: None,
            pbkdf_disable_cache: false,
            anchor: false,
            signer: None,
            format: output::OutputFormat::Text,
            inline: false,
            policy_file: None,
        }
    }
}

/// Encrypt-specific cryptographic knobs.
#[derive(Args, Default)]
pub struct EncryptOpts {
    /// Set the PBKDF algorithm to use when encrypting.
    #[arg(long, value_parser = PossibleValuesParser::new(consts::VALID_PBKDF_ALGS.to_vec()))]
    pub pbkdf: Option<String>,

    /// Set the millisecond count for the PBKDF algorithm.
    #[arg(long, value_name = "MSEC", value_parser = parse_positive_u32)]
    pub pbkdf_msec: Option<u32>,

    /// Set the salt length for the PBKDF.
    #[arg(long, value_name = "BYTES", value_parser = parse_positive_usize)]
    pub pbkdf_salt_len: Option<usize>,

    /// Advanced option for testing, do not use.
    #[arg(long, value_name = "PARAMS", hide = true)]
    pub pbkdf_params: Option<String>,

    /// Advanced option for testing, do not use.
    #[arg(long, value_name = "HEX", hide = true)]
    pub pbkdf_salt: Option<String>,

    /// Set the cipher algorithm to use when encrypting.
    #[arg(long, value_parser = PossibleValuesParser::new(consts::VALID_CIPHER_ALGS.to_vec()))]
    pub cipher: Option<String>,

    /// Advanced option for testing, do not use.
    #[arg(long, value_name = "ALG", hide = true)]
    pub cipher_iv: Option<String>,
}

/// Input/output wiring: which WORDs to operate on, which files to read,
/// where to write results.
#[derive(Args)]
pub struct OutputArgs {
    /// WORD segment to operate on. Repeatable; also accepts a
    /// comma-separated list (`-w Agent_007,GEHEIM`).
    #[arg(short = 'w', long = "word", value_name = "WORD", value_delimiter = ',')]
    pub word: Vec<String>,

    /// Specify output file for previous input.
    #[arg(short = 'o', long = "output", value_name = "FILE")]
    pub output: Vec<String>,

    /// Use PREFIX for output filenames. If PREFIX ends with `/` or is an
    /// existing directory, each output is placed inside it with its
    /// original basename (issue #18). Otherwise PREFIX is prepended to
    /// each input path verbatim (the legacy behavior).
    #[arg(
        short = 'p',
        long = "prefix",
        default_value = "",
        allow_hyphen_values = true
    )]
    pub prefix: String,

    /// Directory to write outputs into. Shorthand for `--prefix DIR/`.
    /// Conflicts with `--prefix`.
    #[arg(long, value_name = "DIR", value_parser = parse_output_dir, conflicts_with = "prefix")]
    pub output_dir: Option<PathBuf>,

    /// Input file(s). "-" means stdin; default "-" if omitted.
    #[arg(value_name = "FILE", default_value = "-")]
    pub files: Vec<String>,
}

/// Load multiple PEM files into a Vec<String>. Used for --recipient
/// (pubkey) and --key-file (privkey) flags. (TODO.roadmap/60.)
fn load_pems(paths: &[PathBuf]) -> Result<Vec<String>> {
    paths
        .iter()
        .map(|p| fs::read_to_string(p).map_err(Error::from))
        .collect()
}

fn load_privkey_pems(paths: &[PathBuf]) -> Result<Vec<String>> {
    load_pems(paths)
}

fn parse_word_password(s: &str) -> std::result::Result<(String, String), String> {
    let (word, pass) = s
        .split_once('=')
        .ok_or_else(|| format!("Must be of the form WORD=PASSWORD, got '{}'", s))?;
    if word.is_empty() || pass.is_empty() {
        return Err(format!("Must be of the form WORD=PASSWORD, got '{}'", s));
    }
    Ok((word.to_string(), pass.to_string()))
}

fn parse_casdir(s: &str) -> std::result::Result<PathBuf, String> {
    let p = PathBuf::from(s);
    if p.is_dir() {
        Ok(p)
    } else {
        Err(format!("'{}' is not a directory", s))
    }
}

/// Value parser for `--output-dir`. The directory must already exist —
/// enprot doesn't create output trees for the user (yet). Use `-p` for
/// the prepend-string behavior if you want a non-existent prefix.
fn parse_output_dir(s: &str) -> std::result::Result<PathBuf, String> {
    let p = PathBuf::from(s);
    if p.is_dir() {
        Ok(p)
    } else {
        Err(format!("--output-dir '{}' is not a directory", s))
    }
}

fn parse_positive_u32(s: &str) -> std::result::Result<u32, String> {
    let n: u32 = s
        .parse()
        .map_err(|_| format!("expected a number > 0, got '{}'", s))?;
    if n == 0 {
        return Err(format!("expected a number > 0, got '{}'", s));
    }
    Ok(n)
}

fn parse_positive_usize(s: &str) -> std::result::Result<usize, String> {
    let n: usize = s
        .parse()
        .map_err(|_| format!("expected a number > 0, got '{}'", s))?;
    if n == 0 {
        return Err(format!("expected a number > 0, got '{}'", s));
    }
    Ok(n)
}

pub fn app_main<I, T>(args: I) -> Result<()>
where
    I: IntoIterator<Item = T>,
    T: Into<OsString> + Clone,
{
    // <( ENCRYPTED AUTHOR )>
    // <( DATA X417HVMRRAs6Z1xGo5yY4TxUQ2tpAHEKQ1sg9+kfku5uUikK3y2tODtsUiGqfRGW )>
    // <( DATA xUCGYFu02BCdqPM7uuX5UNvbfrLvKkj6gLYwg/cr42PJmr4o5xnw1qo= )>
    // <( END AUTHOR )>

    let cli = Cli::parse_from(args);
    // `init` is the one subcommand that does NOT load config — it
    // writes a fresh template, so applying existing config would be
    // noise. Dispatch it before the layered-load step below.
    if let Command::Init(a) = cli.command {
        return init_config(a);
    }
    // `merge-driver` is invoked by git with a fixed argv shape and
    // doesn't take enprot flags. Dispatch it directly.
    if let Command::MergeDriver(a) = cli.command {
        return run_merge_driver(a);
    }
    // `resolve` needs to read the file but doesn't load config —
    // dispatch directly so a malformed config doesn't block cleanup.
    if let Command::Resolve(a) = cli.command {
        return run_resolve(a);
    }
    if let Command::Conflicts(a) = cli.command {
        return run_conflicts(a);
    }
    if let Command::Inspect(a) = cli.command {
        return run_inspect(a, cli.common.clone());
    }
    // `clean` / `smudge` / `textconv` are stdin→stdout pipes
    // invoked by git filter machinery; they don't take the full
    // CommonArgs shape and bypass config layering.
    if let Command::Clean(a) = cli.command {
        return run_smudge_clean(SmudgeMode::Clean, a, cli.common);
    }
    if let Command::Smudge(a) = cli.command {
        return run_smudge_clean(SmudgeMode::Smudge, a, cli.common);
    }
    if let Command::Textconv(a) = cli.command {
        return run_smudge_clean(SmudgeMode::Smudge, a, cli.common);
    }
    if let Command::Manifest(a) = cli.command {
        return run_manifest(a);
    }
    if let Command::Attest(a) = cli.command {
        return run_attest(a);
    }
    if let Command::Scm(a) = cli.command {
        return run_scm(a);
    }
    let mut common = cli.common;
    common = apply_config(common)?;
    match cli.command {
        Command::Encrypt(a) => run(
            common,
            a.output,
            Some((a.encrypt, Operation::Encrypt)),
            load_pems(&a.recipients)?,
            Vec::new(),
        ),
        Command::Decrypt(a) => run(
            common,
            a.output,
            Some((EncryptOpts::default(), Operation::Decrypt)),
            Vec::new(),
            load_privkey_pems(&a.key_files)?,
        ),
        Command::Store(a) => run(
            common,
            a.output,
            Some((EncryptOpts::default(), Operation::Store)),
            Vec::new(),
            Vec::new(),
        ),
        Command::Fetch(a) => run(
            common,
            a.output,
            Some((EncryptOpts::default(), Operation::Fetch)),
            Vec::new(),
            Vec::new(),
        ),
        Command::EncryptStore(a) => run(
            common,
            a.output,
            Some((a.encrypt, Operation::EncryptStore)),
            load_pems(&a.recipients)?,
            Vec::new(),
        ),
        Command::Passthrough(a) => run(common, a.output, None, Vec::new(), Vec::new()),
        Command::Verify(a) => verify_files(common, a.output),
        Command::List(a) => list_files(common, a.output),
        Command::Completions { shell } => {
            clap_complete::generate(shell, &mut Cli::command(), "enprot", &mut std::io::stdout());
            Ok(())
        }
        Command::Keygen(a) => pki_keygen(common, a),
        Command::Sign(a) => pki_sign(common, a),
        Command::VerifySig(a) => pki_verify_sig(common, a),
        Command::Fingerprint(a) => pki_fingerprint(a),
        Command::VerifyChain(a) => verify_chain_files(common, a),
        Command::AuditLog(a) => audit_log_stream(common, a),
        Command::Snapshot(a) => snapshot_file(a),
        Command::Pin(a) => pin_file(a),
        Command::Capabilities => {
            let policy = resolve_policy(&common)?;
            let mut paops = ParseOps::new(policy)?;
            apply_common(&common, &mut paops);
            let caps = capability::CapabilitySet::from_paops(&paops);
            let stdout = std::io::stdout();
            let mut out = stdout.lock();
            match common.format {
                output::OutputFormat::Text => {
                    for c in caps.iter_sorted() {
                        writeln!(out, "{}", c)?;
                    }
                }
                output::OutputFormat::Json => {
                    let dtos = caps
                        .iter_sorted()
                        .into_iter()
                        .map(capability_to_dto)
                        .collect::<Vec<_>>();
                    let payload = output::CapabilitiesOutput { capabilities: dtos };
                    writeln!(out, "{}", output::to_json(&payload)?)?;
                }
            }
            Ok(())
        }
        // Init is dispatched at the top of app_main so it skips config
        // loading entirely. The wildcard here keeps the match exhaustive.
        Command::Init(_) => unreachable!("dispatched at top of app_main"),
        Command::MergeDriver(_) => unreachable!("dispatched at top of app_main"),
        Command::Resolve(_) => unreachable!("dispatched at top of app_main"),
        Command::Conflicts(_) => unreachable!("dispatched at top of app_main"),
        Command::Inspect(_) => unreachable!("dispatched at top of app_main"),
        Command::Clean(_) | Command::Smudge(_) | Command::Textconv(_) => {
            unreachable!("dispatched at top of app_main")
        }
        Command::Manifest(_) | Command::Attest(_) => {
            unreachable!("dispatched at top of app_main")
        }
        Command::Scm(_) => unreachable!("dispatched at top of app_main"),
    }
}

/// Load layered TOML config and fill in `Option<T>` fields on `common`
/// where the user did not pass an explicit CLI flag. Built-in defaults
/// (clap `default_value_t`) are treated as "not explicitly set" — they
/// defer to config when present.
fn apply_config(mut common: CommonArgs) -> Result<CommonArgs> {
    let cfg = config::Config::load(&PathBuf::from("."))?;
    if common.casdir.is_none() {
        common.casdir = cfg.casdir.clone();
    }
    if common.policy.is_none() {
        common.policy = cfg.policy.clone();
    }
    if common.defaults.is_none() {
        common.defaults = cfg.defaults.clone();
    }
    if common.lang.is_none() {
        common.lang = cfg.lang.clone();
    }
    if common.signer.is_none() {
        common.signer = cfg.chain.signer.as_ref().map(PathBuf::from);
    }
    if cfg.chain.auto_anchor == Some(true) {
        common.anchor = true;
    }
    if cfg.fips == Some(true) {
        common.fips = true;
    }
    Ok(common)
}

/// `enprot init` implementation: write the commented template either
/// to `.enprot.toml` in cwd or, with `--global`, to
/// `~/.config/enprot/config.toml`. Refuses to overwrite unless `--force`.
fn init_config(a: InitSubcmd) -> Result<()> {
    let target = if a.global {
        config::user_config_path()
            .ok_or_else(|| Error::msg("could not resolve user config path (is $HOME set?)"))?
    } else {
        PathBuf::from(".enprot.toml")
    };
    if target.exists() && !a.force {
        return Err(Error::msg(format!(
            "{} already exists; pass --force to overwrite",
            target.display()
        )));
    }
    if let Some(parent) = target.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::write(&target, config::Config::template())?;
    println!("wrote {}", target.display());

    if a.git {
        init_gitattributes()?;
    }
    // Create the CAS directory if it doesn't exist — most commands
    // assume it's there; creating it at init time saves the user
    // a separate mkdir.
    let cas_path = PathBuf::from("cas");
    if !cas_path.exists() {
        std::fs::create_dir(&cas_path)?;
        eprintln!("created {}", cas_path.display());
    }
    Ok(())
}

/// Write `.gitattributes` so *.ept files route through enprot's
/// filter/diff/merge machinery. Prints the `.git/config` snippet to
/// stdout — we don't write to `.git/config` directly to avoid
/// clobbering unrelated entries.
fn init_gitattributes() -> Result<()> {
    let path = PathBuf::from(".gitattributes");
    let snippet = "# Route *.ept through enprot's clean/smudge filters.\n\
                   *.ept filter=enprot diff=enprot merge=enprot\n";
    if path.exists() {
        return Err(Error::msg(format!(
            "{} already exists; merge this snippet in manually:\n{}",
            path.display(),
            snippet
        )));
    }
    std::fs::write(&path, snippet)?;
    println!("wrote {}", path.display());
    println!(
        "\nAdd the following to .git/config (or run `git config -f .git/config ...`):\n\
               [filter \"enprot\"]\n\
               \x20   clean = enprot clean -w WORD -k WORD=PASSWORD\n\
               \x20   smudge = enprot smudge -w WORD -k WORD=PASSWORD\n\
               [diff \"enprot\"]\n\
               \x20   textconv = enprot textconv -w WORD -k WORD=PASSWORD\n\
               [merge \"enprot\"]\n\
               \x20   driver = enprot merge-driver %O %A %B %P\n"
    );
    Ok(())
}

/// `merge-driver` entry point. Performs a three-way WORD-aware
/// merge and writes the result back into the "ours" path. Exits
/// zero on success even when conflicts are emitted; the caller
/// detects conflicts by scanning the output for CONFLICT markers.
/// Exits non-zero only on parse / IO errors.
fn run_merge_driver(a: MergeDriverSubcmd) -> Result<()> {
    let conflicts = merge::merge_paths(&a.base, &a.ours, &a.theirs)?;
    if conflicts > 0 {
        eprintln!(
            "merge-driver: {} conflict(s) emitted in {}",
            conflicts,
            a.ours.display()
        );
    }
    Ok(())
}

/// `resolve` entry point. Reads FILE, walks CONFLICT blocks, applies
/// the chosen mode, writes the result back to FILE in-place.
fn run_resolve(a: ResolveSubcmd) -> Result<()> {
    use std::io::{BufReader, BufWriter, IsTerminal};
    let mode = resolve::ResolveMode::from_cli_flag(&a.mode)?;
    let overrides = resolve::WordOverride::from_cli_flags(&a.word)?;
    if matches!(mode, resolve::ResolveMode::Interactive) && !std::io::stdin().is_terminal() {
        return Err(Error::msg(
            "resolve --interactive requires a TTY (pass --mode ours/theirs/both/skip for non-interactive runs)",
        ));
    };

    let policy = Box::new(crypto::CryptoPolicyDefault {}) as Box<dyn crypto::CryptoPolicy>;
    let mut paops = ParseOps::new(policy)?;
    paops.runtime.fname = a.file.display().to_string();
    let f = File::open(&a.file)?;
    let tree = etree::parse(BufReader::new(f), &mut paops)?;
    let (resolved, n) = resolve::resolve_tree_with_overrides(&tree, mode, &overrides)?;
    let out = File::create(&a.file)?;
    etree::tree_write(&mut BufWriter::new(out), &resolved, &mut paops)?;
    eprintln!("resolve: cleared {} conflict(s) in {}", n, a.file.display());
    Ok(())
}

/// `conflicts` entry point: walk FILE and report unresolved
/// CONFLICT blocks. Exits non-zero if any are present.
fn run_conflicts(a: ConflictsSubcmd) -> Result<()> {
    use std::io::BufReader;
    let policy = Box::new(crypto::CryptoPolicyDefault {}) as Box<dyn crypto::CryptoPolicy>;
    let mut paops = ParseOps::new(policy)?;
    paops.runtime.fname = a.file.display().to_string();
    let f = File::open(&a.file)?;
    let tree = etree::parse(BufReader::new(f), &mut paops)?;

    let entries: Vec<output::ConflictEntry> = tree
        .iter()
        .filter_map(|n| match n {
            etree::TextNode::Conflict { keyw, ours, theirs } => Some(output::ConflictEntry {
                word: keyw.clone(),
                ours_nodes: ours.len(),
                theirs_nodes: theirs.len(),
            }),
            _ => None,
        })
        .collect();

    let count = entries.len();
    match a.format {
        output::OutputFormat::Text => {
            if entries.is_empty() {
                println!("no conflicts in {}", a.file.display());
            } else {
                for e in &entries {
                    println!(
                        "{:<16} {} nodes ours / {} nodes theirs",
                        e.word, e.ours_nodes, e.theirs_nodes
                    );
                }
            }
        }
        output::OutputFormat::Json => {
            let payload = output::ConflictsOutput { conflicts: entries };
            println!("{}", output::to_json(&payload)?);
        }
    }

    if count > 0 {
        std::process::exit(1);
    }
    Ok(())
}

/// `inspect` entry point (TODO.finalize/42): combined diagnostic.
/// Parses the file, lists structure, checks chain anchors, and
/// shows what the current flag set can do with the file. One
/// pass, one output, no file modification.
fn run_inspect(a: InspectSubcmd, common: CommonArgs) -> Result<()> {
    let policy = resolve_policy(&common)?;
    let mut paops = ParseOps::new(policy)?;
    apply_common(&common, &mut paops);

    let reader: Box<dyn BufRead> = match &a.file {
        Some(p) if p != &PathBuf::from("-") => {
            let path_str = p.display().to_string();
            paops.runtime.fname = path_str.clone();
            Box::new(BufReader::new(File::open(p).map_err(|e| {
                Error::msg(format!("inspect: failed to open {}: {}", path_str, e))
            })?))
        }
        _ => {
            paops.runtime.fname = "<stdin>".into();
            Box::new(BufReader::new(std::io::stdin()))
        }
    };

    let tree = etree::parse(reader, &mut paops)?;

    // Section 1: structure (same as `list`)
    println!("== structure ==");
    let stdout = std::io::stdout();
    list_tree(&tree, 0, &mut stdout.lock())?;

    // Section 2: chain anchors
    let mut dag = ledger::AnchorDag::new();
    collect_chain_anchors(&tree, &mut dag)?;
    println!("\n== chain anchors ==");
    if dag.is_empty() {
        println!("  (none)");
    } else {
        println!("  {} anchor(s)", dag.len());
        for (id, signed) in dag.iter() {
            println!("    {} signer={}", id.to_hex(), signed.anchor.signer);
        }
    }

    // Section 3: conflicts
    let conflict_count = tree
        .iter()
        .filter(|n| matches!(n, etree::TextNode::Conflict { .. }))
        .count();
    println!("\n== conflicts ==");
    if conflict_count == 0 {
        println!("  (none)");
    } else {
        println!("  {} unresolved conflict(s)", conflict_count);
    }

    // Section 4: capabilities
    let caps = capability::CapabilitySet::from_paops(&paops);
    println!("\n== capabilities ==");
    for c in caps.iter_sorted() {
        println!("  {}", c);
    }

    if conflict_count > 0 {
        std::process::exit(1);
    }
    Ok(())
}

/// Direction of the smudge/clean filter. Clean encrypts (plaintext
/// in, ciphertext out); Smudge decrypts (ciphertext in, plaintext
/// out). Textconv is the same as Smudge — git just calls it from a
/// different context (diff rendering vs. checkout).
#[derive(Copy, Clone, Eq, PartialEq)]
enum SmudgeMode {
    Clean,
    Smudge,
}

/// `manifest` entry point: build a provenance manifest for a project
/// tree. Walks the directory, stores each file in CAS, emits an EPT
/// file with INCLUDE per source. Output goes to `--output` or stdout.
fn run_manifest(a: ManifestSubcmd) -> Result<()> {
    let casdir = a
        .casdir
        .clone()
        .or_else(|| {
            if Path::new("cas").is_dir() {
                Some(PathBuf::from("cas"))
            } else {
                Some(PathBuf::from("."))
            }
        })
        .unwrap();
    if !casdir.is_dir() {
        std::fs::create_dir_all(&casdir)?;
    }

    eprintln!("manifest: walking {}...", a.dir.display());
    let tree = provenance::build_manifest(&a.dir, &casdir)?;
    eprintln!(
        "manifest: {} entries",
        tree.iter()
            .filter(|n| matches!(n, etree::TextNode::Include { .. }))
            .count()
    );
    let policy = crypto::default_policy();
    let mut paops = ParseOps::new(policy)?;
    paops.runtime.fname = a
        .output
        .as_ref()
        .map(|p| p.display().to_string())
        .unwrap_or_else(|| "<stdout>".into());

    match a.output.as_ref() {
        Some(path) => {
            let f = File::create(path)?;
            etree::tree_write(&mut BufWriter::new(f), &tree, &mut paops)?;
            eprintln!("manifest: wrote {}", path.display());
        }
        None => {
            let stdout = std::io::stdout();
            etree::tree_write(&mut stdout.lock(), &tree, &mut paops)?;
        }
    }
    Ok(())
}

/// `attest` entry point: append a signed chain anchor to a manifest.
fn run_attest(a: AttestSubcmd) -> Result<()> {
    let priv_pem = fs::read_to_string(&a.signer)?;
    let body = fs::read_to_string(&a.file)?;
    let policy = Box::new(crypto::CryptoPolicyDefault {}) as Box<dyn crypto::CryptoPolicy>;
    let mut paops = ParseOps::new(policy)?;
    paops.runtime.fname = a.file.display().to_string();
    let cursor = std::io::Cursor::new(body.into_bytes());
    let tree = etree::parse(cursor, &mut paops)?;

    // Default casdir to `.` so attest doesn't fail when the manifest
    // has no CAS-referenced content (the chain anchor just needs to
    // hash the file state).
    if paops.io.casdir.as_os_str().is_empty() {
        paops.io.casdir = PathBuf::from(".");
    }

    let attested = provenance::attest(&tree, &priv_pem, &paops.io.casdir, Vec::new())?;
    let f = File::create(&a.file)?;
    etree::tree_write(&mut BufWriter::new(f), &attested, &mut paops)?;
    eprintln!("attest: signed {}", a.file.display());
    Ok(())
}

/// `scm` entry point: dispatch to the appropriate sub-operation.
/// Re-uses provenance::attest for signing so the wire format is
/// identical to TODO.roadmap/51.
fn run_scm(a: ScmSubcmd) -> Result<()> {
    let casdir = a.casdir.clone().unwrap_or_else(|| {
        if Path::new("cas").is_dir() {
            PathBuf::from("cas")
        } else {
            PathBuf::from(".")
        }
    });
    if !casdir.is_dir() {
        std::fs::create_dir_all(&casdir)?;
    }
    match a.command {
        ScmCommand::Init { manifest } => {
            scm::init_manifest(&manifest)?;
            println!("scm init: wrote {}", manifest.display());
            Ok(())
        }
        ScmCommand::Add { manifest, path } => {
            let n = scm::add_to_manifest(&manifest, &path, &casdir)?;
            println!("scm add: appended {} entries to {}", n, manifest.display());
            Ok(())
        }
        ScmCommand::Deps {
            manifest,
            cargo_toml,
        } => {
            let n = scm::add_cargo_deps(&manifest, &cargo_toml, &casdir)?;
            println!("scm deps: appended {} entries to {}", n, manifest.display());
            Ok(())
        }
        ScmCommand::Attest { signer, manifest } => {
            run_attest(AttestSubcmd {
                signer,
                file: manifest.clone(),
            })?;
            println!("scm attest: signed {}", manifest.display());
            Ok(())
        }
        ScmCommand::Verify {
            trust_root,
            manifest,
        } => {
            // Delegate to the existing verify-chain implementation so
            // customers get identical semantics to `enprot verify-
            // chain --trust-root X FILE`. CommonArgs is constructed
            // with the filter-context defaults via the helper.
            verify_chain_files(
                CommonArgs::for_filter(Some(casdir.clone())),
                VerifyChainSubcmd {
                    trust_roots: vec![trust_root],
                    files: vec![manifest.to_string_lossy().into_owned()],
                },
            )
        }
        ScmCommand::Diff { old, new } => {
            let d = scm::diff_manifests(&old, &new)?;
            print!("{d}");
            Ok(())
        }
    }
}

/// `clean` / `smudge` / `textconv` entry point. Pipes stdin through
/// the encrypt or decrypt pipeline and writes the result to stdout.
fn run_smudge_clean(mode: SmudgeMode, a: SmudgeCleanSubcmd, common: CommonArgs) -> Result<()> {
    use std::io::{Read, Write};
    let password = lookup_word_password(&common, &a.word)?;

    let mut input = Vec::new();
    std::io::stdin().read_to_end(&mut input)?;
    let stdout = std::io::stdout();
    let mut out = stdout.lock();

    let policy = Box::new(crypto::CryptoPolicyDefault {}) as Box<dyn crypto::CryptoPolicy>;
    let mut paops = ParseOps::new(policy)?;
    paops.passwords.insert(a.word.clone(), password);

    match mode {
        SmudgeMode::Clean => {
            paops.crypto.cipheropts.alg = a
                .cipher
                .clone()
                .unwrap_or_else(|| "aes-256-gcm-siv-det".to_string());
            if let Some(p) = a.pbkdf.as_ref() {
                paops.crypto.pbkdfopts.alg = p.clone();
            }
            // Bypass the tree pipeline: the input is opaque plaintext
            // bytes, not parsed EPT markup. Encrypt directly and emit
            // a single self-describing Encrypted block.
            let (ct, extfields) = prot::encrypt(
                input,
                paops.passwords.get(&a.word).unwrap(),
                &mut paops.crypto.rng,
                &paops.crypto.pbkdfopts,
                &paops.crypto.cipheropts,
                &mut paops.crypto.pbkdf_cache,
                &*paops.crypto.policy,
            )?;
            let tree: etree::TextTree = vec![etree::TextNode::Encrypted {
                keyw: a.word.clone(),
                txt: vec![etree::TextNode::Data(ct)],
                extfields,
            }];
            etree::tree_write(&mut out, &tree, &mut paops)?;
        }
        SmudgeMode::Smudge => {
            // Parse the EPT input to find the Encrypted block, then
            // decrypt and emit raw plaintext bytes.
            paops.runtime.fname = "<smudge-stdin>".into();
            let cursor = std::io::Cursor::new(input);
            let tree = etree::parse(cursor, &mut paops)?;
            let (ct, pbkdf, cipher) = extract_first_encrypted(&tree, &a.word)
                .ok_or_else(|| Error::msg(format!("no ENCRYPTED {} block in input", a.word)))?;
            let pt = prot::decrypt(
                ct,
                paops.passwords.get(&a.word).unwrap(),
                &pbkdf.as_ref(),
                &cipher.as_ref(),
                &mut paops.crypto.pbkdf_cache,
                &*paops.crypto.policy,
            )?;
            out.write_all(&pt)?;
        }
    }
    out.flush()?;
    Ok(())
}

/// Walk a parsed tree and return the first Encrypted block's
/// ciphertext payload (Data or Stored) plus its extfields for the
/// named WORD. Returns (ct, pbkdf, cipher) — the values decrypt needs.
fn extract_first_encrypted(
    tree: &etree::TextTree,
    word: &str,
) -> Option<(Vec<u8>, Option<String>, Option<String>)> {
    for node in tree {
        match node {
            etree::TextNode::Encrypted {
                keyw,
                txt,
                extfields,
            } if keyw == word => {
                if let Some(first) = txt.first() {
                    let payload = match first {
                        etree::TextNode::Data(d) => Some(d.clone()),
                        _ => None,
                    };
                    if let Some(ct) = payload {
                        let pbkdf = extfields.get("pbkdf").cloned();
                        let cipher = extfields.get("cipher").cloned();
                        return Some((ct, pbkdf, cipher));
                    }
                }
            }
            etree::TextNode::BeginEnd { txt, .. } => {
                if let Some(found) = extract_first_encrypted(txt, word) {
                    return Some(found);
                }
            }
            _ => {}
        }
    }
    None
}

/// Pull the WORD password from `-k` or `ENPROPT_KEY=WORD=password`.
/// Git filters can't prompt interactively, so the env-var fallback
/// is required for non-interactive use.
fn lookup_word_password(common: &CommonArgs, word: &str) -> Result<String> {
    for (w, p) in &common.password {
        if w == word {
            return Ok(p.clone());
        }
    }
    if let Ok(env_val) = std::env::var("ENPROPT_KEY") {
        if let Some((w, p)) = env_val.split_once('=') {
            if w == word && !p.is_empty() {
                return Ok(p.to_string());
            }
        }
    }
    Err(Error::msg(format!(
        "no password supplied for WORD '{}' (pass `-k {0}=PASSWORD` or set ENPROPT_KEY={0}=PASSWORD)",
        word
    )))
}

#[derive(Copy, Clone)]
enum Operation {
    Encrypt,
    Decrypt,
    Store,
    Fetch,
    EncryptStore,
}

impl Operation {
    /// Human-readable label for chain-anchor `mut:` field.
    fn label(self) -> &'static str {
        match self {
            Operation::Encrypt => "encrypt",
            Operation::Decrypt => "decrypt",
            Operation::Store => "store",
            Operation::Fetch => "fetch",
            Operation::EncryptStore => "encrypt-store",
        }
    }
}

fn run(
    common: CommonArgs,
    output: OutputArgs,
    op: Option<(EncryptOpts, Operation)>,
    recipient_pubs: Vec<String>,
    recipient_privs: Vec<String>,
) -> Result<()> {
    let explicit_policy = common.policy.clone();
    let mut policy_name = explicit_policy
        .clone()
        .unwrap_or_else(|| consts::DEFAULT_POLICY.to_string());

    let fips = common.fips
        || (cfg!(unix)
            && match fs::read_to_string("/proc/sys/crypto/fips_enabled") {
                Ok(s) => s.starts_with('1'),
                Err(_) => false,
            });
    if fips {
        if let Some(p) = explicit_policy.as_deref() {
            if p != "nist" {
                return Err(Error::Msg(format!(
                    "Policy setting of '{}' conflicts with --fips",
                    p
                )));
            }
        }
        policy_name = "nist".to_string();
    }

    let policy = make_policy(&policy_name);
    let mut paops = if let Some(defaults) = common.defaults.as_deref() {
        let mut p = ParseOps::new(make_policy(defaults))?;
        p.crypto.policy = policy;
        p
    } else {
        ParseOps::new(policy)?
    };

    if let Some(dir) = common.casdir.clone() {
        paops.io.casdir = dir;
    } else if Path::new("cas").is_dir() {
        paops.io.casdir = Path::new("cas").to_path_buf();
    } else {
        paops.io.casdir = Path::new(".").to_path_buf();
    }

    paops.io.verbose = common.verbose && !common.quiet;
    paops.io.inline_data = common.inline || common.casdir.is_none();
    paops.max_depth = common.max_depth;
    let (left, right) = resolve_separators(&common);
    paops.separators.left = left;
    paops.separators.right = right;
    paops.passwords.extend(common.password);
    paops.crypto.recipient_pubs = recipient_pubs;
    for (i, w) in output.word.iter().enumerate() {
        if let Some(priv_pem) = recipient_privs.get(i).or_else(|| recipient_privs.first()) {
            paops
                .crypto
                .recipient_privkeys
                .insert(w.clone(), priv_pem.clone());
        }
    }
    if common.pbkdf_disable_cache {
        paops.crypto.pbkdf_cache = None;
    }

    // Apply the operation: populate the transform sets on paops. `op == None`
    // means Passthrough — leave the sets empty.
    if let Some((enc_opts, op_kind)) = op.as_ref() {
        // Capability policy check (TODO.roadmap/46): when encrypting,
        // refuse to write blocks for a WORD whose required capability
        // the caller doesn't hold. Decrypt/store/fetch don't gate on
        // per-WORD capability — they're not capability-changing ops.
        if matches!(op_kind, Operation::Encrypt | Operation::EncryptStore) {
            if let Some(p) = common
                .policy_file
                .as_ref()
                .map(|p| cappolicy::CapPolicy::load_file(p))
                .transpose()?
            {
                let held = capability::CapabilitySet::from_paops(&paops);
                for w in &output.word {
                    p.check_word_capability(w, &held)?;
                }
            }
        }
        for w in &output.word {
            match op_kind {
                Operation::Encrypt => {
                    paops.transforms.encrypt.insert(w.clone());
                }
                Operation::Decrypt => {
                    paops.transforms.decrypt.insert(w.clone());
                }
                Operation::Store => {
                    paops.transforms.store.insert(w.clone());
                }
                Operation::Fetch => {
                    paops.transforms.fetch.insert(w.clone());
                }
                Operation::EncryptStore => {
                    paops.transforms.encrypt.insert(w.clone());
                    paops.transforms.store.insert(w.clone());
                }
            }
        }

        // PBKDF + cipher options only meaningful for encrypt / encrypt-store.
        if matches!(op_kind, Operation::Encrypt | Operation::EncryptStore) {
            if let Some(alg) = enc_opts.pbkdf.as_deref() {
                paops.crypto.pbkdfopts.alg = alg.to_string();
            }
            if let Some(saltlen) = enc_opts.pbkdf_salt_len {
                paops.crypto.pbkdfopts.saltlen = saltlen;
            }
            if let Some(msec) = enc_opts.pbkdf_msec {
                paops.crypto.pbkdfopts.msec = Some(msec);
            }
            if let Some(raw) = enc_opts.pbkdf_params.as_deref() {
                paops.crypto.pbkdfopts.msec = None;
                let params: std::collections::BTreeMap<String, usize> = raw
                    .split(',')
                    .map(|kv| {
                        let (k, v) = kv.split_once('=').unwrap_or(("", "0"));
                        (k.to_string(), v.parse().unwrap_or(0))
                    })
                    .collect();
                paops.crypto.pbkdfopts.params = Some(params);
            }
            if let Some(salt_hex) = enc_opts.pbkdf_salt.as_deref() {
                paops.crypto.pbkdfopts.salt = Some(hex::decode(salt_hex).map_err(Error::from)?);
            }
            if let Some(c) = enc_opts.cipher.as_deref() {
                paops.crypto.cipheropts.alg = c.to_string();
            }
            if let Some(iv_hex) = enc_opts.cipher_iv.as_deref() {
                paops.crypto.cipheropts.iv = Some(hex::decode(iv_hex).map_err(Error::from)?);
            }
        }
    }

    if paops.io.verbose {
        eprintln!(
            "LEFT_SEP='{}' RIGHT_SEP='{}' casdir = '{}'",
            paops.separators.left,
            paops.separators.right,
            paops.io.casdir.display(),
        );
    }

    let files = pair_inputs_to_outputs(
        &output.files,
        &output.output,
        &output.prefix,
        output.output_dir.as_deref(),
    );

    // Populate the anchor context once. `passthrough` (op == None) is
    // excluded because it performs no transformation and therefore
    // has nothing meaningful to anchor.
    paops.anchor = build_anchor_config(
        common.anchor,
        common.signer.as_deref(),
        op.as_ref().map(|(_, k)| *k),
        &output.word,
    )?;

    for (path_in, path_out) in files {
        process_one_file(&path_in, &path_out, &mut paops)?;
    }
    Ok(())
}

/// Pair each input with its output, following the rules in
/// `TODO.issues/18-output-directory-mode.md`:
///
/// 1. `--output <FILE>` paired with this input → use it as-is.
/// 2. `--output-dir <DIR>` given → `DIR + "/" + basename(input)`.
/// 3. `--prefix <PREFIX>` where PREFIX ends in `/` or is an existing
///    directory → same as `--output-dir` behaviour.
/// 4. `--prefix <PREFIX>` (other) → PREFIX prepended to input verbatim
///    (the legacy flat-CLI behavior).
/// 5. Input is `-` (stdin) → output is `-` (stdout passthrough).
/// 6. Otherwise → output = input (in-place).
fn pair_inputs_to_outputs(
    inputs: &[String],
    outputs: &[String],
    prefix: &str,
    output_dir: Option<&Path>,
) -> Vec<(String, String)> {
    let mut result = Vec::with_capacity(inputs.len());
    let mut out_iter = outputs.iter();
    let prefix_is_dir = !prefix.is_empty() && (prefix.ends_with('/') || Path::new(prefix).is_dir());

    for input in inputs {
        if let Some(output) = out_iter.next() {
            result.push((input.clone(), output.clone()));
            continue;
        }
        let output = if input == "-" {
            "-".to_string()
        } else if let Some(dir) = output_dir {
            join_with_basename(dir, input)
        } else if prefix_is_dir {
            let dir_str = prefix.trim_end_matches('/');
            join_with_basename(Path::new(dir_str), input)
        } else if prefix.is_empty() {
            input.clone()
        } else {
            format!("{}{}", prefix, input)
        };
        result.push((input.clone(), output));
    }
    result
}

fn join_with_basename(dir: &Path, input: &str) -> String {
    let base = Path::new(input)
        .file_name()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_else(|| input.to_string());
    dir.join(base).to_string_lossy().into_owned()
}

fn build_anchor_config(
    anchor_flag: bool,
    signer_path: Option<&Path>,
    op_kind: Option<Operation>,
    words: &[String],
) -> Result<etree::AnchorConfig> {
    if !anchor_flag {
        return Ok(etree::AnchorConfig::disabled());
    }
    let signer_path =
        signer_path.ok_or_else(|| Error::msg("--anchor requires --signer <PRIV.pem>"))?;
    let priv_pem = fs::read_to_string(signer_path)?;
    let op = op_kind
        .map(|k| k.label())
        .unwrap_or("passthrough")
        .to_string();
    Ok(etree::AnchorConfig {
        enabled: true,
        operation: op,
        words: words.to_vec(),
        signer_priv_pem: Some(priv_pem),
    })
}

fn process_one_file(path_in: &str, path_out: &str, paops: &mut ParseOps) -> Result<()> {
    if paops.io.verbose {
        eprintln!("Reading {}", path_in);
    }

    let reader_in: Box<dyn BufRead> = if path_in == "-" {
        Box::new(BufReader::new(std::io::stdin()))
    } else {
        match File::open(path_in) {
            Ok(f) => Box::new(BufReader::new(f)),
            Err(e) => {
                return Err(Error::Msg(format!(
                    "Failed to open {} for reading: {}",
                    path_in, e
                )));
            }
        }
    };

    paops.runtime.fname = if path_in == "-" {
        "<stdin>".to_string()
    } else {
        path_in.to_string()
    };

    let tree_in = etree::parse(reader_in, paops)
        .map_err(|e| Error::Msg(format!("{} in {}, aborting.", e, path_in)))?;

    if paops.io.verbose {
        eprintln!("Transforming {}", path_in);
    }
    let mut tree_out = etree::transform(&tree_in, paops)
        .map_err(|e| Error::Msg(format!("{} in {}, aborting.", e, path_in)))?;

    // Optionally append a CHAIN block signing the new file state.
    // Must happen BEFORE tree_write so the anchor lands in the output.
    if paops.anchor.enabled {
        let chain_node = build_chain_anchor_node(&tree_out, paops)?;
        tree_out.push(chain_node);
    }

    if paops.io.verbose {
        eprintln!("Writing {}", path_out);
    }

    let mut writer_out: Box<dyn Write> = if path_out == "-" {
        Box::new(BufWriter::new(std::io::stdout()))
    } else {
        match File::create(path_out) {
            Ok(f) => Box::new(BufWriter::new(f)),
            Err(e) => {
                return Err(Error::Msg(format!(
                    "Failed to open {} for writing: {}",
                    path_out, e
                )));
            }
        }
    };

    etree::tree_write(&mut writer_out, &tree_out, paops)
        .map_err(|e| Error::Msg(format!("Write to {} failed: {}", path_out, e)))?;
    Ok(())
}

/// Build a [`TextNode::Chain`] node that signs the post-transform
/// `tree_out` state. The payload hash commits to the file content
/// EXCLUDING any chain anchors — that way the anchor isn't
/// self-referential and the hash is stable across re-anchoring.
///
/// parents: hashes of every CHAIN block already present in tree_out,
/// in file order. This makes the new anchor a linear descendant of
/// the most-recent prior anchor (TODO.finalize/17 DAG semantics;
/// multiple-parents / merge anchors are a future extension).
fn build_chain_anchor_node(
    tree_out: &etree::TextTree,
    paops: &mut ParseOps,
) -> Result<etree::TextNode> {
    use crate::ledger::{Anchor, PayloadHash, SignerId};
    use crate::pki::SigAlgKind;
    use std::collections::BTreeMap;

    let priv_pem = paops
        .anchor
        .signer_priv_pem
        .clone()
        .ok_or_else(|| Error::msg("anchor config missing signer_priv_pem"))?;

    // Derive pubkey from privkey; compute fingerprint.
    let botan_priv = botan::Privkey::load_pem(&priv_pem).map_err(Error::botan)?;
    let botan_pub = botan_priv.pubkey().map_err(Error::botan)?;
    let pub_pem = botan_pub.pem_encode().map_err(Error::botan)?;
    let fp = capability::KeyFp::from_pem(&pub_pem)?;

    // payload_hash: SHA3-256 over the ENTIRE post-transform tree
    // (including any prior CHAIN blocks). This gives end-to-end
    // tamper detection: changing any earlier content invalidates
    // every subsequent anchor's payload. The new anchor itself
    // isn't in `tree_out` yet, so there's no self-reference.
    let blob = etree::tree_to_blob(tree_out, paops)?;
    let policy = crate::crypto::CryptoPolicyDefault {};
    let payload_hex = crate::crypto::hexdigest("sha3-256", &blob, &policy)?;
    let mut payload_arr = [0u8; 32];
    payload_arr.copy_from_slice(&hex::decode(payload_hex)?);
    let payload_hash = PayloadHash(payload_arr);

    // parents: latest existing CHAIN anchor only (linear chain).
    let parents = latest_existing_anchors(tree_out, paops)?;

    // mutations: e.g., "encrypt+Agent_007,GEHEIM". URL-encoded space.
    let words_joined = paops.anchor.words.join(",");
    let mutations = if words_joined.is_empty() {
        paops.anchor.operation.clone()
    } else {
        format!("{}+{}", paops.anchor.operation, words_joined)
    };

    let signer = SignerId::new(SigAlgKind::Ed25519, fp);
    let anchor = Anchor::builder(signer, payload_hash)
        .with_parents(parents)
        .with_mutations(mutations)
        .build();
    let signed = anchor.sign(&priv_pem, &pub_pem, SigAlgKind::Ed25519)?;
    let extfields: BTreeMap<String, String> = signed.to_extfields();
    Ok(etree::TextNode::Chain { extfields })
}

/// Return at most one parent: the [`AnchorHash`] of the LAST
/// [`TextNode::Chain`] in document order, or `None` if the tree has
/// no anchors. Linear-chain semantic — new anchors build on the tip.
fn latest_existing_anchors(
    tree: &etree::TextTree,
    _paops: &ParseOps,
) -> Result<Vec<crate::ledger::AnchorHash>> {
    let mut all = Vec::new();
    walk_for_chains(tree, &mut all)?;
    Ok(all.pop().into_iter().collect())
}

fn walk_for_chains(tree: &etree::TextTree, out: &mut Vec<crate::ledger::AnchorHash>) -> Result<()> {
    for node in tree {
        match node {
            etree::TextNode::Chain { extfields } => {
                let signed = crate::ledger::SignedAnchor::from_extfields(extfields)?;
                if let Ok(h) = signed.id() {
                    out.push(h);
                }
            }
            etree::TextNode::BeginEnd { txt, .. } | etree::TextNode::Encrypted { txt, .. } => {
                walk_for_chains(txt, out)?;
            }
            _ => {}
        }
    }
    Ok(())
}

/// Translate a [`capability::Capability`] into a stable DTO for JSON output.
fn capability_to_dto(c: &capability::Capability) -> output::CapabilityDto {
    use capability::Capability::*;
    match c {
        Viewer => output::CapabilityDto {
            tier: "viewer",
            word: None,
            key_fp: None,
        },
        Reader => output::CapabilityDto {
            tier: "reader",
            word: None,
            key_fp: None,
        },
        Decryptor(w) => output::CapabilityDto {
            tier: "decryptor",
            word: Some(w.to_string()),
            key_fp: None,
        },
        Signer(fp) => output::CapabilityDto {
            tier: "signer",
            word: None,
            key_fp: Some(fp.to_hex()),
        },
        Verifier(fp) => output::CapabilityDto {
            tier: "verifier",
            word: None,
            key_fp: Some(fp.to_hex()),
        },
    }
}

/// Parse each input and list all WORD segments to stdout. One line per
/// directive node, with keyword, type, and crypto metadata.
fn list_files(common: CommonArgs, output_args: OutputArgs) -> Result<()> {
    let policy = resolve_policy(&common)?;
    let mut paops = ParseOps::new(policy)?;
    apply_common(&common, &mut paops);

    let files = pair_inputs_to_outputs(
        &output_args.files,
        &output_args.output,
        &output_args.prefix,
        output_args.output_dir.as_deref(),
    );

    let stdout = std::io::stdout();
    let mut out = stdout.lock();
    let mut json_listings: Vec<output::FileListing> = Vec::new();

    for (path_in, _) in &files {
        let reader: Box<dyn BufRead> = if path_in == "-" {
            Box::new(BufReader::new(std::io::stdin()))
        } else {
            Box::new(BufReader::new(File::open(path_in).map_err(|e| {
                Error::Msg(format!("Failed to open {}: {}", path_in, e))
            })?))
        };
        paops.runtime.fname = path_in.clone();

        let tree = etree::parse(reader, &mut paops)?;

        match common.format {
            output::OutputFormat::Text => {
                if files.len() > 1 {
                    writeln!(out, "== {} ==", path_in)?;
                }
                list_tree(&tree, 0, &mut out)?;
            }
            output::OutputFormat::Json => {
                let mut nodes = Vec::new();
                list_tree_to_nodes(&tree, 0, &mut nodes);
                json_listings.push(output::FileListing {
                    path: path_in.clone(),
                    nodes,
                });
            }
        }
    }

    if matches!(common.format, output::OutputFormat::Json) {
        let payload = output::ListOutput {
            files: json_listings,
        };
        writeln!(out, "{}", output::to_json(&payload)?)?;
    }
    Ok(())
}

fn list_tree<W: Write>(tree: &etree::TextTree, depth: usize, out: &mut W) -> Result<()> {
    let indent = "  ".repeat(depth);
    for node in tree {
        match node {
            etree::TextNode::BeginEnd { keyw, txt } => {
                writeln!(out, "{}BEGIN/END  {}", indent, keyw)?;
                list_tree(txt, depth + 1, out)?;
            }
            etree::TextNode::Encrypted {
                keyw, extfields, ..
            } => {
                let cipher = extfields
                    .get("cipher")
                    .map(|s| s.as_str())
                    .unwrap_or("aes-256-siv");
                let pbkdf = extfields
                    .get("pbkdf")
                    .map(|s| s.split('$').nth(1).unwrap_or("?"))
                    .unwrap_or("legacy");
                writeln!(
                    out,
                    "{}ENCRYPTED {}  cipher={}  pbkdf={}",
                    indent, keyw, cipher, pbkdf
                )?;
            }
            etree::TextNode::Stored { keyw, cas } => {
                writeln!(
                    out,
                    "{}STORED    {}  cas={}",
                    indent,
                    keyw,
                    &cas[..cas.len().min(16)]
                )?;
            }
            etree::TextNode::Plain(_) | etree::TextNode::Data(_) => {}
            etree::TextNode::Chain { extfields } => {
                let signer = extfields.get("signer").map(|s| s.as_str()).unwrap_or("?");
                let payload = extfields.get("payload").map(|s| s.as_str()).unwrap_or("?");
                let short_payload = &payload[..payload.len().min(16)];
                writeln!(
                    out,
                    "{}CHAIN     signer={}  payload={}",
                    indent, signer, short_payload
                )?;
            }
            etree::TextNode::Include { hash } => {
                writeln!(out, "{}INCLUDE   {}", indent, &hash[..hash.len().min(16)])?;
            }
            etree::TextNode::Conflict { keyw, .. } => {
                writeln!(out, "{}CONFLICT  {}", indent, keyw)?;
            }
        }
    }
    Ok(())
}

/// Flatten the parsed tree into JSON DTO nodes. Same selection logic
/// as [`list_tree`] (skips Plain/Data); recurses into BeginEnd.
fn list_tree_to_nodes(tree: &etree::TextTree, depth: usize, out: &mut Vec<output::ListNode>) {
    for node in tree {
        match node {
            etree::TextNode::BeginEnd { keyw, txt } => {
                let mut children = Vec::new();
                list_tree_to_nodes(txt, depth + 1, &mut children);
                out.push(output::ListNode {
                    kind: "begin-end",
                    word: keyw.clone(),
                    depth,
                    cipher: None,
                    pbkdf: None,
                    cas: None,
                    signer: None,
                    payload: None,
                    children,
                });
            }
            etree::TextNode::Encrypted {
                keyw, extfields, ..
            } => {
                let cipher = extfields
                    .get("cipher")
                    .cloned()
                    .or_else(|| Some("aes-256-siv".to_string()));
                let pbkdf = extfields
                    .get("pbkdf")
                    .and_then(|s| s.split('$').nth(1).map(String::from))
                    .or_else(|| Some("legacy".to_string()));
                out.push(output::ListNode {
                    kind: "encrypted",
                    word: keyw.clone(),
                    depth,
                    cipher,
                    pbkdf,
                    cas: None,
                    signer: None,
                    payload: None,
                    children: Vec::new(),
                });
            }
            etree::TextNode::Stored { keyw, cas } => {
                out.push(output::ListNode {
                    kind: "stored",
                    word: keyw.clone(),
                    depth,
                    cipher: None,
                    pbkdf: None,
                    cas: Some(cas.clone()),
                    signer: None,
                    payload: None,
                    children: Vec::new(),
                });
            }
            etree::TextNode::Plain(_) | etree::TextNode::Data(_) => {}
            etree::TextNode::Chain { extfields } => {
                out.push(output::ListNode {
                    kind: "chain",
                    word: String::new(),
                    depth,
                    cipher: None,
                    pbkdf: None,
                    cas: None,
                    signer: extfields.get("signer").cloned(),
                    payload: extfields.get("payload").cloned(),
                    children: Vec::new(),
                });
            }
            etree::TextNode::Include { hash } => {
                out.push(output::ListNode {
                    kind: "include",
                    word: hash.clone(),
                    depth,
                    cipher: None,
                    pbkdf: None,
                    cas: None,
                    signer: None,
                    payload: None,
                    children: Vec::new(),
                });
            }
            etree::TextNode::Conflict { keyw, .. } => {
                out.push(output::ListNode {
                    kind: "conflict",
                    word: keyw.clone(),
                    depth,
                    cipher: None,
                    pbkdf: None,
                    cas: None,
                    signer: None,
                    payload: None,
                    children: Vec::new(),
                });
            }
        }
    }
}

/// Parse each input and check structural integrity: valid EPT markup,
/// resolvable CAS pointers (file exists + hash matches), well-formed
/// cipher/pbkdf extfields. Reports per-file status to stderr; returns
/// Err on the first problem.
fn verify_files(common: CommonArgs, output: OutputArgs) -> Result<()> {
    let policy = resolve_policy(&common)?;
    let mut paops = ParseOps::new(policy)?;
    apply_common(&common, &mut paops);

    let files = pair_inputs_to_outputs(
        &output.files,
        &output.output,
        &output.prefix,
        output.output_dir.as_deref(),
    );

    let mut issues = 0usize;
    for (path_in, _) in &files {
        if paops.io.verbose {
            eprintln!("Verifying {}", path_in);
        }

        let reader: Box<dyn BufRead> = if path_in == "-" {
            Box::new(BufReader::new(std::io::stdin()))
        } else {
            Box::new(BufReader::new(File::open(path_in).map_err(|e| {
                Error::Msg(format!("Failed to open {}: {}", path_in, e))
            })?))
        };
        paops.runtime.fname = path_in.clone();

        let tree = match etree::parse(reader, &mut paops) {
            Ok(t) => t,
            Err(e) => {
                eprintln!("FAIL {}: parse error: {}", path_in, e);
                issues += 1;
                continue;
            }
        };

        for node in &tree {
            let node_issues = verify_node(node, &mut paops);
            issues += node_issues;
        }

        if issues == 0 {
            eprintln!("OK   {}", path_in);
        }
    }

    if issues > 0 {
        return Err(Error::Msg(format!("{} issue(s) found", issues)));
    }
    Ok(())
}

fn verify_node(node: &etree::TextNode, paops: &mut ParseOps) -> usize {
    match node {
        etree::TextNode::Stored { keyw, cas } => match cas::load(cas, paops) {
            Ok(_) => 0,
            Err(e) => {
                eprintln!("FAIL: CAS pointer '{}' for WORD '{}': {}", cas, keyw, e);
                1
            }
        },
        etree::TextNode::Encrypted { txt, extfields, .. } => {
            let mut n = 0;
            // Check inner node
            for child in txt {
                n += verify_node(child, paops);
            }
            // Validate extfield format
            if let Some(cipher_str) = extfields.get("cipher") {
                if let Err(e) = cipher::parse_cipher_extfield(cipher_str) {
                    eprintln!("FAIL: cipher extfield '{}': {}", cipher_str, e);
                    n += 1;
                }
            }
            if let Some(phc_str) = extfields.get("pbkdf") {
                if let Err(e) = pbkdf::parse_phc(phc_str) {
                    eprintln!("FAIL: pbkdf extfield '{}': {}", phc_str, e);
                    n += 1;
                }
            }
            n
        }
        etree::TextNode::BeginEnd { txt, .. } => {
            let mut n = 0;
            for child in txt {
                n += verify_node(child, paops);
            }
            n
        }
        _ => 0,
    }
}

/// Resolve the crypto policy from CommonArgs (shared by `run` and `verify_files`).
fn resolve_policy(common: &CommonArgs) -> Result<Box<dyn crypto::CryptoPolicy>> {
    let explicit_policy = common.policy.clone();
    let mut policy_name = explicit_policy
        .clone()
        .unwrap_or_else(|| consts::DEFAULT_POLICY.to_string());
    let fips = common.fips
        || (cfg!(unix)
            && match fs::read_to_string("/proc/sys/crypto/fips_enabled") {
                Ok(s) => s.starts_with('1'),
                Err(_) => false,
            });
    if fips {
        if let Some(p) = explicit_policy.as_deref() {
            if p != "nist" {
                return Err(Error::Msg(format!(
                    "Policy setting of '{}' conflicts with --fips",
                    p
                )));
            }
        }
        policy_name = "nist".to_string();
    }
    Ok(make_policy(&policy_name))
}

/// Resolve the final left/right separator strings from CLI args.
///
/// `--lang` provides a preset; explicit `-l`/`-r` flags override
/// the preset's value. The override is detected by comparing against
/// `consts::DEFAULT_*` — if the user didn't change the default, the
/// preset is used; if they did, the explicit value wins.
///
/// Single source of truth: `run()` and `apply_common()` both call
/// this. Before this helper existed, the logic was duplicated in
/// both, risking drift (TODO.finalize/32).
fn resolve_separators(common: &CommonArgs) -> (String, String) {
    if let Some(ref lang) = common.lang {
        if let Some((left, right)) = consts::lang_separators(lang) {
            let l = if common.left_separator == consts::DEFAULT_LEFT_SEP {
                left.to_string()
            } else {
                common.left_separator.clone()
            };
            let r = if common.right_separator == consts::DEFAULT_RIGHT_SEP {
                right.to_string()
            } else {
                common.right_separator.clone()
            };
            return (l, r);
        }
    }
    (
        common.left_separator.clone(),
        common.right_separator.clone(),
    )
}

/// Apply common args to ParseOps (shared by `run` and `verify_files`).
fn apply_common(common: &CommonArgs, paops: &mut ParseOps) {
    if let Some(dir) = common.casdir.clone() {
        paops.io.casdir = dir;
    } else if Path::new("cas").is_dir() {
        paops.io.casdir = Path::new("cas").to_path_buf();
    } else {
        paops.io.casdir = Path::new(".").to_path_buf();
    }
    paops.io.verbose = common.verbose && !common.quiet;
    paops.io.inline_data = common.inline || common.casdir.is_none();
    paops.max_depth = common.max_depth;
    let (left, right) = resolve_separators(common);
    paops.separators.left = left;
    paops.separators.right = right;
    paops.passwords.extend(common.password.clone());
}

// ===== Public-key subcommands (`keygen`, `sign`, `verify-sig`) =====
//
// These don't touch EPT markup at all; they expose the Ed25519
// primitives in `pki` as standalone commands. Future PQC variants
// (ML-DSA, composites) plug into the same subcommand surface.

fn pki_keygen(_common: CommonArgs, a: KeygenSubcmd) -> Result<()> {
    let kind: pki::SigAlgKind = a.alg.parse()?;
    let mut rng = botan::RandomNumberGenerator::new_system().map_err(Error::botan)?;
    let (priv_pem, pub_pem) = pki::keygen(kind, &mut rng)?;
    write_key_or_stdout(a.out_priv.as_deref(), priv_pem.as_bytes())?;
    write_key_or_stdout(a.out_pub.as_deref(), pub_pem.as_bytes())?;
    Ok(())
}

fn pki_sign(_common: CommonArgs, a: SignSubcmd) -> Result<()> {
    if a.key.is_empty() {
        return Err(Error::Msg(
            "sign: at least one --key-file is required".into(),
        ));
    }
    let kind: pki::SigAlgKind = a.alg.parse()?;
    let msg = read_file_or_stdin(a.input.as_deref())?;
    let mut rng = botan::RandomNumberGenerator::new_system().map_err(Error::botan)?;

    let out_path = match (&a.out, &a.input) {
        (Some(p), _) => p.clone(),
        (None, Some(input)) => append_sig_ext(input),
        (None, None) => PathBuf::from("-"),
    };

    if a.key.len() == 1 {
        // Backwards-compat single-sig path: raw signature bytes.
        let priv_pem = fs::read_to_string(&a.key[0])?;
        let sig = pki::sign(kind, &priv_pem, &msg, &mut rng)?;
        if out_path == Path::new("-") {
            std::io::stdout().write_all(&sig)?;
        } else {
            fs::write(&out_path, &sig)?;
        }
        return Ok(());
    }

    // Multi-sig bundle path (TODO.roadmap/59). Each signer signs
    // the same payload; the bundle carries (alg, fp, sig) per
    // signer.
    let mut entries = Vec::with_capacity(a.key.len());
    for key_path in &a.key {
        let priv_pem = fs::read_to_string(key_path)?;
        let botan_priv = botan::Privkey::load_pem(&priv_pem).map_err(Error::botan)?;
        let botan_pub = botan_priv.pubkey().map_err(Error::botan)?;
        let pub_pem = botan_pub.pem_encode().map_err(Error::botan)?;
        let fp = capability::KeyFp::from_pem(&pub_pem)?;
        let sig = pki::sign(kind, &priv_pem, &msg, &mut rng)?;
        entries.push(pki::SigEntry {
            alg: kind,
            fp: fp.to_hex(),
            sig,
        });
    }
    let bundle = pki::SigBundle { entries };
    let body = bundle.serialize();
    if out_path == Path::new("-") {
        std::io::stdout().write_all(body.as_bytes())?;
    } else {
        fs::write(&out_path, body.as_bytes())?;
    }
    Ok(())
}

fn pki_verify_sig(_common: CommonArgs, a: VerifySigSubcmd) -> Result<()> {
    if a.key.is_empty() {
        return Err(Error::Msg(
            "verify-sig: at least one --key-file is required".into(),
        ));
    }
    let kind: pki::SigAlgKind = a.alg.parse()?;
    let sig_bytes = match (&a.sig, &a.input) {
        (Some(p), _) => fs::read(p)?,
        (None, Some(input)) => fs::read(append_sig_ext(input))?,
        (None, None) => {
            return Err(Error::Msg(
                "verify-sig: no signature file or input file given".into(),
            ));
        }
    };
    let msg = read_file_or_stdin(a.input.as_deref())?;

    if a.key.len() == 1 {
        // Backwards-compat single-sig path.
        let pub_pem = fs::read_to_string(&a.key[0])?;
        let ok = pki::verify(kind, &pub_pem, &msg, &sig_bytes)?;
        return if ok {
            Ok(())
        } else {
            Err(Error::Msg("signature verification failed".into()))
        };
    }

    // Multi-sig bundle path. Parse the bundle and verify each
    // entry against the supplied pubkeys (matched by fingerprint).
    let body = String::from_utf8(sig_bytes)
        .map_err(|e| Error::Msg(format!("signature bundle is not UTF-8: {e}")))?;
    let bundle = pki::SigBundle::parse(&body)?;
    if bundle.entries.len() != a.key.len() {
        return Err(Error::Msg(format!(
            "verify-sig: {} signatures in bundle but {} pubkeys supplied",
            bundle.entries.len(),
            a.key.len()
        )));
    }
    // Build fp → pem lookup from the supplied pubkeys.
    let mut by_fp: HashMap<String, String> = HashMap::new();
    for key_path in &a.key {
        let pem = fs::read_to_string(key_path)?;
        let fp = capability::KeyFp::from_pem(&pem)?;
        by_fp.insert(fp.to_hex(), pem);
    }
    for entry in &bundle.entries {
        let pem = by_fp
            .get(&entry.fp)
            .ok_or_else(|| Error::Msg(format!("no pubkey for fp {}", entry.fp)))?;
        let ok = pki::verify(entry.alg, pem, &msg, &entry.sig)?;
        if !ok {
            return Err(Error::Msg(format!(
                "signature verification failed for fp {}",
                entry.fp
            )));
        }
    }
    Ok(())
}

/// `foo.txt` → `foo.txt.sig`, `foo` → `foo.sig`. Idempotent if the
/// `.sig` extension is already present.
fn append_sig_ext(input: &Path) -> PathBuf {
    let mut p = input.to_path_buf();
    if p.extension().and_then(|e| e.to_str()) == Some("sig") {
        return p;
    }
    match p.extension() {
        Some(e) => {
            let mut new_ext = e.to_os_string();
            new_ext.push(".sig");
            p.set_extension(new_ext);
        }
        None => {
            p.set_extension("sig");
        }
    }
    p
}

fn pki_fingerprint(a: FingerprintSubcmd) -> Result<()> {
    let pem = fs::read_to_string(&a.key)?;
    let fp = capability::KeyFp::from_pem(&pem)?;
    println!("{}", fp);
    Ok(())
}

/// Compute the chain head hash of a file: SHA3-256 over the
/// canonical serialized tree. This detects ANY byte-level change —
/// content, anchors, metadata. For external pinning (publish the
/// hash out-of-band, later compare with `enprot pin`), this is the
/// strongest guarantee.
fn compute_chain_head(path: &str) -> Result<String> {
    let mut paops = ParseOps::new(Box::new(crate::crypto::CryptoPolicyDefault {}))?;
    paops.runtime.fname = path.to_string();
    let reader: Box<dyn BufRead> = if path == "-" {
        Box::new(BufReader::new(std::io::stdin()))
    } else {
        Box::new(BufReader::new(File::open(path)?))
    };
    let tree = etree::parse(reader, &mut paops)?;

    // Always hash the full canonical tree serialization. This catches
    // any tampering — content, anchors, separators, whitespace.
    let mut blob = Vec::new();
    etree::tree_write(&mut blob, &tree, &mut paops)?;
    let policy = crate::crypto::CryptoPolicyDefault {};
    crate::crypto::hexdigest("sha3-256", &blob, &policy)
}

fn snapshot_file(a: SnapshotSubcmd) -> Result<()> {
    let head = compute_chain_head(&a.file)?;
    println!("{}", head);
    Ok(())
}

fn pin_file(a: PinSubcmd) -> Result<()> {
    let head = compute_chain_head(&a.file)?;
    if head == a.expected {
        println!("OK");
        Ok(())
    } else {
        Err(Error::msg(format!(
            "chain head mismatch: expected {}, got {}",
            a.expected, head
        )))
    }
}

/// `audit-log` implementation: read stdin lines, append each as a
/// signed CHAIN anchor to FILE. The result is a linear, tamper-evident
/// log where each anchor's parent is the previous anchor (or empty
/// for the genesis line).
fn audit_log_stream(_common: CommonArgs, a: AuditLogSubcmd) -> Result<()> {
    let priv_pem = fs::read_to_string(&a.signer)?;

    // Read existing content (if any) → tree. Missing file = empty tree.
    let mut tree: etree::TextTree = if Path::new(&a.file).exists() {
        let mut paops = ParseOps::new(Box::new(crate::crypto::CryptoPolicyDefault {}))?;
        paops.runtime.fname = a.file.clone();
        let f = File::open(&a.file)?;
        etree::parse(BufReader::new(f), &mut paops)?
    } else {
        Vec::new()
    };

    // Find the most recent existing CHAIN anchor; new lines chain off it.
    let mut last_anchor = latest_anchor_hash(&tree);

    // Read stdin lines.
    let stdin = std::io::stdin();
    let mut line_count = 0usize;
    for line_in in stdin.lock().lines() {
        let line = line_in?;
        // Strip a trailing newline if present (lines() already does;
        // be defensive in case callers pipe raw bytes).
        let trimmed = line.trim_end_matches('\n').trim_end_matches('\r');
        tree.push(etree::TextNode::Plain(trimmed.to_string()));

        let chain_node =
            build_chain_anchor_node_with_parent(&tree, &priv_pem, "append", "", last_anchor)?;
        // Track the new anchor's hash so the next iteration parents off it.
        if let etree::TextNode::Chain { extfields } = &chain_node {
            if let Ok(signed) = ledger::SignedAnchor::from_extfields(extfields) {
                if let Ok(h) = signed.id() {
                    last_anchor = Some(h);
                }
            }
        }
        tree.push(chain_node);
        line_count += 1;
    }

    if line_count == 0 {
        eprintln!("audit-log: no lines read from stdin; file unchanged.");
        return Ok(());
    }

    // Write the full tree back atomically.
    let tmp_path = format!("{}.tmp", a.file);
    let mut paops = ParseOps::new(Box::new(crate::crypto::CryptoPolicyDefault {}))?;
    paops.runtime.fname = a.file.clone();
    let mut writer = BufWriter::new(File::create(&tmp_path)?);
    etree::tree_write(&mut writer, &tree, &mut paops)?;
    writer.flush()?;
    drop(writer);
    fs::rename(&tmp_path, &a.file)?;

    eprintln!("audit-log: appended {} anchor(s) to {}", line_count, a.file);
    Ok(())
}

/// Walk the tree and return the [`AnchorHash`](crate::ledger::AnchorHash)
/// of the LAST [`TextNode::Chain`] in document order, or `None` if
/// the tree has no anchors. Used by [`audit_log_stream`] to extend
/// the linear chain.
fn latest_anchor_hash(tree: &etree::TextTree) -> Option<ledger::AnchorHash> {
    let mut all = Vec::new();
    let _ = walk_for_chains(tree, &mut all);
    all.pop()
}

/// Build a [`TextNode::Chain`] signing the post-content state of
/// `tree`, with explicit `parent` (None for genesis). Used by
/// [`audit_log_stream`] where the parent is the previous anchor in
/// the stream, not all anchors in the file.
fn build_chain_anchor_node_with_parent(
    tree: &etree::TextTree,
    priv_pem: &str,
    operation: &str,
    words_csv: &str,
    parent: Option<ledger::AnchorHash>,
) -> Result<etree::TextNode> {
    use crate::ledger::{Anchor, PayloadHash, SignerId};
    use crate::pki::SigAlgKind;
    use std::collections::BTreeMap;

    // Derive pubkey from privkey.
    let botan_priv = botan::Privkey::load_pem(priv_pem).map_err(Error::botan)?;
    let botan_pub = botan_priv.pubkey().map_err(Error::botan)?;
    let pub_pem = botan_pub.pem_encode().map_err(Error::botan)?;
    let fp = capability::KeyFp::from_pem(&pub_pem)?;

    // payload_hash: SHA3-256 over EVERYTHING currently in the tree
    // (including any prior CHAIN blocks). This gives end-to-end tamper
    // detection: changing any earlier content invalidates every
    // subsequent anchor's payload. The anchor itself isn't in `tree`
    // yet (the caller pushes it AFTER this function returns), so no
    // self-reference.
    let mut paops = ParseOps::new(Box::new(crate::crypto::CryptoPolicyDefault {}))?;
    let blob = etree::tree_to_blob(tree, &mut paops)?;
    let policy = crate::crypto::CryptoPolicyDefault {};
    let payload_hex = crate::crypto::hexdigest("sha3-256", &blob, &policy)?;
    let mut payload_arr = [0u8; 32];
    payload_arr.copy_from_slice(&hex::decode(payload_hex)?);
    let payload_hash = PayloadHash(payload_arr);

    let mutations = if words_csv.is_empty() {
        operation.to_string()
    } else {
        format!("{}+{}", operation, words_csv)
    };

    let parents: Vec<_> = parent.into_iter().collect();
    let signer = SignerId::new(SigAlgKind::Ed25519, fp);
    let anchor = Anchor::builder(signer, payload_hash)
        .with_parents(parents)
        .with_mutations(mutations)
        .build();
    let signed = anchor.sign(priv_pem, &pub_pem, SigAlgKind::Ed25519)?;
    let extfields: BTreeMap<String, String> = signed.to_extfields();
    Ok(etree::TextNode::Chain { extfields })
}

/// `verify-chain` implementation: parse each file, collect CHAIN
/// blocks into an [`AnchorDag`], verify signatures against the
/// caller-supplied trust roots. Exit non-zero on any failure.
fn verify_chain_files(common: CommonArgs, a: VerifyChainSubcmd) -> Result<()> {
    // Load trust roots into a fingerprint → PEM map.
    let mut trust: HashMap<String, String> = HashMap::new();
    for pem_path in &a.trust_roots {
        let pem = fs::read_to_string(pem_path)?;
        let fp = capability::KeyFp::from_pem(&pem)?;
        trust.insert(fp.to_hex(), pem);
    }

    let cap_policy = common
        .policy_file
        .as_ref()
        .map(|p| cappolicy::CapPolicy::load_file(p))
        .transpose()?;

    let policy = resolve_policy(&common)?;
    let mut paops = ParseOps::new(policy)?;
    apply_common(&common, &mut paops);

    let mut json_reports: Vec<output::VerifyChainFileReport> = Vec::new();
    let mut any_failure = false;
    for path_in in &a.files {
        let result = verify_chain_one_file(path_in, &mut paops, &trust, cap_policy.as_ref());
        match common.format {
            output::OutputFormat::Text => match &result {
                Ok(()) => println!("OK    {}", path_in),
                Err(e) => {
                    any_failure = true;
                    eprintln!("FAIL  {}: {}", path_in, e);
                }
            },
            output::OutputFormat::Json => {
                let report = verify_chain_report_from_result(path_in, &result, &mut paops);
                if !report.ok {
                    any_failure = true;
                }
                json_reports.push(report);
            }
        }
    }

    if matches!(common.format, output::OutputFormat::Json) {
        let payload = output::VerifyChainOutput {
            ok: !any_failure,
            files: json_reports,
        };
        println!("{}", output::to_json(&payload)?);
    }

    if any_failure {
        Err(Error::msg("one or more files failed chain verification"))
    } else {
        Ok(())
    }
}

/// Build a JSON-friendly per-file report from a verify result. Even on
/// failure, we want to surface the structured errors (and as much of
/// the DAG as we parsed before the failure) rather than a bare string.
fn verify_chain_report_from_result(
    path_in: &str,
    result: &Result<()>,
    paops: &mut ParseOps,
) -> output::VerifyChainFileReport {
    let (ok, message) = match result {
        Ok(()) => (true, None),
        Err(e) => (false, Some(e.to_string())),
    };

    // Re-parse to collect the DAG info. On success this matches what
    // verify_chain_one_file already did; on failure, we re-parse here
    // because the error path returns early without exposing the DAG.
    let reader: Box<dyn BufRead> = if path_in == "-" {
        Box::new(BufReader::new(std::io::stdin()))
    } else {
        match File::open(path_in) {
            Ok(f) => Box::new(BufReader::new(f)),
            Err(_) => {
                return output::VerifyChainFileReport {
                    path: path_in.to_string(),
                    ok: false,
                    anchors_total: 0,
                    signers: Vec::new(),
                    forks: Vec::new(),
                    errors: vec![output::VerifyError {
                        anchor: None,
                        message: message.unwrap_or_else(|| "unknown error".into()),
                    }],
                };
            }
        }
    };
    paops.runtime.fname = path_in.into();
    let tree = match etree::parse(reader, paops) {
        Ok(t) => t,
        Err(e) => {
            return output::VerifyChainFileReport {
                path: path_in.to_string(),
                ok: false,
                anchors_total: 0,
                signers: Vec::new(),
                forks: Vec::new(),
                errors: vec![output::VerifyError {
                    anchor: None,
                    message: e.to_string(),
                }],
            };
        }
    };

    let mut dag = ledger::AnchorDag::new();
    if let Err(e) = collect_chain_anchors(&tree, &mut dag) {
        return output::VerifyChainFileReport {
            path: path_in.to_string(),
            ok: false,
            anchors_total: 0,
            signers: Vec::new(),
            forks: Vec::new(),
            errors: vec![output::VerifyError {
                anchor: None,
                message: e.to_string(),
            }],
        };
    }

    let tips = dag.tips();
    let signers: Vec<String> = dag
        .iter()
        .map(|(_, s)| s.anchor.signer.to_string())
        .collect();
    let forks: Vec<output::ForkPoint> = tips
        .into_iter()
        .map(|id| {
            let parents = dag
                .get(&id)
                .map(|s| s.anchor.parents.iter().map(|p| p.to_string()).collect())
                .unwrap_or_default();
            output::ForkPoint {
                anchor: id.to_string(),
                parents,
            }
        })
        .collect();

    let errors = match message {
        Some(m) => vec![output::VerifyError {
            anchor: None,
            message: m,
        }],
        None => Vec::new(),
    };

    output::VerifyChainFileReport {
        path: path_in.to_string(),
        ok,
        anchors_total: dag.len(),
        signers,
        forks,
        errors,
    }
}

fn verify_chain_one_file(
    path_in: &str,
    paops: &mut ParseOps,
    trust: &HashMap<String, String>,
    cap_policy: Option<&cappolicy::CapPolicy>,
) -> Result<()> {
    paops.runtime.fname = path_in.into();
    let reader: Box<dyn BufRead> = if path_in == "-" {
        Box::new(BufReader::new(std::io::stdin()))
    } else {
        Box::new(BufReader::new(File::open(path_in).map_err(|e| {
            Error::Msg(format!("Failed to open {}: {}", path_in, e))
        })?))
    };
    let tree = etree::parse(reader, paops)?;

    // Signature + DAG verification.
    let mut dag = ledger::AnchorDag::new();
    collect_chain_anchors(&tree, &mut dag)?;
    let report = dag.verify_signatures(|fp_hex| trust.get(fp_hex).cloned());

    let mut errors: Vec<String> = Vec::new();
    for r in &report.reports {
        if !r.ok {
            if let Some(ref e) = r.error {
                errors.push(format!("{}: {}", r.id, e));
            }
        }
        if let Some(p) = cap_policy {
            if let Some(signed) = dag.get(&r.id) {
                if !p.trust_root_allows(&signed.anchor.signer) {
                    errors.push(format!(
                        "{}: signer {} not in policy trust_roots",
                        r.id, signed.anchor.signer
                    ));
                }
            }
        }
    }

    if let Some(p) = cap_policy {
        if p.chain.require_monotonic_timestamps {
            errors.extend(check_monotonic_timestamps(&dag));
        }
    }

    // Content integrity: recompute payload_hash for each CHAIN block
    // over the file state BEFORE that block (tree prefix), and compare
    // with the recorded `payload:` field. Mismatch means content was
    // tampered after the anchor was created.
    let payload_errors = verify_payload_hashes(&tree, paops)?;
    errors.extend(payload_errors);

    if !errors.is_empty() {
        return Err(Error::msg(format!(
            "{} anchor(s) failed verification: {}",
            errors.len(),
            errors.join("; ")
        )));
    }
    Ok(())
}

/// For each CHAIN block at position i, recompute SHA3-256 over
/// tree[0..i] (all nodes before this CHAIN) and compare with the
/// recorded `payload:` field. Mismatch means the file was tampered
/// after the anchor was created.
///
/// Returns a list of human-readable error strings (empty = all
/// payloads match).
fn verify_payload_hashes(tree: &etree::TextTree, paops: &mut ParseOps) -> Result<Vec<String>> {
    let policy = crate::crypto::CryptoPolicyDefault {};
    let mut errors = Vec::new();
    let mut prefix: etree::TextTree = Vec::new();

    for node in tree {
        if let etree::TextNode::Chain { extfields } = node {
            // Recompute payload over everything we've seen so far
            // (i.e., all nodes BEFORE this CHAIN).
            let blob = etree::tree_to_blob(&prefix, paops)?;
            let recomputed = crate::crypto::hexdigest("sha3-256", &blob, &policy)?;

            let recorded = extfields.get("payload").map(|s| s.as_str()).unwrap_or("");
            if recomputed != recorded {
                errors.push(format!(
                    "payload mismatch: anchor payload={} but file content hashes to {}",
                    recorded, recomputed
                ));
            }
            // The CHAIN node itself becomes part of the prefix for
            // the NEXT anchor (so tampering an anchor also breaks
            // subsequent anchors).
        }
        prefix.push(node.clone());
    }
    Ok(errors)
}

/// Walks the DAG in insertion order and reports any anchor whose
/// timestamp is strictly less than the maximum timestamp of its
/// parents. Anchors without a timestamp are skipped (treated as
/// not-monotonic-data). Empty timestamps on every anchor → no errors.
fn check_monotonic_timestamps(dag: &ledger::AnchorDag) -> Vec<String> {
    let mut errors = Vec::new();
    for (id, signed) in dag.iter() {
        let Some(child_ts) = signed.anchor.timestamp.as_ref() else {
            continue;
        };
        for parent_id in &signed.anchor.parents {
            let Some(parent) = dag.get(parent_id) else {
                continue;
            };
            let Some(parent_ts) = parent.anchor.timestamp.as_ref() else {
                continue;
            };
            if child_ts < parent_ts {
                errors.push(format!(
                    "{}: timestamp {} older than parent {} ({})",
                    id, child_ts, parent_id, parent_ts
                ));
            }
        }
    }
    errors
}

/// Walk a parsed tree and push every `TextNode::Chain` into the DAG.
/// Recurses into `BeginEnd` and `Encrypted` children; CHAIN blocks
/// typically live at the top level but can appear inside any block.
fn collect_chain_anchors(tree: &etree::TextTree, dag: &mut ledger::AnchorDag) -> Result<()> {
    for node in tree {
        match node {
            etree::TextNode::Chain { extfields } => {
                let signed = ledger::SignedAnchor::from_extfields(extfields)?;
                dag.push(signed)
                    .map_err(|e| Error::msg(format!("DAG construction failed: {}", e)))?;
            }
            etree::TextNode::BeginEnd { txt, .. } | etree::TextNode::Encrypted { txt, .. } => {
                collect_chain_anchors(txt, dag)?;
            }
            _ => {}
        }
    }
    Ok(())
}

fn read_file_or_stdin(path: Option<&Path>) -> Result<Vec<u8>> {
    match path {
        Some(p) if p != Path::new("-") => Ok(fs::read(p)?),
        _ => {
            use std::io::Read;
            let mut buf = Vec::new();
            std::io::stdin().read_to_end(&mut buf)?;
            Ok(buf)
        }
    }
}

fn write_key_or_stdout(path: Option<&Path>, data: &[u8]) -> Result<()> {
    match path {
        Some(p) if p != Path::new("-") => {
            fs::write(p, data)?;
            // Private keys should be owner-read-only on Unix.
            // We can't tell from the data whether this is a priv
            // or pub key, so set 0600 unconditionally — pubkeys
            // don't need to be world-readable (the caller usually
            // distributes them via other channels).
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                fs::set_permissions(p, fs::Permissions::from_mode(0o600))?;
            }
        }
        _ => {
            std::io::stdout().write_all(data)?;
        }
    }
    Ok(())
}