scrt4 0.4.6

Hardware-bound secrets vault for AI coding agents. Secrets are injected into a subprocess and scrubbed from its output, so an agent can use a credential without ever seeing it. The vault key is derived from a FIDO2 authenticator via WebAuthn PRF and is never stored.
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
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
#!/usr/bin/env bash
# scrt4-core — trusted computing base for the v0.2 architecture
#
# This file is the core of the v0.2 scrt4 distribution. It contains:
#
#   1. The auth gates and vault-protocol handoffs that are in the trusted
#      computing base for formal verification (issue #60). These functions
#      are annotated with a `# TCB:` comment block above them. Grep for
#      `^# TCB:` to enumerate the in-scope items.
#
#   2. The module registration system. Modules under
#      daemon/bin/scrt4-modules/<name>.sh call `_register_command NAME FN`
#      from a `scrt4_module_<name>_register` function. The build script
#      (scripts/build-scrt4.sh) concatenates this file with the selected
#      modules into a single self-contained bash binary.
#
#   3. The minimum command set every distribution must support:
#      help, status, unlock, lock/logout, list, add, run, view (text).
#      Everything else lives in a module.
#
# This file does not ship as-is. The build script produces
# /usr/local/bin/scrt4 by concatenating this file and the module files
# selected by `modules.manifest` for the current distribution. The marker
# `## SCRT4_MODULE_SOURCE_HOOK ##` below is where the build script injects
# module source.
#
# The v0.1.0 monolith at daemon/bin/scrt4 is unchanged by the v0.2 work.
# It still ships the hardened release on main. This file is parallel
# infrastructure on the architecture/v0.2.0 branch.

# errexit + pipefail stay on. `nounset` is intentionally OFF: bash 3.2
# (macOS) treats `"${arr[@]}"` on an empty array as an unbound-variable
# error, which poisons every lazy-init loop (command registry, module
# arg vectors, etc.). Bash 4.4+ fixed this; 3.2 never will. Rather than
# wrap every array expansion in `"${arr[@]+"${arr[@]}"}"` we drop -u.
# The TCB is in the Rust daemon — the shell CLI is the dispatcher.
set -eo pipefail

# ── Runtime requirements ────────────────────────────────────────────
# Bash 3.2 is what macOS ships (Apple froze it over GPLv3). We target
# 3.2+ so a stock Mac can run this without `brew install bash`. Anything
# below 3.2 (genuinely rare in 2026 — mostly very old enterprise Linux)
# must bail cleanly rather than die with cryptic parse errors.
if [ -n "${BASH_VERSION:-}" ]; then
    _scrt4_bash_major="${BASH_VERSION%%.*}"
    _scrt4_bash_minor="${BASH_VERSION#*.}"; _scrt4_bash_minor="${_scrt4_bash_minor%%.*}"
    if [ "${_scrt4_bash_major:-0}" -lt 3 ] \
    || { [ "${_scrt4_bash_major:-0}" -eq 3 ] && [ "${_scrt4_bash_minor:-0}" -lt 2 ]; }; then
        printf 'scrt4: requires bash 3.2 or newer; found %s\n' "$BASH_VERSION" >&2
        printf '  macOS: brew install bash\n' >&2
        printf '  linux: upgrade coreutils / bash package via your package manager\n' >&2
        exit 1
    fi
    unset _scrt4_bash_major _scrt4_bash_minor
fi

# ── Constants ────────────────────────────────────────────────────────

# VERSION is overwritten at build time by scripts/build-scrt4.sh from
# the SCRT4_VERSION env. The "-dev" default is only seen when someone
# sources scrt4-core directly (not the released binary).
VERSION="0.2.14-community"
# Socket path must match daemon/src/main.rs::get_socket_path. On Linux
# both resolve $XDG_RUNTIME_DIR/scrt4.sock. On macOS XDG_RUNTIME_DIR is
# unset, so the daemon falls back to /tmp/scrt4-<uid>.sock — this shell
# client has to use the same uid-suffixed fallback or every send_request
# silently fails (connect error is swallowed, CLI prints nothing).
if [ -n "${XDG_RUNTIME_DIR:-}" ]; then
    SOCKET="${XDG_RUNTIME_DIR}/scrt4.sock"
else
    SOCKET="/tmp/scrt4-$(id -u).sock"
fi

# CONFIG_DIR follows the daemon's keystore::config_dir(). Modules read
# this for tags.json, backup paths, etc. Must stay in sync with
# daemon/src/keystore.rs.
CONFIG_DIR="$HOME/.scrt4"
export CONFIG_DIR

RELAY_BASE="https://auth.llmsecrets.com"
RELAY_POLL="https://llmsecrets-auth.vercel.app"  # CLI polling host (bypasses corporate filters)

# Color constants — exported to modules
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'
export RED GREEN YELLOW CYAN BOLD NC

# CLI mode flag (set by --cli or "agent" submode) — skips zenity even if a
# display is reachable. Used by AI-agent flows that can't see GUI dialogs.
FORCE_CLI=false

# Agent mode flag (set by --agent) — implies --cli and switches the QR
# renderer to plain ASCII with loud "pass this through" markers around it
# so tools like Claude Code include the QR verbatim in their response
# instead of summarizing/truncating the ANSI escape sequences.
AGENT_MODE=false

# ── Module registration system (issue #61) ───────────────────────────

# Map of registered command names to handler function names. We use two
# parallel arrays for bash 3.x compatibility (macOS ships /bin/bash 3.2).
declare -a _SCRT4_CMDS=()
declare -a _SCRT4_HANDLERS=()
declare -a _SCRT4_MODULES_REGISTERED=()

# _register_command NAME HANDLER_FN
#
# Public API. Modules call this from their *_register function to claim
# a subcommand name. Re-registration is rejected so two modules can't
# silently shadow each other.
_register_command() {
    local name="$1"
    local handler="$2"

    local existing
    for existing in "${_SCRT4_CMDS[@]}"; do
        if [ "$existing" = "$name" ]; then
            printf 'scrt4-core: command "%s" already registered\n' "$name" >&2
            return 1
        fi
    done

    _SCRT4_CMDS+=("$name")
    _SCRT4_HANDLERS+=("$handler")
}

# _resolve_command NAME -> echoes handler function or returns 1
_resolve_command() {
    local name="$1"
    local i
    for i in "${!_SCRT4_CMDS[@]}"; do
        if [ "${_SCRT4_CMDS[$i]}" = "$name" ]; then
            echo "${_SCRT4_HANDLERS[$i]}"
            return 0
        fi
    done
    return 1
}

# _module_loaded NAME -> 0 if loaded, 1 if not
_module_loaded() {
    local name="$1"
    local m
    for m in "${_SCRT4_MODULES_REGISTERED[@]}"; do
        if [ "$m" = "$name" ]; then
            return 0
        fi
    done
    return 1
}

# _modules_init — called after all module source has been injected. Each
# module file defines a function `scrt4_module_<name>_register`; we
# discover and call them all here.
_modules_init() {
    local fn
    for fn in $(declare -F | awk '/^declare -f scrt4_module_.*_register$/ {print $3}'); do
        local name="${fn#scrt4_module_}"
        name="${name%_register}"
        if _module_loaded "$name"; then
            continue
        fi
        "$fn"
        _SCRT4_MODULES_REGISTERED+=("$name")
    done
}

# ── GUI detection (shared with all modules) ──────────────────────────

# True iff a usable GUI is available: zenity is installed AND a display
# is reachable. `command -v zenity` alone is not enough — the hardened
# Docker image has zenity installed but no DISPLAY, so every zenity call
# fails silently. v0.1.0 PR #55 shipped this same fix in the monolith.
#
# SCRT4_NO_GUI=1 forces a CLI-only path for users who have zenity +
# DISPLAY set for unrelated reasons (e.g. WSL) but don't want scrt4 to
# pop dialogs.
_has_gui() {
    # SCRT4_FORCE_GUI=1 overrides dev-mode suppression so the GUI wizard
    # flows can be exercised from the dev-cloud-crypt harness. Everything
    # else still requires zenity + an actual display.
    if [ "${SCRT4_FORCE_GUI:-0}" != "1" ]; then
        [ "${SCRT4_DEV_MODE:-0}" = "1" ] && return 1
        [ "${SCRT4_NO_GUI:-0}" = "1" ] && return 1
    fi
    command -v zenity >/dev/null 2>&1 || return 1
    [ -n "${DISPLAY:-}" ] || [ -n "${WAYLAND_DISPLAY:-}" ]
}
export -f _has_gui

# ── Standard panel helpers (scrt4 GUI contract) ──────────────────────
# Every module's GUI is built from exactly three panel kinds so cross-
# module wizards feel seamless. See docs/issues/module-gui-spec.md.
#
# Purpose rule: the GUI is for PLAINTEXT (decrypted content the user
# needs to read/act on). It never renders ciphertext. If a panel has
# no plaintext to show (e.g. after encrypt), say so explicitly.

# _scrt4_gui_list_panel <title> <subtitle> [CRIT|NORMAL|TAB-separated-row ...]
# Rows are 4 TAB-separated fields:  crit_marker  id  name  summary
# crit_marker is "CRIT" or "" — renders as a leading ● in column 1.
# Prints the chosen ID on stdout (empty if cancelled), exit 0 always.
_scrt4_gui_list_panel() {
    local title="$1" subtitle="$2"; shift 2
    local rows=()
    local r marker id name summary
    for r in "$@"; do
        marker="${r%%$'\t'*}";      r="${r#*$'\t'}"
        id="${r%%$'\t'*}";          r="${r#*$'\t'}"
        name="${r%%$'\t'*}";        summary="${r#*$'\t'}"
        [ "$marker" = "CRIT" ] && marker="" || marker=" "
        rows+=( "$marker" "$id" "$name" "$summary" )
    done
    zenity --list --title="$title" --text="$subtitle" \
        --width=820 --height=420 \
        --column="!" --column="ID" --column="Name" --column="Summary" \
        --print-column=2 \
        "${rows[@]}" 2>/dev/null || true
}
export -f _scrt4_gui_list_panel

# _scrt4_gui_action_panel <title> <body> [--critical] [--already-ciphertext]
# Renders the plaintext body and asks for confirm. --critical adds an
# unmissable banner. --already-ciphertext replaces body with the
# "body hidden by design" disclaimer (Wizard B step 4).
# Exit 0 on confirm, non-zero on cancel.
_scrt4_gui_action_panel() {
    local title="$1" body="$2"; shift 2
    local critical=false ciphertext=false
    while [ $# -gt 0 ]; do
        case "$1" in
            --critical)           critical=true ;;
            --already-ciphertext) ciphertext=true ;;
        esac
        shift
    done
    local banner=""
    $critical      && banner="⚠  CRITICAL — step-up auth required. Review carefully.

"
    if $ciphertext; then
        body="Body is encrypted. Hidden by design — nothing readable to show here.

(Metadata only is displayed below.)

${body}"
    fi
    zenity --question --title="$title" \
        --width=640 \
        --ok-label="Confirm" --cancel-label="Cancel" \
        --text="${banner}${body}" 2>/dev/null
}
export -f _scrt4_gui_action_panel

# _scrt4_gui_status_panel <title> [OK|WARN|FAIL<TAB>label<TAB>detail ...]
_scrt4_gui_status_panel() {
    local title="$1"; shift
    local rows=()
    local r state label detail icon
    for r in "$@"; do
        state="${r%%$'\t'*}";  r="${r#*$'\t'}"
        label="${r%%$'\t'*}";  detail="${r#*$'\t'}"
        case "$state" in
            OK)   icon="" ;;
            WARN) icon="!" ;;
            FAIL) icon="" ;;
            *)    icon="?" ;;
        esac
        rows+=( "$icon" "$label" "$detail" )
    done
    zenity --list --title="$title" --text="Module health" \
        --width=700 --height=360 \
        --column="" --column="Check" --column="Detail" \
        "${rows[@]}" 2>/dev/null || true
}
export -f _scrt4_gui_status_panel

# Run a command in the background if a GUI is usable and we're not in
# CLI mode. Used by zenity-based flows that should not block the terminal.
_bg_if_gui() {
    local has_cli=false
    local arg
    for arg in "$@"; do
        [ "$arg" = "--cli" ] && has_cli=true
    done
    if [ "$FORCE_CLI" = true ] || [ "$has_cli" = true ] || ! _has_gui; then
        "$@"
    else
        "$@" &
        disown
    fi
}
export -f _bg_if_gui

# ── Daemon I/O ───────────────────────────────────────────────────────

# send_request JSON [TIMEOUT] — sends a single newline-terminated JSON
# message to the daemon socket and returns the response on stdout.
#
# This is the only path through which CLI code reaches the daemon. All
# vault and session state is owned by the daemon; the CLI is a thin
# client that authenticates the user and shapes commands.
send_request() {
    local json="$1"
    local timeout="${2:-10}"
    # If the socket doesn't exist, tell the user instead of swallowing the
    # failure. This used to silently return empty, leaving callers with
    # "Setup failed: Unknown error" or (worse) no output at all.
    if [ ! -S "$SOCKET" ]; then
        printf 'scrt4: daemon socket not found at %s\n' "$SOCKET" >&2
        printf '  Is the daemon running? Try: scrt4 daemon  (or check launchctl / systemctl)\n' >&2
        return 1
    fi
    if command -v socat >/dev/null 2>&1; then
        echo "$json" | socat - UNIX-CONNECT:"$SOCKET" 2>/dev/null
    else
        python3 -c "
import socket, sys
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.settimeout($timeout)
s.connect('$SOCKET')
data = b' '.join(sys.stdin.buffer.read().split()) + b'\n'
s.sendall(data)
s.shutdown(socket.SHUT_WR)
chunks = []
while True:
    try:
        d = s.recv(65536)
        if not d: break
        chunks.append(d)
    except: break
s.close()
sys.stdout.buffer.write(b''.join(chunks))
" <<< "$json" 2>/dev/null
    fi
}
export -f send_request

# ── WebAuthn flow helpers (ported from v0.1.0 monolith, ISS016) ──────
#
# These helpers drive the QR-code + relay polling flow used by cmd_unlock
# and cmd_setup in the hardened distribution. They are ported verbatim
# from daemon/bin/scrt4 (the v0.1.0 monolith) so the v0.2 distribution
# no longer needs to delegate to the monolith for unlock/setup.

# show_qr_terminal URL — render a QR code in the terminal.
#
# ANSIUTF8 uses half-block glyphs (▀▄) to pack 2 QR rows per terminal
# row — compact and scans reliably across platforms. Override with
# SCRT4_QR_FORMAT if a specific terminal needs a different format.
# Always prints the URL as well so headless/SSH sessions that can't
# render blocks still have something to copy.
show_qr_terminal() {
    local url="$1"
    local qr_format="${SCRT4_QR_FORMAT:-ANSIUTF8}"

    # Agent mode: plain ASCII glyphs (`#` / space) with banner markers.
    # Agent harnesses relay stdout as text; ANSI-escaped block glyphs
    # often get collapsed or truncated, so we switch to a format that
    # survives a round-trip through a chat UI and loudly instruct the
    # agent not to strip it.
    if [ "$AGENT_MODE" = true ]; then
        qr_format=ASCII
        echo ""
        echo "=============================================================="
        echo "  AGENT: DO NOT SUMMARIZE OR TRUNCATE THE QR CODE BELOW."
        echo "  Pass it through VERBATIM in your next response so the user"
        echo "  can scan it with their phone. Keep the '#' grid intact."
        echo "=============================================================="
        echo ""
        if command -v qrencode >/dev/null 2>&1; then
            qrencode -t "$qr_format" -m 2 -l L "$url"
        else
            echo "  Install qrencode for QR display (apt install qrencode / brew install qrencode)"
        fi
        echo ""
        echo "=============================================================="
        echo "  END QR CODE. URL fallback (open on phone if QR won't scan):"
        echo "  ${url}"
        echo "=============================================================="
        echo ""
        return 0
    fi

    echo ""
    echo -e "  ${YELLOW}If the QR code is cut off, press Ctrl+0 to expand the terminal${NC}"
    echo ""
    if command -v qrencode >/dev/null 2>&1; then
        qrencode -t "$qr_format" -m 1 -l L "$url"
    else
        echo -e "  ${YELLOW}Install qrencode for QR display (apt install qrencode / brew install qrencode)${NC}"
    fi
    echo ""
    echo -e "  ${CYAN}If the QR code isn't working, copy this URL to your phone:${NC}"
    echo -e "  ${url}"
    echo ""
}

# poll_relay SESSION_ID — poll the relay endpoint until the encrypted
# payload appears, then echo it on stdout. Blocks indefinitely. Caller
# is responsible for any timeout/cancellation wrapping.
poll_relay() {
    local session_id="$1"
    local url="${RELAY_POLL}/api/relay/${session_id}"
    while true; do
        local body
        body=$(curl -sf "$url" 2>/dev/null) || true
        if [ -n "$body" ]; then
            local payload
            payload=$(echo "$body" | jq -r '.payload // empty' 2>/dev/null)
            if [ -n "$payload" ]; then
                echo "$payload"
                return 0
            fi
        fi
        sleep 1.5
    done
}

# poll_relay_gui SESSION_ID URL — wrap poll_relay in a Zenity pulsating
# progress dialog so the terminal doesn't block silently. Used only when
# _has_gui is true. Echoes the payload on stdout on success, returns 1
# on user cancel.
poll_relay_gui() {
    local session_id="$1"
    local url="$2"
    local result_file="/tmp/scrt4-result-$$.txt"

    (
        while true; do
            local body
            body=$(curl -sf "${RELAY_POLL}/api/relay/${session_id}" 2>/dev/null) || true
            if [ -n "$body" ]; then
                local payload
                payload=$(echo "$body" | jq -r '.payload // empty' 2>/dev/null)
                if [ -n "$payload" ]; then
                    echo "$payload" > "$result_file"
                    exit 0
                fi
            fi
            sleep 1.5
        done
    ) &
    local poll_pid=$!

    (
        while kill -0 $poll_pid 2>/dev/null; do
            if [ -f "$result_file" ]; then
                echo "100"
                break
            fi
            echo "#"
            sleep 1
        done
    ) | zenity --progress --pulsate --auto-close \
        --title="scrt4 — Waiting for Phone" \
        --text="Scan the QR code in the terminal with your phone camera.\n\nOr open this URL on your phone:\n<span font_family='monospace' font='10'>${url}</span>\n\nWaiting for authentication..." \
        --cancel-label="  Cancel  " \
        --width=520 2>/dev/null
    local zenity_rc=$?

    if [ $zenity_rc -ne 0 ] && [ ! -f "$result_file" ]; then
        kill $poll_pid 2>/dev/null
        wait $poll_pid 2>/dev/null
        rm -f "$result_file"
        return 1
    fi

    wait $poll_pid 2>/dev/null

    local result=""
    [ -f "$result_file" ] && result=$(cat "$result_file")
    rm -f "$result_file"

    if [ -z "$result" ]; then
        return 1
    fi
    echo "$result"
}

# shorten_qr_url FULL_URL SESSION_ID — ask the relay to issue a 4-digit
# AuthCode so users can type a code on auth.llmsecrets.com instead of
# scanning a QR. Echoes the original URL unchanged; the code itself is
# stored in the global AUTHCODE_DISPLAY so callers can print it.
AUTHCODE_DISPLAY=""

shorten_qr_url() {
    local full_url="$1"
    local session_id="$2"
    AUTHCODE_DISPLAY=""

    local shorten_resp
    shorten_resp=$(curl -sf -X POST "${RELAY_POLL}/api/relay/shorten" \
        -H "Content-Type: application/json" \
        -d "{\"session_id\":\"${session_id}\"}" 2>/dev/null) || true

    if [ -n "$shorten_resp" ]; then
        local code
        code=$(echo "$shorten_resp" | jq -r '.code // empty' 2>/dev/null)
        if [ -n "$code" ]; then
            AUTHCODE_DISPLAY="$code"
        fi
    fi

    echo "$full_url"
}

# trigger_push SESSION_ID AUTH_URL — fire a web-push notification to any
# phone that previously registered with auth.llmsecrets.com for this
# relay. Non-blocking, best-effort; failures are silent because this is
# a convenience on top of the QR/AuthCode path, not a hard dependency.
trigger_push() {
    local session_id="$1"
    local auth_url="$2"
    [ -z "$session_id" ] || [ -z "$auth_url" ] && return 0
    local push_json
    push_json=$(jq -nc --arg sid "$session_id" --arg url "$auth_url" \
        '{session_id: $sid, auth_url: $url}')
    curl -sf -X POST "${RELAY_POLL}/api/relay/push" \
        -H "Content-Type: application/json" \
        -d "$push_json" \
        -o /dev/null 2>/dev/null &
}

# open_browser URL — open URL in the system browser. Supports WSL2
# (cmd.exe), Linux (xdg-open), and macOS (open). Silent on failure —
# callers should still print the URL to the terminal so the user has a
# copyable fallback.
open_browser() {
    local url="$1"
    if command -v wslpath >/dev/null 2>&1 && command -v cmd.exe >/dev/null 2>&1; then
        cmd.exe /c start "" "$url" >/dev/null 2>&1
    elif command -v xdg-open >/dev/null 2>&1; then
        xdg-open "$url" >/dev/null 2>&1 &
    elif command -v open >/dev/null 2>&1; then
        open "$url" >/dev/null 2>&1 &
    else
        echo -e "  ${YELLOW}Could not open browser. Open this URL manually:${NC}" >&2
        echo -e "  ${url}" >&2
    fi
}

# run_unlock_flow [TTL] — drive the remote QR/phone unlock flow. Asks
# the daemon for a relay URL, renders the QR, polls for the encrypted
# payload, then submits it back to the daemon for completion.
run_unlock_flow() {
    local ttl="${1:-72000}"

    local response
    response=$(send_request "$(jq -nc --argjson ttl "$ttl" '{method:"unlock_webauthn",params:{ttl:$ttl}}')")
    local success
    success=$(echo "$response" | jq -r '.success // false')
    if [ "$success" != "true" ]; then
        local error
        error=$(echo "$response" | jq -r '.error // "Unknown error"')
        echo -e "${RED}Unlock failed: ${error}${NC}" >&2
        return 1
    fi

    local full_url session_id wrapping_key
    full_url=$(echo "$response" | jq -r '.data.url // empty')
    session_id=$(echo "$response" | jq -r '.data.session_id // empty')
    wrapping_key=$(echo "$response" | jq -r '.data.wrapping_key // empty')

    # If the daemon returned no URL, the unlock already succeeded
    # (e.g. cached session).
    if [ -z "$full_url" ]; then
        local count
        count=$(echo "$response" | jq -r '.data.count // empty')
        if [ -n "$count" ]; then
            echo -e "${GREEN}Unlocked (${count} secrets)${NC}"
        else
            echo -e "${GREEN}OK${NC}"
        fi
        return 0
    fi

    local url
    url=$(shorten_qr_url "$full_url" "$session_id")

    # Fire push notification to any phones subscribed via auth.llmsecrets.com.
    # Always uses the full URL (with fragment) so the tap lands on a
    # page that has the wrapping key.
    trigger_push "$session_id" "$full_url"

    echo -e "  ${CYAN}Auth URL:${NC} ${url}" >&2
    if [ -n "$AUTHCODE_DISPLAY" ]; then
        echo "" >&2
        echo -e "  ${CYAN}AuthCode:${NC}  ${GREEN}${AUTHCODE_DISPLAY}${NC}" >&2
        echo -e "  Enter at ${CYAN}auth.llmsecrets.com${NC}" >&2
        echo "" >&2
    fi

    # Always print the QR in the terminal — the zenity dialog text
    # references it ("scan the QR code in the terminal"), and CLI-only
    # users obviously need it too.
    show_qr_terminal "$url"
    if [ -n "$AUTHCODE_DISPLAY" ]; then
        echo -e "  Scan the QR code or enter AuthCode ${GREEN}${AUTHCODE_DISPLAY}${NC} at auth.llmsecrets.com"
    else
        echo -e "  Scan the QR code with your phone camera."
    fi
    echo -e "  Then tap 'Unlock with Passkey' on the page."
    echo ""

    local payload=""
    if [ "$FORCE_CLI" = false ] && _has_gui; then
        payload=$(poll_relay_gui "$session_id" "$url") || {
            echo -e "${YELLOW}GUI unavailable, switching to terminal mode...${NC}"
            echo -ne "  ${CYAN}Waiting for phone...${NC}"
            payload=$(poll_relay "$session_id")
            echo -e " ${GREEN}received!${NC}"
        }
    else
        echo -ne "  ${CYAN}Waiting for phone...${NC}"
        payload=$(poll_relay "$session_id")
        echo -e " ${GREEN}received!${NC}"
    fi

    echo -e "${CYAN}Decrypting vault...${NC}"
    local complete_json
    complete_json=$(jq -cn \
        --arg payload "$payload" \
        --arg key "$wrapping_key" \
        --argjson ttl "$ttl" \
        '{method:"unlock_webauthn_complete",params:{encrypted_payload:$payload,wrapping_key:$key,ttl:$ttl}}')

    response=$(send_request "$complete_json")
    success=$(echo "$response" | jq -r '.success // false')
    if [ "$success" = "true" ]; then
        local count
        count=$(echo "$response" | jq -r '.data.count // 0')
        echo -e "${GREEN}Unlocked ${count} secret(s).${NC}"
    else
        local error
        error=$(echo "$response" | jq -r '.error // "Unknown error"')
        echo -e "${RED}Unlock failed: ${error}${NC}" >&2
        return 1
    fi
}

# run_setup_flow — drive the remote passkey enrollment flow. Same shape
# as run_unlock_flow but uses the setup_webauthn / setup_webauthn_complete
# RPC pair and carries a prf_salt_b64 in the completion payload.
run_setup_flow() {
    local response
    response=$(send_request '{"method":"setup_webauthn"}')
    local success
    success=$(echo "$response" | jq -r '.success // false')
    if [ "$success" != "true" ]; then
        local error
        error=$(echo "$response" | jq -r '.error // "Unknown error"')
        echo -e "${RED}Setup failed: ${error}${NC}" >&2
        return 1
    fi

    local full_url session_id wrapping_key prf_salt_b64
    full_url=$(echo "$response" | jq -r '.data.url')
    session_id=$(echo "$response" | jq -r '.data.session_id')
    wrapping_key=$(echo "$response" | jq -r '.data.wrapping_key')
    prf_salt_b64=$(echo "$response" | jq -r '.data.prf_salt_b64')

    local url
    url=$(shorten_qr_url "$full_url" "$session_id")

    # Fire push notification to any phones subscribed via auth.llmsecrets.com.
    # Always uses the full URL (with fragment) so the tap lands on a
    # page that has the wrapping key.
    trigger_push "$session_id" "$full_url"

    echo -e "  ${CYAN}Auth URL:${NC} ${url}" >&2
    if [ -n "$AUTHCODE_DISPLAY" ]; then
        echo "" >&2
        echo -e "  ${CYAN}AuthCode:${NC}  ${GREEN}${AUTHCODE_DISPLAY}${NC}" >&2
        echo -e "  Enter at ${CYAN}auth.llmsecrets.com${NC}" >&2
        echo "" >&2
    fi

    show_qr_terminal "$url"
    if [ -n "$AUTHCODE_DISPLAY" ]; then
        echo -e "  Scan the QR code or enter AuthCode ${GREEN}${AUTHCODE_DISPLAY}${NC} at auth.llmsecrets.com"
    fi
    echo -e "  Then tap 'Register Passkey' on the page."
    echo ""

    local payload=""
    if [ "$FORCE_CLI" = false ] && _has_gui; then
        payload=$(poll_relay_gui "$session_id" "$url") || {
            echo -e "${YELLOW}GUI unavailable, switching to terminal mode...${NC}"
            echo -ne "  ${CYAN}Waiting for phone...${NC}"
            payload=$(poll_relay "$session_id")
            echo -e " ${GREEN}received!${NC}"
        }
    else
        echo -ne "  ${CYAN}Waiting for phone...${NC}"
        payload=$(poll_relay "$session_id")
        echo -e " ${GREEN}received!${NC}"
    fi

    echo -e "${CYAN}Completing registration...${NC}"
    local complete_json
    complete_json=$(jq -cn \
        --arg payload "$payload" \
        --arg key "$wrapping_key" \
        --arg salt "$prf_salt_b64" \
        '{method:"setup_webauthn_complete",params:{encrypted_payload:$payload,wrapping_key:$key,prf_salt_b64:$salt}}')

    response=$(send_request "$complete_json")
    success=$(echo "$response" | jq -r '.success // false')
    if [ "$success" = "true" ]; then
        echo -e "${GREEN}Credential registered successfully!${NC}"
        echo -e "${GREEN}Empty secret store created.${NC}"
        echo -e "${CYAN}Add secrets with: scrt4 add KEY=value${NC}"
    else
        local error
        error=$(echo "$response" | jq -r '.error // "Unknown error"')
        echo -e "${RED}Registration failed: ${error}${NC}" >&2
        return 1
    fi
}

# ── TCB: auth gates ──────────────────────────────────────────────────

# TCB: cli session gate
# Verifies: every secret-revealing command path checks for an active
#           daemon session before issuing the secret-reveal request.
#           The check goes to the daemon — the CLI does not cache
#           session state independently.
# Adversary: malicious CLI invocation in a context where the user has
#            not unlocked the vault; should be rejected before the
#            daemon ever sees a reveal request.
ensure_unlocked() {
    local response
    response=$(send_request '{"method":"status"}' 2>/dev/null || true)
    local active
    active=$(echo "$response" | jq -r '.data.active // false' 2>/dev/null || echo "false")
    if [ "$active" = "true" ]; then
        return 0
    fi

    echo -e "${YELLOW}Session not active. Run: ${BOLD}scrt4 unlock${NC}" >&2
    return 1
}

# open_ceremony_browser URL — open the platform-passkey ceremony, in Chrome
# where we can find it.
#
# Deliberately narrower than open_browser. The relay flow is a QR code and
# works anywhere; this ceremony needs an authenticator that exposes the
# WebAuthn PRF extension, and on macOS "the platform authenticator" is not
# one thing — Safari reaches iCloud Keychain, Chrome has its own
# profile-bound authenticator behind Touch ID, and their PRF support differs
# by version. Chrome's is the one we target.
#
# Falls back to the default browser rather than failing: a user with no
# Chrome should still get a shot at it, and the URL is always printed so
# they can paste it wherever they like.
open_ceremony_browser() {
    local url="$1"
    local os
    os=$(uname -s 2>/dev/null || echo unknown)

    if [ "$os" = "Darwin" ]; then
        for app in "Google Chrome" "Chromium" "Microsoft Edge" "Brave Browser"; do
            if open -a "$app" "$url" >/dev/null 2>&1; then
                echo -e "  ${CYAN}Opened in ${app}.${NC}" >&2
                return 0
            fi
        done
    else
        for bin in google-chrome google-chrome-stable chromium chromium-browser microsoft-edge brave-browser; do
            if command -v "$bin" >/dev/null 2>&1; then
                "$bin" "$url" >/dev/null 2>&1 &
                echo -e "  ${CYAN}Opened in ${bin}.${NC}" >&2
                return 0
            fi
        done
    fi

    echo -e "  ${YELLOW}Chrome not found — using your default browser.${NC}" >&2
    echo -e "  ${YELLOW}If registration fails, try again in Chrome.${NC}" >&2
    open_browser "$url"
}

# ── platform passkey (Touch ID / Windows Hello) ───────────────────────
#
# The daemon wraps the EXISTING master key with the PRF output of a
# localhost-rpId credential, so what lands on disk is only openable by a
# live biometric ceremony. That is why setup requires an unlocked session:
# there has to be a master key in memory to wrap.

# run_setup_local_flow — enrol this machine's authenticator.
run_setup_local_flow() {
    local start
    start=$(send_request '{"method":"setup_local"}' 2>/dev/null || true)
    if [ "$(echo "$start" | jq -r '.success // false' 2>/dev/null)" != "true" ]; then
        local err
        err=$(echo "$start" | jq -r '.error // "unknown error"' 2>/dev/null)
        echo -e "${RED}setup --local failed: ${err}${NC}" >&2
        case "$err" in
            *"ession"*|*"master key"*)
                echo -e "${YELLOW}This adds a second way to open a vault that already exists,${NC}" >&2
                echo -e "${YELLOW}so unlock first with your phone: ${NC}scrt4 unlock" >&2 ;;
        esac
        return 1
    fi

    local url
    url=$(echo "$start" | jq -r '.data.url // empty' 2>/dev/null)
    if [ -z "$url" ]; then
        echo -e "${RED}setup --local failed: daemon returned no URL.${NC}" >&2
        return 1
    fi

    echo -e "${CYAN}Registering this device's passkey...${NC}" >&2
    open_ceremony_browser "$url"
    echo -e "  ${CYAN}URL:${NC} ${url}" >&2
    echo -e "  Register a passkey in the browser window (Touch ID, Windows Hello)." >&2
    echo -e "  ${YELLOW}Chrome is the tested browser for this step.${NC}" >&2
    echo "" >&2
    echo -ne "  ${CYAN}Waiting for registration...${NC}" >&2

    local done_resp
    done_resp=$(send_request '{"method":"setup_local_complete"}' 180 2>/dev/null || true)
    echo "" >&2
    if [ "$(echo "$done_resp" | jq -r '.success // false' 2>/dev/null)" = "true" ]; then
        echo -e "${GREEN}Device passkey registered.${NC}" >&2
        echo -e "${GREEN}You can now unlock with: ${NC}scrt4 unlock --local" >&2
        return 0
    fi
    echo -e "${RED}setup --local failed: $(echo "$done_resp" | jq -r '.error // "unknown"')${NC}" >&2
    return 1
}

# run_unlock_local_flow [ttl] — unlock using this machine's authenticator,
# with no phone and no relay. Same ceremony as _wa_gate phase 1.
run_unlock_local_flow() {
    local ttl="${1:-72000}"
    local start
    start=$(send_request "$(jq -nc --argjson t "$ttl" '{method:"unlock_local",params:{ttl:$t}}')" 2>/dev/null || true)
    if [ "$(echo "$start" | jq -r '.success // false' 2>/dev/null)" != "true" ]; then
        local err
        err=$(echo "$start" | jq -r '.error // "unknown error"' 2>/dev/null)
        echo -e "${RED}unlock --local failed: ${err}${NC}" >&2
        echo -e "${YELLOW}If this device has no passkey yet: ${NC}scrt4 unlock && scrt4 setup --local" >&2
        return 1
    fi

    local url
    url=$(echo "$start" | jq -r '.data.url // empty' 2>/dev/null)
    if [ -z "$url" ]; then
        echo -e "${RED}unlock --local failed: daemon returned no URL.${NC}" >&2
        return 1
    fi

    echo -e "${CYAN}Opening browser for authentication...${NC}" >&2
    open_ceremony_browser "$url"
    echo -e "  ${CYAN}URL:${NC} ${url}" >&2
    echo -e "  Authenticate in the browser window." >&2
    echo "" >&2
    echo -ne "  ${CYAN}Waiting for authentication...${NC}" >&2

    local done_resp
    done_resp=$(send_request "$(jq -nc --argjson t "$ttl" '{method:"unlock_local_complete",params:{ttl:$t}}')" 180 2>/dev/null || true)
    echo "" >&2
    if [ "$(echo "$done_resp" | jq -r '.success // false' 2>/dev/null)" = "true" ]; then
        echo -e "${GREEN}Session active.${NC}" >&2
        return 0
    fi
    echo -e "${RED}unlock --local failed: $(echo "$done_resp" | jq -r '.error // "unknown"')${NC}" >&2
    return 1
}

# TCB: webauthn step-up gate
# Verifies: sensitive operations trigger a fresh WebAuthn challenge
#           regardless of session state. The session token alone is
#           insufficient.
# Adversary: a stolen unlock token (e.g. from a snapshot of the daemon's
#            session memory) should not be enough to reveal secrets —
#            the user's authenticator must be physically present at
#            the moment of reveal.
_wa_gate() {
    echo -e "${CYAN}WebAuthn verification required...${NC}" >&2

    # Phase 1: try the localhost browser flow (platform authenticator / hardware key).
    # unlock_local returns a URL for the user to authenticate; unlock_local_complete
    # blocks until the challenge is resolved or times out.
    local _start
    _start=$(send_request '{"method":"unlock_local","params":{"ttl":7200}}' 2>/dev/null || true)
    if [ "$(echo "$_start" | jq -r '.success // false' 2>/dev/null)" = "true" ]; then
        local _url
        _url=$(echo "$_start" | jq -r '.data.url // empty' 2>/dev/null)
        if [ -n "$_url" ]; then
            echo -e "${CYAN}Opening browser for authentication...${NC}" >&2
            open_browser "$_url"
            echo -e "  ${CYAN}URL:${NC} ${_url}" >&2
            echo -e "  Authenticate in the browser window." >&2
            echo "" >&2
            echo -ne "  ${CYAN}Waiting for authentication...${NC}" >&2
            local _done
            _done=$(send_request '{"method":"unlock_local_complete","params":{"ttl":7200}}' 180 2>/dev/null || true)
            echo "" >&2
            if [ "$(echo "$_done" | jq -r '.success // false' 2>/dev/null)" = "true" ]; then
                echo -e "${GREEN}WebAuthn verified.${NC}" >&2
                return 0
            fi
        fi
    fi

    # Phase 2: fall back to remote QR/phone flow. Useful when no localhost
    # credential is registered (e.g. user only has a phone passkey).
    echo -e "${YELLOW}Trying remote authentication...${NC}" >&2
    run_unlock_flow "7200" || {
        echo -e "${RED}WebAuthn verification failed.${NC}" >&2
        return 1
    }
    return 0
}

# TCB: subprocess injection of secret values
# Verifies: secret values reach exactly one place — the env of the
#           subprocess we are about to spawn. They never appear in argv,
#           never in stdout/stderr of the wrapper, never in any file.
# Adversary: a malicious caller of `scrt4 run` who hopes the substitution
#            leaks the value into the parent environment, the command
#            string, or the audit log.
# Implementation: substitution happens in the daemon (see daemon/src/
#                 subprocess.rs); the CLI hands the daemon the literal
#                 command string with $env[NAME] placeholders intact.
_run_with_injected_secrets() {
    local cmd="$1"
    local cwd="${2:-$PWD}"
    local response
    # Daemon protocol: Run takes `command` (not `cmd`). See daemon/src/protocol.rs.
    #
    # working_dir matters: the daemon is a long-lived process whose own cwd is
    # wherever it was started — often / — so without this every relative path
    # in the command resolves against that instead of the caller's directory.
    response=$(send_request "$(jq -nc --arg c "$cmd" --arg d "$cwd" '{method:"run",params:{command:$c,working_dir:$d}}')" 2>/dev/null || true)
    local ok
    ok=$(echo "$response" | jq -r '.success // false' 2>/dev/null || echo "false")
    if [ "$ok" != "true" ]; then
        local err
        err=$(echo "$response" | jq -r '.error // "unknown error"' 2>/dev/null)
        echo -e "${RED}scrt4 run failed: ${err}${NC}" >&2
        return 1
    fi

    echo "$response" | jq -r '.data.output // ""'
    local exit_code
    exit_code=$(echo "$response" | jq -r '.data.exit_code // 0' 2>/dev/null)
    return "$exit_code"
}

# ── Core commands ────────────────────────────────────────────────────

# cmd_help — prints the help text for the active build (core + loaded
# modules). Each command's one-line description comes from the registered
# handler's leading comment, fetched via `declare -f`.
cmd_help() {
    # Quoted heredoc terminator so shell does not try to expand $env[K].
    cat <<'EOF'
scrt4 — secure secret manager (v0.2 architecture)

USAGE:
    scrt4 <command> [options]

CORE COMMANDS:
    help                Show this help
    daemon              Start scrt4-daemon in the foreground
    status              Check session status
    setup [--agent]     Register a WebAuthn passkey (first-time enrollment)
    setup --local       Add this device's own passkey (Touch ID / Windows
                        Hello) so unlocking needs no phone. Unlock first.
    unlock [--local] [--agent] [ttl] Authenticate and start a session
                        (--local uses this device's own passkey)
                        (--agent renders the QR in plain ASCII with banner
                         markers so AI coding assistants pass it through
                         unmodified instead of truncating it)
    extend [ttl]        Reset session timer (optionally update TTL)
    logout              Lock the session (aliases: lock, clear)
    list [--tags] [--tag T]  List secret names (optionally with tags / filtered)
    add [KEY=value ...] Add secrets (GUI notepad if no args)
    run [--cwd DIR] 'cmd $env[K]'
                        Run a command with secret injection. Runs in the
                        current directory unless --cwd is given.
    view [--cli]        View secrets (GUI default, --cli for terminal)
    rotate              Rotate the vault master key (re-encrypts all secrets)
    backup-vault [--local DIR]   Tar the vault directory into a dated archive
    backup-key [--save DIR]      Show or save the master key
    recover FILE                 Recover a master key from an encrypted backup
    recover-key KEY [--reveal]   Emergency vault recovery with a plaintext
                                 base64 master key (FIDO2 not required)
    backup-guide        Open backup & recovery guide
    list-encrypted      List registered .scrt4 archives
    cleanup-encrypted [--prune]  Show or prune stale inventory entries
    llm [--json]        Print LLM/agent capability map (llms.txt)
    upgrade [--check]   Install the published release (verifies SHA256 first)
    verify-self         Verify the scrt4 binary against the published SHA256SUMS
EOF
    printf '\nVersion: %s\n' "$VERSION"

    # Module commands. Skip the names that are core registrations so we
    # don't double-list (ISS015). We only care about commands whose
    # handler does NOT match the core cmd_* prefix.
    local module_listed=false
    local i
    for i in "${!_SCRT4_CMDS[@]}"; do
        local handler="${_SCRT4_HANDLERS[$i]}"
        case "$handler" in
            cmd_help|cmd_status|cmd_setup|cmd_unlock|cmd_extend|cmd_logout|cmd_list|cmd_add|cmd_run|cmd_view|cmd_rotate|cmd_list_encrypted|cmd_cleanup_encrypted|cmd_daemon|cmd_backup_vault|cmd_backup_key|cmd_recover|cmd_recover_key|cmd_backup_guide|cmd_verify_self|cmd_upgrade)
                # Core handlers — already shown in the CORE COMMANDS block above.
                continue ;;
        esac
        if [ "$module_listed" = false ]; then
            echo
            echo "MODULE COMMANDS:"
            module_listed=true
        fi
        printf '    %-20s (%s)\n' "${_SCRT4_CMDS[$i]}" "$handler"
    done
}

# cmd_extend [TTL] — reset the session timer, optionally update TTL.
# Ports cmd_extend from the v0.1.0 monolith. F009 in the tracker sheet.
cmd_extend() {
    ensure_unlocked || return 1
    local ttl="${1:-}"
    local req
    # Always include `params` — the Rust enum has `ttl: Option<u64>`,
    # but serde's tag+content layout needs the params object present
    # even when ttl is null. Sending `{"method":"extend"}` alone fails
    # to deserialize.
    if [ -n "$ttl" ]; then
        req=$(jq -nc --argjson ttl "$ttl" '{method:"extend",params:{ttl:$ttl}}')
    else
        req='{"method":"extend","params":{"ttl":null}}'
    fi
    local response
    response=$(send_request "$req")
    local ok
    ok=$(echo "$response" | jq -r '.success // false')
    if [ "$ok" != "true" ]; then
        echo -e "${RED}extend failed: $(echo "$response" | jq -r '.error // "unknown"')${NC}" >&2
        return 1
    fi
    local remaining hours mins
    remaining=$(echo "$response" | jq -r '.data.remaining // 0')
    hours=$((remaining / 3600))
    mins=$(( (remaining % 3600) / 60 ))
    echo -e "${GREEN}Session extended. ${hours}h ${mins}m remaining.${NC}"
}

# cmd_status — prints session status. Out of TCB: returns active/inactive
# and remaining seconds, never any secret material.
cmd_status() {
    local response
    response=$(send_request '{"method":"status"}' 2>/dev/null || true)
    if [ -z "$response" ]; then
        echo -e "${YELLOW}Daemon not reachable. Start with: scrt4-daemon &${NC}" >&2
        return 1
    fi
    echo "$response" | jq .
}

# cmd_unlock [TTL] [--cli] — start a session via WebAuthn.
#
# Drives the full QR/relay flow (run_unlock_flow) — ported from the
# v0.1.0 monolith (ISS016). The daemon issues a relay URL, the user
# scans a QR on their phone, the phone authenticates with a passkey,
# and the encrypted PRF payload comes back through the relay.
cmd_unlock() {
    local _unlock_local=false
    local ttl="72000"
    while [ $# -gt 0 ]; do
        case "$1" in
            --local)     _unlock_local=true; shift ;;
            --agent)     AGENT_MODE=true; FORCE_CLI=true; shift ;;
            --cli|agent) FORCE_CLI=true; shift ;;
            *)           ttl="$1"; shift ;;
        esac
    done

    if [ "$_unlock_local" = true ]; then
        run_unlock_local_flow "${ttl:-72000}"
        return $?
    fi

    run_unlock_flow "$ttl"
}

# cmd_setup [--cli] — enroll a new WebAuthn credential (passkey).
#
# Drives the full QR/relay registration flow. Generates fresh keys on
# the daemon side, so if the user already has secrets this WILL DESTROY
# them — we print a loud warning and require typed "YES" confirmation
# before proceeding. Ported from the v0.1.0 monolith.
cmd_setup() {
    local use_local=false
    while [ $# -gt 0 ]; do
        case "$1" in
            --local)     use_local=true; shift ;;
            --agent)     AGENT_MODE=true; FORCE_CLI=true; shift ;;
            --cli|agent) FORCE_CLI=true; shift ;;
            *)           shift ;;
        esac
    done

    if [ "$use_local" = true ]; then
        run_setup_local_flow
        return $?
    fi

    # Warn if existing secrets would be wiped. Registration generates
    # a new master key, and the old vault becomes unrecoverable without
    # a separate backup.
    local existing_secrets=0
    local list_resp
    list_resp=$(send_request '{"method":"list"}' 2>/dev/null || true)
    if [ -n "$list_resp" ]; then
        existing_secrets=$(echo "$list_resp" | jq -r '.data.names | length // 0' 2>/dev/null || echo 0)
    fi

    if [ "$existing_secrets" -gt 0 ] 2>/dev/null; then
        echo ""
        echo -e "${RED}╔══════════════════════════════════════════════════════════╗${NC}"
        echo -e "${RED}║  WARNING: You have existing secrets in your vault!       ║${NC}"
        echo -e "${RED}╠══════════════════════════════════════════════════════════╣${NC}"
        echo -e "${RED}║  Setting up WebAuthn generates new encryption keys.      ║${NC}"
        echo -e "${RED}║  ALL existing secrets will be permanently deleted.       ║${NC}"
        echo -e "${RED}╠══════════════════════════════════════════════════════════╣${NC}"
        echo -e "${RED}║  Before proceeding, you should:                          ║${NC}"
        echo -e "${RED}║    1. Run 'scrt4 backup-key --save ~/Desktop'            ║${NC}"
        echo -e "${RED}║       (saves encrypted master key backup)                ║${NC}"
        echo -e "${RED}║    2. Run 'scrt4 view' and copy your secret values       ║${NC}"
        echo -e "${RED}║    3. After setup, re-add with 'scrt4 add KEY=value'     ║${NC}"
        echo -e "${RED}╚══════════════════════════════════════════════════════════╝${NC}"
        echo ""
        echo -n "Type YES to proceed, or anything else to abort: "
        local confirm
        read -r confirm
        if [ "$confirm" != "YES" ]; then
            echo -e "${YELLOW}Aborted. Your secrets are safe.${NC}"
            return 0
        fi
        echo ""
    fi

    run_setup_flow
}

# cmd_list_encrypted — list registered .scrt4 archives. Core command.
#
# F027. Reads the daemon-side inventory (handle_list_encrypted in
# daemon/src/handlers.rs + crate::encrypted_inventory) and pretty-prints
# one row per registered archive with a present/missing marker.
cmd_list_encrypted() {
    ensure_unlocked || return 1
    local response
    response=$(send_request '{"method":"list_encrypted"}')
    local ok
    ok=$(echo "$response" | jq -r '.success // false')
    if [ "$ok" != "true" ]; then
        echo -e "${RED}list_encrypted failed: $(echo "$response" | jq -r '.error // "unknown"')${NC}" >&2
        return 1
    fi
    local count
    count=$(echo "$response" | jq -r '.data.entries | length')
    if [ "$count" = "0" ]; then
        echo -e "${YELLOW}No encrypted folders registered.${NC}"
        echo "  Create one with: scrt4 encrypt-folder PATH"
        return 0
    fi
    echo -e "${CYAN}Registered encrypted folders (${count}):${NC}"
    echo "$response" | jq -r '.data.entries[] | "  [\(if .exists then "ok" else "MISSING" end)] \(.folder_name)  (\(.file_count) files, \(.archive_size) bytes)\n      \(.path)\n      id: \(.id)"'
}

# cmd_cleanup_encrypted — remove inventory entries whose files are gone.
#
# F028. Default is a dry run: reports present/missing counts without
# touching the inventory. Pass --prune to actually remove missing
# entries.
cmd_cleanup_encrypted() {
    ensure_unlocked || return 1
    local remove_missing=false
    while [ $# -gt 0 ]; do
        case "$1" in
            --prune) remove_missing=true; shift ;;
            *) echo -e "${RED}Unknown flag: ${1}${NC}" >&2; return 1 ;;
        esac
    done
    local req
    req=$(jq -nc --argjson rm "$remove_missing" '{method:"cleanup_encrypted",params:{remove_missing:$rm}}')
    local response
    response=$(send_request "$req")
    local ok
    ok=$(echo "$response" | jq -r '.success // false')
    if [ "$ok" != "true" ]; then
        echo -e "${RED}cleanup_encrypted failed: $(echo "$response" | jq -r '.error // "unknown"')${NC}" >&2
        return 1
    fi
    local present missing removed
    present=$(echo "$response" | jq -r '.data.present_count')
    missing=$(echo "$response" | jq -r '.data.missing_count')
    removed=$(echo "$response" | jq -r '.data.removed_count')
    echo -e "${CYAN}Encrypted inventory summary:${NC}"
    echo "  Present on disk:  ${present}"
    echo "  Missing from disk: ${missing}"
    echo "  Removed this pass: ${removed}"
    if [ "$missing" != "0" ]; then
        echo ""
        echo -e "${YELLOW}Missing paths:${NC}"
        echo "$response" | jq -r '.data.missing_paths[]' | sed 's/^/  /'
        if [ "$remove_missing" = false ]; then
            echo ""
            echo -e "${YELLOW}Pass --prune to remove missing entries from the inventory.${NC}"
        fi
    fi
}

# cmd_rotate — vault rotation (F043). Core command, not a module.
#
# Generates a new master key, re-encrypts the vault under it, updates
# the active session. Mirrors the migrate_secrets pattern from the
# legacy llm-secrets daemon (wsl-daemon/src/keystore.rs::migrate_secrets)
# — daemon-side handler: daemon/src/handlers.rs::handle_rotate_vault.
#
# The ~/.scrt4/master.key wrapper is NOT re-wrapped — that requires a
# fresh WebAuthn PRF ceremony. Instead the daemon returns the new raw
# master key and the CLI prompts the user to save it (via `scrt4
# backup-key --save DIR`) or re-enroll (`scrt4 setup`) before the
# session ends. Leaving the session without either means a fresh
# unlock would fail because master.key unwraps to the OLD key.
cmd_rotate() {
    ensure_unlocked || return 1

    # Step-up is enforced daemon-side; call _wa_gate here too so the
    # client surfaces the prompt before the RPC comes back with a
    # step-up-required error.
    _wa_gate || {
        echo -e "${RED}Step-up cancelled; vault rotation aborted.${NC}" >&2
        return 1
    }

    local response
    response=$(send_request '{"method":"rotate_vault"}' 30)
    local ok
    ok=$(echo "$response" | jq -r '.success // false')
    if [ "$ok" != "true" ]; then
        echo -e "${RED}rotate_vault failed: $(echo "$response" | jq -r '.error // "unknown"')${NC}" >&2
        return 1
    fi

    local new_key count wrapper_stale
    new_key=$(echo "$response" | jq -r '.data.new_master_key_b64')
    count=$(echo "$response" | jq -r '.data.secret_count')
    wrapper_stale=$(echo "$response" | jq -r '.data.wrapper_stale')

    echo -e "${GREEN}Vault rotated.${NC}"
    echo "  Secrets re-encrypted: ${count}"

    if [ "$wrapper_stale" = "true" ]; then
        echo ""
        echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        echo -e "${YELLOW}  HARDENED MODE: master.key wrapper is now STALE${NC}"
        echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        echo -e "${YELLOW}  Your WebAuthn credential still unwraps the OLD master key,${NC}"
        echo -e "${YELLOW}  but the vault is now encrypted under a NEW master key.${NC}"
        echo -e "${YELLOW}  Before this session ends, do ONE of the following:${NC}"
        echo ""
        echo -e "${YELLOW}    1) scrt4 backup-key --save ~/Desktop${NC}"
        echo -e "${YELLOW}       Saves the NEW master key so you can recover manually${NC}"
        echo -e "${YELLOW}    2) scrt4 setup${NC}"
        echo -e "${YELLOW}       Re-enrolls WebAuthn against the new master key${NC}"
        echo ""
        echo -e "${YELLOW}  If you do neither and the session ends, the next unlock${NC}"
        echo -e "${YELLOW}  will fail because master.key unwraps to the old key.${NC}"
        echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    fi

    # The raw new master key is the "escape hatch" if the wrapper can
    # no longer be re-derived. Print to stderr so it doesn't get
    # captured by command substitution but the user still sees it.
    echo ""
    echo -e "${CYAN}New master key (base64, 32 bytes):${NC}" >&2
    printf '%s\n' "$new_key" >&2
    echo "" >&2
    echo -e "${YELLOW}Store this somewhere safe. It's your recovery key.${NC}" >&2
}

# cmd_logout — clears the session.
#
# Registered under three names that all route here:
#   - logout  (primary, matches v0.1.0 monolith)
#   - lock    (alias, same behaviour)
#   - clear   (alias, same behaviour — listed in the v0.1.0 menu)
cmd_logout() {
    send_request '{"method":"clear"}'
}

# cmd_backup_vault [--local DIR] — tar the vault directory into a
# date-stamped archive. Core command (vault format operation).
#
# Writes scrt4-backup-YYYY-MM-DD.tar.gz to $local_dest (or the current
# directory if no --local given). The archive contains the entire
# $CONFIG_DIR (including the still-encrypted secrets file), so it is
# safe to store offline without additional encryption — decrypting
# it requires the master key, which is NOT in the archive. Use
# `scrt4 backup-key --save` alongside this to save the master key
# under a separate password.
#
# Ported from the backup-vault module (2026-04-13); the module was
# retired because backup-vault, backup-key, recover, and backup-guide
# all operate on the vault format or master key and are Core by the
# architecture decision tree.
cmd_backup_vault() {
    local local_dest=""
    while [ $# -gt 0 ]; do
        case "$1" in
            --local)
                local_dest="${2:-}"
                if [ -z "$local_dest" ]; then
                    echo -e "${RED}Usage: scrt4 backup-vault --local <directory>${NC}" >&2
                    return 1
                fi
                shift 2
                ;;
            *)
                echo -e "${RED}Unknown option: $1${NC}" >&2
                echo "Usage: scrt4 backup-vault [--local <directory>]" >&2
                return 1
                ;;
        esac
    done
    [ -z "$local_dest" ] && local_dest="."

    if [ ! -d "$CONFIG_DIR" ]; then
        echo -e "${RED}Config directory not found: ${CONFIG_DIR}${NC}" >&2
        return 1
    fi
    if [ ! -d "$local_dest" ]; then
        echo -e "${RED}Destination directory not found: ${local_dest}${NC}" >&2
        return 1
    fi

    local timestamp
    timestamp=$(date +%Y-%m-%d)
    local archive="${local_dest}/scrt4-backup-${timestamp}.tar.gz"

    local file_count
    file_count=$(find "$CONFIG_DIR" -type f 2>/dev/null | wc -l)
    if [ "$file_count" -eq 0 ]; then
        echo -e "${RED}No files in ${CONFIG_DIR}${NC}" >&2
        return 1
    fi

    echo -e "${CYAN}Backing up ${CONFIG_DIR} (${file_count} files)...${NC}"
    local config_basename config_parent
    config_basename=$(basename "$CONFIG_DIR")
    config_parent=$(dirname "$CONFIG_DIR")
    if ! tar -czf "$archive" -C "$config_parent" "$config_basename" 2>/dev/null; then
        echo -e "${RED}tar failed${NC}" >&2
        return 1
    fi

    local inventory_file="${CONFIG_DIR}/encrypted-inventory.json"
    if [ -f "$inventory_file" ]; then
        local inv_count
        inv_count=$(jq -r '.entries | length' "$inventory_file" 2>/dev/null || echo "?")
        echo -e "${CYAN}  + cloud-crypt inventory: ${inv_count} entries tracked${NC}"
    fi

    local size
    size=$(stat -c%s "$archive" 2>/dev/null || stat -f%z "$archive" 2>/dev/null || echo 0)
    echo -e "${GREEN}Wrote ${archive} (${size} bytes)${NC}"
    echo
    echo -e "${YELLOW}Note: the vault file inside the archive is still encrypted.${NC}"
    echo -e "${YELLOW}You also need the master key to recover. Run: scrt4 backup-key${NC}"
}

# cmd_backup_key [--save DIR] — show or save the master key. Core
# command (literally touches the master key).
#
# Without --save: prints the raw base64 master key to stdout after
# ensure_unlocked + _wa_gate. With --save DIR: writes a password-
# encrypted JSON file compatible with the v0.1.0 monolith's
# encrypted-master-key-instructions.json format (PBKDF2-SHA256 100k
# iterations + AES-256-CBC). cmd_recover reads the same format.
#
# SCRT4_TEST_PASSWORD env var is a non-interactive escape hatch for
# smoke tests that can't drive a read -s prompt.
cmd_backup_key() {
    local save_dir=""
    case "${1:-}" in
        --save)
            save_dir="${2:-.}"
            if [ ! -d "$save_dir" ]; then
                echo -e "${RED}Directory not found: ${save_dir}${NC}" >&2
                return 1
            fi
            ;;
        --to-drive)
            shift
            cmd_backup_key_to_drive "$@"
            return $?
            ;;
    esac

    ensure_unlocked || return 1
    _wa_gate || return 1

    echo -e "${CYAN}Retrieving master key from daemon...${NC}"
    local response
    response=$(send_request '{"method":"backup_key"}')
    local success
    success=$(echo "$response" | jq -r '.success // false')
    if [ "$success" != "true" ]; then
        local err
        err=$(echo "$response" | jq -r '.error // "Unknown error"')
        echo -e "${RED}Failed to retrieve master key: ${err}${NC}" >&2
        return 1
    fi
    local key
    key=$(echo "$response" | jq -r '.data.key')

    if [ -z "$save_dir" ]; then
        echo -e "${GREEN}Master key (${#key} characters):${NC}"
        echo
        echo "$key"
        echo
        echo -e "${YELLOW}Store this somewhere safe and offline.${NC}"
        echo -e "${YELLOW}Never paste it into Claude Code or any AI agent.${NC}"
        return 0
    fi

    local abs_save_dir
    abs_save_dir=$(cd "$save_dir" && pwd)
    local out_file="${abs_save_dir}/encrypted-master-key-instructions.json"

    echo
    echo -e "${CYAN}Creating encrypted master key backup at:${NC}"
    echo "  $out_file"
    echo

    local password password2
    if [ -n "${SCRT4_TEST_PASSWORD:-}" ]; then
        password="$SCRT4_TEST_PASSWORD"
        password2="$SCRT4_TEST_PASSWORD"
        echo -e "${YELLOW}(using SCRT4_TEST_PASSWORD from environment)${NC}"
    else
        echo -n "Recovery password (min 8 chars): "
        read -r -s password
        echo
        echo -n "Confirm password: "
        read -r -s password2
        echo
    fi

    if [ "$password" != "$password2" ]; then
        echo -e "${RED}Passwords do not match. No file written.${NC}" >&2
        return 1
    fi
    if [ ${#password} -lt 8 ]; then
        echo -e "${RED}Password must be at least 8 characters. No file written.${NC}" >&2
        return 1
    fi

    local encrypt_script
    encrypt_script=$(mktemp)
    cat > "$encrypt_script" << 'PYEOF'
import json, os, sys, hashlib, base64, subprocess, datetime
lines = sys.stdin.read().split('\n', 1)
master_key, password = lines[0], lines[1]
out_file = sys.argv[1]
salt = os.urandom(16)
iv = os.urandom(16)
derived_key = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 100000, dklen=32)
proc = subprocess.run(
    ['openssl', 'enc', '-aes-256-cbc',
     '-K', derived_key.hex(), '-iv', iv.hex(), '-nosalt'],
    input=master_key.encode(), capture_output=True)
if proc.returncode != 0:
    print('Encryption failed', file=sys.stderr); sys.exit(1)
backup = {
    'Type': 'MasterKeyBackup',
    'Version': '2.0',
    'CreatedAt': datetime.datetime.now().astimezone().isoformat(),
    'SecurityMode': 'webauthn-prf',
    'Salt': base64.b64encode(salt).decode(),
    'IV': base64.b64encode(iv).decode(),
    'EncryptedMasterKey': base64.b64encode(proc.stdout).decode(),
    'DecryptionInstructions': {
        'Algorithm': 'AES-256-CBC',
        'KeyDerivation': 'PBKDF2-SHA256',
        'Iterations': 100000,
        'KeyLength': 32,
    },
}
with open(out_file, 'w') as f:
    json.dump(backup, f, indent=2)
print('OK')
PYEOF

    local result
    result=$(printf '%s\n%s' "$key" "$password" | python3 "$encrypt_script" "$out_file")
    local rc=$?
    rm -f "$encrypt_script"
    if [ $rc -ne 0 ] || [ "$result" != "OK" ]; then
        echo -e "${RED}Failed to create encrypted backup.${NC}" >&2
        return 1
    fi

    chmod 600 "$out_file"
    echo -e "${GREEN}Wrote ${out_file}${NC}"
    echo
    echo -e "${YELLOW}Recover with: scrt4 recover ${out_file}${NC}"
    echo -e "${YELLOW}You will need the password you just set.${NC}"
}

# cmd_recover FILE — recover a master key from a password-encrypted
# backup produced by backup-key --save. Core command.
#
# Also accepts `--from-drive DRIVE_ID [--out DIR]` which pulls a
# SCRT4ENC-wrapped master-key bundle from cloud-crypt/Drive and
# reconstitutes the local ~/.scrt4/master.key file. The Drive path
# requires the same FIDO2 authenticator used to create the backup —
# the bundle body is the existing master.key AES-GCM ciphertext,
# unchanged.
cmd_recover() {
    if [ "${1:-}" = "--from-drive" ]; then
        shift
        cmd_recover_from_drive "$@"
        return $?
    fi
    local backup_file="${1:-}"
    if [ -z "$backup_file" ]; then
        echo -e "${RED}Usage: scrt4 recover <encrypted-master-key-instructions.json>${NC}" >&2
        echo -e "${RED}   or: scrt4 recover --from-drive DRIVE_ID${NC}" >&2
        return 1
    fi
    if [ ! -f "$backup_file" ]; then
        echo -e "${RED}File not found: ${backup_file}${NC}" >&2
        return 1
    fi
    if ! jq -e '.EncryptedMasterKey' "$backup_file" >/dev/null 2>&1; then
        echo -e "${RED}Not a scrt4 master-key backup (missing EncryptedMasterKey field)${NC}" >&2
        return 1
    fi

    echo -e "${CYAN}=== scrt4 master key recovery ===${NC}"
    local created version
    created=$(jq -r '.CreatedAt // "unknown"' "$backup_file")
    version=$(jq -r '.Version // "1.0"' "$backup_file")
    echo "  Backup created: $created"
    echo "  Format version: $version"
    echo

    local password
    if [ -n "${SCRT4_TEST_PASSWORD:-}" ]; then
        password="$SCRT4_TEST_PASSWORD"
        echo -e "${YELLOW}(using SCRT4_TEST_PASSWORD from environment)${NC}"
    else
        echo -n "Recovery password: "
        read -r -s password
        echo
    fi

    local decrypt_script
    decrypt_script=$(mktemp)
    cat > "$decrypt_script" << 'PYEOF'
import json, sys, hashlib, base64, subprocess
password = sys.stdin.read()
with open(sys.argv[1], encoding='utf-8-sig') as f:
    backup = json.load(f)
salt = base64.b64decode(backup['Salt'])
iv = base64.b64decode(backup['IV'])
encrypted = base64.b64decode(backup['EncryptedMasterKey'])
iters = backup.get('DecryptionInstructions', {}).get('Iterations', 100000)
derived_key = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, iters, dklen=32)
result = subprocess.run(['openssl', 'enc', '-aes-256-cbc', '-d',
    '-K', derived_key.hex(), '-iv', iv.hex(), '-nosalt'],
    input=encrypted, capture_output=True)
if result.returncode != 0: sys.exit(1)
print(result.stdout.decode().rstrip(chr(0)))
PYEOF
    local recovered_key
    recovered_key=$(printf '%s' "$password" | python3 "$decrypt_script" "$backup_file" 2>/dev/null)
    local rc=$?
    rm -f "$decrypt_script"

    if [ $rc -ne 0 ] || [ -z "$recovered_key" ]; then
        echo -e "${RED}Decryption failed. Check your recovery password.${NC}" >&2
        return 1
    fi

    echo
    echo -e "${GREEN}SUCCESS — your master key:${NC}"
    echo
    echo "  $recovered_key"
    echo
    echo "  Length: ${#recovered_key} characters"
    echo
    echo -e "${CYAN}Next steps:${NC}"
    echo "  1. Place this key in ~/.scrt4/master.key (or let setup do it)"
    echo "  2. Run: scrt4 setup   — register a new FIDO2 authenticator"
    echo "  3. Run: scrt4 unlock  — authenticate and start a session"
    echo
    echo "  Your vault (secrets.enc) is still encrypted with this key."
    echo "  Once setup + unlock completes, all your secrets are accessible."
}

# cmd_recover_key MASTER_KEY_B64 [--reveal] — emergency vault recovery
# using a plaintext base64 master key. Use when the FIDO2 authenticator
# is lost but the raw master key was backed up elsewhere (e.g. printed
# from `scrt4 backup-key` and written down).
#
# Decrypts ~/.scrt4/vault/secrets.enc directly with openssl — no daemon,
# no FIDO2. Default prints secret names only. Pass --reveal to dump full
# KEY=value pairs to stdout (plaintext; handle with care).
#
# This is the true escape hatch: if you have the master key (32 bytes,
# base64), you can always get your secrets back, even without scrt4.
cmd_recover_key() {
    local master_key="${1:-}"
    local reveal=false
    shift || true
    while [ $# -gt 0 ]; do
        case "$1" in
            --reveal) reveal=true; shift ;;
            *)        shift ;;
        esac
    done

    if [ -z "$master_key" ]; then
        echo -e "${RED}Usage: scrt4 recover-key <base64-master-key> [--reveal]${NC}" >&2
        echo "" >&2
        echo "  Emergency vault recovery using a plaintext master key." >&2
        echo "  Use when the FIDO2 authenticator is lost but you have" >&2
        echo "  the raw 32-byte master key (base64) saved elsewhere." >&2
        return 1
    fi

    local vault_path="${CONFIG_DIR}/vault/secrets.enc"
    if [ ! -f "$vault_path" ]; then
        echo -e "${RED}Vault not found: ${vault_path}${NC}" >&2
        return 1
    fi

    local decrypt_script
    decrypt_script=$(mktemp)
    cat > "$decrypt_script" << 'PYEOF'
import json, sys, base64, subprocess
master_key_b64, vault_path = sys.argv[1], sys.argv[2]
try:
    key = base64.b64decode(master_key_b64)
except Exception as e:
    print(f"ERR: invalid master key base64: {e}", file=sys.stderr); sys.exit(2)
if len(key) != 32:
    print(f"ERR: master key must be 32 bytes, got {len(key)}", file=sys.stderr); sys.exit(2)
try:
    with open(vault_path, encoding='utf-8-sig') as f:
        env_json = json.load(f)
    data = base64.b64decode(env_json['Data'])
except Exception as e:
    print(f"ERR: cannot read vault: {e}", file=sys.stderr); sys.exit(2)
if len(data) < 17:
    print("ERR: vault ciphertext too short", file=sys.stderr); sys.exit(2)
iv, ciphertext = data[:16], data[16:]
result = subprocess.run(
    ['openssl', 'enc', '-aes-256-cbc', '-d',
     '-K', key.hex(), '-iv', iv.hex(), '-nosalt'],
    input=ciphertext, capture_output=True)
if result.returncode != 0:
    print("ERR: decryption failed — master key is wrong", file=sys.stderr); sys.exit(3)
sys.stdout.write(result.stdout.decode('utf-8', errors='replace'))
PYEOF

    local plaintext
    plaintext=$(python3 "$decrypt_script" "$master_key" "$vault_path" 2>/dev/null)
    local rc=$?
    rm -f "$decrypt_script"

    if [ $rc -ne 0 ]; then
        echo -e "${RED}Recovery failed. Check the master key.${NC}" >&2
        return 1
    fi

    local names count
    names=$(echo "$plaintext" | awk -F= '/^[A-Za-z_][A-Za-z0-9_]*=/ { print $1 }')
    count=$(echo "$names" | grep -c . 2>/dev/null || echo 0)

    echo -e "${GREEN}✓ Recovery successful — ${count} secret(s) decrypted from vault.${NC}"
    echo ""

    if [ "$reveal" = true ]; then
        echo -e "${YELLOW}Printing plaintext secrets to stdout.${NC}" >&2
        echo ""
        echo "$plaintext"
    else
        echo -e "${CYAN}Secret names:${NC}"
        echo "$names" | sed 's/^/  /'
        echo ""
        echo -e "${CYAN}To dump plaintext KEY=value pairs:${NC}"
        echo "  scrt4 recover-key <key> --reveal > recovered.env"
        echo ""
        echo -e "${CYAN}Then rebuild your vault and start a session:${NC}"
        echo "  scrt4 setup --agent               # register a new FIDO2 passkey"
        echo "  scrt4 import-env recovered.env    # restore all secrets"
        echo "  rm -f recovered.env               # wipe the plaintext"
        echo "  scrt4 unlock --agent              # access your secrets"
    fi
}

# cmd_backup_key_to_drive — wrap the local master.key file in a
# SCRT4ENC envelope and push it to Google Drive via cloud-crypt.
# One FIDO2 tap total (the active session covers it).
#
# Design rationale:
#   master.key is already AES-256-GCM ciphertext wrapped under a key
#   derived from the FIDO2 PRF output — the hardware authenticator
#   never leaves the user's device. Uploading it to Drive is safe
#   without additional encryption: an attacker who obtains the cloud
#   copy still needs the physical authenticator to decrypt it.
#
#   We wrap it in a SCRT4ENC(\x00) envelope with kind=master-key-export
#   so:
#     (a) cloud-crypt's ciphertext-only gate (_scrt4_cc_assert_ciphertext)
#         accepts it — the TCB invariant holds by construction.
#     (b) cmd_recover_from_drive can detect the bundle format and
#         reassemble the master.key JSON on the other end.
#
# Never writes plaintext to the filesystem or the network.
cmd_backup_key_to_drive() {
    ensure_unlocked || return 1

    local master_key_file="${CONFIG_DIR}/master.key"
    if [ ! -f "$master_key_file" ]; then
        echo -e "${RED}Master key file not found: ${master_key_file}${NC}" >&2
        echo -e "${RED}Run 'scrt4 setup' first.${NC}" >&2
        return 1
    fi

    local cache_dir="${XDG_DATA_HOME:-$HOME/.local/share}/scrt4/cloud-crypt/archives"
    mkdir -p "$cache_dir"
    local timestamp bundle
    timestamp=$(date +%Y-%m-%d-%H%M%S)
    bundle="${cache_dir}/scrt4-master-key-${timestamp}.scrt4"

    echo -e "${CYAN}Wrapping master.key in SCRT4ENC envelope...${NC}"

    local wrap_script
    wrap_script=$(mktemp)
    cat > "$wrap_script" << 'PYEOF'
import json, struct, sys, time, base64
src, dst = sys.argv[1], sys.argv[2]
with open(src, 'rb') as f:
    master_key_json_bytes = f.read()
try:
    mk = json.loads(master_key_json_bytes.decode('utf-8'))
except Exception as e:
    print(json.dumps({'error': f'master.key is not valid JSON: {e}'})); sys.exit(0)
for required in ('salt', 'nonce', 'ciphertext'):
    if required not in mk:
        print(json.dumps({'error': f'master.key missing field: {required}'})); sys.exit(0)
ciphertext = base64.b64decode(mk['ciphertext'])
header = json.dumps({
    'kind': 'master-key-export',
    'scrt4_version': 1,
    'master_key_version': mk.get('version', 2),
    'salt': mk['salt'],
    'nonce': mk['nonce'],
    'auth_method': mk.get('auth_method', 'WebAuthnPrf'),
    'webauthn_credential_id': mk.get('webauthn_credential_id'),
    'created': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
}, separators=(',', ':')).encode('utf-8')
with open(dst, 'wb') as f:
    f.write(b'SCRT4ENC\x00')
    f.write(b'\x01')
    f.write(struct.pack('>I', len(header)))
    f.write(header)
    f.write(ciphertext)
print(json.dumps({'ok': True, 'path': dst, 'size': len(ciphertext) + len(header) + 14}))
PYEOF

    local result
    result=$(python3 "$wrap_script" "$master_key_file" "$bundle" 2>&1)
    local rc=$?
    rm -f "$wrap_script"
    if [ $rc -ne 0 ] || ! echo "$result" | jq -e '.ok' >/dev/null 2>&1; then
        echo -e "${RED}Failed to wrap master.key:${NC}" >&2
        echo "$result" >&2
        rm -f "$bundle" 2>/dev/null || true
        return 1
    fi
    chmod 600 "$bundle"
    echo -e "${GREEN}Bundle written: ${bundle}${NC}"

    # Self-check: bundle must start with SCRT4ENC magic, otherwise the
    # cloud-crypt gate will reject it — catching the error here gives
    # a clearer message.
    local magic_hex
    magic_hex=$(head -c 9 "$bundle" | od -An -tx1 2>/dev/null | tr -d ' \n')
    if [ "$magic_hex" != "5343525434454e4300" ]; then
        echo -e "${RED}Bundle failed self-check (missing SCRT4ENC magic).${NC}" >&2
        rm -f "$bundle"
        return 1
    fi

    echo
    echo -e "${CYAN}Uploading via cloud-crypt (Google Drive)...${NC}"
    echo -e "${YELLOW}This requires 'scrt4 cloud-crypt auth' to be set up.${NC}"

    # Delegate to the module. _scrt4_cc_assert_ciphertext will re-check
    # the SCRT4ENC magic — defence in depth.
    if ! scrt4_module_cloud_crypt_dispatch push "$bundle" --yes; then
        echo -e "${RED}cloud-crypt push failed.${NC}" >&2
        echo -e "${YELLOW}Bundle left at: ${bundle}${NC}" >&2
        echo -e "${YELLOW}You can retry: scrt4 cloud-crypt push '${bundle}'${NC}" >&2
        return 1
    fi

    echo
    echo -e "${GREEN}Master key exported to Google Drive.${NC}"
    echo -e "${CYAN}Recover with: scrt4 recover --from-drive <drive_file_id>${NC}"
    echo
    echo -e "${YELLOW}The local bundle is kept at:${NC}"
    echo "  $bundle"
    echo -e "${YELLOW}It is safe to delete; the Drive copy is the canonical backup.${NC}"
}

# cmd_recover_from_drive DRIVE_ID [--out DIR] — pull a master-key
# export bundle from Drive and reconstitute ~/.scrt4/master.key.
#
# The bundle is a SCRT4ENC envelope produced by
# cmd_backup_key_to_drive. Its body is the existing AES-GCM
# ciphertext of the master key; unwrapping it recovers the original
# master.key JSON file byte-for-byte. The user then runs
# `scrt4 unlock` (one FIDO2 tap) with the authenticator that
# originally protected the key.
cmd_recover_from_drive() {
    local drive_id="${1:-}"
    if [ -z "$drive_id" ]; then
        echo -e "${RED}Usage: scrt4 recover --from-drive DRIVE_ID [--out DIR]${NC}" >&2
        return 1
    fi
    shift
    local out_dir=""
    while [ $# -gt 0 ]; do
        case "$1" in
            --out) out_dir="${2:-}"; shift 2 ;;
            *) echo -e "${RED}Unknown flag: $1${NC}" >&2; return 1 ;;
        esac
    done
    [ -z "$out_dir" ] && out_dir="${XDG_DATA_HOME:-$HOME/.local/share}/scrt4/cloud-crypt/inbox"
    mkdir -p "$out_dir"

    echo -e "${CYAN}Downloading master-key bundle from Drive...${NC}"
    if ! scrt4_module_cloud_crypt_dispatch pull "$drive_id" --out "$out_dir" --yes; then
        echo -e "${RED}cloud-crypt pull failed.${NC}" >&2
        return 1
    fi

    # cloud-crypt names the downloaded file after the Drive metadata name.
    # Find the freshest scrt4-master-key-*.scrt4 under $out_dir.
    local bundle
    bundle=$(find "$out_dir" -maxdepth 1 -name 'scrt4-master-key-*.scrt4' -type f -printf '%T@ %p\n' 2>/dev/null \
        | sort -nr | head -1 | awk '{print $2}')
    if [ -z "$bundle" ] || [ ! -f "$bundle" ]; then
        echo -e "${RED}Downloaded bundle not found under ${out_dir}${NC}" >&2
        echo -e "${RED}The Drive file may not be a scrt4 master-key export.${NC}" >&2
        return 1
    fi

    echo -e "${CYAN}Unwrapping SCRT4ENC envelope: ${bundle}${NC}"
    local unwrap_script tmp_master
    unwrap_script=$(mktemp)
    tmp_master=$(mktemp -t scrt4-recovered-master-XXXXXX)
    cat > "$unwrap_script" << 'PYEOF'
import json, struct, sys, base64
src, dst = sys.argv[1], sys.argv[2]
with open(src, 'rb') as f:
    if f.read(9) != b'SCRT4ENC\x00':
        print(json.dumps({'error': 'not a SCRT4ENC file'})); sys.exit(0)
    if f.read(1) != b'\x01':
        print(json.dumps({'error': 'unsupported version'})); sys.exit(0)
    hlen = struct.unpack('>I', f.read(4))[0]
    if hlen > 65536:
        print(json.dumps({'error': 'header too large'})); sys.exit(0)
    header = json.loads(f.read(hlen).decode('utf-8'))
    body = f.read()
if header.get('kind') != 'master-key-export':
    print(json.dumps({'error': f"not a master-key-export bundle (kind={header.get('kind')})"})); sys.exit(0)
mk = {
    'version': header.get('master_key_version', 2),
    'salt': header['salt'],
    'nonce': header['nonce'],
    'ciphertext': base64.b64encode(body).decode('ascii'),
    'auth_method': header.get('auth_method', 'WebAuthnPrf'),
}
cid = header.get('webauthn_credential_id')
if cid:
    mk['webauthn_credential_id'] = cid
with open(dst, 'w') as f:
    json.dump(mk, f, indent=2)
print(json.dumps({'ok': True, 'path': dst, 'created': header.get('created', 'unknown')}))
PYEOF
    local result
    result=$(python3 "$unwrap_script" "$bundle" "$tmp_master" 2>&1)
    local rc=$?
    rm -f "$unwrap_script"
    if [ $rc -ne 0 ] || ! echo "$result" | jq -e '.ok' >/dev/null 2>&1; then
        echo -e "${RED}Failed to unwrap bundle:${NC}" >&2
        echo "$result" >&2
        rm -f "$tmp_master"
        return 1
    fi
    local created
    created=$(echo "$result" | jq -r '.created')
    echo -e "${GREEN}Bundle parsed — created ${created}${NC}"

    local target="${CONFIG_DIR}/master.key"
    if [ -f "$target" ]; then
        echo
        echo -e "${YELLOW}A master.key already exists at ${target}${NC}"
        echo -e "${YELLOW}Overwriting will make the local vault unusable until${NC}"
        echo -e "${YELLOW}the recovered key is unlocked with its authenticator.${NC}"
        if [ -n "${SCRT4_YES:-}" ]; then
            echo -e "${YELLOW}(SCRT4_YES set — proceeding without prompt)${NC}"
        else
            echo -n "Overwrite? [y/N] "
            local ans; read -r ans
            if [ "$ans" != "y" ] && [ "$ans" != "Y" ]; then
                echo "Aborted. Recovered key left at: $tmp_master"
                return 1
            fi
        fi
        cp "$target" "${target}.pre-recover.$(date +%s)" 2>/dev/null || true
    fi
    mkdir -p "$CONFIG_DIR"
    mv "$tmp_master" "$target"
    chmod 600 "$target"
    echo -e "${GREEN}Wrote ${target}${NC}"
    echo
    echo -e "${CYAN}Next step:${NC}"
    echo "  scrt4 unlock     # tap the authenticator that made the backup"
    echo
    echo -e "${YELLOW}Your vault (secrets.enc) remains encrypted with this key.${NC}"
    echo -e "${YELLOW}Once unlock succeeds, all secrets are accessible.${NC}"
}

# cmd_backup_guide — text guide about backup and recovery. Core
# because it is the user-facing documentation for backup-vault,
# backup-key, and recover above.
cmd_backup_guide() {
    cat <<'GUIDE'

╔═══════════════════════════════════════════════════════════════════╗
║              SCRT4 — BACKUP & RECOVERY GUIDE                      ║
╚═══════════════════════════════════════════════════════════════════╝

Full guide: https://github.com/llmsecrets/llm-secrets/blob/main/BUILD.md

HOW SCRT4 AUTHENTICATION WORKS:

  scrt4 uses FIDO2/WebAuthn — your hardware authenticator (YubiKey,
  phone passkey, caBLE) IS the key. There are no passwords or TOTP
  codes. The master key is derived from the FIDO2 hmac-secret
  extension every time you authenticate.

PRIMARY RECOVERY (you still have your authenticator):

  Just re-authenticate. Your authenticator derives the same master
  key every time — no backup files or passwords needed.

    scrt4 unlock            # tap your authenticator → session active
    scrt4 backup-key        # prints the master key (if you need it)

DISASTER RECOVERY (authenticator lost or broken):

  You need TWO things:

    1. The encrypted vault file
       scrt4 backup-vault          # writes scrt4-backup-DATE.tar.gz
       scrt4 backup-vault --local /path/to/USB

    2. The master key (one of these):
       - Paper printout from `scrt4 backup-key`
       - Password-encrypted file from `scrt4 backup-key --save DIR`
       - Cloud copy from `scrt4 backup-key --to-drive`

  WITHOUT BOTH, RECOVERY IS IMPOSSIBLE BY DESIGN.

  To recover:
    scrt4 recover <encrypted-master-key-instructions.json>   # local file
    scrt4 recover --from-drive DRIVE_FILE_ID                 # cloud copy

CLOUD KEY ESCROW (`--to-drive` / `--from-drive`):

  `scrt4 backup-key --to-drive` wraps your local master.key file in a
  SCRT4ENC envelope (no re-encryption — the file is already AES-GCM
  ciphertext under your FIDO2 authenticator) and uploads via
  cloud-crypt to the `claude-crypt` folder in Google Drive. One tap:
  the active session covers the operation.

  `scrt4 recover --from-drive DRIVE_ID` downloads the bundle, unwraps
  it, and writes ~/.scrt4/master.key. Then `scrt4 unlock` with the
  SAME authenticator reconstitutes the full vault (one tap).

  Security: the Drive copy is never plaintext. An attacker with access
  to your Drive still needs your physical authenticator to decrypt it.
  The cloud-crypt module's TCB gate refuses to upload anything that
  is not already SCRT4ENC ciphertext — plaintext leakage is prevented
  by construction.

WHAT'S IN THE BACKUP:

  `scrt4 backup-vault` archives the entire ~/.scrt4 directory:
    - secrets.enc           — encrypted vault (still AES-256-GCM ciphertext)
    - master.key            — FIDO2-wrapped master key (still wrapped)
    - encrypted-inventory.json — cloud-crypt ledger: names, Drive IDs,
                                 sizes, timestamps, tags of archives pushed
                                 to Drive. Preserved so `scrt4 recover`
                                 rebuilds both vault AND cloud-crypt index.
    - audit.log             — append-only daemon audit trail

  No plaintext is written. The archive is safe at rest; the master key
  is needed to decrypt anything inside it.

BACKUP BEST PRACTICES:

  - Run `scrt4 backup-vault` regularly (automated or weekly)
  - Run `scrt4 backup-key --save /path/to/USB` at least once
  - Store the USB/paper key offline (safe, lockbox)
  - Never paste the master key into a chat, email, or repo
  - After recovery, re-register a new authenticator with `scrt4 setup`
  - For off-site encrypted key escrow: `scrt4 backup-key --to-drive`
    (re-wraps the key under AES-GCM, uploads ciphertext to Drive via
    cloud-crypt; plaintext never leaves the machine).

GUIDE
}

# cmd_daemon — start scrt4-daemon in the foreground.
#
# Thin wrapper around the daemon binary so users don't have to remember
# its install path. Matches `scrt4 daemon` in the v0.1.0 menu. Exits
# with an error if the binary isn't on PATH; the user can always run
# the daemon directly in that case.
cmd_daemon() {
    local bin
    if command -v scrt4-daemon >/dev/null 2>&1; then
        bin=scrt4-daemon
    elif [ -x "/usr/local/bin/scrt4-daemon" ]; then
        bin="/usr/local/bin/scrt4-daemon"
    elif [ -x "$HOME/.local/bin/scrt4-daemon" ]; then
        bin="$HOME/.local/bin/scrt4-daemon"
    else
        echo -e "${RED}scrt4-daemon binary not found on PATH or in the usual install locations.${NC}" >&2
        echo "Install it or run the daemon directly from its build output." >&2
        return 1
    fi
    echo -e "${CYAN}Starting scrt4-daemon...${NC}"
    exec "$bin" "$@"
}

# cmd_list [--tags] [--tag TAG] — lists secret names.
#
# With no flags, prints one name per line (same as the v0.1.0 monolith
# when called without flags, and compatible with scripts that parse
# the output).
#
# --tags    also print each name's tag set in `[tag1, tag2]` form
# --tag T   only list secrets carrying tag T (case-insensitive)
#
# Tags are read from $CONFIG_DIR/tags.json — the same file the `tags`
# module writes to.
cmd_list() {
    ensure_unlocked || return 1

    local filter_tag=""
    local show_tags=false
    while [ $# -gt 0 ]; do
        case "$1" in
            --tag)  filter_tag="${2:-}"; shift 2 ;;
            --tags) show_tags=true; shift ;;
            *)      shift ;;
        esac
    done

    local response
    response=$(send_request '{"method":"list"}')
    local ok
    ok=$(echo "$response" | jq -r '.success // false')
    if [ "$ok" != "true" ]; then
        echo -e "${RED}list failed: $(echo "$response" | jq -r '.error // "unknown"')${NC}" >&2
        return 1
    fi

    local names
    names=$(echo "$response" | jq -r '.data.names[]?' 2>/dev/null)
    if [ -z "$names" ]; then
        echo -e "${YELLOW}No secrets stored. Add with: scrt4 add KEY=value${NC}"
        return 0
    fi

    # Fast path: no flags, no tags file read — preserve the historical
    # script-parseable one-name-per-line output.
    if [ -z "$filter_tag" ] && [ "$show_tags" = false ]; then
        echo "$names"
        return 0
    fi

    # Load the tags file. If it doesn't exist, treat every secret as untagged.
    local tags_file="${CONFIG_DIR}/tags.json"
    local tags_json='{}'
    if [ -f "$tags_file" ]; then
        tags_json=$(cat "$tags_file")
    fi

    if [ -n "$filter_tag" ]; then
        local filtered=""
        while IFS= read -r name; do
            local has
            has=$(printf '%s' "$tags_json" | jq -r --arg k "$name" --arg t "$filter_tag" \
                '(.[$k] // []) | map(ascii_downcase) | if index($t | ascii_downcase) then "yes" else "no" end')
            if [ "$has" = "yes" ]; then
                filtered+="${name}"$'\n'
            fi
        done <<< "$names"
        names="${filtered%$'\n'}"
        if [ -z "$names" ]; then
            echo -e "${YELLOW}No secrets with tag '${filter_tag}'.${NC}"
            return 0
        fi
    fi

    local count
    count=$(printf '%s\n' "$names" | grep -c .)
    if [ -n "$filter_tag" ]; then
        echo -e "${CYAN}${count} secret(s) tagged '${filter_tag}':${NC}"
    else
        echo -e "${CYAN}${count} secret(s):${NC}"
    fi
    while IFS= read -r name; do
        [ -z "$name" ] && continue
        if [ "$show_tags" = true ] || [ -n "$filter_tag" ]; then
            local t
            t=$(printf '%s' "$tags_json" | jq -r --arg k "$name" '.[$k] // [] | join(", ")')
            if [ -n "$t" ]; then
                echo "  ${name}  [${t}]"
            else
                echo "  ${name}"
            fi
        else
            echo "$name"
        fi
    done <<< "$names"
}

# _regen_claude_md — write the vault secret-name block into a CLAUDE.md.
#
# Called from cmd_learn and auto-triggered after cmd_add / cmd_view mutations
# so that Claude Code agents always see a fresh list of available secret
# NAMES (never values) as part of their global context.
#
# Target file resolution order:
#   1. $SCRT4_CLAUDE_MD if set
#   2. ~/.claude/CLAUDE.md if the ~/.claude directory exists
#   3. Silently no-op otherwise (user has no Claude Code install)
#
# The block is delimited by <!-- scrt4:begin --> / <!-- scrt4:end --> so
# repeated runs replace the block without clobbering the rest of CLAUDE.md.
# Runs only when unlocked AND with an active session — no prompting, no
# auth challenge — so it can safely be called from any post-mutation hook.
_regen_claude_md() {
    local target="${SCRT4_CLAUDE_MD:-}"
    if [ -z "$target" ]; then
        if [ -d "${HOME}/.claude" ]; then
            target="${HOME}/.claude/CLAUDE.md"
        else
            return 0
        fi
    fi

    # Ask the daemon for the name list. If it errors (no session, no
    # vault, etc.) we silently do nothing — post-mutation hooks must
    # never block or fail the mutation itself.
    local resp
    resp=$(send_request '{"method":"list"}' 2>/dev/null) || return 0
    local ok
    ok=$(echo "$resp" | jq -r '.success // false' 2>/dev/null)
    [ "$ok" = "true" ] || return 0

    local names
    names=$(echo "$resp" | jq -r '.data.names[]?' 2>/dev/null | sort)

    local today
    today=$(date -u +%Y-%m-%d)

    local block
    block=$(
        echo '<!-- scrt4:begin -->'
        echo '## scrt4 vault — available secret names'
        echo ''
        echo 'These secrets live in the local scrt4 vault. The values are encrypted at'
        echo 'rest and only decrypted into subprocess environment for the lifetime of'
        echo 'one command. **Never** ask the user for these values, never echo them,'
        echo 'never write them to files.'
        echo ''
        echo 'Use them by writing commands with `$env[NAME]` placeholders:'
        echo ''
        echo '```bash'
        echo "scrt4 run 'curl -H \"Authorization: Bearer \$env[GITHUB_PAT]\" https://api.github.com/user'"
        echo '```'
        echo ''
        if [ -z "$names" ]; then
            echo '_No secrets stored yet. Run `scrt4 add NAME=value` to add one._'
        else
            echo '| Name |'
            echo '|------|'
            while IFS= read -r n; do
                [ -z "$n" ] && continue
                printf '| `%s` |\n' "$n"
            done <<< "$names"
        fi
        echo ''
        echo "_Last updated: ${today} by \`scrt4 learn\`._"
        echo '<!-- scrt4:end -->'
    )

    local tmp
    tmp=$(mktemp "${target}.tmp.XXXXXX") || return 0
    if [ -f "$target" ]; then
        awk -v block="$block" '
            BEGIN { in_block = 0 }
            /<!-- scrt4:begin -->/ { in_block = 1; print block; next }
            /<!-- scrt4:end -->/   { in_block = 0; next }
            !in_block { print }
        ' "$target" > "$tmp"
        if ! grep -q '<!-- scrt4:begin -->' "$target"; then
            printf '\n%s\n' "$block" >> "$tmp"
        fi
    else
        mkdir -p "$(dirname "$target")"
        printf '%s\n' "$block" > "$tmp"
    fi
    mv -f "$tmp" "$target"
}

# cmd_learn — regenerate the scrt4 secret-name block in CLAUDE.md.
#
# User-facing alias of _regen_claude_md with verbose output. Called from
# the first-run flow (quickstart module) and any time the user wants to
# refresh Claude's view of the vault.
cmd_learn() {
    ensure_unlocked || return 1

    local target="${SCRT4_CLAUDE_MD:-}"
    if [ -z "$target" ]; then
        if [ -d "${HOME}/.claude" ]; then
            target="${HOME}/.claude/CLAUDE.md"
        else
            echo -e "${YELLOW}No ~/.claude directory — skipping CLAUDE.md regen.${NC}"
            echo -e "${YELLOW}Set SCRT4_CLAUDE_MD=/path/to/CLAUDE.md to override.${NC}"
            return 0
        fi
    fi

    _regen_claude_md
    if [ -f "$target" ]; then
        local n
        n=$(awk '/<!-- scrt4:begin -->/,/<!-- scrt4:end -->/' "$target" | grep -c '^| `')
        echo -e "${GREEN}Updated ${target}${n} secret name(s) in the vault block.${NC}"
    else
        echo -e "${YELLOW}Could not write ${target}.${NC}"
        return 1
    fi
}

# cmd_add [KEY=value ...] — add one or more secrets.
#
# Two modes:
#   - KEY=value arguments on the command line → add them directly
#   - No arguments → open a zenity notepad so the user can paste a
#     KEY=value block. Lines starting with `#` are ignored. Falls back
#     to a usage-error message when zenity is not available (dev image
#     deliberately ships without zenity).
#
# Ported from v0.1.0 monolith cmd_add; kept the Python parser verbatim
# because it handles both `KEY=value` and `KEY: value` shapes and
# reports the set of skipped lines via stderr.
cmd_add() {
    ensure_unlocked || return 1

    if [ $# -eq 0 ]; then
        # ── GUI mode: zenity notepad ──
        if ! _has_gui; then
            echo -e "${RED}Usage: scrt4 add KEY=value [KEY=value ...]${NC}" >&2
            echo -e "${YELLOW}GUI mode needs zenity + DISPLAY. This distribution has neither; pass KEY=value arguments on the command line.${NC}" >&2
            return 1
        fi

        local tmpfile
        tmpfile=$(mktemp /tmp/scrt4-add-XXXXXX.txt)
        cat > "$tmpfile" << 'PLACEHOLDER'
# Paste your secrets below, one per line
# Format: KEY=value
# Lines starting with # are ignored
# Example:
# API_KEY=sk-abc123
# DB_PASSWORD=mysecretpassword
PLACEHOLDER

        local input
        input=$(zenity --text-info --editable \
            --title="scrt4 — Add Secrets" \
            --width=700 --height=500 \
            --font="monospace" \
            --filename="$tmpfile" 2>/dev/null)
        local zenity_rc=$?
        rm -f "$tmpfile"

        if [ $zenity_rc -ne 0 ] || [ -z "$input" ]; then
            echo -e "${YELLOW}Cancelled.${NC}"
            return 0
        fi

        local parse_log="/tmp/scrt4-add-parse-$$.log"
        local secrets_json
        secrets_json=$(printf '%s' "$input" | python3 -c '
import sys, json, re
lines = sys.stdin.read().splitlines()
secrets = {}
skipped = []
for line in lines:
    stripped = line.strip()
    if not stripped or stripped.startswith("#"):
        continue
    if "=" in stripped:
        key, value = stripped.split("=", 1)
        key = key.strip()
        if key:
            secrets[key] = value
            continue
    if ":" in stripped:
        key, value = stripped.split(":", 1)
        key = key.strip()
        value = value.strip()
        if key and re.match(r"^[A-Za-z_][A-Za-z0-9_]*$", key):
            secrets[key] = value
            continue
    skipped.append(stripped)
for s in skipped:
    print(f"SKIPPED:{s}", file=sys.stderr)
print(f"COUNT:{len(secrets)}", file=sys.stderr)
print(json.dumps(secrets), end="")
' 2>"$parse_log")

        while IFS= read -r logline; do
            if [[ "$logline" == SKIPPED:* ]]; then
                echo -e "${YELLOW}Skipping: ${logline#SKIPPED:}${NC}" >&2
            fi
        done < "$parse_log"
        local count
        count=$(grep '^COUNT:' "$parse_log" | head -1 | cut -d: -f2)
        rm -f "$parse_log"

        if [ "${count:-0}" -eq 0 ]; then
            echo -e "${YELLOW}No valid KEY=value lines found.${NC}"
            return 0
        fi

        local req
        req=$(jq -nc --argjson secrets "$secrets_json" '{method:"add_secrets",params:{secrets:$secrets}}')
        local resp
        resp=$(send_request "$req")
        local ok
        ok=$(echo "$resp" | jq -r '.success // false')
        if [ "$ok" = "true" ]; then
            echo -e "${GREEN}Added $(echo "$resp" | jq -r '.data.count // 0') secret(s).${NC}"
            _regen_claude_md 2>/dev/null || true
        else
            echo -e "${RED}$(echo "$resp" | jq -r '.error // "unknown error"')${NC}" >&2
            return 1
        fi
        return 0
    fi

    # ── CLI mode: KEY=value arguments ──
    # Daemon protocol: AddSecrets takes a flat `secrets` map {NAME: VALUE}.
    local secrets_json='{}'
    local arg
    for arg in "$@"; do
        if [[ "$arg" != *=* ]]; then
            echo -e "${RED}Invalid entry: ${arg} (expected KEY=value)${NC}" >&2
            return 1
        fi
        local k="${arg%%=*}"
        local v="${arg#*=}"
        secrets_json=$(echo "$secrets_json" | jq --arg k "$k" --arg v "$v" '. + {($k):$v}')
    done
    local req
    req=$(jq -nc --argjson secrets "$secrets_json" '{method:"add_secrets",params:{secrets:$secrets}}')
    local resp
    resp=$(send_request "$req")
    local ok
    ok=$(echo "$resp" | jq -r '.success // false')
    if [ "$ok" = "true" ]; then
        echo -e "${GREEN}Added $(echo "$resp" | jq -r '.data.count // 0') secret(s).${NC}"
        _regen_claude_md 2>/dev/null || true
    else
        echo -e "${RED}$(echo "$resp" | jq -r '.error // "unknown error"')${NC}" >&2
        return 1
    fi
}

# cmd_run 'CMD' — runs a command with $env[NAME] substitution.
# This is one of the most security-sensitive paths; the substitution
# itself happens daemon-side (see TCB note on _run_with_injected_secrets).
# cmd_run [--cwd DIR] 'cmd $env[KEY]'
#
# Runs in the caller's directory by default; --cwd overrides it.
cmd_run() {
    ensure_unlocked || return 1
    local cwd="$PWD"
    while [ $# -gt 0 ]; do
        case "$1" in
            --cwd)
                [ $# -ge 2 ] || { echo "scrt4 run: --cwd needs a directory" >&2; return 1; }
                cwd="$2"; shift 2 ;;
            --cwd=*)
                cwd="${1#--cwd=}"; shift ;;
            *) break ;;
        esac
    done
    if [ $# -eq 0 ]; then
        echo "Usage: scrt4 run [--cwd DIR] 'cmd \$env[KEY]'" >&2
        return 1
    fi
    if [ ! -d "$cwd" ]; then
        echo "scrt4 run: no such directory: $cwd" >&2
        return 1
    fi
    local cmd="$*"
    _run_with_injected_secrets "$cmd" "$cwd"
}

# cmd_view [--cli] — view secret values.
#
# Default: zenity dialog (hardened + GUI-capable environments). This
# is the GUI the v0.1.0 monolith uses — intentionally a GUI-only dialog
# so secret values never touch terminal scrollback or stdout pipes.
#
# --cli:   text mode — secrets are printed to stdout. Required for
#          headless/SSH/agent contexts, and used automatically when
#          no GUI is available (_has_gui returns false).
#
# Uses the daemon's two-phase reveal_all + reveal_all_confirm flow,
# gated by _wa_gate (WebAuthn step-up).
cmd_view() {
    ensure_unlocked || return 1

    local cli_mode=false
    if [ "${1:-}" = "--cli" ] || [ "$FORCE_CLI" = true ]; then
        cli_mode=true
    fi
    # Auto-fallback: if no GUI is reachable, force CLI mode so the
    # command doesn't silently fail on a missing zenity.
    if [ "$cli_mode" = false ] && ! _has_gui; then
        cli_mode=true
    fi

    _wa_gate || return 1

    local resp1
    resp1=$(send_request '{"method":"reveal_all"}')
    local ok1
    ok1=$(echo "$resp1" | jq -r '.success // false')
    if [ "$ok1" != "true" ]; then
        echo -e "${RED}view failed: $(echo "$resp1" | jq -r '.error // "unknown"')${NC}" >&2
        return 1
    fi
    local challenge code
    challenge=$(echo "$resp1" | jq -r '.data.challenge')
    code=$(echo "$resp1" | jq -r '.data.code')

    local resp2
    resp2=$(send_request "$(jq -nc --arg c "$challenge" --arg k "$code" '{method:"reveal_all_confirm",params:{challenge:$c,code:$k}}')")
    local ok2
    ok2=$(echo "$resp2" | jq -r '.success // false')
    if [ "$ok2" != "true" ]; then
        echo -e "${RED}view confirm failed: $(echo "$resp2" | jq -r '.error // "unknown"')${NC}" >&2
        return 1
    fi

    local count
    count=$(echo "$resp2" | jq -r '.data.secrets | length // 0')
    if [ "${count:-0}" -eq 0 ] 2>/dev/null; then
        echo -e "${YELLOW}No secrets stored. Add with: scrt4 add KEY=value${NC}"
        return 0
    fi

    local secrets
    secrets=$(echo "$resp2" | jq -r '.data.secrets | to_entries | sort_by(.key) | .[] | "\(.key)=\(.value)"')

    if [ "$cli_mode" = true ]; then
        echo ""
        printf '%s\n' "$secrets"
        echo ""
        secrets="[CLEARED]"
        resp2="[CLEARED]"
        return 0
    fi

    # GUI mode — zenity editable text dialog. On Save, parse KEY=value
    # lines and round-trip through add_secrets so edits persist.
    local edited
    edited=$(zenity --text-info --title="scrt4 — View All" \
        --editable --width=800 --height=600 \
        --font="monospace" \
        --ok-label="Save" \
        <<< "$secrets" 2>/dev/null)
    local zenity_rc=$?
    if [ $zenity_rc -ne 0 ]; then
        secrets="[CLEARED]"; resp2="[CLEARED]"; return 0
    fi

    if [ -n "$edited" ]; then
        local save_json save_count parse_log
        parse_log="/tmp/scrt4-view-parse-$$.log"
        save_json=$(printf '%s' "$edited" | python3 -c '
import sys, json, re
lines = sys.stdin.read().splitlines()
secrets = {}
for line in lines:
    stripped = line.strip()
    if not stripped or stripped.startswith("#"):
        continue
    if "=" in stripped:
        key, value = stripped.split("=", 1)
        key = key.strip()
        if key:
            secrets[key] = value
print(f"COUNT:{len(secrets)}", file=sys.stderr)
print(json.dumps(secrets), end="")
' 2>"$parse_log")
        save_count=$(grep '^COUNT:' "$parse_log" | head -1 | cut -d: -f2)
        rm -f "$parse_log"

        if [ "${save_count:-0}" -gt 0 ]; then
            local save_resp
            save_resp=$(send_request "$(jq -nc --argjson s "$save_json" '{method:"add_secrets",params:{secrets:$s}}')")
            local save_ok
            save_ok=$(echo "$save_resp" | jq -r '.success // false')
            if [ "$save_ok" = "true" ]; then
                echo -e "${GREEN}Saved ${save_count} secret(s).${NC}"
                _regen_claude_md 2>/dev/null || true
            else
                echo -e "${RED}Save failed: $(echo "$save_resp" | jq -r '.error // "unknown"')${NC}" >&2
            fi
        fi
    fi
    secrets="[CLEARED]"; edited="[CLEARED]"; resp2="[CLEARED]"
}

# ── Argument parsing for global flags ────────────────────────────────

# --cli sets FORCE_CLI; other args fall through to the command dispatcher.
_parse_global_flags() {
    local -a passthrough=()
    while [ $# -gt 0 ]; do
        case "$1" in
            --cli)
                FORCE_CLI=true
                shift
                ;;
            *)
                passthrough+=("$1")
                shift
                ;;
        esac
    done
    printf '%s\n' "${passthrough[@]}"
}

# ── LLM / agent discovery ────────────────────────────────────────────
#
# One-stop discovery command for LLM agents (Claude Code and friends).
# `scrt4 llm` prints an llms.txt-style capability map: what scrt4 does,
# how to invoke it, which capabilities need setup, and the exact one-
# command paths to configure each optional capability. Safe to call
# without unlock — it only probes session status, never reveals values.

cmd_llm() {
    local format="text"
    while [ $# -gt 0 ]; do
        case "$1" in
            --json) format="json"; shift ;;
            --help|-h) echo "Usage: scrt4 llm [--json]"; return 0 ;;
            *) shift ;;
        esac
    done

    # Probe session status — non-fatal.
    local status_resp unlocked="unknown"
    status_resp=$(send_request '{"method":"status"}' 2>/dev/null || true)
    if [ -n "$status_resp" ]; then
        unlocked=$(echo "$status_resp" | jq -r '.data.unlocked // false' 2>/dev/null || echo "unknown")
    fi

    # Detect which modules are present (by checking for their register fns).
    local -a modules=()
    declare -F scrt4_module_cloud_crypt_register >/dev/null 2>&1 && modules+=("cloud-crypt")
    declare -F scrt4_module_encrypt_folder_register >/dev/null 2>&1 && modules+=("encrypt-folder")
    declare -F scrt4_module_import_env_register >/dev/null 2>&1 && modules+=("import-env")
    declare -F scrt4_module_menu_register >/dev/null 2>&1 && modules+=("menu")
    declare -F scrt4_module_wallet_register >/dev/null 2>&1 && modules+=("wallet")
    declare -F scrt4_module_github_register >/dev/null 2>&1 && modules+=("github")
    declare -F scrt4_module_stripe_register >/dev/null 2>&1 && modules+=("stripe")
    declare -F scrt4_module_domain_register >/dev/null 2>&1 && modules+=("domain")
    declare -F scrt4_module_gcp_register >/dev/null 2>&1 && modules+=("gcp")
    declare -F scrt4_module_website_register >/dev/null 2>&1 && modules+=("website")
    declare -F scrt4_module_messages_register >/dev/null 2>&1 && modules+=("messages")
    declare -F scrt4_module_wizards_register >/dev/null 2>&1 && modules+=("wizards")
    declare -F scrt4_module_quickstart_register >/dev/null 2>&1 && modules+=("quickstart")

    # cloud-crypt auth probe.
    local cc_auth="not configured"
    if declare -F _scrt4_cc_resolve_oauth_name >/dev/null 2>&1; then
        local cc_name; cc_name=$(_scrt4_cc_resolve_oauth_name)
        if [ -n "${SCRT4_CC_DRIVE_TOKEN:-}" ]; then
            cc_auth="env override (SCRT4_CC_DRIVE_TOKEN)"
        elif [ "$unlocked" = "true" ] && declare -F _scrt4_cc_has_vault_oauth >/dev/null 2>&1 && _scrt4_cc_has_vault_oauth; then
            cc_auth="vault OAuth ($cc_name)"
        elif command -v gcloud >/dev/null 2>&1 && gcloud auth application-default print-access-token >/dev/null 2>&1; then
            cc_auth="gcloud ADC"
        fi
    fi

    if [ "$format" = "json" ]; then
        jq -nc \
            --arg version "$VERSION" \
            --arg unlocked "$unlocked" \
            --arg cc_auth "$cc_auth" \
            --argjson modules "$(printf '%s\n' "${modules[@]}" | jq -R . | jq -sc .)" \
            '{
              name: "scrt4",
              version: $version,
              unlocked: ($unlocked == "true"),
              modules: $modules,
              capabilities: {
                cloud_crypt_auth: $cc_auth
              },
              setup_commands: {
                register_passkey:           "scrt4 setup agent",
                unlock:                     "scrt4 unlock",
                cloud_crypt_auth_gws:       "scrt4 cloud-crypt auth setup --from-gws",
                cloud_crypt_auth_existing:  "scrt4 cloud-crypt auth setup --from-secret personal_google_workspace",
                cloud_crypt_auth_paste:     "scrt4 cloud-crypt auth setup --paste",
                cloud_crypt_auth_guide:     "scrt4 cloud-crypt auth guide"
              }
            }'
        return 0
    fi

    cat <<LLMEOF
# scrt4 — LLM capability map (llms.txt)

> Runtime secrets engine with FIDO2/WebAuthn-bound encryption.
> Single-user CLI + background daemon. Secrets are injected into a
> subprocess's environment at run time. LLM agents can USE them via
> \$env[NAME] placeholders but cannot SEE their values — the daemon
> substitutes values only inside the subprocess and redacts all
> stored-secret values from that subprocess's stdout/stderr before
> returning output.

## Current state

- version:   $VERSION
- unlocked:  $unlocked
- modules:   ${modules[*]:-(none)}

## First-time user onboarding (agents: follow this order)

If the user is new to scrt4 or their session is locked, walk them through:

1. \`scrt4 setup\` — register a FIDO2 passkey (once per machine).
2. \`scrt4 unlock\` — open a session.
3. Run \`scrt4 llm\` again now that the session is live to see vault state.
4. Set up **encrypted Google Drive backup** (see cloud-crypt below). The
   ciphertext goes to Drive; Google cannot read it. This is the recommended
   disaster-recovery path — prioritize it over plain \`backup-key\`.
5. Save a master-key recovery copy: \`scrt4 backup-key --save \$HOME/Desktop\`,
   then move it into a password manager — do not leave it on disk.
6. Offer to import existing \`.env\` files (see below). Ask first before
   scanning the filesystem.

## Setup commands (for agents)

    scrt4 llm                 # Print this doc
    scrt4 llm --json          # Same, machine-readable

## Importing existing .env files (import-env module)

Plaintext \`.env\` files on disk should move into scrt4. With user consent:

    scrt4 import path/to/.env

Parser handles \`export KEY=value\`, quoted values, and \`#\` comments.
After a successful import, suggest deleting the plaintext file (confirm
first — some tooling still reads \`.env\` directly).

Finding candidate files (paths only, never content):

    find \$HOME/your/projects -name '.env' -o -name '.env.local' \\
        -o -name '.env.production' 2>/dev/null

## Core commands (always available)

    scrt4 setup [agent]       # Register a WebAuthn passkey (first-time only)
    scrt4 unlock [ttl]        # Authenticate & open a session (default 2h)
    scrt4 status              # Session status
    scrt4 list                # List secret NAMES (never values)
    scrt4 add KEY=value ...   # Add one or more secrets
    scrt4 run 'cmd \$env[K]'  # Run a command with secret injection
    scrt4 view [--cli]        # View secrets (GUI-only by default)
    scrt4 logout              # Lock the session

## Secret-injection contract (IMPORTANT for agents)

Write \`\$env[NAME]\` literally (NOT \`\$NAME\`, NOT \`\${NAME}\`) inside
the command string passed to \`scrt4 run\`. Example:

    scrt4 run 'curl -H "Authorization: Bearer \$env[API_KEY]" https://api.example.com'

The daemon replaces \`\$env[API_KEY]\` with the literal secret value
before spawning the shell. Values never appear in argv of any child
process of this CLI and are scrubbed from stdout before return.

## Optional capabilities

### cloud-crypt — encrypted Google Drive backup
Status: ${cc_auth}

Push/pull/encrypt-and-push .scrt4 ciphertext archives to the user's
personal Google Drive. All crypto lives in Core (TCB); the module
only moves ciphertext + metadata. Needs a Drive-scoped OAuth token.

Setup paths (pick one):

    scrt4 cloud-crypt auth setup --from-gws
        Uses Google Workspace CLI (\`gws\`). Fastest — handles the
        browser-consent + refresh-token dance automatically.

    scrt4 cloud-crypt auth setup --from-secret personal_google_workspace
        Reuses an existing OAuth blob already in the vault (e.g.
        the \`personal_google_workspace\` secret). Nothing is copied;
        cloud-crypt is pointed at the existing secret via
        ~/.scrt4/cloud-crypt.conf. Zero browser hops.

    scrt4 cloud-crypt auth setup --paste
        Prompts for the blob interactively. Format:
        {client_id:X,client_secret:Y,refresh_token:Z,token_uri:...}

    scrt4 cloud-crypt auth guide
        Prints the full step-by-step walkthrough (install gws,
        create OAuth client, enable APIs, run consent flow).

    scrt4 cloud-crypt auth status
        Shows which token source is currently active.

Commands (after setup):

    scrt4 cloud-crypt list
    scrt4 cloud-crypt encrypt-and-push PATH [PATH...]
    scrt4 cloud-crypt push FILE.scrt4 [--yes]
    scrt4 cloud-crypt pull DRIVE_ID [--out DIR] [--yes]
    scrt4 cloud-crypt decrypt DRIVE_ID [--out DIR] [--yes]

### Other modules (if loaded)

Each module has its own subcommand set. Run \`scrt4 help\` for the
full list on this build, or \`scrt4 <module> help\` for per-module
help. Modules present in this build: ${modules[*]:-(none)}

## Agent-friendly flags

    --json        Machine-readable output on list/status/where
    --yes / -y    Skip confirmations (required in non-interactive shells)
    --dry-run     Preview a write without performing it

## Trust model (short version)

1. LLM agents never see secret values.
2. LLM agents CAN use secrets via \$env[NAME] in \`scrt4 run\`.
3. Vault is AES-256-GCM encrypted at rest.
4. Master key is hardware-bound (FIDO2 hmac-secret on a passkey/YubiKey).
5. Daemon scrubs known secret values from all subprocess output.

## Quick prompt for users

If you are Claude and the user asks to "set up scrt4" or "configure
scrt4 cloud storage", walk them through the onboarding steps above
(\`scrt4 setup\`\`scrt4 unlock\` → cloud-crypt backup → import). For
a non-interactive audit, run:

    scrt4 llm --json
LLMEOF
}

# ── upgrade ───────────────────────────────────────────────────────────
#
# Channels are a fixed table, deliberately. Resolving a caller-supplied URL
# here would mean "download this and put it on $PATH", which is remote code
# execution with extra steps. Unknown names are rejected rather than treated
# as a host.
_scrt4_channel_base() {
    case "$1" in
        public) printf 'https://install.llmsecrets.com' ;;
        *)      return 1 ;;
    esac
}

# cmd_upgrade [--channel NAME] [--version TAG] [--check] [--force]
#
# Replaces the running CLI and daemon with a published build. Everything is
# downloaded and checksum-verified before anything on disk is touched, so a
# failed download leaves a working install rather than half of one.
cmd_upgrade() {
    local channel="public" want_version="" check_only=false force=false

    while [ $# -gt 0 ]; do
        case "$1" in
            --channel) channel="${2:-}"; shift 2 ;;
            --channel=*) channel="${1#--channel=}"; shift ;;
            --version) want_version="${2:-}"; shift 2 ;;
            --version=*) want_version="${1#--version=}"; shift ;;
            --check) check_only=true; shift ;;
            --force) force=true; shift ;;
            *) echo -e "${RED}upgrade: unknown argument: $1${NC}" >&2
               echo "Usage: scrt4 upgrade [--channel NAME] [--version TAG] [--check] [--force]" >&2
               return 1 ;;
        esac
    done

    local base
    if ! base=$(_scrt4_channel_base "$channel"); then
        echo -e "${RED}upgrade: unknown channel: ${channel}${NC}" >&2
        echo "Available: public" >&2
        return 1
    fi
    # SCRT4_RELEASE_HOST already overrides the host for verify-self; honour it
    # here too so a mirror can be tested without editing the table.
    base="${SCRT4_RELEASE_HOST:-$base}"

    local target="$want_version"
    if [ -z "$target" ]; then
        target=$(curl -fsSL --max-time 20 "${base}/releases/latest.txt" 2>/dev/null | tr -d '[:space:]')
        if [ -z "$target" ]; then
            echo -e "${RED}upgrade: could not read the published version from ${base}.${NC}" >&2
            return 1
        fi
    fi

    local current="v${VERSION#v}"
    local wanted="v${target#v}"
    echo -e "${CYAN}Installed:${NC} ${current}"
    echo -e "${CYAN}Published:${NC} ${wanted}  (${channel})"

    if [ "$current" = "$wanted" ] && [ "$force" != true ]; then
        echo -e "${GREEN}Already up to date.${NC}"
        return 0
    fi

    # Going backwards is almost never what someone typing "upgrade" wants,
    # and a channel that has not caught up yet would otherwise silently
    # downgrade a newer build. Comparing for inequality alone is not enough.
    if [ "$current" != "$wanted" ] && [ "$force" != true ] && [ -z "$want_version" ]; then
        local lower
        lower=$(printf '%s\n%s\n' "${current#v}" "${wanted#v}" | sort -V 2>/dev/null | head -1)
        if [ "$lower" = "${wanted#v}" ]; then
            echo -e "${YELLOW}The ${channel} channel is behind this build — not downgrading.${NC}"
            echo -e "${YELLOW}Use --version ${wanted} to install it anyway.${NC}"
            return 0
        fi
    fi

    if [ "$check_only" = true ]; then
        echo -e "${YELLOW}Update available. Run: scrt4 upgrade${NC}"
        return 0
    fi

    local os arch
    case "$(uname -s 2>/dev/null)" in
        Linux)  os=linux ;;
        Darwin) os=darwin ;;
        *) echo -e "${RED}upgrade: unsupported OS.${NC}" >&2; return 1 ;;
    esac
    case "$(uname -m 2>/dev/null)" in
        x86_64|amd64)  arch=x86_64 ;;
        aarch64|arm64) arch=aarch64 ;;
        *) echo -e "${RED}upgrade: unsupported architecture.${NC}" >&2; return 1 ;;
    esac
    # Only aarch64 darwin is published; Intel Macs run it under Rosetta 2.
    [ "$os" = darwin ] && arch=aarch64

    local sha_cmd=""
    if command -v sha256sum >/dev/null 2>&1; then
        sha_cmd="sha256sum"
    elif command -v shasum >/dev/null 2>&1; then
        sha_cmd="shasum -a 256"
    else
        echo -e "${RED}upgrade: no sha256sum or shasum — refusing to install unverified binaries.${NC}" >&2
        return 1
    fi

    # Where the running install lives. Replacing whatever is on PATH would
    # upgrade a different copy than the one in use.
    local cli_path="${BASH_SOURCE[0]:-$0}"
    if command -v readlink >/dev/null 2>&1; then
        local resolved
        resolved=$(readlink -f "$cli_path" 2>/dev/null || true)
        [ -n "$resolved" ] && cli_path="$resolved"
    fi
    local install_dir
    install_dir=$(dirname "$cli_path")
    local daemon_path="${install_dir}/scrt4-daemon"
    if [ ! -w "$install_dir" ]; then
        echo -e "${RED}upgrade: ${install_dir} is not writable.${NC}" >&2
        echo -e "${YELLOW}Re-run with the permissions that installed scrt4.${NC}" >&2
        return 1
    fi

    local tmp
    tmp=$(mktemp -d "${TMPDIR:-/tmp}/scrt4-upgrade.XXXXXX") || return 1
    # shellcheck disable=SC2064
    trap "rm -rf '$tmp'" RETURN

    local rel="${base}/releases/${wanted}"
    local daemon_file="scrt4-daemon-${os}-${arch}"
    echo -e "${CYAN}Downloading:${NC} ${rel}"
    if ! curl -fsSL --max-time 300 "${rel}/scrt4"          -o "${tmp}/scrt4" \
    || ! curl -fsSL --max-time 300 "${rel}/${daemon_file}" -o "${tmp}/${daemon_file}" \
    || ! curl -fsSL --max-time 60  "${rel}/SHA256SUMS"     -o "${tmp}/SHA256SUMS"; then
        echo -e "${RED}upgrade: download failed — nothing was changed.${NC}" >&2
        return 1
    fi

    # Verify before anything is replaced. Filter to the two files we fetched
    # so other-arch entries do not fail the check.
    (
        cd "$tmp" || exit 1
        grep -E "  [*]?(scrt4|${daemon_file})\$" SHA256SUMS > expected.sums 2>/dev/null
        [ -s expected.sums ] || { echo "manifest has no entry for scrt4/${daemon_file}" >&2; exit 1; }
        # shellcheck disable=SC2086
        $sha_cmd -c expected.sums >/dev/null 2>&1
    )
    if [ $? -ne 0 ]; then
        echo -e "${RED}upgrade: checksum verification FAILED — nothing was changed.${NC}" >&2
        return 1
    fi
    echo -e "${GREEN}Checksums verified.${NC}"

    # Install via a temp name + mv so a crash mid-write cannot leave a
    # truncated binary in place. Replacing a running file is fine on Unix:
    # the open inode survives until the process exits.
    chmod 755 "${tmp}/scrt4" "${tmp}/${daemon_file}"
    mv -f "${tmp}/scrt4"          "${cli_path}.new"    && mv -f "${cli_path}.new"    "$cli_path"
    mv -f "${tmp}/${daemon_file}" "${daemon_path}.new" && mv -f "${daemon_path}.new" "$daemon_path"
    echo -e "${GREEN}Installed ${wanted} to ${install_dir}.${NC}"

    # The old daemon keeps running until restarted, so the session survives
    # the upgrade but the new binary is not in use until this happens.
    if command -v systemctl >/dev/null 2>&1 && systemctl --user is-enabled scrt4-daemon.service >/dev/null 2>&1; then
        systemctl --user restart scrt4-daemon.service 2>/dev/null \
            && echo -e "${GREEN}Restarted scrt4-daemon.service.${NC}" \
            || echo -e "${YELLOW}Restart scrt4-daemon.service to finish.${NC}"
    elif [ "$os" = darwin ] && command -v launchctl >/dev/null 2>&1; then
        local plist="$HOME/Library/LaunchAgents/com.llmsecrets.scrt4-daemon.plist"
        if [ -f "$plist" ]; then
            launchctl unload "$plist" 2>/dev/null || true
            launchctl load "$plist" 2>/dev/null \
                && echo -e "${GREEN}Reloaded the scrt4 launch agent.${NC}" \
                || echo -e "${YELLOW}Reload the scrt4 launch agent to finish.${NC}"
        fi
    else
        echo -e "${YELLOW}Restart scrt4-daemon to finish.${NC}"
    fi

    echo -e "${YELLOW}Your session was not affected; run 'scrt4 status' to confirm.${NC}"
    return 0
}

# cmd_verify_self — hash the running scrt4 binary and compare against the
# published SHA256SUMS at install.llmsecrets.com. Exit 0 on match, 1 on
# mismatch or fetch failure. Core command: the user's first question is
# "am I running what I think I'm running?" and the answer shouldn't depend
# on any module being loaded.
cmd_verify_self() {
    local release_host="${SCRT4_RELEASE_HOST:-https://install.llmsecrets.com}"
    # Hash the file that is actually executing, not whatever scrt4 resolves to
    # on PATH — those can differ when a user is testing a locally-built binary.
    local bin_path="${BASH_SOURCE[0]:-$0}"
    if [ ! -f "$bin_path" ]; then
        bin_path=$(command -v scrt4 2>/dev/null || true)
    fi
    # Resolve symlinks so we hash the real file. readlink -f isn't on BSD; use a portable dance.
    if command -v readlink >/dev/null 2>&1; then
        local resolved
        resolved=$(readlink -f "$bin_path" 2>/dev/null || true)
        [ -n "$resolved" ] && bin_path="$resolved"
    fi

    echo -e "${CYAN}Verifying scrt4 binary:${NC} ${bin_path}"
    echo -e "${CYAN}Expected version:${NC} ${VERSION}"

    # Pick a SHA256 tool — prefer sha256sum (Linux), fall back to shasum -a 256 (macOS).
    local sha_cmd=""
    if command -v sha256sum >/dev/null 2>&1; then
        sha_cmd="sha256sum"
    elif command -v shasum >/dev/null 2>&1; then
        sha_cmd="shasum -a 256"
    else
        echo -e "${RED}No sha256sum or shasum available — cannot verify.${NC}" >&2
        return 1
    fi

    local local_hash
    # shellcheck disable=SC2086
    local_hash=$($sha_cmd "$bin_path" 2>/dev/null | awk '{print $1}')
    if [ -z "$local_hash" ] || [ ${#local_hash} -ne 64 ]; then
        echo -e "${RED}Failed to compute SHA256 of ${bin_path}.${NC}" >&2
        return 1
    fi
    echo -e "${CYAN}Local hash:${NC}    ${local_hash}"

    # Release directories use a `v` prefix by convention (vX.Y.Z-community).
    # Try that first, fall back to the raw VERSION string for tolerance.
    local tag_with_v="v${VERSION#v}"
    local sums_url="${release_host}/releases/${tag_with_v}/SHA256SUMS"
    echo -e "${CYAN}Fetching:${NC}       ${sums_url}"
    local manifest
    manifest=$(curl -fsSL --max-time 20 "$sums_url" 2>/dev/null || true)
    if [ -z "$manifest" ]; then
        local fallback_url="${release_host}/releases/${VERSION}/SHA256SUMS"
        if [ "$fallback_url" != "$sums_url" ]; then
            manifest=$(curl -fsSL --max-time 20 "$fallback_url" 2>/dev/null || true)
            [ -n "$manifest" ] && sums_url="$fallback_url"
        fi
    fi
    if [ -z "$manifest" ]; then
        echo -e "${RED}Could not fetch ${sums_url}.${NC}" >&2
        echo -e "${YELLOW}Check your network, or confirm ${VERSION} has been published.${NC}" >&2
        return 1
    fi

    # Expected hash for the file named "scrt4" in the manifest.
    local expected_hash
    expected_hash=$(printf '%s\n' "$manifest" | awk '$2 == "scrt4" || $2 == "*scrt4" {print $1; exit}')
    if [ -z "$expected_hash" ]; then
        echo -e "${RED}Manifest has no entry for 'scrt4'.${NC}" >&2
        echo -e "${YELLOW}Published entries:${NC}" >&2
        printf '%s\n' "$manifest" >&2
        return 1
    fi
    echo -e "${CYAN}Expected hash:${NC} ${expected_hash}"

    if [ "$local_hash" = "$expected_hash" ]; then
        echo -e "${GREEN}✓ Match — this binary is the published ${VERSION} release.${NC}"
        return 0
    fi

    echo -e "${RED}✗ Mismatch — local binary does not match ${VERSION}.${NC}" >&2
    echo -e "${YELLOW}This could mean:${NC}" >&2
    echo -e "  - you are running a locally-patched or development build (fine for contributors)" >&2
    echo -e "  - your \$PATH is pointing at a different binary than you expect" >&2
    echo -e "  - the release tag has been rotated — re-install to get the latest" >&2
    return 1
}

# ── Dispatch ─────────────────────────────────────────────────────────

# main_dispatch CMD ARGS... — registers built-in commands, calls all
# loaded modules' *_register functions, then dispatches the requested
# subcommand. This is the entry point called from the bottom of the
# concatenated build.
main_dispatch() {
    # Register core commands first so modules cannot shadow them.
    _register_command help    cmd_help
    _register_command daemon  cmd_daemon
    _register_command status  cmd_status
    _register_command setup   cmd_setup
    _register_command unlock  cmd_unlock
    _register_command extend  cmd_extend
    _register_command logout  cmd_logout
    _register_command lock    cmd_logout
    _register_command clear   cmd_logout
    _register_command list    cmd_list
    _register_command add     cmd_add
    _register_command learn   cmd_learn
    _register_command run     cmd_run
    _register_command view    cmd_view
    _register_command rotate  cmd_rotate
    _register_command backup-vault      cmd_backup_vault
    _register_command backup-key        cmd_backup_key
    _register_command recover           cmd_recover
    _register_command recover-key       cmd_recover_key
    _register_command backup-guide      cmd_backup_guide
    _register_command list-encrypted    cmd_list_encrypted
    _register_command cleanup-encrypted cmd_cleanup_encrypted
    _register_command llm               cmd_llm
    _register_command upgrade      cmd_upgrade
    _register_command verify-self       cmd_verify_self

    # Modules are sourced after this file by the build script, so their
    # *_register functions are now defined. Call them.
    _modules_init

    # No subcommand → help.
    if [ $# -eq 0 ]; then
        cmd_help
        return 0
    fi

    # Parse global flags (--cli) and re-extract the subcommand.
    local raw_cmd="$1"
    shift
    local -a rest=()
    while [ $# -gt 0 ]; do
        case "$1" in
            --cli)  FORCE_CLI=true; shift ;;
            *)      rest+=("$1"); shift ;;
        esac
    done

    case "$raw_cmd" in
        help|--help|-h)     cmd_help; return 0 ;;
        --version|-v)       echo "scrt4 v${VERSION}"; return 0 ;;
    esac

    local handler
    if handler=$(_resolve_command "$raw_cmd"); then
        # NOTE: expand without a default. `"${rest[@]:-}"` would expand
        # an empty array to a single empty-string argument — handlers
        # that do `case "$1" in` would see "" and hit their
        # unknown-flag branch. `"${rest[@]}"` expands to nothing when
        # the array is empty, which is what we want.
        "$handler" "${rest[@]}"
        return $?
    fi

    echo -e "${RED}Unknown command: ${raw_cmd}${NC}" >&2
    echo "Run: scrt4 help" >&2
    return 1
}

## SCRT4_MODULE_SOURCE_HOOK ##
# The build script (scripts/build-scrt4.sh) injects module file contents
# above this line, between this hook and the final main_dispatch call
# below. When this file is run standalone (no modules), main_dispatch
# still works — it just registers the core commands and dispatches.

# ── Entry point ──────────────────────────────────────────────────────

main_dispatch "$@"