loonfs-cli 0.2.0

The LoonFS command-line interface.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
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
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
use serde_json::Value;
use std::env;
use std::fs;
use std::io::Write;
use std::net::TcpListener;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Output, Stdio};
use std::thread;
use std::time::{Duration, Instant};
use tempfile::TempDir;

/// A config file with no profiles: enough to load, for the tests that care
/// about which file was loaded rather than what was in it.
const MINIMAL_CONFIG: &str = "config_version = 1\n";

#[test]
fn profile_create_list_show_delete_work() {
    let harness = Harness::new();

    let add_embedded = harness.run(&[
        "--json",
        "profile",
        "create",
        "default",
        "--mode",
        "embedded",
        "--store-kind",
        "local-fs",
        "--root",
        harness.store_root("default").to_str().expect("utf-8 path"),
    ]);
    assert_success(&add_embedded);
    assert_eq!(json_data(&add_embedded)["mode"], "embedded");

    let external = harness
        .start_external_server(harness.write_server_config("remote", "profile-create-remote"));
    let add_remote = harness.run(&[
        "--json",
        "profile",
        "create",
        "prod",
        "--mode",
        "remote",
        "--server-url",
        &external.server_url,
        "--auth-token",
        "test-token",
    ]);
    assert_success(&add_remote);
    assert_eq!(json_data(&add_remote)["mode"], "remote");

    let list = harness.run(&["--json", "profile", "list"]);
    assert_success(&list);
    let list_data = json_data(&list);
    let profiles = list_data["profiles"].as_array().expect("json array");
    assert_eq!(profiles.len(), 2);
    assert_eq!(profiles[0]["name"], "default");
    assert_eq!(profiles[1]["name"], "prod");

    let show = harness.run(&["config", "show"]);
    assert_success(&show);
    let stdout = stdout_string(&show);
    assert!(stdout.contains("mode = \"remote\""));
    assert!(stdout.contains("<redacted>"));
    assert!(!stdout.contains("test-token"));

    let show_default = harness.run(&["--json", "profile", "show"]);
    assert_success(&show_default);
    assert_eq!(json_data(&show_default)["mode"], "embedded");

    let remove_default = harness.run(&["--json", "profile", "delete", "default"]);
    assert_success(&remove_default);
    assert_eq!(json_data(&remove_default)["name"], "default");

    let list_after_remove = harness.run(&["--json", "profile", "list"]);
    assert_success(&list_after_remove);
    assert!(json_data(&list_after_remove)["default_profile"].is_null());

    let show_without_default = harness.run(&["--json", "profile", "show"]);
    assert_failure(&show_without_default);
    assert_eq!(
        json_error(&show_without_default)["code"],
        "no_default_profile"
    );
}

#[test]
fn broken_configs_stay_repairable_with_the_repair_commands() {
    let harness = Harness::new();
    harness.write_cli_config(format!(
        r#"config_version = 1
default_profile = "broken"

[profiles.broken]
mode = "remote"
server_url = "https://loonfs.example.com"
auth_token = "secret-degraded-token"
unknown_knob = true

[profiles.keeper]
mode = "embedded"

[profiles.keeper.store]
kind = "local-fs"
root = "{}"
"#,
        harness.store_root("keeper").display()
    ));

    // Ordinary commands reject the file, naming it and the offending key.
    let list = harness.run(&["profile", "list"]);
    assert_failure(&list);
    let message = stderr_string(&list);
    assert!(message.contains("config.toml"), "{message}");
    assert!(message.contains("unknown_knob"), "{message}");

    // The repair commands still work. Show renders the file as parsed, with
    // the failure on top and secrets masked.
    let show = harness.run(&["config", "show"]);
    assert_success(&show);
    let shown = stdout_string(&show);
    assert!(shown.contains("warning:"), "{shown}");
    assert!(shown.contains("unknown_knob"), "{shown}");
    assert!(shown.contains("<redacted>"), "{shown}");
    assert!(!shown.contains("secret-degraded-token"), "{shown}");

    // Use switches the default while the file is still degraded; delete then
    // removes the broken profile, which heals the file for every command.
    assert_success(&harness.run(&["profile", "use", "keeper"]));
    let delete = harness.run(&["--json", "profile", "delete", "broken"]);
    assert_success(&delete);
    assert_eq!(json_data(&delete)["name"], "broken");
    assert_eq!(json_data(&delete)["mode"], "remote");

    let healed = harness.run(&["--json", "profile", "list"]);
    assert_success(&healed);
    let healed_data = json_data(&healed);
    assert_eq!(healed_data["default_profile"], "keeper");
    assert_eq!(
        healed_data["profiles"]
            .as_array()
            .expect("json array")
            .len(),
        1
    );

    // A config for another version is a hard error, named before any
    // unknown-field noise; repair commands do not edit files written for a
    // different version.
    harness.write_cli_config("config_version = 2\nfuture_setting = true\n");
    let future = harness.run(&["config", "show"]);
    assert_failure(&future);
    let future_message = stderr_string(&future);
    assert!(
        future_message.contains("`config_version = 2`"),
        "{future_message}"
    );
    assert!(
        !future_message.contains("future_setting"),
        "{future_message}"
    );
}

/// The resolution chain, first match wins: `--config`, then
/// `LOONFS_CONFIG`, then `$XDG_CONFIG_HOME/loonfs/config.toml`, then
/// `~/.loonfs/config.toml`.
#[test]
fn config_resolution_prefers_the_flag_then_the_environment_then_xdg_then_legacy() {
    let harness = Harness::new();
    harness.write_cli_config(MINIMAL_CONFIG);
    let legacy_path = harness.config_path.display().to_string();

    let xdg_home = harness.temp_dir.path().join("xdg");
    let xdg_path = xdg_home.join("loonfs").join("config.toml");
    let named_path = harness.temp_dir.path().join("named.toml");
    let flagged_path = harness.temp_dir.path().join("flagged.toml");

    // Without XDG the legacy path is simply the default, with nothing to
    // migrate to.
    let default = json_data(&harness.run(&["--json", "config", "path"]));
    assert_eq!(default["path"], legacy_path);
    assert_eq!(default["source"], "legacy");
    assert!(default["preferred_path"].is_null(), "{default}");

    // XDG set but holding no config: the existing legacy file keeps
    // working, and the answer names where it belongs.
    let migrating = json_data(&harness.run_with_env(
        &[("XDG_CONFIG_HOME", &xdg_home)],
        &["--json", "config", "path"],
    ));
    assert_eq!(migrating["path"], legacy_path);
    assert_eq!(migrating["source"], "legacy");
    assert_eq!(migrating["preferred_path"], xdg_path.display().to_string());

    // A config at the preferred path wins as soon as one exists there.
    fs::create_dir_all(xdg_path.parent().expect("xdg config dir")).expect("create xdg config dir");
    fs::write(&xdg_path, MINIMAL_CONFIG).expect("write xdg config");
    let xdg = json_data(&harness.run_with_env(
        &[("XDG_CONFIG_HOME", &xdg_home)],
        &["--json", "config", "path"],
    ));
    assert_eq!(xdg["path"], xdg_path.display().to_string());
    assert_eq!(xdg["source"], "xdg");
    assert!(xdg["preferred_path"].is_null(), "{xdg}");

    // The environment beats both defaults, by being spelled rather than by
    // the file it names existing.
    let from_env = json_data(&harness.run_with_env(
        &[
            ("XDG_CONFIG_HOME", &xdg_home),
            ("LOONFS_CONFIG", &named_path),
        ],
        &["--json", "config", "path"],
    ));
    assert_eq!(from_env["path"], named_path.display().to_string());
    assert_eq!(from_env["source"], "env");
    assert!(!named_path.exists(), "the named file need not exist yet");

    // The flag beats everything, and being global it may follow the
    // subcommand as readily as precede it.
    for args in [
        vec![
            "--json",
            "--config",
            flagged_path.to_str().expect("utf-8 path"),
            "config",
            "path",
        ],
        vec![
            "--json",
            "config",
            "path",
            "--config",
            flagged_path.to_str().expect("utf-8 path"),
        ],
    ] {
        let from_flag = json_data(&harness.run_with_env(
            &[
                ("XDG_CONFIG_HOME", &xdg_home),
                ("LOONFS_CONFIG", &named_path),
            ],
            &args,
        ));
        assert_eq!(from_flag["path"], flagged_path.display().to_string());
        assert_eq!(from_flag["source"], "flag");
    }
}

/// `config path` is the command that answers "which file is this build even
/// looking at", so it never reads that file.
#[test]
fn config_path_answers_while_the_config_file_is_unreadable() {
    let harness = Harness::new();
    harness.write_cli_config("config_version = 1\nunknown_knob = true\n");

    assert_failure(&harness.run(&["profile", "list"]));

    let path = harness.run(&["--json", "config", "path"]);
    assert_success(&path);
    assert_eq!(
        json_data(&path)["path"],
        harness.config_path.display().to_string()
    );
    assert_eq!(json_data(&path)["source"], "legacy");

    // The human line carries both answers: the file, and why that file.
    let human = harness.run(&["config", "path"]);
    assert_success(&human);
    let shown = stdout_string(&human);
    assert!(
        shown.contains(&harness.config_path.display().to_string()),
        "{shown}"
    );
    assert!(shown.contains("default location"), "{shown}");
}

/// The recovery path: an override reaches a config file of its own while
/// the default file is one this build refuses to read.
#[test]
fn init_runs_through_an_override_while_the_default_config_is_unreadable() {
    let harness = Harness::new();
    harness.write_cli_config("config_version = 1\nunknown_knob = true\n");
    let broken = fs::read_to_string(&harness.config_path).expect("read broken config");

    let flagged_path = harness.temp_dir.path().join("recovery").join("config.toml");
    let flagged = flagged_path.to_str().expect("utf-8 path");
    let init = harness.run(&[
        "--json",
        "--config",
        flagged,
        "init",
        "rescue",
        "--mode",
        "embedded",
        "--store-kind",
        "local-fs",
        "--root",
        harness.store_root("rescue").to_str().expect("utf-8 path"),
    ]);
    assert_success(&init);
    assert_eq!(json_data(&init)["mode"], "embedded");
    assert!(
        flagged_path.exists(),
        "init creates the directories it needs"
    );

    let list = harness.run(&["--json", "--config", flagged, "profile", "list"]);
    assert_success(&list);
    assert_eq!(json_data(&list)["profiles"][0]["name"], "rescue");

    // The environment is the same way out.
    let env_path = harness.temp_dir.path().join("by-env").join("config.toml");
    let env_init = harness.run_with_env(
        &[("LOONFS_CONFIG", &env_path)],
        &[
            "--json",
            "init",
            "byenv",
            "--mode",
            "embedded",
            "--store-kind",
            "local-fs",
            "--root",
            harness.store_root("byenv").to_str().expect("utf-8 path"),
        ],
    );
    assert_success(&env_init);
    let env_list = harness.run_with_env(
        &[("LOONFS_CONFIG", &env_path)],
        &["--json", "profile", "list"],
    );
    assert_success(&env_list);
    assert_eq!(json_data(&env_list)["profiles"][0]["name"], "byenv");

    // Neither route read or rewrote the file that started this.
    assert_eq!(
        fs::read_to_string(&harness.config_path).expect("read unchanged config"),
        broken
    );
}

/// A file this build will not read names itself, what in it went wrong, and
/// the two ways past it.
#[test]
fn unreadable_config_errors_name_the_file_the_field_and_the_way_out() {
    let harness = Harness::new();
    harness.write_cli_config("config_version = 1\ndefault_profil = \"typo\"\n");

    let list = harness.run(&["--json", "profile", "list"]);
    assert_failure(&list);
    let error = json_error(&list);
    assert_eq!(error["code"], "invalid_config");
    let message = error["message"].as_str().expect("json string");
    assert!(
        message.contains(&harness.config_path.display().to_string()),
        "{message}"
    );
    assert!(message.contains("default_profil"), "{message}");
    assert!(message.contains("line 2"), "{message}");
    assert!(message.contains("--config"), "{message}");
    assert!(message.contains("LOONFS_CONFIG"), "{message}");

    // A semantic failure is just as much a wall, so it carries the same way
    // past it.
    harness.write_cli_config("config_version = 1\ndefault_profile = \"missing\"\n");
    let unresolvable = harness.run(&["--json", "profile", "list"]);
    assert_failure(&unresolvable);
    let message = json_error(&unresolvable)["message"]
        .as_str()
        .expect("json string")
        .to_owned();
    assert!(
        message.contains(&harness.config_path.display().to_string()),
        "{message}"
    );
    assert!(message.contains("--config"), "{message}");
    assert!(message.contains("LOONFS_CONFIG"), "{message}");
}

#[test]
fn unreachable_servers_are_named_with_their_url() {
    let harness = Harness::new();
    // A port that was just free with nothing listening: connection refused.
    let dead_url = format!("http://127.0.0.1:{}", available_port());
    let create = harness.run(&[
        "--json",
        "profile",
        "create",
        "dead",
        "--mode",
        "remote",
        "--server-url",
        &dead_url,
    ]);
    assert_success(&create);

    let attempt = harness.run(&["namespace", "create", "ghost"]);
    assert_failure(&attempt);
    let message = stderr_string(&attempt);
    assert!(message.contains("cannot connect to"), "{message}");
    assert!(message.contains(&dead_url), "{message}");
    assert!(message.contains("`server_url`"), "{message}");
}

#[test]
fn embedded_profile_filesystem_flow_works_end_to_end() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");

    let upload_path = harness.temp_dir.path().join("upload.txt");
    let update_path = harness.temp_dir.path().join("updated.txt");
    let download_path = harness.temp_dir.path().join("downloaded.txt");
    fs::write(&upload_path, b"hello from direct core\n").expect("upload payload");
    fs::write(&update_path, b"updated from direct core\n").expect("updated payload");

    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let mkdir = harness.run(&["--json", "mkdir", "/docs"]);
    assert_success(&mkdir);
    assert_eq!(json_data(&mkdir)["target"], "demo:/docs");

    let docs = harness.run(&["--json", "stat", "/docs"]);
    assert_success(&docs);
    assert_eq!(json_data(&docs)["inode_kind"], "dir");

    let put = harness.run(&[
        "--json",
        "put",
        upload_path.to_str().expect("utf-8 path"),
        "/docs/hello.txt",
    ]);
    assert_success(&put);
    assert_eq!(json_data(&put)["target"], "demo:/docs/hello.txt");

    let put_conflict = harness.run(&[
        "--json",
        "put",
        upload_path.to_str().expect("utf-8 path"),
        "/docs/hello.txt",
    ]);
    assert_failure(&put_conflict);
    assert_eq!(json_error(&put_conflict)["code"], "path_conflict");

    let put_force = harness.run(&[
        "--json",
        "put",
        update_path.to_str().expect("utf-8 path"),
        "/docs/hello.txt",
        "--force",
    ]);
    assert_success(&put_force);

    let revisions = harness.run(&["--json", "revisions", "/docs/hello.txt"]);
    assert_success(&revisions);
    assert_eq!(
        json_data(&revisions)["revisions"]
            .as_array()
            .expect("json array")
            .len(),
        2
    );

    let old_cat = harness.run(&["cat", "--revision", "1", "/docs/hello.txt"]);
    assert_success(&old_cat);
    assert_eq!(old_cat.stdout, b"hello from direct core\n");

    let cp = harness.run(&["--json", "cp", "/docs/hello.txt", "/docs/copy.txt"]);
    assert_success(&cp);

    let source = harness.run(&["--json", "stat", "/docs/hello.txt"]);
    let copy = harness.run(&["--json", "stat", "/docs/copy.txt"]);
    assert_success(&source);
    assert_success(&copy);
    assert_ne!(json_data(&source)["inode_id"], json_data(&copy)["inode_id"]);
    assert_eq!(
        json_data(&source)["content_ref"],
        json_data(&copy)["content_ref"]
    );

    let cat = harness.run(&["cat", "/docs/hello.txt"]);
    assert_success(&cat);
    assert_eq!(cat.stdout, b"updated from direct core\n");

    let get_stdout = harness.run(&["get", "/docs/hello.txt", "-"]);
    assert_success(&get_stdout);
    assert_eq!(get_stdout.stdout, b"updated from direct core\n");

    let get_old_stdout = harness.run(&["get", "--revision", "1", "/docs/hello.txt", "-"]);
    assert_success(&get_old_stdout);
    assert_eq!(get_old_stdout.stdout, b"hello from direct core\n");

    let get_file = harness.run(&[
        "--json",
        "get",
        "/docs/hello.txt",
        download_path.to_str().expect("utf-8 path"),
    ]);
    assert_success(&get_file);
    assert_eq!(
        fs::read(&download_path).expect("downloaded bytes"),
        b"updated from direct core\n"
    );

    let restore = harness.run(&["--json", "restore", "--revision", "1", "/docs/hello.txt"]);
    assert_success(&restore);
    let restored = harness.run(&["cat", "/docs/hello.txt"]);
    assert_success(&restored);
    assert_eq!(restored.stdout, b"hello from direct core\n");

    let mv = harness.run(&["--json", "mv", "/docs/copy.txt", "/docs/final.txt"]);
    assert_success(&mv);

    let rm_dir = harness.run(&["--json", "rm", "/docs"]);
    assert_failure(&rm_dir);
    assert_eq!(json_error(&rm_dir)["code"], "directory_not_empty");

    let rm = harness.run(&["--json", "rm", "/docs/final.txt"]);
    assert_success(&rm);
}

#[test]
fn put_expected_revision_replaces_only_the_observed_revision() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let payload = harness.temp_dir.path().join("doc.txt");
    fs::write(&payload, b"v1").expect("write payload");
    assert_success(&harness.run(&["put", payload.to_str().expect("utf-8 path"), "/doc.txt"]));

    // The guard implies --force: replacing the revision the caller observed
    // needs no second flag.
    fs::write(&payload, b"v2").expect("write payload");
    let guarded = harness.run(&[
        "--json",
        "put",
        payload.to_str().expect("utf-8 path"),
        "/doc.txt",
        "--expected-revision",
        "1",
    ]);
    assert_success(&guarded);
    let stat = harness.run(&["--json", "stat", "/doc.txt"]);
    assert_success(&stat);
    assert_eq!(json_data(&stat)["revision_no"], 2);

    // A raced write fails instead of stacking on it: the file has moved on
    // from revision 1, so the same guard now reports the stale revision.
    fs::write(&payload, b"v3").expect("write payload");
    let stale = harness.run(&[
        "--json",
        "put",
        payload.to_str().expect("utf-8 path"),
        "/doc.txt",
        "--expected-revision",
        "1",
    ]);
    assert_failure(&stale);
    assert_eq!(json_error(&stale)["code"], "stale_revision");
    // The rejection reads as a sentence, with both revisions in it and no
    // Rust formatting of the one that may be absent.
    let stale_error = json_error(&stale);
    let message = stale_error["message"].as_str().unwrap_or_default();
    assert!(
        message.ends_with("expected revision 1, found revision 2"),
        "{message}"
    );
    // The embedded backend carries the same structured details a server's
    // envelope would, so `--json` consumers read one contract from both
    // profiles.
    assert_eq!(stale_error["details"]["expected_revision"], 1);
    assert_eq!(stale_error["details"]["actual_revision"], 2);
    let cat = harness.run(&["cat", "/doc.txt"]);
    assert_success(&cat);
    assert_eq!(cat.stdout, b"v2");
}

#[test]
fn concurrent_embedded_puts_land_or_report_the_fence() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let mut payloads = Vec::new();
    for index in 0..4 {
        let path = harness.temp_dir.path().join(format!("payload-{index}.txt"));
        fs::write(&path, format!("payload {index}")).expect("write payload");
        payloads.push(path);
    }

    // Four simultaneous processes: each is its own writer session, so they
    // fence each other on acquisition. Fencing is terminal — no silent
    // reacquisition — so the contract is honesty, not recovery: every
    // process either lands its put or reports `writer_fenced`, the last
    // acquirer always lands, and a fenced put commits nothing.
    let children: Vec<Child> = payloads
        .iter()
        .enumerate()
        .map(|(index, path)| {
            Command::new(loon_binary_path())
                .env("HOME", &harness.home_dir)
                .args([
                    "--json",
                    "put",
                    path.to_str().expect("utf-8 path"),
                    &format!("/docs/file-{index}.txt"),
                ])
                .stdout(std::process::Stdio::piped())
                .stderr(std::process::Stdio::piped())
                .spawn()
                .expect("spawn loonfs put")
        })
        .collect();
    let mut landed = Vec::new();
    for (index, child) in children.into_iter().enumerate() {
        let output = child.wait_with_output().expect("join loonfs put");
        if output.status.success() {
            landed.push(index);
        } else {
            assert_eq!(json_error(&output)["code"], "writer_fenced");
        }
    }
    assert!(
        !landed.is_empty(),
        "the last writer to acquire faces no later fence and must land"
    );

    for index in 0..4 {
        let stat = harness.run(&["--json", "stat", &format!("/docs/file-{index}.txt")]);
        if landed.contains(&index) {
            assert_success(&stat);
        } else {
            assert_failure(&stat);
            assert_eq!(json_error(&stat)["code"], "path_not_found");
        }
    }
}

#[test]
fn commit_messages_ride_the_feed_and_bind_identity() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let payload = harness.temp_dir.path().join("doc.txt");
    fs::write(&payload, b"v1").expect("write payload");
    assert_success(&harness.run(&[
        "put",
        payload.to_str().expect("utf-8 path"),
        "/doc.txt",
        "-m",
        "initial import",
    ]));
    // The audit's motivating case: a restore is indistinguishable from an
    // edit in the feed without a message.
    fs::write(&payload, b"v2").expect("write payload");
    assert_success(&harness.run(&[
        "put",
        payload.to_str().expect("utf-8 path"),
        "/doc.txt",
        "--force",
    ]));
    assert_success(&harness.run(&[
        "--json",
        "restore",
        "--revision",
        "1",
        "/doc.txt",
        "-m",
        "roll back to the imported copy",
    ]));

    let changes = harness.run(&["--json", "changes"]);
    assert_success(&changes);
    let rows = json_data(&changes)["changes"]
        .as_array()
        .expect("changes array")
        .clone();
    assert_eq!(rows[0]["message"], "initial import");
    assert!(rows[1].get("message").is_none());
    assert_eq!(rows[2]["message"], "roll back to the imported copy");

    // The message is part of the commit's identity: the same commit id with
    // a different message conflicts instead of silently replaying.
    let first = harness.run(&[
        "--json",
        "mkdir",
        "/pinned",
        "--commit-id",
        "pinned-mkdir",
        "--message",
        "one",
    ]);
    assert_success(&first);
    let replay = harness.run(&[
        "--json",
        "mkdir",
        "/pinned",
        "--commit-id",
        "pinned-mkdir",
        "--message",
        "one",
    ]);
    assert_success(&replay);
    assert_eq!(
        json_data(&first)["committed_seq"],
        json_data(&replay)["committed_seq"],
        "an identical retry replays the original commit"
    );
    let conflicted = harness.run(&[
        "--json",
        "mkdir",
        "/pinned",
        "--commit-id",
        "pinned-mkdir",
        "--message",
        "two",
    ]);
    assert_failure(&conflicted);
    assert_eq!(
        json_error(&conflicted)["code"],
        "commit_id_reuse_conflict",
        "{}",
        json_error(&conflicted)
    );

    // A put's identity includes *which* content object it attaches, and
    // `loonfs put` uploads its file every time it runs, so a rerun under the
    // same commit id is a different mutation as far as the server is
    // concerned. What makes rerunning safe anyway is the client comparing
    // the bytes it just sent against what that commit id actually
    // committed: identical bytes mean the command had already succeeded, so
    // it reports the same commit rather than a conflict.
    let local_payload = payload.to_str().expect("utf-8 path");
    let first = harness.run(&[
        "--json",
        "put",
        local_payload,
        "/pinned.txt",
        "--commit-id",
        "pinned-put",
    ]);
    assert_success(&first);
    let rerun = harness.run(&[
        "--json",
        "put",
        local_payload,
        "/pinned.txt",
        "--commit-id",
        "pinned-put",
    ]);
    assert_success(&rerun);
    assert_eq!(
        json_data(&rerun)["committed_seq"],
        json_data(&first)["committed_seq"],
        "rerunning an identical put must report the commit that already landed"
    );

    // Different bytes under that commit id are a different operation, and
    // the conflict stands.
    let changed = harness.temp_dir.path().join("changed.txt");
    fs::write(&changed, b"different pinned bytes\n").expect("write changed payload");
    let conflicting = harness.run(&[
        "--json",
        "put",
        changed.to_str().expect("utf-8 path"),
        "/pinned.txt",
        "--commit-id",
        "pinned-put",
    ]);
    assert_failure(&conflicting);
    assert_eq!(
        json_error(&conflicting)["code"],
        "commit_id_reuse_conflict",
        "{}",
        json_error(&conflicting)
    );
}

/// A file small enough that a tree holding it uploads it in one request,
/// beside one that is not.
const SMALL_TREE_FILE: &[u8] = b"small enough to hold";

/// A payload past the size at which a put stops holding its bytes whole.
/// It is the smallest payload that exercises the streaming path at all.
fn streaming_payload() -> Vec<u8> {
    let len = 8 * 1024 * 1024 + 1_024;
    (0..len).map(|offset| (offset % 251) as u8).collect()
}

/// Reads a remote file back through the CLI and returns its bytes.
fn download(harness: &Harness, remote_path: &str, name: &str) -> Vec<u8> {
    let local = harness.temp_dir.path().join(name);
    assert_success(&harness.run(&[
        "get",
        remote_path,
        local.to_str().expect("utf-8 path"),
        "--force",
    ]));
    fs::read(&local).expect("read downloaded file")
}

/// Events of one kind, in the order they were reported.
fn events_of_kind(output: &Output, kind: &str) -> Vec<Value> {
    json_progress_events(output)
        .into_iter()
        .filter(|event| event["kind"] == kind)
        .collect()
}

/// A download that takes real time says where it has got to, in events an
/// agent can tell apart from a hang, and says so without disturbing the
/// result document on standard output.
#[test]
fn a_download_reports_its_progress_to_an_agent() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let payload = streaming_payload();
    let local = harness.temp_dir.path().join("big.bin");
    fs::write(&local, &payload).expect("write payload");
    assert_success(&harness.run(&["put", local.to_str().expect("utf-8 path"), "/big.bin"]));

    let back = harness.temp_dir.path().join("back.bin");
    let get = harness.run(&[
        "--json",
        "get",
        "/big.bin",
        back.to_str().expect("utf-8 path"),
    ]);
    assert_success(&get);
    assert_eq!(json_data(&get)["bytes_written"], payload.len() as u64);

    let started = events_of_kind(&get, "file_started");
    assert_eq!(started.len(), 1, "one file, one start: {started:?}");
    assert_eq!(started[0]["op"], "get");
    assert_eq!(started[0]["path"], "/big.bin");
    assert_eq!(started[0]["bytes_total"], payload.len() as u64);

    let progress = events_of_kind(&get, "progress");
    assert!(
        !progress.is_empty(),
        "a download past one chunk reports as it lands"
    );
    let last = progress.last().expect("a progress event");
    assert_eq!(last["op"], "get");
    assert_eq!(last["bytes_done"], payload.len() as u64);
    assert_eq!(last["bytes_total"], payload.len() as u64);
    assert_eq!(last["files_total"], 1);
    assert!(last["rate_bps"].is_u64(), "a rate is always reported");
    assert!(last["elapsed_ms"].is_u64());

    let finished = events_of_kind(&get, "file_finished");
    assert_eq!(finished.len(), 1, "one file, one finish: {finished:?}");
    assert_eq!(finished[0]["bytes_done"], payload.len() as u64);
    assert_eq!(finished[0]["path"], "/big.bin");
}

/// An upload counts the payload as it is read and then names the commit,
/// which is the stretch where time passes and no bytes move.
#[test]
fn an_upload_reports_bytes_read_and_then_the_commit() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let payload = streaming_payload();
    let local = harness.temp_dir.path().join("big.bin");
    fs::write(&local, &payload).expect("write payload");
    let put = harness.run(&[
        "--json",
        "put",
        local.to_str().expect("utf-8 path"),
        "/big.bin",
    ]);
    assert_success(&put);

    let progress = events_of_kind(&put, "progress");
    let last = progress.last().expect("a progress event");
    assert_eq!(last["op"], "put");
    assert_eq!(last["path"], "/big.bin");
    assert_eq!(last["bytes_done"], payload.len() as u64);
    assert_eq!(last["bytes_total"], payload.len() as u64);

    let phases = events_of_kind(&put, "phase");
    assert_eq!(phases.len(), 1, "one transition to report: {phases:?}");
    assert_eq!(phases[0]["phase"], "committing");
    assert_eq!(phases[0]["op"], "put");

    // A payload with no knowable length still counts its bytes; it just
    // has no total to measure them against.
    let piped = harness.run_with_stdin(&["--json", "put", "-", "/piped.bin"], &payload);
    assert_success(&piped);
    let piped_progress = events_of_kind(&piped, "progress");
    let last = piped_progress.last().expect("a progress event");
    assert_eq!(last["bytes_done"], payload.len() as u64);
    assert!(
        last["bytes_total"].is_null(),
        "a pipe has no total: {last:?}"
    );
}

/// A tree is measured as a tree: one operation's bytes and files, plus a
/// start and a finish for every file inside it.
#[test]
fn a_recursive_transfer_counts_files_and_bytes_for_the_whole_tree() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let tree = harness.temp_dir.path().join("tree");
    fs::create_dir_all(tree.join("docs")).expect("create tree dirs");
    fs::write(tree.join("top.txt"), b"top").expect("write top");
    fs::write(tree.join("docs/a.txt"), b"alpha").expect("write a");
    fs::write(tree.join("docs/b.txt"), b"beta").expect("write b");
    let tree_bytes = (b"top".len() + b"alpha".len() + b"beta".len()) as u64;

    let put = harness.run(&[
        "--json",
        "put",
        "-r",
        tree.to_str().expect("utf-8 path"),
        "/up",
    ]);
    assert_success(&put);
    assert_eq!(events_of_kind(&put, "file_started").len(), 3);
    assert_eq!(events_of_kind(&put, "file_finished").len(), 3);
    let last = events_of_kind(&put, "progress")
        .pop()
        .expect("a progress event");
    assert_eq!(last["op"], "put");
    assert_eq!(last["path"], "demo:/up");
    assert_eq!(last["bytes_done"], tree_bytes);
    assert_eq!(last["bytes_total"], tree_bytes);
    assert_eq!(last["files_total"], 3);
    assert!(
        events_of_kind(&put, "phase").is_empty(),
        "several files of a tree are in flight at once, so no one file's \
         commit is the operation's: {:?}",
        events_of_kind(&put, "phase")
    );

    let back = harness.temp_dir.path().join("back");
    let get = harness.run(&[
        "--json",
        "get",
        "-r",
        "/up",
        back.to_str().expect("utf-8 path"),
    ]);
    assert_success(&get);
    assert_eq!(events_of_kind(&get, "file_started").len(), 3);
    assert_eq!(events_of_kind(&get, "file_finished").len(), 3);
    let last = events_of_kind(&get, "progress")
        .pop()
        .expect("a progress event");
    assert_eq!(last["op"], "get");
    assert_eq!(last["path"], "demo:/up");
    assert_eq!(last["bytes_done"], tree_bytes);
    assert_eq!(last["bytes_total"], tree_bytes);
    assert_eq!(last["files_done"], 3);
    assert_eq!(last["files_total"], 3);
}

/// A tree's large file is read once, a piece at a time, exactly as a single
/// `put` of it is. So the tree's byte count moves through that file rather
/// than jumping over it once the whole thing has been read — which is what
/// an upload that held each file whole could only ever report.
#[test]
fn a_recursive_put_counts_a_large_file_as_it_is_read() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let tree = harness.temp_dir.path().join("tree");
    fs::create_dir_all(tree.join("docs")).expect("create tree dirs");
    let payload = streaming_payload();
    fs::write(tree.join("docs/big.bin"), &payload).expect("write big");
    fs::write(tree.join("small.txt"), SMALL_TREE_FILE).expect("write small");
    let tree_bytes = (payload.len() + SMALL_TREE_FILE.len()) as u64;

    let put = harness.run(&[
        "--json",
        "put",
        "-r",
        tree.to_str().expect("utf-8 path"),
        "/up",
    ]);
    assert_success(&put);
    assert_eq!(json_data(&put)["files"], 2);

    let counts: Vec<u64> = events_of_kind(&put, "progress")
        .iter()
        .map(|event| event["bytes_done"].as_u64().expect("a byte count"))
        .collect();
    // The only counts a whole-file-at-a-time upload could ever report.
    let whole_files = [
        0,
        SMALL_TREE_FILE.len() as u64,
        payload.len() as u64,
        tree_bytes,
    ];
    assert!(
        counts.iter().any(|count| !whole_files.contains(count)),
        "a payload read in pieces reports counts taken part way through it: {counts:?}"
    );
    assert_eq!(counts.last(), Some(&tree_bytes), "{counts:?}");
    assert_eq!(
        download(&harness, "/up/docs/big.bin", "big-back.bin"),
        payload
    );
}

/// The same tree over the remote transport, where a large file is the one
/// upload with parts to lose. Each file keeps its own resume record, named
/// by the profile, namespace, remote path, and local file that decide which
/// upload it is — and a run that committed leaves none of them behind.
#[test]
fn a_recursive_put_streams_a_large_file_over_the_remote_transport() {
    let harness = Harness::new();
    let remote_server =
        harness.start_external_server(harness.write_server_config("remote", "recursive-remote"));
    assert_success(&harness.run(&[
        "--json",
        "profile",
        "create",
        "default",
        "--mode",
        "remote",
        "--server-url",
        &remote_server.server_url,
        "--auth-token",
        "test-token",
    ]));
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let tree = harness.temp_dir.path().join("tree");
    fs::create_dir_all(tree.join("docs")).expect("create tree dirs");
    let payload = streaming_payload();
    fs::write(tree.join("docs/big.bin"), &payload).expect("write big");
    fs::write(tree.join("small.txt"), SMALL_TREE_FILE).expect("write small");

    let state_home = harness.temp_dir.path().join("state");
    let put = harness.run_with_env(
        &[("XDG_STATE_HOME", state_home.as_path())],
        &[
            "--json",
            "put",
            "-r",
            tree.to_str().expect("utf-8 path"),
            "/up",
        ],
    );
    assert_success(&put);
    assert_eq!(json_data(&put)["files"], 2);
    assert_eq!(
        download(&harness, "/up/docs/big.bin", "big-back.bin"),
        payload
    );
    assert_eq!(
        download(&harness, "/up/small.txt", "small-back.txt"),
        SMALL_TREE_FILE
    );

    let records: Vec<PathBuf> = fs::read_dir(state_home.join("loonfs").join("uploads"))
        .map(|entries| {
            entries
                .map(|entry| entry.expect("dir entry").path())
                .collect()
        })
        .unwrap_or_default();
    assert!(
        records.is_empty(),
        "an upload that committed keeps no record for a rerun to pick up: {records:?}"
    );
}

/// What a tree holds that is neither a file nor a directory is named and
/// skipped rather than silently dropped, and the walk carries on around it.
/// Unix only: nothing else in the suite can make one.
#[cfg(unix)]
#[test]
fn a_recursive_put_names_what_it_will_not_transfer() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let tree = harness.temp_dir.path().join("tree");
    fs::create_dir_all(&tree).expect("create tree dir");
    fs::write(tree.join("real.txt"), b"real").expect("write file");
    std::os::unix::fs::symlink(tree.join("real.txt"), tree.join("link.txt")).expect("make symlink");

    let put = harness.run(&[
        "--json",
        "put",
        "-r",
        tree.to_str().expect("utf-8 path"),
        "/up",
    ]);
    assert_failure(&put);
    let data = json_data(&put);
    assert_eq!(
        data["files"], 1,
        "the regular file still transferred: {data}"
    );
    let failures = data["failures"].as_array().expect("failures");
    assert_eq!(failures.len(), 1, "{data}");
    assert!(
        failures[0]["path"]
            .as_str()
            .expect("a path")
            .ends_with("link.txt"),
        "{data}"
    );
    assert!(
        failures[0]["error"]["message"]
            .as_str()
            .expect("a message")
            .contains("symlinks and special"),
        "{data}"
    );
    assert_success(&harness.run(&["--json", "stat", "/up/real.txt"]));
}

/// Nobody asked, so nobody is told: a run whose standard error is a pipe
/// and which asked for no events says nothing about the transfer, and
/// --no-progress silences the agent stream too.
#[test]
fn progress_is_silent_unless_someone_is_watching() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let local = harness.temp_dir.path().join("doc.txt");
    fs::write(&local, b"body").expect("write payload");
    let put = harness.run(&["put", local.to_str().expect("utf-8 path"), "/doc.txt"]);
    assert_success(&put);
    assert_eq!(
        stderr_string(&put),
        "",
        "a piped run draws no line, the way curl does not"
    );

    let quiet = harness.run(&[
        "--json",
        "--no-progress",
        "put",
        local.to_str().expect("utf-8 path"),
        "/quiet.txt",
    ]);
    assert_success(&quiet);
    assert_eq!(
        stderr_string(&quiet),
        "",
        "--no-progress silences the event stream"
    );

    // A failure still reports itself, and is still the last document on
    // standard error when progress preceded it.
    let clash = harness.run(&[
        "--json",
        "put",
        local.to_str().expect("utf-8 path"),
        "/doc.txt",
    ]);
    assert_failure(&clash);
    assert_eq!(json_error(&clash)["code"], "path_conflict");
}

/// A large file and a pipe both round-trip through an embedded profile,
/// and the retry contract holds for them exactly as it does for a payload
/// small enough to hold.
#[test]
fn large_and_piped_puts_round_trip_through_an_embedded_profile() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));
    let payload = streaming_payload();

    let local = harness.temp_dir.path().join("big.bin");
    fs::write(&local, &payload).expect("write payload");
    let local_path = local.to_str().expect("utf-8 path");
    // `--force` on every run of this id, first included: the replacement
    // behavior is part of a commit's identity, so a rerun that adds the
    // flag is asking for a different mutation and conflicts.
    let first = harness.run(&[
        "--json",
        "put",
        local_path,
        "/big.bin",
        "--commit-id",
        "pinned-big",
        "--force",
    ]);
    assert_success(&first);
    assert_eq!(download(&harness, "/big.bin", "big-back.bin"), payload);

    // The same reconciliation the buffered path has: the rerun uploads
    // again, conflicts on identity, and resolves to the commit that landed.
    let rerun = harness.run(&[
        "--json",
        "put",
        local_path,
        "/big.bin",
        "--commit-id",
        "pinned-big",
        "--force",
    ]);
    assert_success(&rerun);
    assert_eq!(
        json_data(&rerun)["committed_seq"],
        json_data(&first)["committed_seq"],
        "rerunning an identical large put must report the commit that already landed"
    );

    let mut changed = payload.clone();
    changed[0] ^= 0xff;
    let changed_path = harness.temp_dir.path().join("changed.bin");
    fs::write(&changed_path, &changed).expect("write changed payload");
    let conflicting = harness.run(&[
        "--json",
        "put",
        changed_path.to_str().expect("utf-8 path"),
        "/big.bin",
        "--commit-id",
        "pinned-big",
        "--force",
    ]);
    assert_failure(&conflicting);
    assert_eq!(
        json_error(&conflicting)["code"],
        "commit_id_reuse_conflict",
        "{}",
        json_error(&conflicting)
    );

    // Standard input has no length to declare and no name to derive a
    // destination from, so it needs one spelled out and takes the same
    // read-once path.
    assert_success(&harness.run_with_stdin(&["--json", "put", "-", "/piped.bin"], &payload));
    assert_eq!(download(&harness, "/piped.bin", "piped-back.bin"), payload);

    let no_destination = harness.run_with_stdin(&["--json", "put", "-"], b"anything");
    assert_failure(&no_destination);
    assert_eq!(json_error(&no_destination)["code"], "invalid_input");
}

/// A payload of several download chunks, so a `get` that read the file whole
/// and one that reads it in chunks are told apart by what comes back rather
/// than by what a comment claims.
fn multi_chunk_payload() -> Vec<u8> {
    let len = 3 * loonfs::CONTENT_READ_CHUNK_BYTES as usize + 1_024;
    (0..len).map(|offset| (offset % 251) as u8).collect()
}

/// A file many chunks long round-trips through an embedded profile to a
/// local file and to standard output, byte for byte.
#[test]
fn a_multi_chunk_file_round_trips_to_a_file_and_to_stdout() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));
    let payload = multi_chunk_payload();

    let local = harness.temp_dir.path().join("chunked.bin");
    fs::write(&local, &payload).expect("write payload");
    assert_success(&harness.run(&["put", local.to_str().expect("utf-8 path"), "/chunked.bin"]));

    assert_eq!(
        download(&harness, "/chunked.bin", "chunked-back.bin"),
        payload,
        "a downloaded file is the file that was uploaded"
    );

    let streamed = harness.run(&["get", "/chunked.bin", "-"]);
    assert_success(&streamed);
    assert_eq!(
        streamed.stdout, payload,
        "streaming to stdout writes the content and nothing else"
    );
}

/// Content that no longer matches its reference fails the download, and
/// fails it without leaving anything at the destination: no file, and no
/// partial file beside it. A verified-looking local copy of unverified bytes
/// is the outcome the temp-file-then-rename order exists to prevent.
#[test]
fn a_download_of_corrupted_content_leaves_nothing_at_the_destination() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let payload = b"the bytes that were committed".to_vec();
    let local = harness.temp_dir.path().join("source.bin");
    fs::write(&local, &payload).expect("write payload");
    assert_success(&harness.run(&["put", local.to_str().expect("utf-8 path"), "/doc.bin"]));

    // Same length, different bytes: the reference's digest is the only
    // thing that can tell, which is what the read has to notice.
    let object = content_object_path(&harness.store_root("default"), payload.len() as u64);
    let mut corrupted = payload.clone();
    corrupted[0] ^= 0xff;
    fs::write(&object, &corrupted).expect("corrupt content object");

    let destination = harness.temp_dir.path().join("downloads").join("doc.bin");
    fs::create_dir_all(destination.parent().expect("parent")).expect("create download dir");
    let failed = harness.run(&[
        "--json",
        "get",
        "/doc.bin",
        destination.to_str().expect("utf-8 path"),
    ]);
    assert_failure(&failed);
    assert_eq!(json_error(&failed)["code"], "namespace_corrupt");
    assert!(
        !destination.exists(),
        "a failed download must not install a file"
    );
    let leftovers: Vec<PathBuf> = fs::read_dir(destination.parent().expect("parent"))
        .expect("read download dir")
        .map(|entry| entry.expect("dir entry").path())
        .collect();
    assert!(
        leftovers.is_empty(),
        "the partial file must be cleaned up, found {leftovers:?}"
    );
}

/// The bytes and the note an interrupted download leaves beside its
/// destination, as this CLI names them.
fn partial_paths(destination: &Path) -> (PathBuf, PathBuf) {
    let name = destination
        .file_name()
        .expect("destination file name")
        .to_str()
        .expect("utf-8 name");
    let parent = destination.parent().expect("destination parent");
    (
        parent.join(format!(".{name}.loonfs-partial")),
        parent.join(format!(".{name}.loonfs-partial.meta")),
    )
}

/// Lays down the bytes and note an interrupted download of `remote_path`
/// would have left, having got `held` bytes in.
fn leave_a_partial_download(
    harness: &Harness,
    remote_path: &str,
    destination: &Path,
    payload: &[u8],
    held: usize,
) {
    let stat = harness.run(&["--json", "stat", remote_path]);
    assert_success(&stat);
    let content_ref = json_data(&stat)["content_ref"].clone();
    let (partial, meta) = partial_paths(destination);
    fs::write(&partial, &payload[..held]).expect("write partial bytes");
    let mut note = serde_json::json!({
        "content_id": content_ref["content_id"],
        "size_bytes": content_ref["size_bytes"],
    });
    if let Some(sha256) = content_ref.get("whole_file_sha256") {
        note["whole_file_sha256"] = sha256.clone();
    }
    fs::write(&meta, serde_json::to_vec(&note).expect("encode note")).expect("write note");
}

/// A download that stopped part way is picked up rather than started over:
/// the bytes already on disk are fetched again by nobody, and the file that
/// lands is still verified as a whole.
#[test]
fn an_interrupted_download_resumes_from_what_it_already_has() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let payload = streaming_payload();
    let source = harness.temp_dir.path().join("source.bin");
    fs::write(&source, &payload).expect("write payload");
    assert_success(&harness.run(&["put", source.to_str().expect("utf-8 path"), "/big.bin"]));

    let destination = harness.temp_dir.path().join("big.bin");
    let held = 3 * 1024 * 1024;
    leave_a_partial_download(&harness, "/big.bin", &destination, &payload, held);

    let get = harness.run(&[
        "--json",
        "get",
        "/big.bin",
        destination.to_str().expect("utf-8 path"),
    ]);
    assert_success(&get);
    assert_eq!(
        fs::read(&destination).expect("read destination"),
        payload,
        "a resumed download still lands the whole verified file"
    );

    let resuming: Vec<Value> = events_of_kind(&get, "phase")
        .into_iter()
        .filter(|event| event["phase"] == "resuming")
        .collect();
    assert_eq!(resuming.len(), 1, "one resume to report: {resuming:?}");
    assert_eq!(
        resuming[0]["bytes_done"], held as u64,
        "the run started at what was already on disk, not at zero"
    );

    let (partial, meta) = partial_paths(&destination);
    assert!(!partial.exists(), "an installed download leaves no partial");
    assert!(!meta.exists(), "and takes its note with it");
}

/// The note is what makes leftover bytes resumable. Bytes belonging to
/// other content, and bytes with nothing vouching for them, are dropped
/// without a word and the download starts over.
#[test]
fn a_partial_that_does_not_describe_this_file_is_started_over() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let payload = streaming_payload();
    let source = harness.temp_dir.path().join("source.bin");
    fs::write(&source, &payload).expect("write payload");
    assert_success(&harness.run(&["put", source.to_str().expect("utf-8 path"), "/big.bin"]));
    assert_success(&harness.run(&["put", source.to_str().expect("utf-8 path"), "/other.bin"]));

    // The note of a different file: same length, same bytes, and a content
    // id that says it is not this object.
    let destination = harness.temp_dir.path().join("big.bin");
    let held = 3 * 1024 * 1024;
    leave_a_partial_download(&harness, "/other.bin", &destination, &payload, held);

    let get = harness.run(&[
        "--json",
        "get",
        "/big.bin",
        destination.to_str().expect("utf-8 path"),
    ]);
    assert_success(&get);
    assert_eq!(fs::read(&destination).expect("read destination"), payload);
    assert!(
        events_of_kind(&get, "phase").is_empty(),
        "a download that started over reports no resume"
    );

    // Bytes with no note beside them say nothing about themselves either.
    let elsewhere = harness.temp_dir.path().join("again.bin");
    let (partial, _) = partial_paths(&elsewhere);
    fs::write(&partial, &payload[..held]).expect("write orphan partial");
    let get = harness.run(&[
        "--json",
        "get",
        "/big.bin",
        elsewhere.to_str().expect("utf-8 path"),
    ]);
    assert_success(&get);
    assert_eq!(fs::read(&elsewhere).expect("read destination"), payload);
    assert!(events_of_kind(&get, "phase").is_empty());
}

/// The one content object of a given length under a store root. Content
/// objects live at `content-stores/<store>/objects/<shard>/<id>`, and the
/// tests that use this write one file whose length nothing else shares.
fn content_object_path(store_root: &Path, size_bytes: u64) -> PathBuf {
    let objects = walkdir::WalkDir::new(store_root.join("content-stores"))
        .into_iter()
        .filter_map(|entry| entry.ok())
        .filter(|entry| {
            entry.file_type().is_file()
                && entry
                    .metadata()
                    .is_ok_and(|metadata| metadata.len() == size_bytes)
        })
        .map(|entry| entry.path().to_path_buf())
        .collect::<Vec<_>>();
    assert_eq!(
        objects.len(),
        1,
        "expected exactly one content object of {size_bytes} bytes, found {objects:?}"
    );
    objects.into_iter().next().expect("one content object")
}

/// The same two payloads over the remote transport. This deployment stores
/// to a local filesystem, so it cannot authorize direct part uploads and
/// the payload streams through the server instead — the fallback the client
/// picks from the capability document rather than from a guess.
#[test]
fn large_and_piped_puts_round_trip_over_the_remote_transport() {
    let harness = Harness::new();
    let remote_server =
        harness.start_external_server(harness.write_server_config("remote", "streaming-remote"));
    assert_success(&harness.run(&[
        "--json",
        "profile",
        "create",
        "default",
        "--mode",
        "remote",
        "--server-url",
        &remote_server.server_url,
        "--auth-token",
        "test-token",
    ]));
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));
    let payload = streaming_payload();

    let local = harness.temp_dir.path().join("big.bin");
    fs::write(&local, &payload).expect("write payload");
    assert_success(&harness.run(&[
        "--json",
        "put",
        local.to_str().expect("utf-8 path"),
        "/big.bin",
    ]));
    assert_eq!(download(&harness, "/big.bin", "big-back.bin"), payload);

    // No `Content-Length` to send: this body is chunked, and the server's
    // own incremental accounting is what bounds it.
    assert_success(&harness.run_with_stdin(&["--json", "put", "-", "/piped.bin"], &payload));
    assert_eq!(download(&harness, "/piped.bin", "piped-back.bin"), payload);
}

/// Every mutating command takes `-m`, and each one lands its annotation on
/// its own commit. Reading the feed back through `loonfs changes` covers the
/// flag, the threading, and the rendering in a single pass.
#[test]
fn every_mutating_command_records_its_message() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let payload = harness.temp_dir.path().join("doc.txt");
    fs::write(&payload, b"body").expect("write payload");
    let local = payload.to_str().expect("utf-8 path");

    assert_success(&harness.run(&["mkdir", "/dir", "-m", "mkdir message"]));
    assert_success(&harness.run(&["put", local, "/dir/doc.txt", "-m", "put message"]));
    assert_success(&harness.run(&["cp", "/dir/doc.txt", "/dir/copy.txt", "-m", "cp message"]));
    assert_success(&harness.run(&["mv", "/dir/copy.txt", "/dir/moved.txt", "-m", "mv message"]));
    assert_success(&harness.run(&[
        "put",
        local,
        "/dir/doc.txt",
        "--force",
        "-m",
        "second put message",
    ]));
    assert_success(&harness.run(&[
        "restore",
        "--revision",
        "1",
        "/dir/doc.txt",
        "-m",
        "restore message",
    ]));
    let removed = harness.run(&["--json", "rm", "/dir/moved.txt", "-m", "rm message"]);
    assert_success(&removed);
    let inode_id = json_data(&removed)["inode_id"]
        .as_u64()
        .expect("rm reports the deleted inode id");
    let deleted_at = json_data(&removed)["committed_seq"]
        .as_u64()
        .expect("rm reports the committed seq");
    assert_success(&harness.run(&[
        "undelete",
        "/dir/moved.txt",
        "--inode",
        &inode_id.to_string(),
        "--deleted-at",
        &deleted_at.to_string(),
        "-m",
        "undelete message",
    ]));

    assert_eq!(
        feed_messages(&harness),
        vec![
            "mkdir message",
            "put message",
            "cp message",
            "mv message",
            "second put message",
            "restore message",
            "rm message",
            "undelete message",
        ]
    );
}

/// The remote arm has to hand the message to the client's mutation options,
/// not just the embedded arm. Same flag, same feed rows, over HTTP.
#[test]
fn commit_messages_ride_the_feed_over_the_remote_transport() {
    let harness = Harness::new();
    let remote_server =
        harness.start_external_server(harness.write_server_config("remote", "message-remote"));
    let add_remote = harness.run(&[
        "--json",
        "profile",
        "create",
        "default",
        "--mode",
        "remote",
        "--server-url",
        &remote_server.server_url,
        "--auth-token",
        "test-token",
    ]);
    assert_success(&add_remote);
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let payload = harness.temp_dir.path().join("doc.txt");
    fs::write(&payload, b"body").expect("write payload");
    assert_success(&harness.run(&[
        "put",
        payload.to_str().expect("utf-8 path"),
        "/doc.txt",
        "-m",
        "landed over http",
    ]));
    assert_success(&harness.run(&["mkdir", "/dir", "-m", "made over http"]));

    assert_eq!(
        feed_messages(&harness),
        vec!["landed over http", "made over http"]
    );
}

/// Reads the namespace's change feed through the CLI and returns the
/// annotations in commit order, dropping the rows that carry none.
fn feed_messages(harness: &Harness) -> Vec<String> {
    let changes = harness.run(&["--json", "changes"]);
    assert_success(&changes);
    json_data(&changes)["changes"]
        .as_array()
        .expect("changes array")
        .iter()
        .filter_map(|row| row["message"].as_str().map(ToOwned::to_owned))
        .collect()
}

#[test]
fn trash_lists_recoverable_deletions_with_their_handles() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let payload = harness.temp_dir.path().join("doc.txt");
    fs::write(&payload, b"body").expect("write payload");
    assert_success(&harness.run(&[
        "put",
        payload.to_str().expect("utf-8 path"),
        "/docs/Quarterly Report.PDF",
    ]));
    assert_success(&harness.run(&[
        "put",
        payload.to_str().expect("utf-8 path"),
        "/notes/scratch.txt",
    ]));
    assert_success(&harness.run(&["rm", "/docs/Quarterly Report.PDF"]));
    assert_success(&harness.run(&["rm", "-r", "/notes"]));

    let trash = harness.run(&["--json", "trash"]);
    assert_success(&trash);
    let data = json_data(&trash);
    let entries = data["entries"].as_array().expect("entries").clone();
    assert_eq!(entries.len(), 2, "{data}");
    let report = entries
        .iter()
        .find(|entry| entry["display_name"] == "Quarterly Report.PDF")
        .expect("report entry");
    assert!(report["deleted_at_ms"].as_u64().expect("ms") > 0);

    // The human table prints the exact undelete invocation.
    let human = harness.run(&["trash"]);
    assert_success(&human);
    let table = stdout_string(&human);
    assert!(
        table.contains("DELETED\tNAME\tINODE\tSEQ\tRECOVER"),
        "{table}"
    );
    assert!(table.contains("Quarterly Report.PDF"), "{table}");
    assert!(table.contains("loonfs undelete "), "{table}");

    // Recovering through the listed handle empties that entry out of trash.
    let inode = report["root_inode_id"].as_u64().expect("inode");
    let seq = report["deleted_at_seq"].as_u64().expect("seq");
    assert_success(&harness.run(&[
        "undelete",
        "/docs/Quarterly Report.PDF",
        "--inode",
        &inode.to_string(),
        "--deleted-at",
        &seq.to_string(),
    ]));
    let after = harness.run(&["--json", "trash"]);
    assert_success(&after);
    assert_eq!(
        json_data(&after)["entries"]
            .as_array()
            .expect("entries")
            .len(),
        1
    );

    // Pagination pins the cursor contract: a one-entry page of a one-entry
    // trash carries no next cursor.
    let page = harness.run(&["--json", "trash", "--limit", "1"]);
    assert_success(&page);
    assert!(json_data(&page)["next_cursor"].is_null());
}

/// The printed recovery commands are meant to be pasted, so they name the
/// namespace they belong to and quote a path a shell would otherwise split.
#[test]
fn recovery_hints_name_their_namespace_and_quote_the_path() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let payload = harness.temp_dir.path().join("doc.txt");
    fs::write(&payload, b"body").expect("write payload");
    assert_success(&harness.run(&[
        "put",
        payload.to_str().expect("utf-8 path"),
        "/docs/Quarterly Report.PDF",
    ]));
    let inode = json_data(&harness.run(&["--json", "stat", "/docs/Quarterly Report.PDF"]))
        ["inode_id"]
        .as_u64()
        .expect("the stored inode id");

    // Nothing here is spelled on the command line, so the namespace is the
    // only ambient value the hint has to pin down.
    let removed = harness.run(&["rm", "/docs/Quarterly Report.PDF"]);
    assert_success(&removed);
    let entry = json_data(&harness.run(&["--json", "trash"]))["entries"][0].clone();
    let deleted_at = entry["deleted_at_seq"].as_u64().expect("the deletion seq");
    assert_eq!(
        hinted_recovery_command(&removed),
        format!("loonfs undelete --inode {inode} --deleted-at {deleted_at} --namespace demo")
    );

    // The trash table offers the same command for the same deletion. Neither
    // names a destination: a recorded binding restores in place, under the
    // parent and name the delete recorded.
    let listed = harness.run(&["trash"]);
    assert_success(&listed);
    assert_eq!(
        trash_recovery_command(&listed, "Quarterly Report.PDF"),
        format!("loonfs undelete --inode {inode} --deleted-at {deleted_at} --namespace demo")
    );

    // Pasting the hint into a shell recovers the file, which is the whole
    // reason the path is quoted.
    let replayed = harness.replay_in_shell(&hinted_recovery_command(&removed));
    assert_success(&replayed);
    let cat = harness.run(&["cat", "/docs/Quarterly Report.PDF"]);
    assert_success(&cat);
    assert_eq!(cat.stdout, b"body");
}

/// A hint that leaves out a profile or a config file a bare invocation would
/// not find again sends the paste at some other filesystem, so both are
/// spelled whenever this run did not reach them the default way.
#[test]
fn recovery_hints_name_a_profile_and_config_a_bare_invocation_would_miss() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    harness.add_embedded_profile("staging");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));
    assert_success(&harness.run(&["namespace", "create", "release", "--profile", "staging"]));

    let payload = harness.temp_dir.path().join("doc.txt");
    fs::write(&payload, b"body").expect("write payload");
    let put = |extra: &[&str]| {
        let mut args = vec!["put", payload.to_str().expect("utf-8 path"), "/notes.txt"];
        args.extend_from_slice(extra);
        assert_success(&harness.run(&args));
    };

    // A spelled --profile means the config's default is some other profile,
    // so the hint has to say which one it meant.
    put(&["--profile", "staging", "--namespace", "release"]);
    let removed = harness.run(&[
        "rm",
        "/notes.txt",
        "--profile",
        "staging",
        "--namespace",
        "release",
    ]);
    assert_success(&removed);
    let command = hinted_recovery_command(&removed);
    assert!(
        command.ends_with(" --namespace release --profile staging"),
        "{command}"
    );

    // The config flag names a file a later paste would not look at.
    let elsewhere = harness.temp_dir.path().join("elsewhere.toml");
    let elsewhere_arg = elsewhere.to_str().expect("utf-8 config path");
    fs::copy(&harness.config_path, &elsewhere).expect("copy the config aside");
    put(&[]);
    let removed = harness.run(&["--config", elsewhere_arg, "rm", "/notes.txt"]);
    assert_success(&removed);
    let command = hinted_recovery_command(&removed);
    assert!(
        command.ends_with(&format!(" --namespace demo --config {elsewhere_arg}")),
        "{command}"
    );

    // So does the environment variable: the pasting shell need not still
    // export it, so the hint carries the path instead of relying on it.
    put(&[]);
    let removed = harness.run_with_env(&[("LOONFS_CONFIG", elsewhere_arg)], &["rm", "/notes.txt"]);
    assert_success(&removed);
    let command = hinted_recovery_command(&removed);
    assert!(
        command.ends_with(&format!(" --namespace demo --config {elsewhere_arg}")),
        "{command}"
    );

    // The default locations need no flag: they are what a bare invocation
    // reads.
    put(&[]);
    let removed = harness.run(&["rm", "/notes.txt"]);
    assert_success(&removed);
    let command = hinted_recovery_command(&removed);
    assert!(command.ends_with(" --namespace demo"), "{command}");
    assert!(!command.contains("--config"), "{command}");
    assert!(!command.contains("--profile"), "{command}");
}

#[test]
fn human_output_shows_dates_and_event_names() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let payload = harness.temp_dir.path().join("doc.txt");
    fs::write(&payload, b"v1").expect("write payload");
    assert_success(&harness.run(&[
        "put",
        payload.to_str().expect("utf-8 path"),
        "/docs/Report.PDF",
    ]));
    assert_success(&harness.run(&["rm", "/docs/Report.PDF"]));

    let changes = harness.run(&["changes"]);
    assert_success(&changes);
    let feed = stdout_string(&changes);
    assert!(feed.contains("SEQ\tDATE\tEVENTS\tMESSAGE"), "{feed}");
    assert!(feed.contains("create 'Report.PDF'"), "{feed}");
    assert!(feed.contains("delete 'Report.PDF'"), "{feed}");
    // Dates render as UTC wall-clock, not raw milliseconds.
    assert!(feed.contains("Z\t"), "{feed}");

    fs::write(&payload, b"v2").expect("write payload");
    assert_success(&harness.run(&["put", payload.to_str().expect("utf-8 path"), "/doc.txt"]));
    let revisions = harness.run(&["revisions", "/doc.txt"]);
    assert_success(&revisions);
    let table = stdout_string(&revisions);
    assert!(
        table.contains("REVISION\tDATE\tSEQ\tSIZE\tDIGEST"),
        "{table}"
    );

    let stat_file = harness.run(&["stat", "/doc.txt"]);
    assert_success(&stat_file);
    assert!(
        stdout_string(&stat_file).contains("modified: "),
        "{}",
        stdout_string(&stat_file)
    );
}

#[test]
fn naming_strictness_and_directory_intent_hold_end_to_end() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let payload = harness.temp_dir.path().join("report.pdf");
    fs::write(&payload, b"body").expect("write payload");

    // A trailing slash means into-directory, never a file named like the
    // directory; other noncanonical spellings fail like the wire.
    assert_success(&harness.run(&["mkdir", "/docs"]));
    assert_success(&harness.run(&["put", payload.to_str().expect("utf-8 path"), "/docs/"]));
    assert_success(&harness.run(&["--json", "stat", "/docs/report.pdf"]));
    let double_slash = harness.run(&["put", payload.to_str().expect("utf-8 path"), "//x.txt"]);
    assert_failure(&double_slash);

    // Case-only rename works in place — including without --force — and a
    // no-op respelling stays a conflict.
    assert_success(&harness.run(&["--json", "mv", "/docs/report.pdf", "/docs/REPORT.PDF"]));
    let stat = harness.run(&["--json", "stat", "/docs/REPORT.PDF"]);
    assert_success(&stat);
    assert_eq!(json_data(&stat)["display_name"], "REPORT.PDF");
    let noop = harness.run(&["--json", "mv", "/docs/REPORT.PDF", "/docs/REPORT.PDF"]);
    assert_failure(&noop);
    assert_eq!(json_error(&noop)["code"], "path_conflict");

    // A normalization-equal collision names the stored spelling, so two
    // visually identical names stop looking like the same one.
    let collision = harness.run(&[
        "put",
        payload.to_str().expect("utf-8 path"),
        "/docs/report.pdf",
    ]);
    assert_failure(&collision);
    let message = stderr_string(&collision);
    assert!(message.contains("stored as `REPORT.PDF`"), "{message}");
    assert!(message.contains("case folding"), "{message}");

    // The portability floor rejects what no target filesystem can hold.
    for name in ["/docs/CON", "/docs/notes.", "/docs/draft "] {
        let rejected = harness.run(&["put", payload.to_str().expect("utf-8 path"), name]);
        assert_failure(&rejected);
    }
}

#[test]
fn recursive_transfers_roundtrip_a_tree() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    // A local tree with nesting, an empty directory chain, and a root file.
    let tree = harness.temp_dir.path().join("tree");
    fs::create_dir_all(tree.join("docs/nested")).expect("create tree dirs");
    fs::create_dir_all(tree.join("empty/inner")).expect("create empty chain");
    fs::write(tree.join("top.txt"), b"top").expect("write top");
    fs::write(tree.join("docs/a.txt"), b"alpha").expect("write a");
    fs::write(tree.join("docs/nested/b.txt"), b"beta").expect("write b");

    // A plain put on a directory names the recursive flag.
    let plain = harness.run(&["--json", "put", tree.to_str().expect("utf-8 path"), "/up"]);
    assert_failure(&plain);
    assert!(json_error(&plain)["message"]
        .as_str()
        .expect("error message")
        .contains("put -r"),);

    let put = harness.run(&[
        "--json",
        "put",
        "-r",
        tree.to_str().expect("utf-8 path"),
        "/up",
    ]);
    assert_success(&put);
    let put_data = json_data(&put);
    assert_eq!(put_data["kind"], "tree_transfer");
    assert_eq!(put_data["files"], 3);
    assert_eq!(put_data["directories"], 1);
    assert_eq!(put_data["failures"].as_array().expect("failures").len(), 0);
    for path in ["/up/top.txt", "/up/docs/nested/b.txt", "/up/empty/inner"] {
        assert_success(&harness.run(&["--json", "stat", path]));
    }

    // Rerunning without --force reports per-file conflicts and exits
    // nonzero while the summary stays structured; --force replaces cleanly.
    let rerun = harness.run(&[
        "--json",
        "put",
        "-r",
        tree.to_str().expect("utf-8 path"),
        "/up",
    ]);
    assert_failure(&rerun);
    let rerun_data = json_data(&rerun);
    assert_eq!(rerun_data["files"], 0);
    assert_eq!(
        rerun_data["failures"].as_array().expect("failures").len(),
        4
    );
    assert_eq!(
        rerun_data["failures"][0]["error"]["code"], "path_conflict",
        "{rerun_data}"
    );
    let forced = harness.run(&[
        "--json",
        "put",
        "-r",
        tree.to_str().expect("utf-8 path"),
        "/up",
        "--force",
    ]);
    assert_failure(&forced);
    let forced_data = json_data(&forced);
    assert_eq!(forced_data["files"], 3);
    assert_eq!(
        forced_data["failures"].as_array().expect("failures").len(),
        1,
        "the empty directory still conflicts: {forced_data}"
    );

    // Download the tree and compare bytes; empty directories materialize.
    let downloaded = harness.temp_dir.path().join("downloaded");
    let get = harness.run(&[
        "--json",
        "get",
        "-r",
        "/up",
        downloaded.to_str().expect("utf-8 path"),
    ]);
    assert_success(&get);
    let get_data = json_data(&get);
    assert_eq!(get_data["files"], 3);
    assert_eq!(
        fs::read(downloaded.join("docs/nested/b.txt")).expect("downloaded bytes"),
        b"beta"
    );
    assert!(downloaded.join("empty/inner").is_dir());

    // Server-side copy: the tree lands without moving bytes — the copied
    // file shares its source's content reference.
    let cp = harness.run(&["--json", "cp", "-r", "/up", "/copy"]);
    assert_success(&cp);
    let cp_data = json_data(&cp);
    assert_eq!(cp_data["files"], 3);
    assert_eq!(cp_data["directories"], 5);
    let source = harness.run(&["--json", "stat", "/up/docs/a.txt"]);
    let copy = harness.run(&["--json", "stat", "/copy/docs/a.txt"]);
    assert_success(&source);
    assert_success(&copy);
    assert_eq!(
        json_data(&source)["content_ref"],
        json_data(&copy)["content_ref"]
    );
    assert_success(&harness.run(&["--json", "stat", "/copy/empty/inner"]));

    // mv still moves a directory in one commit, no flag involved.
    assert_success(&harness.run(&["--json", "mv", "/copy", "/moved"]));
    assert_success(&harness.run(&["--json", "stat", "/moved/docs/a.txt"]));
    let mv_recursive = harness.run(&["--json", "mv", "-r", "/moved", "/again"]);
    assert_failure(&mv_recursive);
    assert_eq!(json_error(&mv_recursive)["code"], "invalid_input");
}

/// A recursive get creates the destination it was handed, parents included,
/// the way `cp -r` creates its target. The shape that used to fail on every
/// file is a remote directory holding nothing but files: no subdirectory
/// existed to create the root as a side effect of its own `mkdir`.
#[test]
fn recursive_get_creates_an_absent_destination_root_in_both_modes() {
    let harness = Harness::new();
    harness.add_embedded_profile("embedded");
    let remote_server =
        harness.start_external_server(harness.write_server_config("remote", "get-destination"));
    let add_remote = harness.run(&[
        "--json",
        "profile",
        "create",
        "remote",
        "--mode",
        "remote",
        "--server-url",
        &remote_server.server_url,
        "--auth-token",
        "test-token",
    ]);
    assert_success(&add_remote);

    let flat = harness.temp_dir.path().join("flat");
    fs::create_dir_all(&flat).expect("create flat source");
    for name in ["a.txt", "b.txt"] {
        fs::write(flat.join(name), name.as_bytes()).expect("write source file");
    }

    for profile in ["embedded", "remote"] {
        assert_success(&harness.run(&["namespace", "create", "--profile", profile, "demo"]));
        assert_success(&harness.run(&["use", "--profile", profile, "demo"]));
        assert_success(&harness.run(&[
            "put",
            "-r",
            "--profile",
            profile,
            flat.to_str().expect("utf-8 path"),
            "/flat",
        ]));
        // A directory holding nothing, inside another holding nothing.
        assert_success(&harness.run(&["mkdir", "-p", "--profile", profile, "/nested/empty/inner"]));

        // Files with no subdirectory among them: nothing but the transfer
        // itself can bring the destination root into being. Neither the root
        // nor its parent exists here.
        let destination = harness.temp_dir.path().join(profile).join("dest");
        let get = harness.run(&[
            "--json",
            "get",
            "-r",
            "--profile",
            profile,
            "/flat",
            destination.to_str().expect("utf-8 path"),
        ]);
        assert_success(&get);
        let data = json_data(&get);
        assert_eq!(data["files"], 2, "{data}");
        // The destination root, counted the way `cp -r` counts its own.
        assert_eq!(data["directories"], 1, "{data}");
        assert_eq!(data["failures"].as_array().expect("failures").len(), 0);
        assert_eq!(
            fs::read(destination.join("a.txt")).expect("downloaded a.txt"),
            b"a.txt"
        );

        // Empty directories, nested, land as local directories.
        let nested = harness.temp_dir.path().join(profile).join("nested");
        let nested_get = harness.run(&[
            "--json",
            "get",
            "-r",
            "--profile",
            profile,
            "/nested",
            nested.to_str().expect("utf-8 path"),
        ]);
        assert_success(&nested_get);
        let nested_data = json_data(&nested_get);
        assert_eq!(nested_data["files"], 0, "{nested_data}");
        assert_eq!(nested_data["directories"], 3, "{nested_data}");
        assert!(nested.join("empty/inner").is_dir());

        // A tree with nothing in it at all still leaves the caller with the
        // directory they named.
        let empty_destination = harness.temp_dir.path().join(profile).join("only-empty");
        let empty = harness.run(&[
            "--json",
            "get",
            "-r",
            "--profile",
            profile,
            "/nested/empty/inner",
            empty_destination.to_str().expect("utf-8 path"),
        ]);
        assert_success(&empty);
        let empty_data = json_data(&empty);
        assert_eq!(empty_data["files"], 0, "{empty_data}");
        assert_eq!(empty_data["directories"], 1, "{empty_data}");
        assert!(empty_destination.is_dir());
    }
}

/// One unwritable destination path fails alone. A local file sitting where a
/// directory has to go takes down that directory and the files under it —
/// each named on its own — while every sibling still lands.
#[test]
fn recursive_get_names_only_the_paths_it_could_not_write_in_both_modes() {
    let harness = Harness::new();
    harness.add_embedded_profile("embedded");
    let remote_server =
        harness.start_external_server(harness.write_server_config("remote", "get-partial"));
    let add_remote = harness.run(&[
        "--json",
        "profile",
        "create",
        "remote",
        "--mode",
        "remote",
        "--server-url",
        &remote_server.server_url,
        "--auth-token",
        "test-token",
    ]);
    assert_success(&add_remote);

    let tree = harness.temp_dir.path().join("tree");
    fs::create_dir_all(tree.join("docs")).expect("create docs");
    fs::create_dir_all(tree.join("other")).expect("create other");
    fs::write(tree.join("top.txt"), b"top").expect("write top");
    fs::write(tree.join("docs/a.txt"), b"alpha").expect("write a");
    fs::write(tree.join("docs/b.txt"), b"beta").expect("write b");
    fs::write(tree.join("other/c.txt"), b"gamma").expect("write c");

    for profile in ["embedded", "remote"] {
        assert_success(&harness.run(&["namespace", "create", "--profile", profile, "demo"]));
        assert_success(&harness.run(&["use", "--profile", profile, "demo"]));
        assert_success(&harness.run(&[
            "put",
            "-r",
            "--profile",
            profile,
            tree.to_str().expect("utf-8 path"),
            "/src",
        ]));

        // A plain file occupies the place `docs` has to be.
        let destination = harness.temp_dir.path().join(profile);
        fs::create_dir_all(&destination).expect("create destination");
        fs::write(destination.join("docs"), b"in the way").expect("block docs");

        let get = harness.run(&[
            "--json",
            "get",
            "-r",
            "--profile",
            profile,
            "/src",
            destination.to_str().expect("utf-8 path"),
        ]);
        assert_failure(&get);
        let data = json_data(&get);
        assert_eq!(data["files"], 2, "{data}");
        // The destination root and `other`; `docs` is the one that failed.
        assert_eq!(data["directories"], 2, "{data}");

        // The blocked directory is named by the local path that failed, the
        // files under it by the remote paths that could not be written.
        let failed: Vec<&str> = data["failures"]
            .as_array()
            .expect("failures")
            .iter()
            .map(|failure| failure["path"].as_str().expect("failure path"))
            .collect();
        assert_eq!(failed.len(), 3, "{data}");
        assert!(
            failed.contains(&destination.join("docs").to_str().expect("utf-8 path")),
            "{data}"
        );
        assert!(failed.contains(&"/src/docs/a.txt"), "{data}");
        assert!(failed.contains(&"/src/docs/b.txt"), "{data}");
        for failure in data["failures"].as_array().expect("failures") {
            assert_eq!(failure["error"]["code"], "io_error", "{data}");
        }

        // Everything outside the blocked subtree downloaded.
        assert_eq!(
            fs::read(destination.join("top.txt")).expect("downloaded top.txt"),
            b"top"
        );
        assert_eq!(
            fs::read(destination.join("other/c.txt")).expect("downloaded c.txt"),
            b"gamma"
        );
    }
}

/// One file into a directory that does not exist fails, exactly as `cp` into
/// a missing parent fails: only `-r`, which owns the destination tree it is
/// asked to build, creates directories.
#[test]
fn single_file_get_refuses_a_missing_parent_directory() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let payload = harness.temp_dir.path().join("payload.txt");
    fs::write(&payload, b"body").expect("write payload");
    assert_success(&harness.run(&["put", payload.to_str().expect("utf-8 path"), "/docs/a.txt"]));

    let missing = harness.temp_dir.path().join("no-such-dir");
    let get = harness.run(&[
        "--json",
        "get",
        "/docs/a.txt",
        missing.join("a.txt").to_str().expect("utf-8 path"),
    ]);
    assert_failure(&get);
    let error = json_error(&get);
    assert_eq!(error["code"], "io_error");
    let message = error["message"].as_str().expect("error message");
    assert!(
        message.contains(missing.to_str().expect("utf-8 path")),
        "the message names the directory to create, got: {message}"
    );
    assert!(
        !message.contains(".loonfs-partial"),
        "the message keeps the CLI's own temporary file out of it, got: {message}"
    );
    assert!(!missing.exists(), "a failed get created no directory");
}

#[test]
fn rm_recursive_deletes_a_populated_directory_in_one_commit() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let payload = harness.temp_dir.path().join("payload.txt");
    fs::write(&payload, b"body").expect("write payload");
    for path in ["/docs/a.txt", "/docs/nested/b.txt"] {
        assert_success(&harness.run(&["put", payload.to_str().expect("utf-8 path"), path]));
    }

    // Without -r a populated directory still refuses, exactly as before.
    let refused = harness.run(&["--json", "rm", "/docs"]);
    assert_failure(&refused);
    assert_eq!(json_error(&refused)["code"], "directory_not_empty");

    let removed = harness.run(&["--json", "rm", "-r", "/docs"]);
    assert_success(&removed);
    assert_eq!(json_data(&removed)["target"], "demo:/docs");

    for path in ["/docs", "/docs/a.txt", "/docs/nested/b.txt"] {
        let stat = harness.run(&["--json", "stat", path]);
        assert_failure(&stat);
        assert_eq!(json_error(&stat)["code"], "path_not_found");
    }
}

#[test]
fn embedded_profile_namespace_fork_reads_shared_content_and_diverges() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");

    let upload_path = harness.temp_dir.path().join("upload.txt");
    let clone_upload_path = harness.temp_dir.path().join("clone-upload.txt");
    fs::write(&upload_path, b"base from cli\n").expect("upload payload");
    fs::write(&clone_upload_path, b"clone from cli\n").expect("clone upload payload");

    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));
    assert_success(&harness.run(&[
        "put",
        upload_path.to_str().expect("utf-8 path"),
        "/docs/shared.txt",
    ]));

    let fork = harness.run(&["--json", "namespace", "fork", "demo", "clone"]);
    assert_success(&fork);
    assert_eq!(json_data(&fork)["namespace_id"], "clone");

    let source = harness.run(&["--json", "stat", "/docs/shared.txt"]);
    let clone = harness.run(&["--json", "stat", "--namespace", "clone", "/docs/shared.txt"]);
    assert_success(&source);
    assert_success(&clone);
    assert_eq!(
        json_data(&source)["content_ref"],
        json_data(&clone)["content_ref"]
    );

    assert_success(&harness.run(&[
        "put",
        "--namespace",
        "clone",
        clone_upload_path.to_str().expect("utf-8 path"),
        "/docs/shared.txt",
        "--force",
    ]));

    let source_cat = harness.run(&["cat", "/docs/shared.txt"]);
    assert_success(&source_cat);
    assert_eq!(source_cat.stdout, b"base from cli\n");

    let clone_cat = harness.run(&["cat", "--namespace", "clone", "/docs/shared.txt"]);
    assert_success(&clone_cat);
    assert_eq!(clone_cat.stdout, b"clone from cli\n");
}

#[test]
fn init_creates_embedded_profile_and_current_reports_namespace_unset() {
    let harness = Harness::new();

    let init = harness.run(&[
        "--json",
        "init",
        "mystore",
        "--mode",
        "embedded",
        "--store-kind",
        "local-fs",
        "--root",
        harness.store_root("mystore").to_str().expect("utf-8 path"),
    ]);
    assert_success(&init);
    assert_eq!(json_data(&init)["mode"], "embedded");

    let show = harness.run(&["--json", "profile", "show"]);
    assert_success(&show);
    assert_eq!(json_data(&show)["mode"], "embedded");

    let current = harness.run(&["--json", "current"]);
    assert_success(&current);
    assert_eq!(json_data(&current)["profile"], "mystore");
    assert!(json_data(&current)["namespace"].is_null());

    assert_success(&harness.run(&["namespace", "create", "demo"]));
    let use_namespace = harness.run(&["--json", "use", "demo"]);
    assert_success(&use_namespace);
    assert_eq!(json_data(&use_namespace)["namespace"], "demo");
}

#[test]
fn invalid_profile_mode_is_rejected() {
    let harness = Harness::new();

    let result = harness.run(&[
        "--json",
        "profile",
        "create",
        "default",
        "--mode",
        "not-a-mode",
        "--store-kind",
        "local-fs",
        "--root",
        harness.store_root("default").to_str().expect("utf-8 path"),
    ]);

    assert_failure(&result);
    let error = json_error(&result);
    assert_eq!(error["code"], "invalid_input");
    let message = error["message"].as_str().expect("json string");
    assert!(message.contains("expected embedded or remote"));
}

#[test]
fn removing_last_profile_leaves_empty_config() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");

    let remove = harness.run(&["--json", "--no-input", "profile", "delete", "default"]);
    assert_success(&remove);

    let list = harness.run(&["--json", "profile", "list"]);
    assert_success(&list);
    let data = json_data(&list);
    assert!(data["default_profile"].is_null());
    assert_eq!(data["profiles"].as_array().expect("json array").len(), 0);

    let show_config = harness.run(&["config", "show"]);
    assert_success(&show_config);
    assert!(!stdout_string(&show_config).contains("default_profile"));

    let show = harness.run(&["--json", "profile", "show"]);
    assert_failure(&show);
    assert_eq!(json_error(&show)["code"], "no_default_profile");
}

#[test]
fn removing_default_profile_requires_explicit_reselection() {
    let harness = Harness::new();
    harness.add_embedded_profile("alpha");
    harness.add_embedded_profile("beta");

    let remove = harness.run(&["--json", "--no-input", "profile", "delete", "alpha"]);
    assert_success(&remove);

    let list = harness.run(&["--json", "profile", "list"]);
    assert_success(&list);
    let data = json_data(&list);
    assert!(data["default_profile"].is_null());
    assert_eq!(data["profiles"].as_array().expect("json array").len(), 1);

    let current = harness.run(&["--json", "current"]);
    assert_failure(&current);
    assert_eq!(json_error(&current)["code"], "no_default_profile");

    let namespace = harness.run(&["--json", "namespace", "create", "new-ns"]);
    assert_failure(&namespace);
    assert_eq!(json_error(&namespace)["code"], "no_default_profile");

    let filesystem = harness.run(&["--json", "ls", "/"]);
    assert_failure(&filesystem);
    assert_eq!(json_error(&filesystem)["code"], "no_default_profile");

    let use_profile = harness.run(&["--json", "profile", "use", "beta"]);
    assert_success(&use_profile);

    let show_after = harness.run(&["--json", "profile", "show"]);
    assert_success(&show_after);
    assert_eq!(json_data(&show_after)["mode"], "embedded");
}

#[test]
fn profile_update_changes_fields() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");

    let new_root = harness.store_root("updated");
    let update = harness.run(&[
        "--json",
        "profile",
        "update",
        "default",
        "--root",
        new_root.to_str().expect("utf-8 path"),
    ]);
    assert_success(&update);

    let show = harness.run(&["--json", "profile", "show", "default"]);
    assert_success(&show);
    let store = &json_data(&show)["store"];
    assert_eq!(store["root"], new_root.to_str().expect("utf-8 path"));
}

#[test]
fn profile_update_with_only_service_account_key_path_applies() {
    let harness = Harness::new();
    let create = harness.run(&[
        "--json",
        "profile",
        "create",
        "gcp",
        "--mode",
        "embedded",
        "--store-kind",
        "gcp-gcs",
        "--bucket",
        "documents",
        "--service-account-key-path",
        "/old/service-account.json",
    ]);
    assert_success(&create);

    let update = harness.run(&[
        "--json",
        "--no-input",
        "profile",
        "update",
        "gcp",
        "--service-account-key-path",
        "/new/service-account.json",
    ]);
    assert_success(&update);

    let show = harness.run(&["--json", "profile", "show", "gcp"]);
    assert_success(&show);
    assert_eq!(
        json_data(&show)["store"]["service_account_key_path"],
        "/new/service-account.json"
    );
}

#[test]
fn profile_use_switches_default() {
    let harness = Harness::new();
    harness.add_embedded_profile("alpha");
    harness.add_embedded_profile("beta");

    let use_profile = harness.run(&["--json", "profile", "use", "beta"]);
    assert_success(&use_profile);
    assert_eq!(json_data(&use_profile)["name"], "beta");

    let current = harness.run(&["--json", "current"]);
    assert_success(&current);
    assert_eq!(json_data(&current)["profile"], "beta");
}

#[test]
fn profile_use_rejects_missing_profile() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");

    let result = harness.run(&["--json", "profile", "use", "nonexistent"]);
    assert_failure(&result);
    assert_eq!(json_error(&result)["code"], "profile_not_found");
}

#[test]
fn profile_names_matching_top_level_config_keys_are_allowed() {
    // Profiles nest under [profiles.<name>], so names that once collided
    // with top-level settings need no reservation.
    let harness = Harness::new();

    let init = harness.run(&[
        "--json",
        "init",
        "default_profile",
        "--mode",
        "embedded",
        "--store-kind",
        "local-fs",
        "--root",
        harness
            .store_root("default_profile")
            .to_str()
            .expect("utf-8 path"),
    ]);
    assert_success(&init);

    let create = harness.run(&[
        "--json",
        "profile",
        "create",
        "config_version",
        "--mode",
        "embedded",
        "--store-kind",
        "local-fs",
        "--root",
        harness
            .store_root("config_version")
            .to_str()
            .expect("utf-8 path"),
    ]);
    assert_success(&create);

    let list = harness.run(&["--json", "profile", "list"]);
    assert_success(&list);
    let names: Vec<_> = json_data(&list)["profiles"]
        .as_array()
        .expect("profiles array")
        .iter()
        .map(|profile| profile["name"].as_str().expect("profile name").to_owned())
        .collect();
    assert!(names.contains(&"default_profile".to_owned()));
    assert!(names.contains(&"config_version".to_owned()));
}

#[test]
fn ambient_provider_credentials_do_not_look_like_flags() {
    // An AWS key exported for something else is not `--access-key-id`
    // passed to this command, so a provider that cannot use it ignores it.
    let harness = Harness::new();
    let ambient = &[
        ("AWS_ACCESS_KEY_ID", "ambient-access"),
        ("AWS_SECRET_ACCESS_KEY", "ambient-secret"),
        ("AWS_SESSION_TOKEN", "ambient-session"),
        ("LOONFS_AUTH_TOKEN", "ambient-token"),
    ];

    let gcs = harness.run_with_env(
        ambient,
        &[
            "--json",
            "profile",
            "create",
            "gcs",
            "--mode",
            "embedded",
            "--store-kind",
            "gcp-gcs",
            "--bucket",
            "bucket",
            "--service-account-key-path",
            "/tmp/service-account.json",
        ],
    );
    assert_success(&gcs);
    assert_eq!(json_data(&gcs)["store"]["kind"], "gcp-gcs");

    let local_fs = harness.run_with_env(
        ambient,
        &[
            "--json",
            "profile",
            "create",
            "local",
            "--mode",
            "embedded",
            "--store-kind",
            "local-fs",
            "--root",
            harness.store_root("local").to_str().expect("utf-8 path"),
        ],
    );
    assert_success(&local_fs);

    // The same environment still fills the providers that use it.
    let s3 = harness.run_with_env(
        ambient,
        &[
            "--json",
            "profile",
            "create",
            "s3",
            "--mode",
            "embedded",
            "--store-kind",
            "aws-s3",
            "--bucket",
            "bucket",
            "--region",
            "us-east-1",
        ],
    );
    assert_success(&s3);
    assert_eq!(json_data(&s3)["store"]["access_key_id"], "<redacted>");

    // And a typed flag that does not apply is still rejected.
    let typed = harness.run_with_env(
        ambient,
        &[
            "--json",
            "profile",
            "create",
            "gcs-typed",
            "--mode",
            "embedded",
            "--store-kind",
            "gcp-gcs",
            "--bucket",
            "bucket",
            "--service-account-key-path",
            "/tmp/service-account.json",
            "--access-key-id",
            "typed-access",
        ],
    );
    assert_failure(&typed);
    let error = json_error(&typed);
    assert_eq!(error["code"], "invalid_input");
    assert!(error["message"]
        .as_str()
        .expect("json string")
        .contains("`--access-key-id` does not apply"));
}

/// A command line the parser rejected is a failure like any other under
/// `--json`, and keeps clap's own exit status so a script can still tell a
/// command that never ran from one that ran and failed.
#[test]
fn json_covers_command_lines_the_parser_rejects() {
    let harness = Harness::new();

    for arguments in [
        vec!["--json", "bogus-command"],
        vec!["--json", "mkdir"],
        vec![
            "--json",
            "admin",
            "run",
            "--namespace",
            "demo",
            "--drain",
            "--max-steps",
            "abc",
        ],
        // The flag is global, so it still counts after the subcommand.
        vec!["stat", "--json", "--nonexistent-flag"],
    ] {
        let output = harness.run(&arguments);
        assert_failure(&output);
        assert_eq!(
            output.status.code(),
            Some(2),
            "a parse failure keeps clap's usage status for {arguments:?}"
        );
        assert!(
            output.stdout.is_empty(),
            "the failure belongs on stderr for {arguments:?}"
        );
        let envelope = parse_json(&output.stderr);
        assert_eq!(envelope["kind"], "parse_error");
        assert_eq!(envelope["format_version"], 1);
        assert!(envelope["data"].is_null());
        assert_eq!(envelope["error"]["code"], "invalid_usage");
        assert!(!envelope["error"]["message"]
            .as_str()
            .expect("json string")
            .is_empty());
    }

    // Without --json the plain-text rendering and the status are unchanged.
    let plain = harness.run(&["bogus-command"]);
    assert_eq!(plain.status.code(), Some(2));
    assert!(stderr_string(&plain).contains("unrecognized subcommand"));
    assert!(!stderr_string(&plain).starts_with('{'));

    // Help and version are not failures, whatever else is on the line.
    let help = harness.run(&["--json", "--help"]);
    assert_success(&help);
    assert!(stdout_string(&help).contains("Usage:"));
    let version = harness.run(&["--json", "--version"]);
    assert_success(&version);
}

#[test]
fn init_rejects_existing_config_file() {
    let harness = Harness::new();
    harness.write_cli_config(format!(
        r#"
config_version = 1
default_profile = "default"

[profiles.default]
mode = "embedded"

[profiles.default.store]
kind = "local-fs"
root = "{}"
"#,
        harness.store_root("default").display()
    ));
    let existing = fs::read_to_string(&harness.config_path).expect("read existing config");

    let init = harness.run(&[
        "--json",
        "init",
        "mystore",
        "--mode",
        "embedded",
        "--store-kind",
        "local-fs",
        "--root",
        harness.store_root("mystore").to_str().expect("utf-8 path"),
    ]);
    assert_failure(&init);
    let error = json_error(&init);
    assert_eq!(error["code"], "config_already_exists");
    let message = error["message"].as_str().expect("json string");
    assert!(message.contains("loonfs profile create"));
    assert!(message.contains("loonfs profile update"));
    assert!(message.contains("loonfs profile use"));
    assert_eq!(
        fs::read_to_string(&harness.config_path).expect("read unchanged config"),
        existing
    );
}

#[test]
fn profiles_nest_under_their_own_table() {
    let harness = Harness::new();
    harness.write_cli_config(format!(
        r#"
config_version = 1

[profiles.default_profile]
mode = "embedded"

[profiles.default_profile.store]
kind = "local-fs"
root = "{}"
"#,
        harness.store_root("default_profile").display()
    ));

    let list = harness.run(&["--json", "profile", "list"]);
    assert_success(&list);
    assert_eq!(json_data(&list)["profiles"][0]["name"], "default_profile");
}

#[test]
fn empty_default_profile_in_config_is_rejected() {
    let harness = Harness::new();
    harness.write_cli_config(
        r#"
config_version = 1
default_profile = ""
"#,
    );

    let list = harness.run(&["--json", "profile", "list"]);
    assert_failure(&list);
    let error = json_error(&list);
    assert_eq!(error["code"], "invalid_config");
    assert!(error["message"]
        .as_str()
        .expect("json string")
        .contains("default_profile"));
}

#[test]
fn whitespace_default_profile_in_config_is_rejected() {
    let harness = Harness::new();
    harness.write_cli_config(
        r#"
config_version = 1
default_profile = "   "
"#,
    );

    let list = harness.run(&["--json", "profile", "list"]);
    assert_failure(&list);
    let error = json_error(&list);
    assert_eq!(error["code"], "invalid_config");
    assert!(error["message"]
        .as_str()
        .expect("json string")
        .contains("default_profile"));
}

#[test]
fn invalid_store_field_messages_use_flattened_paths() {
    let harness = Harness::new();
    harness.write_cli_config(
        r#"
config_version = 1
default_profile = "default"

[profiles.default]
mode = "embedded"

[profiles.default.store]
kind = "local-fs"
root = ""
"#,
    );

    let list = harness.run(&["--json", "profile", "list"]);
    assert_failure(&list);
    let error = json_error(&list);
    assert_eq!(error["code"], "invalid_config");
    assert!(error["message"]
        .as_str()
        .expect("json string")
        .contains("default.store.root"));
}

#[test]
fn invalid_default_namespace_in_config_is_rejected() {
    let harness = Harness::new();
    harness.write_cli_config(format!(
        r#"
config_version = 1
default_profile = "default"

[profiles.default]
mode = "embedded"
default_namespace = "bad/name"

[profiles.default.store]
kind = "local-fs"
root = "{}"
"#,
        harness.store_root("default").display()
    ));

    let current = harness.run(&["--json", "current"]);
    assert_failure(&current);
    let error = json_error(&current);
    assert_eq!(error["code"], "invalid_config");
    assert!(error["message"]
        .as_str()
        .expect("json string")
        .contains("default.default_namespace"));
}

#[test]
fn embedded_namespace_commands_reject_invalid_namespace_ids() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");

    let create = harness.run(&["--json", "namespace", "create", "bad/name"]);
    assert_failure(&create);
    assert_eq!(json_error(&create)["code"], "invalid_request");
    assert!(json_error(&create)["message"]
        .as_str()
        .expect("json string")
        .contains("invalid namespace_id"));

    assert_success(&harness.run(&["namespace", "create", "demo"]));
    let fork = harness.run(&["--json", "namespace", "fork", "demo", "bad/name"]);
    assert_failure(&fork);
    assert_eq!(json_error(&fork)["code"], "invalid_request");

    let use_namespace = harness.run(&["--json", "use", "bad/name"]);
    assert_failure(&use_namespace);
    assert_eq!(json_error(&use_namespace)["code"], "invalid_request");
}

#[test]
fn remote_namespace_commands_reject_invalid_namespace_ids_before_http() {
    let harness = Harness::new();
    let add_remote = harness.run(&[
        "--json",
        "profile",
        "create",
        "default",
        "--mode",
        "remote",
        "--server-url",
        "http://127.0.0.1:9",
    ]);
    assert_success(&add_remote);

    let create = harness.run(&["--json", "namespace", "create", "bad/name"]);
    assert_failure(&create);
    assert_eq!(json_error(&create)["code"], "invalid_request");

    let fork = harness.run(&["--json", "namespace", "fork", "demo", "bad/name"]);
    assert_failure(&fork);
    assert_eq!(json_error(&fork)["code"], "invalid_request");

    let use_namespace = harness.run(&["--json", "use", "bad/name"]);
    assert_failure(&use_namespace);
    assert_eq!(json_error(&use_namespace)["code"], "invalid_request");
}

#[test]
fn invalid_remote_urls_are_rejected() {
    let harness = Harness::new();

    let missing_host_http = harness.run(&[
        "--json",
        "profile",
        "create",
        "default",
        "--mode",
        "remote",
        "--server-url",
        "http://",
    ]);
    assert_failure(&missing_host_http);
    assert_eq!(json_error(&missing_host_http)["code"], "invalid_config");
    assert!(json_error(&missing_host_http)["message"]
        .as_str()
        .expect("json string")
        .contains("default.server_url"));

    let missing_host_https = harness.run(&[
        "--json",
        "profile",
        "create",
        "default",
        "--mode",
        "remote",
        "--server-url",
        "https://",
    ]);
    assert_failure(&missing_host_https);
    assert_eq!(json_error(&missing_host_https)["code"], "invalid_config");
}

#[test]
fn external_remote_profile_executes_through_http() {
    let harness = Harness::new();
    let remote_server =
        harness.start_external_server(harness.write_server_config("remote", "remote-exec"));
    let add_remote = harness.run(&[
        "--json",
        "profile",
        "create",
        "default",
        "--mode",
        "remote",
        "--server-url",
        &remote_server.server_url,
        "--auth-token",
        "test-token",
    ]);
    assert_success(&add_remote);

    let create = harness.run(&["--json", "namespace", "create", "demo"]);
    assert_success(&create);
    let fork = harness.run(&["--json", "namespace", "fork", "demo", "clone"]);
    assert_success(&fork);
    assert_eq!(json_data(&fork)["namespace_id"], "clone");

    let use_namespace = harness.run(&["--json", "use", "demo"]);
    assert_success(&use_namespace);

    let use_clone = harness.run(&["--json", "use", "clone"]);
    assert_success(&use_clone);
    assert_eq!(json_data(&use_clone)["namespace"], "clone");
}

/// Embedded and remote profiles must report the same `code` for the same
/// failure: registry codes pass through verbatim in both modes instead of
/// being rewritten to CLI-local codes on one side.
#[test]
fn embedded_and_remote_profiles_emit_the_same_error_codes() {
    let harness = Harness::new();
    harness.add_embedded_profile("embedded");
    let remote_server =
        harness.start_external_server(harness.write_server_config("remote", "error-parity"));
    let add_remote = harness.run(&[
        "--json",
        "profile",
        "create",
        "remote",
        "--mode",
        "remote",
        "--server-url",
        &remote_server.server_url,
        "--auth-token",
        "test-token",
    ]);
    assert_success(&add_remote);

    for profile in ["embedded", "remote"] {
        assert_success(&harness.run(&["namespace", "create", "--profile", profile, "demo"]));
    }

    // Creating a namespace that already exists.
    let embedded = harness.run(&[
        "--json",
        "namespace",
        "create",
        "--profile",
        "embedded",
        "demo",
    ]);
    let remote = harness.run(&[
        "--json",
        "namespace",
        "create",
        "--profile",
        "remote",
        "demo",
    ]);
    assert_failure(&embedded);
    assert_failure(&remote);
    assert_eq!(json_error(&embedded)["code"], "namespace_exists");
    assert_eq!(json_error(&embedded)["code"], json_error(&remote)["code"]);

    // A malformed namespace id.
    let embedded = harness.run(&[
        "--json",
        "namespace",
        "create",
        "--profile",
        "embedded",
        "bad/name",
    ]);
    let remote = harness.run(&[
        "--json",
        "namespace",
        "create",
        "--profile",
        "remote",
        "bad/name",
    ]);
    assert_failure(&embedded);
    assert_failure(&remote);
    assert_eq!(json_error(&embedded)["code"], "invalid_request");
    assert_eq!(json_error(&embedded)["code"], json_error(&remote)["code"]);
}

#[test]
fn filesystem_requires_default_namespace_when_omitted() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");

    let output = harness.run(&["--json", "ls", "/"]);
    assert_failure(&output);
    let error = json_error(&output);
    assert_eq!(error["code"], "no_default_namespace");
}

#[test]
fn embedded_profile_missing_namespace_reports_user_facing_message() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");

    let output = harness.run(&["--json", "ls", "--namespace", "missing", "/"]);
    assert_failure(&output);
    let error = json_error(&output);
    assert_eq!(error["code"], "namespace_not_found");
    assert_eq!(error["message"], "namespace `missing` does not exist");
}

#[test]
fn remote_profile_missing_namespace_reports_user_facing_message() {
    let harness = Harness::new();
    let remote_server =
        harness.start_external_server(harness.write_server_config("remote", "remote-missing-ns"));
    let add_remote = harness.run(&[
        "--json",
        "profile",
        "create",
        "default",
        "--mode",
        "remote",
        "--server-url",
        &remote_server.server_url,
        "--auth-token",
        "test-token",
    ]);
    assert_success(&add_remote);

    let output = harness.run(&["--json", "ls", "--namespace", "missing", "/"]);
    assert_failure(&output);
    let error = json_error(&output);
    assert_eq!(error["code"], "namespace_not_found");
    assert_eq!(error["message"], "namespace `missing` does not exist");
}

#[test]
fn current_reports_profile_specific_namespace() {
    let harness = Harness::new();
    harness.add_embedded_profile("alpha");
    harness.add_embedded_profile("beta");

    assert_success(&harness.run(&["namespace", "create", "--profile", "alpha", "alpha-ns"]));
    assert_success(&harness.run(&["use", "--profile", "alpha", "alpha-ns"]));
    assert_success(&harness.run(&["namespace", "create", "--profile", "beta", "beta-ns"]));
    assert_success(&harness.run(&["use", "--profile", "beta", "beta-ns"]));
    assert_success(&harness.run(&["profile", "use", "beta"]));

    let current_default = harness.run(&["--json", "current"]);
    assert_success(&current_default);
    assert_eq!(json_data(&current_default)["profile"], "beta");
    assert_eq!(json_data(&current_default)["namespace"], "beta-ns");

    let current_alpha = harness.run(&["--json", "current", "--profile", "alpha"]);
    assert_success(&current_alpha);
    assert_eq!(json_data(&current_alpha)["profile"], "alpha");
    assert_eq!(json_data(&current_alpha)["namespace"], "alpha-ns");
}

#[test]
fn current_does_not_require_backend_resolution() {
    let harness = Harness::new();
    harness.write_cli_config(format!(
        r#"config_version = 1
default_profile = "broken"

[profiles.broken]
mode = "embedded"
default_namespace = "demo"

[profiles.broken.store]
kind = "local-fs"
root = "{}"
key_prefix = "../bad"
"#,
        harness.store_root("broken").display()
    ));

    let current = harness.run(&["--json", "current"]);
    assert_success(&current);
    assert_eq!(json_data(&current)["profile"], "broken");
    assert_eq!(json_data(&current)["namespace"], "demo");
}

#[test]
fn rm_reports_the_inode_and_undelete_recovers_it() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let payload_one = harness.temp_dir.path().join("one.txt");
    let payload_two = harness.temp_dir.path().join("two.txt");
    fs::write(&payload_one, b"draft one").expect("payload one");
    fs::write(&payload_two, b"draft two").expect("payload two");
    assert_success(&harness.run(&[
        "put",
        payload_one.to_str().expect("utf-8 path"),
        "/docs/report.txt",
    ]));
    assert_success(&harness.run(&[
        "put",
        payload_two.to_str().expect("utf-8 path"),
        "/docs/report.txt",
        "--force",
    ]));

    // rm reports the inode id and the deletion's sequence — together the
    // recovery handle undelete needs.
    let removed = harness.run(&["--json", "rm", "/docs/report.txt"]);
    assert_success(&removed);
    let inode_id = json_data(&removed)["inode_id"]
        .as_u64()
        .expect("rm reports the deleted inode id");
    let deleted_at = json_data(&removed)["committed_seq"]
        .as_u64()
        .expect("rm reports the deletion sequence");
    let gone = harness.run(&["--json", "revisions", "/docs/report.txt"]);
    assert_failure(&gone);
    assert_eq!(json_error(&gone)["code"], "path_not_found");

    // Undelete brings back identity, content, and revision history.
    let recovered = harness.run(&[
        "--json",
        "undelete",
        "/docs/report.txt",
        "--inode",
        &inode_id.to_string(),
        "--deleted-at",
        &deleted_at.to_string(),
    ]);
    assert_success(&recovered);
    assert_eq!(json_data(&recovered)["target"], "demo:/docs/report.txt");
    let cat = harness.run(&["cat", "/docs/report.txt"]);
    assert_success(&cat);
    assert_eq!(cat.stdout, b"draft two");
    let revisions = harness.run(&["--json", "revisions", "/docs/report.txt"]);
    assert_success(&revisions);
    assert_eq!(
        json_data(&revisions)["revisions"]
            .as_array()
            .expect("json array")
            .len(),
        2
    );

    // A recovered inode is no longer deleted; the stale handle conflicts.
    let again = harness.run(&[
        "--json",
        "undelete",
        "/docs/report-copy.txt",
        "--inode",
        &inode_id.to_string(),
        "--deleted-at",
        &deleted_at.to_string(),
    ]);
    assert_failure(&again);
    assert_eq!(json_error(&again)["code"], "not_deleted");
}

/// A pathless undelete restores in place: it re-binds under the parent
/// inode and name the deletion recorded. Renaming the parent between the
/// delete and the recovery is the proof that the anchor is identity, not a
/// remembered path — the entry comes back inside the parent's new name.
#[test]
fn an_undelete_without_a_path_restores_in_place() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let payload = harness.temp_dir.path().join("report.txt");
    fs::write(&payload, b"quarterly numbers").expect("payload");
    assert_success(&harness.run(&[
        "put",
        payload.to_str().expect("utf-8 path"),
        "/docs/report.txt",
    ]));

    let removed = harness.run(&["rm", "/docs/report.txt"]);
    assert_success(&removed);
    // The printed recovery command names no destination: in place needs
    // none.
    let recovery = hinted_recovery_command(&removed);
    assert!(
        recovery.starts_with("loonfs undelete --inode "),
        "{recovery}"
    );
    let trash = harness.run(&["--json", "trash"]);
    assert_success(&trash);
    let entry = json_data(&trash)["entries"][0].clone();
    let inode_id = entry["root_inode_id"]
        .as_u64()
        .expect("trash reports the deleted inode id");
    let deleted_at = entry["deleted_at_seq"]
        .as_u64()
        .expect("trash reports the deletion sequence");

    // The parent moves on while the file sits in the trash.
    assert_success(&harness.run(&["mv", "/docs", "/archive"]));

    let recovered = harness.run(&[
        "--json",
        "undelete",
        "--inode",
        &inode_id.to_string(),
        "--deleted-at",
        &deleted_at.to_string(),
    ]);
    assert_success(&recovered);
    assert_eq!(json_data(&recovered)["target"], "demo:(restored in place)");
    let cat = harness.run(&["cat", "/archive/report.txt"]);
    assert_success(&cat);
    assert_eq!(cat.stdout, b"quarterly numbers");

    // The trash listing offers the same pathless command.
    fs::write(&payload, b"second life").expect("payload");
    assert_success(&harness.run(&[
        "put",
        payload.to_str().expect("utf-8 path"),
        "/archive/notes.txt",
    ]));
    assert_success(&harness.run(&["rm", "/archive/notes.txt"]));
    let listed = harness.run(&["trash"]);
    assert_success(&listed);
    assert!(
        trash_recovery_command(&listed, "notes.txt").starts_with("loonfs undelete --inode "),
        "trash offers a pathless in-place command"
    );

    // A stale pathless handle answers the same code a pathed one does.
    let stale = harness.run(&[
        "--json",
        "undelete",
        "--inode",
        &inode_id.to_string(),
        "--deleted-at",
        &deleted_at.to_string(),
    ]);
    assert_failure(&stale);
    assert_eq!(json_error(&stale)["code"], "not_deleted");
}

#[test]
fn remote_undelete_recovers_through_http() {
    let harness = Harness::new();
    let remote_server =
        harness.start_external_server(harness.write_server_config("remote", "remote-undelete"));
    assert_success(&harness.run(&[
        "--json",
        "profile",
        "create",
        "default",
        "--mode",
        "remote",
        "--server-url",
        &remote_server.server_url,
        "--auth-token",
        "test-token",
    ]));
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let payload = harness.temp_dir.path().join("wire.txt");
    fs::write(&payload, b"over the wire").expect("payload");
    assert_success(&harness.run(&["put", payload.to_str().expect("utf-8 path"), "/wire.txt"]));
    let removed = harness.run(&["--json", "rm", "/wire.txt"]);
    assert_success(&removed);
    let inode_id = json_data(&removed)["inode_id"]
        .as_u64()
        .expect("rm reports the deleted inode id");
    let deleted_at = json_data(&removed)["committed_seq"]
        .as_u64()
        .expect("rm reports the deletion sequence");

    // The hint is built from the invocation, not the backend, so a remote
    // profile prints the same command an embedded one would.
    let listed = harness.run(&["trash"]);
    assert_success(&listed);
    assert_eq!(
        trash_recovery_command(&listed, "wire.txt"),
        format!(
            "loonfs undelete --inode {inode_id} \
             --deleted-at {deleted_at} --namespace demo"
        )
    );

    let recovered = harness.run(&[
        "--json",
        "undelete",
        "/wire.txt",
        "--inode",
        &inode_id.to_string(),
        "--deleted-at",
        &deleted_at.to_string(),
    ]);
    assert_success(&recovered);
    let cat = harness.run(&["cat", "/wire.txt"]);
    assert_success(&cat);
    assert_eq!(cat.stdout, b"over the wire");
}

#[test]
fn mkdir_parents_get_noclobber_and_version_metadata() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    // mkdir still requires the parent by default; -p creates the chain.
    let missing_parent = harness.run(&["--json", "mkdir", "/a/b/c"]);
    assert_failure(&missing_parent);
    assert_eq!(json_error(&missing_parent)["code"], "path_not_found");
    let with_parents = harness.run(&["--json", "mkdir", "-p", "/a/b/c"]);
    assert_success(&with_parents);
    assert_eq!(json_data(&with_parents)["target"], "demo:/a/b/c");
    let created_ancestor = harness.run(&["--json", "stat", "/a/b"]);
    assert_success(&created_ancestor);
    assert_eq!(json_data(&created_ancestor)["inode_kind"], "dir");

    // get refuses to clobber a local file unless forced.
    let payload = harness.temp_dir.path().join("f.txt");
    fs::write(&payload, b"remote bytes").expect("payload");
    assert_success(&harness.run(&["put", payload.to_str().expect("utf-8 path"), "/f.txt"]));
    let dest = harness.temp_dir.path().join("dest.txt");
    fs::write(&dest, b"precious local bytes").expect("existing local file");
    let refused = harness.run(&[
        "--json",
        "get",
        "/f.txt",
        dest.to_str().expect("utf-8 path"),
    ]);
    assert_failure(&refused);
    assert_eq!(json_error(&refused)["code"], "destination_exists");
    assert_eq!(fs::read(&dest).expect("unchanged"), b"precious local bytes");
    let forced = harness.run(&[
        "--json",
        "get",
        "/f.txt",
        dest.to_str().expect("utf-8 path"),
        "--force",
    ]);
    assert_success(&forced);
    assert_eq!(fs::read(&dest).expect("replaced"), b"remote bytes");

    // --version is a real flag now, and both forms carry build metadata.
    assert_success(&harness.run(&["--version"]));
    let version = harness.run(&["--json", "version"]);
    assert_success(&version);
    let data = json_data(&version);
    assert!(!data["commit"].as_str().expect("commit").is_empty());
    assert!(!data["commit_date"]
        .as_str()
        .expect("commit date")
        .is_empty());
}

#[test]
fn namespace_delete_without_yes_fails_cleanly_when_not_interactive() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));

    // Piped stdin (no terminal): the command names the requirement instead
    // of surfacing the prompt machinery's i/o error.
    let refused = harness.run(&["--json", "namespace", "delete", "demo"]);
    assert_failure(&refused);
    assert_eq!(
        json_error(&refused)["code"],
        "non_interactive_input_required"
    );

    let deleted = harness.run(&["--json", "namespace", "delete", "demo", "--yes"]);
    assert_success(&deleted);
}

/// A refused precondition has to say what it wanted and what it found, or
/// the caller cannot tell a raced delete from a mistyped sequence.
#[test]
fn namespace_delete_reports_both_head_sequences_when_the_precondition_fails() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let payload = harness.temp_dir.path().join("doc.txt");
    fs::write(&payload, b"body").expect("write payload");
    assert_success(&harness.run(&["put", payload.to_str().expect("utf-8 path"), "/doc.txt"]));

    let stale = harness.run(&[
        "--json",
        "namespace",
        "delete",
        "demo",
        "--yes",
        "--expected-head-seq",
        "0",
    ]);
    assert_failure(&stale);
    let error = json_error(&stale);
    assert_eq!(error["code"], "stale_head");
    assert_eq!(error["message"], "expected head sequence 0, found 1");

    // The same sentence is what a human run prints, since the renderer
    // writes the message through unchanged.
    let human = harness.run(&[
        "namespace",
        "delete",
        "demo",
        "--yes",
        "--expected-head-seq",
        "0",
    ]);
    assert_failure(&human);
    assert_eq!(
        stderr_string(&human).trim_end(),
        "expected head sequence 0, found 1"
    );

    // Refusing deleted nothing, so the namespace is still readable.
    assert_success(&harness.run(&["--json", "ls", "/"]));
}

#[test]
fn admin_gc_reclaims_a_deleted_namespace_instead_of_refusing() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let payload = harness.temp_dir.path().join("payload.txt");
    fs::write(&payload, b"body").expect("write payload");
    assert_success(&harness.run(&["put", payload.to_str().expect("utf-8 path"), "/doc.txt"]));
    // Materialize derived state so the tombstone has something reclaimable.
    assert_success(&harness.run(&["admin", "flush"]));
    assert_success(&harness.run(&["--json", "namespace", "delete", "demo", "--yes"]));

    // GC is the reclamation path for a tombstoned namespace: it must run
    // and report, not refuse. (Fresh objects sit inside the grace window,
    // so this pins reachability, not byte counts.)
    let gc = harness.run(&["--json", "admin", "gc"]);
    assert_success(&gc);
    assert_eq!(json_data(&gc)["kind"], "garbage_collected");

    // Everything that is not the GC-only step still reports the deletion.
    let step = harness.run(&["--json", "admin", "step"]);
    assert_failure(&step);
    assert_eq!(json_error(&step)["code"], "namespace_deleted");
    let recreate = harness.run(&["--json", "namespace", "create", "demo"]);
    assert_failure(&recreate);
    assert_eq!(json_error(&recreate)["code"], "namespace_deleted");
}

#[test]
fn embedded_grep_works_after_index_enable() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "code"]));
    assert_success(&harness.run(&["use", "code"]));

    let payload = harness.temp_dir.path().join("main.rs");
    fs::write(&payload, b"fn main() {}\n// TODO: expand\n").expect("write payload");
    assert_success(&harness.run(&["put", payload.to_str().expect("utf-8 path"), "/src/main.rs"]));

    // Before the index exists, grep names the missing feature.
    let before = harness.run(&["--json", "grep", "TODO"]);
    assert_failure(&before);
    assert_eq!(json_error(&before)["code"], "not_supported");

    // Enable waits for the backfill in-process: the one-shot CLI is its own
    // grep maintenance, so the query works immediately — no server, no
    // driver, no state that never resolves.
    let enabled = harness.run(&["--json", "admin", "index-enable"]);
    assert_success(&enabled);
    assert_eq!(json_data(&enabled)["state"]["phase"], "steady");
    assert_eq!(json_data(&enabled)["waited_for_seq"], 1);
    assert_eq!(json_data(&enabled)["budget_exhausted"], false);
    let found = harness.run(&["--json", "grep", "TODO"]);
    assert_success(&found);
    assert_eq!(
        json_data(&found)["matches"]
            .as_array()
            .expect("json array")
            .len(),
        1
    );

    // Later writes catch up when enable is re-run.
    let more = harness.temp_dir.path().join("lib.rs");
    fs::write(&more, b"// TODO: also here\n").expect("write payload");
    assert_success(&harness.run(&["put", more.to_str().expect("utf-8 path"), "/src/lib.rs"]));
    let recaught = harness.run(&["--json", "admin", "index-enable"]);
    assert_success(&recaught);
    assert_eq!(json_data(&recaught)["already_enabled"], true);
    let found = harness.run(&["--json", "grep", "TODO"]);
    assert_success(&found);
    assert_eq!(
        json_data(&found)["matches"]
            .as_array()
            .expect("json array")
            .len(),
        2
    );
}

/// `--max-matches` caps the whole search, which `--limit` cannot: `--limit`
/// sizes one page and the deployment rejects a page larger than its own
/// maximum.
#[test]
fn grep_max_matches_caps_the_search_while_limit_sizes_a_page() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "code"]));
    assert_success(&harness.run(&["use", "code"]));

    let payload = harness.temp_dir.path().join("notes.txt");
    fs::write(&payload, b"TODO one\nTODO two\nTODO three\nTODO four\n").expect("write payload");
    assert_success(&harness.run(&["put", payload.to_str().expect("utf-8 path"), "/notes.txt"]));
    assert_success(&harness.run(&["--json", "admin", "index-enable"]));

    let all = harness.run(&["--json", "grep", "TODO"]);
    assert_success(&all);
    let all_data = json_data(&all);
    assert_eq!(all_data["matches"].as_array().expect("json array").len(), 4);
    assert_eq!(all_data["truncated"], false);

    let capped = harness.run(&["--json", "grep", "TODO", "--max-matches", "2"]);
    assert_success(&capped);
    let capped_data = json_data(&capped);
    assert_eq!(
        capped_data["matches"].as_array().expect("json array").len(),
        2
    );
    assert_eq!(capped_data["truncated"], true);

    // A cap the search never reaches is not a truncation.
    let roomy = harness.run(&["--json", "grep", "TODO", "--max-matches", "99"]);
    assert_success(&roomy);
    assert_eq!(
        json_data(&roomy)["matches"]
            .as_array()
            .expect("json array")
            .len(),
        4
    );
    assert_eq!(json_data(&roomy)["truncated"], false);

    // A small page still returns every match, because it bounds a page and
    // the command follows the cursor.
    let paged = harness.run(&["--json", "grep", "TODO", "--limit", "1"]);
    assert_success(&paged);
    assert_eq!(
        json_data(&paged)["matches"]
            .as_array()
            .expect("json array")
            .len(),
        4
    );
    assert_eq!(json_data(&paged)["truncated"], false);

    // The two compose: pages of one, stopped after three.
    let both = harness.run(&[
        "--json",
        "grep",
        "TODO",
        "--limit",
        "1",
        "--max-matches",
        "3",
    ]);
    assert_success(&both);
    assert_eq!(
        json_data(&both)["matches"]
            .as_array()
            .expect("json array")
            .len(),
        3
    );
    assert_eq!(json_data(&both)["truncated"], true);

    // The human rendering says it stopped early.
    let human = harness.run(&["grep", "TODO", "--max-matches", "2"]);
    assert_success(&human);
    assert!(stdout_string(&human).contains("--max-matches"));
}

#[test]
fn index_enable_leaves_core_maintenance_decoupled() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let enabled = harness.run(&["--json", "admin", "index-enable"]);
    assert_success(&enabled);
    assert!(json_data(&enabled).get("backfill_step").is_none());

    let retried = harness.run(&["--json", "admin", "index-enable"]);
    assert_success(&retried);
    assert_eq!(json_data(&retried)["already_enabled"], true);
    assert!(json_data(&retried).get("backfill_step").is_none());
}

/// The index reports the phase it is in, and the phases do not share a
/// field: a backfill names its target, a steady index names its watermark.
#[test]
fn index_status_reports_each_phase_in_its_own_terms() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let disabled = harness.run(&["--json", "admin", "index-status"]);
    assert_success(&disabled);
    assert_eq!(json_data(&disabled)["state"]["phase"], "disabled");
    assert!(json_data(&disabled)["state"]
        .get("built_through_seq")
        .is_none());

    // `--no-wait` returns with the root the enable published: a backfill,
    // naming the sequence it will walk to and nothing it has indexed.
    let enabled = harness.run(&["--json", "admin", "index-enable", "--no-wait"]);
    assert_success(&enabled);
    let state = &json_data(&enabled)["state"];
    assert_eq!(state["phase"], "backfilling");
    assert_eq!(state["target_seq"], 0);
    assert!(state.get("built_through_seq").is_none());
    assert!(json_data(&enabled).get("waited_for_seq").is_none());
    assert_eq!(json_data(&enabled)["steps"], 0);

    let backfilling = harness.run(&["--json", "admin", "index-status"]);
    assert_success(&backfilling);
    assert_eq!(json_data(&backfilling)["state"]["phase"], "backfilling");
    assert_eq!(json_data(&backfilling)["reorganize_pending"], false);
    assert!(backfilling_text_names_no_watermark(&harness));

    // Waiting takes it steady, and only then is there a watermark.
    assert_success(&harness.run(&["admin", "index-enable"]));
    let steady = harness.run(&["--json", "admin", "index-status"]);
    assert_success(&steady);
    assert_eq!(json_data(&steady)["state"]["phase"], "steady");
    assert_eq!(json_data(&steady)["state"]["built_through_seq"], 0);
    assert!(json_data(&steady)["state"].get("target_seq").is_none());
}

fn backfilling_text_names_no_watermark(harness: &Harness) -> bool {
    let rendered = stdout_string(&harness.run(&["admin", "index-status"]));
    rendered.contains("backfilling toward seq") && !rendered.contains("built through")
}

/// The wait stops at the sequence it captured, even while a writer keeps
/// committing past it.
#[test]
fn index_enable_waits_to_its_captured_target_and_not_the_live_head() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));
    let payload = harness.temp_dir.path().join("one.txt");
    fs::write(&payload, b"needle one\n").expect("write payload");
    assert_success(&harness.run(&["put", payload.to_str().expect("utf-8 path"), "/one.txt"]));

    let enabled = harness.run(&["--json", "admin", "index-enable"]);
    assert_success(&enabled);
    assert_eq!(json_data(&enabled)["waited_for_seq"], 1);

    // A commit that lands after the capture is not waited for: the next
    // enable is what picks it up.
    let more = harness.temp_dir.path().join("two.txt");
    fs::write(&more, b"needle two\n").expect("write payload");
    assert_success(&harness.run(&["put", more.to_str().expect("utf-8 path"), "/two.txt"]));
    let status = harness.run(&["--json", "admin", "index-status"]);
    assert_success(&status);
    assert_eq!(
        json_data(&status)["state"]["built_through_seq"],
        1,
        "the earlier wait stopped at the target it captured"
    );

    // An index already at the namespace head returns without stepping.
    assert_success(&harness.run(&["admin", "index-enable"]));
    let caught_up = harness.run(&["--json", "admin", "index-enable"]);
    assert_success(&caught_up);
    assert_eq!(json_data(&caught_up)["already_enabled"], true);
    assert_eq!(json_data(&caught_up)["waited_for_seq"], 2);
    assert_eq!(
        json_data(&caught_up)["steps"],
        0,
        "an index already at the captured target takes no steps"
    );
}

/// A wait that runs out of budget reports where the index got to and exits
/// nonzero — real progress, not an error-shaped lie.
#[test]
fn index_enable_budgets_exit_nonzero_and_report_progress() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));
    let payload = harness.temp_dir.path().join("one.txt");
    fs::write(&payload, b"needle\n").expect("write payload");
    assert_success(&harness.run(&["put", payload.to_str().expect("utf-8 path"), "/one.txt"]));

    for budget in [vec!["--max-steps", "0"], vec!["--deadline-ms", "0"]] {
        let mut args = vec!["--json", "admin", "index-enable"];
        args.extend(budget.iter().copied());
        let stopped = harness.run(&args);
        assert_failure(&stopped);
        let data = json_data(&stopped);
        assert_eq!(data["budget_exhausted"], true, "{budget:?}");
        assert_eq!(data["steps"], 0, "{budget:?}");
        assert_eq!(data["waited_for_seq"], 1, "{budget:?}");
        assert_eq!(
            data["state"]["phase"], "backfilling",
            "the report must say where the index actually is: {budget:?}"
        );
    }

    // The index is untouched by the give-up, and a plain wait still lands.
    assert_success(&harness.run(&["admin", "index-enable"]));
    let found = harness.run(&["--json", "grep", "needle"]);
    assert_success(&found);
}

/// The remote arm answers the same questions the embedded one does, and
/// waits the same way: the server drives its own index, so the command only
/// watches the status endpoint until the captured target is reached.
#[test]
fn index_status_and_enable_answer_the_same_over_the_remote_transport() {
    let harness = Harness::new();
    // A config with no `[grep]` table composes no grep at all, so this
    // deployment says so explicitly.
    let remote_server = harness.start_external_server(harness.write_server_config_with(
        "remote",
        "index-remote",
        "\n[grep]\nmode = \"serve_and_maintain\"\n",
    ));
    assert_success(&harness.run(&[
        "--json",
        "profile",
        "create",
        "default",
        "--mode",
        "remote",
        "--server-url",
        &remote_server.server_url,
        "--auth-token",
        "test-token",
    ]));
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));
    let payload = harness.temp_dir.path().join("one.txt");
    fs::write(&payload, b"remote needle\n").expect("write payload");
    assert_success(&harness.run(&["put", payload.to_str().expect("utf-8 path"), "/one.txt"]));

    let disabled = harness.run(&["--json", "admin", "index-status"]);
    assert_success(&disabled);
    assert_eq!(json_data(&disabled)["state"]["phase"], "disabled");

    let enabled = harness.run(&["--json", "admin", "index-enable"]);
    assert_success(&enabled);
    assert_eq!(json_data(&enabled)["waited_for_seq"], 1);
    assert_eq!(json_data(&enabled)["budget_exhausted"], false);
    assert_eq!(json_data(&enabled)["state"]["phase"], "steady");

    let steady = harness.run(&["--json", "admin", "index-status"]);
    assert_success(&steady);
    assert_eq!(json_data(&steady)["state"]["built_through_seq"], 1);

    let found = harness.run(&["--json", "grep", "remote needle"]);
    assert_success(&found);
    assert_eq!(
        json_data(&found)["matches"]
            .as_array()
            .expect("json array")
            .len(),
        1
    );

    let collected = harness.run(&["--json", "admin", "index-gc"]);
    assert_success(&collected);
    assert_eq!(json_data(&collected)["namespace_reaped"], false);
}

/// `index-gc` loops the cursor like `admin gc`: one accumulated result out
/// of however many bounded passes it took.
#[test]
fn index_gc_loops_its_cursor_and_accumulates() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));
    let payload = harness.temp_dir.path().join("one.txt");
    fs::write(&payload, b"needle\n").expect("write payload");
    assert_success(&harness.run(&["put", payload.to_str().expect("utf-8 path"), "/one.txt"]));
    assert_success(&harness.run(&["admin", "index-enable"]));

    // Nothing here is past its grace window, so a full loop retains what it
    // examines and, having walked to the end, carries no resume cursor.
    let collected = harness.run(&["--json", "admin", "index-gc"]);
    assert_success(&collected);
    let data = json_data(&collected);
    assert_eq!(data["deleted_segments"], 0);
    assert_eq!(data["namespace_reaped"], false);
    assert!(data.get("next_cursor").is_none(), "{data}");

    // One bounded pass stops early and hands back where to resume.
    let single = harness.run(&["--json", "admin", "index-gc", "--max-objects", "1"]);
    assert_success(&single);
    assert!(
        json_data(&single)["next_cursor"].is_string(),
        "{}",
        json_data(&single)
    );
}

/// `admin run --drain` is the assigned host's catch-up: every
/// `{job, namespace}` key it was given reaches a settled conclusion, it
/// exits zero, and the work it did is in durable state rather than in its
/// output.
#[test]
fn admin_run_drains_an_assignment_and_leaves_the_work_done() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    for namespace in ["alpha", "beta"] {
        assert_success(&harness.run(&["namespace", "create", namespace]));
        let payload = harness.temp_dir.path().join(format!("{namespace}.txt"));
        fs::write(&payload, b"assigned needle\n").expect("write payload");
        assert_success(&harness.run(&[
            "put",
            "--namespace",
            namespace,
            payload.to_str().expect("utf-8 path"),
            "/note.txt",
        ]));
        // Enabled and deliberately left behind: catching it up is what the
        // assignment is for.
        assert_success(&harness.run(&[
            "admin",
            "index-enable",
            "--namespace",
            namespace,
            "--no-wait",
        ]));
    }

    let drained = harness.run(&[
        "--json",
        "admin",
        "run",
        "--namespace",
        "alpha",
        "--namespace",
        "beta",
        "--drain",
    ]);
    assert_success(&drained);
    let data = json_data(&drained);
    assert_eq!(data["drained"], true);
    assert_eq!(data["budget_exhausted"], false);
    let keys = data["keys"].as_array().expect("json array");
    assert_eq!(keys.len(), 8, "four jobs over two namespaces: {data}");
    assert!(
        keys.iter().all(|key| key["settled"] == true),
        "an unbudgeted drain settles every key: {data}"
    );
    assert_eq!(
        data["jobs"],
        serde_json::json!(["metadata", "gc", "grep-index", "grep-gc"])
    );

    for namespace in ["alpha", "beta"] {
        let status = harness.run(&["--json", "admin", "index-status", "--namespace", namespace]);
        assert_success(&status);
        assert_eq!(
            json_data(&status)["state"]["built_through_seq"],
            1,
            "the assigned index must reach the head it was behind: {namespace}"
        );
    }
}

/// A drain that runs out of budget reports where every key got to — the one
/// it stopped inside and the ones it never reached — and exits nonzero.
#[test]
fn admin_run_budgets_exit_nonzero_and_report_per_key_progress() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "alpha"]));

    let unstarted = harness.run(&[
        "--json",
        "admin",
        "run",
        "--namespace",
        "alpha",
        "--drain",
        "--max-steps",
        "0",
    ]);
    assert_failure(&unstarted);
    let data = json_data(&unstarted);
    assert_eq!(data["budget_exhausted"], true);
    assert_eq!(data["steps"], 0);
    for key in data["keys"].as_array().expect("json array") {
        assert_eq!(key["settled"], false, "{data}");
        assert_eq!(key["steps"], 0, "{data}");
        assert!(key.get("conclusion").is_none(), "{data}");
    }

    // One step is enough for the first key on a quiet namespace and reaches
    // no other, which is exactly what the report has to say.
    let partial = harness.run(&[
        "admin",
        "run",
        "--namespace",
        "alpha",
        "--drain",
        "--max-steps",
        "1",
    ]);
    assert_failure(&partial);
    let rendered = stdout_string(&partial);
    assert!(
        rendered.contains("alpha/metadata: idle after 1 step"),
        "{rendered}"
    );
    assert!(
        rendered.contains("alpha/gc: not started; the budget ran out first"),
        "{rendered}"
    );
    assert!(rendered.contains("gave up"), "{rendered}");
}

/// The assignment is explicit and the job names are a closed set: neither is
/// something the command guesses at.
#[test]
fn admin_run_requires_an_assignment_and_names_the_jobs_it_hosts() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");

    let unassigned = harness.run(&["admin", "run"]);
    assert_failure(&unassigned);
    assert!(
        stderr_string(&unassigned).contains("--namespace"),
        "{}",
        stderr_string(&unassigned)
    );

    let unknown_job = harness.run(&["admin", "run", "--namespace", "alpha", "--job", "bogus"]);
    assert_failure(&unknown_job);
    let message = stderr_string(&unknown_job);
    for job in ["metadata", "core-gc", "grep-index", "grep-gc"] {
        assert!(
            message.contains(job),
            "the valid set must be listed: {message}"
        );
    }
}

/// The re-assertion cadence is the one timer a hosted run owns, so an
/// operator may shorten it — down to a floor, below which a nudge per
/// assigned key only spends provider requests. A drain never rests between
/// keys, so the flag is inert there.
#[test]
fn admin_run_takes_a_poll_interval_with_a_floor_that_a_drain_ignores() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    for namespace in ["alpha", "beta"] {
        assert_success(&harness.run(&["namespace", "create", namespace]));
    }

    let too_fast = harness.run(&[
        "admin",
        "run",
        "--namespace",
        "alpha",
        "--poll-interval-ms",
        "99",
    ]);
    assert_failure(&too_fast);
    let message = stderr_string(&too_fast);
    assert!(
        message.contains("poll-interval-ms"),
        "the rejection must name the flag: {message}"
    );
    assert!(
        message.contains("100"),
        "the rejection must name the floor: {message}"
    );

    let plain = harness.run(&["--json", "admin", "run", "--namespace", "alpha", "--drain"]);
    assert_success(&plain);
    let paced = harness.run(&[
        "--json",
        "admin",
        "run",
        "--namespace",
        "beta",
        "--drain",
        "--poll-interval-ms",
        "100",
    ]);
    assert_success(&paced);
    let (plain, paced) = (json_data(&plain), json_data(&paced));
    for field in ["drained", "budget_exhausted", "jobs"] {
        assert_eq!(
            paced[field], plain[field],
            "a drain reports the same `{field}` with the cadence flag as without it"
        );
    }
    let keys = paced["keys"].as_array().expect("json array");
    assert_eq!(
        keys.len(),
        plain["keys"].as_array().expect("json array").len()
    );
    assert!(
        keys.iter().all(|key| key["settled"] == true),
        "the drain still settles every key: {paced}"
    );
}

/// The store probe is store-scoped: it needs no namespace, prints one line
/// per check, and exits zero only because every check passed.
#[test]
fn admin_probe_store_reports_every_check_against_the_profile_store() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");

    let probe = harness.run(&["admin", "probe-store"]);
    assert_success(&probe);
    let text = stdout_string(&probe);
    for check in [
        "create_if_absent_enforced",
        "compare_and_swap_rejects_stale",
        "compare_and_swap_missing_object_rejected",
        "overwrite_updates_head_and_body",
        "get_with_metadata_round_trip",
        "visibility_after_write",
        "visibility_after_delete",
        "delete_missing_idempotent",
        "sorted_listing",
        "range_reads",
        "multipart_round_trip",
        "stored_checksum_readback",
        "cleanup_leaves_prefix_empty",
    ] {
        assert!(text.contains(check), "missing `{check}` in: {text}");
    }
    assert!(text.contains("13 checks passed"), "{text}");

    let json = harness.run(&["--json", "admin", "probe-store"]);
    assert_success(&json);
    let data = json_data(&json);
    assert_eq!(data["kind"], "store_probed");
    assert_eq!(data["checks"].as_array().expect("checks array").len(), 13);
    assert_eq!(data["checks"][0]["name"], "create_if_absent_enforced");
    assert_eq!(data["checks"][0]["outcome"], "passed");

    // The probe cleans up after itself, so the store carries no probe keys.
    let probe_runs = harness.store_root("default").join("probe-runs");
    assert!(
        !probe_runs.exists() || fs::read_dir(&probe_runs).is_ok_and(|mut dir| dir.next().is_none()),
        "the probe left objects behind at {}",
        probe_runs.display()
    );
}

/// A remote profile's server hosts its own runner. Stepping one from here
/// would be a second scheduler over the same namespaces, so the command
/// refuses instead of pretending it can.
#[test]
fn admin_run_refuses_a_remote_profile() {
    let harness = Harness::new();
    assert_success(&harness.run(&[
        "--json",
        "profile",
        "create",
        "default",
        "--mode",
        "remote",
        "--server-url",
        "http://127.0.0.1:9",
        "--auth-token",
        "test-token",
    ]));

    let refused = harness.run(&["--json", "admin", "run", "--namespace", "demo", "--drain"]);
    assert_failure(&refused);
    let error = json_error(&refused);
    assert_eq!(error["code"], "not_supported");
    assert!(
        error["message"]
            .as_str()
            .expect("message")
            .contains("embedded profile"),
        "{error}"
    );
}

#[test]
fn help_lists_the_context_commands() {
    let harness = Harness::new();
    let output = Command::new(loon_binary_path())
        .env("HOME", &harness.home_dir)
        .arg("--help")
        .output()
        .expect("run help");
    assert_success(&output);
    let stdout = stdout_string(&output);
    assert!(stdout.contains("current"));
    assert!(stdout.contains("use"));
}

/// Pins the capability registry to the CLI surface: every profile and every
/// feature key advertised by the embedded runtime must map to a CLI command
/// path that exercises it, so no advertised capability is unreachable from
/// this surface.
///
/// When `Fs::capabilities()` (crates/loonfs/src/fs.rs) grows a profile or a
/// feature key, this test fails until the tables below either name the CLI
/// command path that covers the new capability, or record a deliberately
/// deferred CLI gap with a comment (none today).
#[test]
fn every_advertised_capability_maps_to_a_cli_command_path() {
    // Advertised profile -> the CLI command paths exercising that plane.
    const PROFILE_COMMAND_PATHS: &[(&str, &[&[&str]])] = &[
        (
            "core/v0",
            &[
                &["namespace", "create"],
                &["namespace", "delete"],
                &["namespace", "fork"],
                &["use"],
                &["ls"],
                &["stat"],
                &["cat"],
                &["get"],
                &["put"],
                &["mkdir"],
                &["rm"],
                &["mv"],
                &["cp"],
                &["revisions"],
                &["restore"],
                &["changes"],
            ],
        ),
        ("query/v0", &[&["grep"]]),
        (
            "admin/v0",
            &[
                &["admin", "checkpoint"],
                &["admin", "checkpoint-list"],
                &["admin", "checkpoint-release"],
                &["admin", "flush"],
                &["admin", "retention-advance"],
                &["admin", "run"],
                &["admin", "step"],
                &["admin", "gc"],
                &["admin", "probe-store"],
                &["admin", "index-enable"],
                &["admin", "index-disable"],
                &["admin", "index-status"],
                &["admin", "index-gc"],
            ],
        ),
    ];
    // Advertised feature key -> the CLI command path exercising it. Keys are
    // listed whether the embedded build advertises them `true` or `false`;
    // gating is the backend's job, reachability is this surface's job.
    const FEATURE_COMMAND_PATHS: &[(&str, &[&str])] = &[
        ("core.namespaces.create", &["namespace", "create"]),
        ("core.namespaces.delete", &["namespace", "delete"]),
        ("core.namespaces.fork", &["namespace", "fork"]),
        // Both direct transports are modes negotiated inside the same upload
        // staging flow `put` drives; neither needs a separate verb.
        ("core.uploads.direct_put", &["put"]),
        ("core.uploads.direct_multipart", &["put"]),
        // The read half is negotiated the same way, inside `get`: a file
        // past the deployment's proxy cap takes a download grant, and one
        // under it does not.
        ("core.downloads.direct_get", &["get"]),
        ("query.grep", &["grep"]),
    ];

    let harness = Harness::new();
    let document = embedded_capability_document();

    for profile in &document.profiles {
        let (_, command_paths) = PROFILE_COMMAND_PATHS
            .iter()
            .find(|(advertised, _)| *advertised == profile.as_str())
            .unwrap_or_else(|| {
                unreachable!(
                    "capability profile `{profile}` has no CLI command mapping; \
                     add its command paths to PROFILE_COMMAND_PATHS"
                )
            });
        for command_path in *command_paths {
            assert_cli_command_path_exists(&harness, command_path);
        }
    }

    for feature in document.features.keys() {
        let (_, command_path) = FEATURE_COMMAND_PATHS
            .iter()
            .find(|(advertised, _)| *advertised == feature.as_str())
            .unwrap_or_else(|| {
                unreachable!(
                    "capability feature `{feature}` has no CLI command mapping; \
                     add its command path to FEATURE_COMMAND_PATHS"
                )
            });
        assert_cli_command_path_exists(&harness, command_path);
    }
}

/// `mkdir -p` on a directory that is already there succeeds, the way Unix
/// does, and still fails on a file — in both profile modes.
#[test]
fn mkdir_parents_is_idempotent_over_an_existing_directory_in_both_modes() {
    let harness = Harness::new();
    harness.add_embedded_profile("embedded");
    let remote_server =
        harness.start_external_server(harness.write_server_config("remote", "mkdir-idempotent"));
    assert_success(&harness.run(&[
        "--json",
        "profile",
        "create",
        "remote",
        "--mode",
        "remote",
        "--server-url",
        &remote_server.server_url,
        "--auth-token",
        "test-token",
    ]));

    let payload = harness.temp_dir.path().join("file.txt");
    fs::write(&payload, b"bytes\n").expect("payload");

    for profile in ["embedded", "remote"] {
        assert_success(&harness.run(&["namespace", "create", "--profile", profile, "demo"]));
        assert_success(&harness.run(&["use", "--profile", profile, "demo"]));

        let created = harness.run(&["--json", "mkdir", "-p", "/a/b", "--profile", profile]);
        assert_success(&created);
        assert_eq!(json_data(&created)["kind"], "file_mutation");

        // The second -p is a no-op, not a conflict: no commit, and the
        // output says what is already there.
        let again = harness.run(&["--json", "mkdir", "-p", "/a/b", "--profile", profile]);
        assert_success(&again);
        let again_data = json_data(&again);
        assert_eq!(again_data["kind"], "directory_already_exists");
        assert_eq!(again_data["target"], "demo:/a/b");
        assert!(again_data["inode_id"].is_number());

        // Without -p the conflict still surfaces.
        let strict = harness.run(&["--json", "mkdir", "/a/b", "--profile", profile]);
        assert_failure(&strict);
        assert_eq!(json_error(&strict)["code"], "path_conflict");

        // A file at the target is a conflict even with -p.
        assert_success(&harness.run(&[
            "put",
            "--profile",
            profile,
            payload.to_str().expect("utf-8 path"),
            "/a/file.txt",
        ]));
        let over_file =
            harness.run(&["--json", "mkdir", "-p", "/a/file.txt", "--profile", profile]);
        assert_failure(&over_file);
        assert_eq!(json_error(&over_file)["code"], "path_conflict");
    }
}

/// `cp` and `mv` land inside a destination that is already a directory, the
/// way Unix does; a destination that is a file keeps its overwrite rules.
#[test]
fn cp_and_mv_land_inside_an_existing_directory_in_both_modes() {
    let harness = Harness::new();
    harness.add_embedded_profile("embedded");
    let remote_server =
        harness.start_external_server(harness.write_server_config("remote", "transfer-into-dir"));
    assert_success(&harness.run(&[
        "--json",
        "profile",
        "create",
        "remote",
        "--mode",
        "remote",
        "--server-url",
        &remote_server.server_url,
        "--auth-token",
        "test-token",
    ]));

    let payload = harness.temp_dir.path().join("report.pdf");
    fs::write(&payload, b"report bytes\n").expect("payload");
    let other = harness.temp_dir.path().join("other.txt");
    fs::write(&other, b"other bytes\n").expect("other payload");

    for profile in ["embedded", "remote"] {
        assert_success(&harness.run(&["namespace", "create", "--profile", profile, "demo"]));
        assert_success(&harness.run(&["use", "--profile", profile, "demo"]));
        assert_success(&harness.run(&["mkdir", "/docs", "--profile", profile]));
        assert_success(&harness.run(&[
            "put",
            "--profile",
            profile,
            payload.to_str().expect("utf-8 path"),
            "/report.pdf",
        ]));

        // No trailing slash, and /docs is a directory: the file keeps its
        // own name inside it.
        let copied = harness.run(&["--json", "cp", "/report.pdf", "/docs", "--profile", profile]);
        assert_success(&copied);
        assert_eq!(json_data(&copied)["to"], "demo:/docs/report.pdf");

        let moved = harness.run(&["--json", "mv", "/report.pdf", "/docs", "--profile", profile]);
        assert_failure(&moved);
        assert_eq!(
            json_error(&moved)["code"],
            "path_conflict",
            "the copy already occupies /docs/report.pdf"
        );
        let forced = harness.run(&[
            "--json",
            "mv",
            "/report.pdf",
            "/docs",
            "--force",
            "--profile",
            profile,
        ]);
        assert_success(&forced);
        assert_eq!(json_data(&forced)["to"], "demo:/docs/report.pdf");

        // A destination that does not exist is still the exact path typed.
        let renamed = harness.run(&[
            "--json",
            "cp",
            "/docs/report.pdf",
            "/docs/renamed.pdf",
            "--profile",
            profile,
        ]);
        assert_success(&renamed);
        assert_eq!(json_data(&renamed)["to"], "demo:/docs/renamed.pdf");

        // A destination that is a file keeps the overwrite rules it had.
        assert_success(&harness.run(&[
            "put",
            "--profile",
            profile,
            other.to_str().expect("utf-8 path"),
            "/other.txt",
        ]));
        let onto_file = harness.run(&[
            "--json",
            "cp",
            "/other.txt",
            "/docs/renamed.pdf",
            "--profile",
            profile,
        ]);
        assert_failure(&onto_file);
        assert_eq!(json_error(&onto_file)["code"], "path_conflict");
        let onto_file_forced = harness.run(&[
            "--json",
            "cp",
            "/other.txt",
            "/docs/renamed.pdf",
            "--force",
            "--profile",
            profile,
        ]);
        assert_success(&onto_file_forced);
        assert_eq!(json_data(&onto_file_forced)["to"], "demo:/docs/renamed.pdf");

        // A directory tree lands inside an existing directory too.
        assert_success(&harness.run(&["mkdir", "/archive", "--profile", profile]));
        let tree = harness.run(&[
            "--json",
            "cp",
            "-r",
            "/docs",
            "/archive",
            "--profile",
            profile,
        ]);
        assert_success(&tree);
        assert_eq!(json_data(&tree)["destination"], "demo:/archive/docs");
    }
}

/// `ls` bounds its own output on request, and the cursor it reports
/// resumes exactly where it stopped.
#[test]
fn ls_limit_bounds_the_whole_listing_and_resumes_from_its_cursor() {
    let harness = Harness::new();
    harness.add_embedded_profile("default");
    assert_success(&harness.run(&["namespace", "create", "demo"]));
    assert_success(&harness.run(&["use", "demo"]));

    let payload = harness.temp_dir.path().join("entry.txt");
    fs::write(&payload, b"bytes\n").expect("payload");
    for index in 0..5 {
        assert_success(&harness.run(&[
            "put",
            payload.to_str().expect("utf-8 path"),
            &format!("/f{index}.txt"),
        ]));
    }

    // Unbounded still prints everything and reports no cursor.
    let all = harness.run(&["--json", "ls"]);
    assert_success(&all);
    let all_data = json_data(&all);
    assert_eq!(all_data["entries"].as_array().expect("json array").len(), 5);
    assert!(all_data.get("next_cursor").is_none());

    // A bound stops at exactly that many entries and hands back a cursor.
    let first = harness.run(&["--json", "ls", "--limit", "2"]);
    assert_success(&first);
    let first_data = json_data(&first);
    let first_entries = first_data["entries"].as_array().expect("json array");
    assert_eq!(first_entries.len(), 2);
    let cursor = first_data["next_cursor"]
        .as_str()
        .expect("a truncated listing reports where it stopped")
        .to_owned();

    let second = harness.run(&["--json", "ls", "--limit", "2", "--cursor", &cursor]);
    assert_success(&second);
    let second_data = json_data(&second);
    let second_entries = second_data["entries"].as_array().expect("json array");
    assert_eq!(second_entries.len(), 2);
    assert_ne!(
        second_entries[0]["absolute_path"], first_entries[0]["absolute_path"],
        "the cursor resumes after the entries already printed"
    );

    // The last page fits inside the bound and reports no cursor.
    let rest = harness.run(&[
        "--json",
        "ls",
        "--limit",
        "10",
        "--cursor",
        second_data["next_cursor"].as_str().expect("second cursor"),
    ]);
    assert_success(&rest);
    let rest_data = json_data(&rest);
    assert_eq!(
        rest_data["entries"].as_array().expect("json array").len(),
        1
    );
    assert!(rest_data.get("next_cursor").is_none());

    // The human rendering says the listing stopped early.
    let human = harness.run(&["ls", "--limit", "2"]);
    assert_success(&human);
    assert!(stdout_string(&human).contains("next_cursor:"));
}

/// The admin plane and the change feed work end to end, and both profile
/// modes emit the same `--json` shapes and error codes for them.
#[test]
fn admin_and_changes_commands_report_the_same_shapes_in_both_modes() {
    let harness = Harness::new();
    harness.add_embedded_profile("embedded");
    let remote_server =
        harness.start_external_server(harness.write_server_config("remote", "admin-parity"));
    let add_remote = harness.run(&[
        "--json",
        "profile",
        "create",
        "remote",
        "--mode",
        "remote",
        "--server-url",
        &remote_server.server_url,
        "--auth-token",
        "test-token",
    ]);
    assert_success(&add_remote);

    let first_payload = harness.temp_dir.path().join("first.txt");
    let second_payload = harness.temp_dir.path().join("second.txt");
    fs::write(&first_payload, b"first change\n").expect("first payload");
    fs::write(&second_payload, b"second change\n").expect("second payload");

    let mut shapes_by_mode = Vec::new();
    for profile in ["embedded", "remote"] {
        assert_success(&harness.run(&["namespace", "create", "--profile", profile, "demo"]));
        assert_success(&harness.run(&["use", "--profile", profile, "demo"]));
        assert_success(&harness.run(&[
            "put",
            "--profile",
            profile,
            first_payload.to_str().expect("utf-8 path"),
            "/first.txt",
        ]));
        assert_success(&harness.run(&[
            "put",
            "--profile",
            profile,
            second_payload.to_str().expect("utf-8 path"),
            "/second.txt",
        ]));

        let changes = harness.run(&["--json", "changes", "--profile", profile]);
        assert_success(&changes);
        let changes_data = json_data(&changes);
        assert_eq!(changes_data["kind"], "changes");
        assert_eq!(changes_data["namespace_id"], "demo");
        assert_eq!(changes_data["after_seq"], 0);
        assert_eq!(changes_data["through_seq"], 2);
        assert!(changes_data["next_after_seq"].is_null());
        let listed = changes_data["changes"].as_array().expect("json array");
        assert_eq!(listed.len(), 2);
        assert_eq!(listed[0]["seq"], 1);
        assert_eq!(listed[1]["seq"], 2);
        assert!(listed[0]["commit_id"]
            .as_str()
            .expect("json string")
            .starts_with("c_"));
        assert!(!listed[1]["events"]
            .as_array()
            .expect("json array")
            .is_empty());

        let paged = harness.run(&["--json", "changes", "--profile", profile, "--limit", "1"]);
        assert_success(&paged);
        let paged_data = json_data(&paged);
        assert_eq!(
            paged_data["changes"].as_array().expect("json array").len(),
            1
        );
        assert_eq!(paged_data["changes"][0]["seq"], 1);
        assert_eq!(paged_data["next_after_seq"], 1);

        let resumed = harness.run(&["--json", "changes", "--profile", profile, "--after", "1"]);
        assert_success(&resumed);
        let resumed_data = json_data(&resumed);
        assert_eq!(resumed_data["after_seq"], 1);
        assert_eq!(
            resumed_data["changes"]
                .as_array()
                .expect("json array")
                .len(),
            1
        );
        assert_eq!(resumed_data["changes"][0]["seq"], 2);

        let checkpoint = harness.run(&[
            "--json",
            "admin",
            "checkpoint",
            "--name",
            "nightly",
            "--profile",
            profile,
        ]);
        assert_success(&checkpoint);
        let checkpoint_data = json_data(&checkpoint);
        assert_eq!(checkpoint_data["kind"], "checkpoint_created");
        assert_eq!(checkpoint_data["namespace_id"], "demo");
        assert_eq!(checkpoint_data["checkpoint_seq"], 2);
        let checkpoint_id = checkpoint_data["checkpoint_id"]
            .as_str()
            .expect("json string")
            .to_owned();
        assert!(checkpoint_id.starts_with("chk_"));

        // A name is a label, not a key: the same one asked for twice mints a
        // second record, and the listing is how both ids are found again.
        let second_checkpoint = harness.run(&[
            "--json",
            "admin",
            "checkpoint",
            "--name",
            "nightly",
            "--profile",
            profile,
        ]);
        assert_success(&second_checkpoint);
        let second_checkpoint_id = json_data(&second_checkpoint)["checkpoint_id"]
            .as_str()
            .expect("json string")
            .to_owned();
        assert_ne!(second_checkpoint_id, checkpoint_id);

        let listed = harness.run(&["--json", "admin", "checkpoint-list", "--profile", profile]);
        assert_success(&listed);
        let listed_data = json_data(&listed);
        assert_eq!(listed_data["kind"], "checkpoints_listed");
        assert_eq!(listed_data["namespace_id"], "demo");
        let mut listed_ids = listed_data["checkpoints"]
            .as_array()
            .expect("json array")
            .iter()
            .map(|checkpoint| {
                assert_eq!(checkpoint["owner"]["kind"], "user");
                assert_eq!(checkpoint["owner"]["name"], "nightly");
                assert_eq!(checkpoint["checkpoint_seq"], 2);
                checkpoint["checkpoint_id"]
                    .as_str()
                    .expect("json string")
                    .to_owned()
            })
            .collect::<Vec<_>>();
        listed_ids.sort();
        let mut expected_ids = vec![checkpoint_id.clone(), second_checkpoint_id.clone()];
        expected_ids.sort();
        assert_eq!(listed_ids, expected_ids);

        // The human rendering is the same table in both modes, and it names
        // the id the release command takes.
        let listed_human = harness.run(&["admin", "checkpoint-list", "--profile", profile]);
        assert_success(&listed_human);
        let listed_text = stdout_string(&listed_human);
        assert!(listed_text.contains("CREATED\tEXPIRES\tSEQ\tOWNER\tCHECKPOINT"));
        assert!(listed_text.contains(&checkpoint_id));
        assert!(listed_text.contains("nightly"));

        // Releasing one leaves the other listed: a release is per record,
        // never per label.
        assert_success(&harness.run(&[
            "--json",
            "admin",
            "checkpoint-release",
            &second_checkpoint_id,
            "--profile",
            profile,
        ]));
        let after_release =
            harness.run(&["--json", "admin", "checkpoint-list", "--profile", profile]);
        assert_success(&after_release);
        let remaining = json_data(&after_release);
        let remaining = remaining["checkpoints"].as_array().expect("json array");
        assert_eq!(remaining.len(), 1);
        assert_eq!(remaining[0]["checkpoint_id"], checkpoint_id.as_str());

        // `admin flush` runs a maintenance step restricted to the WAL
        // flush, so it reports a step: the flush part acted, the parts `only`
        // excluded report `not_needed`.
        let flush = harness.run(&["--json", "admin", "flush", "--profile", profile]);
        assert_success(&flush);
        let flush_data = json_data(&flush);
        assert_eq!(flush_data["kind"], "maintenance_stepped");
        assert_eq!(flush_data["namespace_id"], "demo");
        assert_eq!(flush_data["reorganize"]["kind"], "not_needed");
        assert!(flush_data["gc"].is_null());

        let release = harness.run(&[
            "--json",
            "admin",
            "checkpoint-release",
            &checkpoint_id,
            "--profile",
            profile,
        ]);
        assert_success(&release);
        let release_data = json_data(&release);
        assert_eq!(release_data["kind"], "checkpoint_released");
        assert_eq!(release_data["checkpoint_id"], checkpoint_id.as_str());
        assert_eq!(release_data["was_active"], true);

        let release_again = harness.run(&[
            "--json",
            "admin",
            "checkpoint-release",
            &checkpoint_id,
            "--profile",
            profile,
        ]);
        assert_success(&release_again);
        assert_eq!(json_data(&release_again)["was_active"], false);

        let retention =
            harness.run(&["--json", "admin", "retention-advance", "--profile", profile]);
        assert_success(&retention);
        let retention_data = json_data(&retention);
        assert_eq!(retention_data["kind"], "maintenance_stepped");
        assert_eq!(retention_data["namespace_id"], "demo");
        assert_eq!(retention_data["retention_floor_seq"], 2);

        // The checkpoint above already covers the head, so a step reports
        // not-needed identically in both modes.
        let step = harness.run(&["--json", "admin", "step", "--profile", profile]);
        assert_success(&step);
        let step_data = json_data(&step);
        assert_eq!(step_data["kind"], "maintenance_stepped");
        assert_eq!(step_data["namespace_id"], "demo");
        assert_eq!(step_data["wal_flush"]["kind"], "not_needed");
        assert_eq!(step_data["reorganize"]["kind"], "not_needed");
        // An unrestricted step never advances the floor on its own; it
        // reports the floor the earlier retention-advance established.
        assert_eq!(step_data["retention_floor_seq"], 2);
        assert_eq!(step_data["status_before"]["namespace_id"], "demo");
        assert!(step_data.get("gc").is_none());

        // A fresh namespace has nothing eligible to sweep.
        let gc = harness.run(&["--json", "admin", "gc", "--profile", profile]);
        assert_success(&gc);
        let gc_data = json_data(&gc);
        assert_eq!(gc_data["kind"], "garbage_collected");
        assert_eq!(gc_data["namespace_id"], "demo");
        assert_eq!(gc_data["deleted_wal_segments"], 0);
        assert_eq!(gc_data["deleted_manifests"], 0);
        assert_eq!(gc_data["degraded_retention"], false);
        assert!(gc_data.get("next_cursor").is_none());
        // Every retention reason is reported whether or not it happened, so
        // a consumer reads a field rather than probing for one, and the
        // breakdown accounts for exactly the total beside it.
        let retained = gc_data["retained"].as_object().expect("json object");
        let reason_total: u64 = retained
            .values()
            .map(|count| count.as_u64().expect("json number"))
            .sum();
        assert_eq!(
            reason_total,
            gc_data["retained_candidates"]
                .as_u64()
                .expect("json number")
        );
        assert!(retained.contains_key("checkpoint_not_releasable"));

        // A run that took one pass says nothing on the way: its summary on
        // standard output is the whole report.
        let quiet_gc = harness.run(&["admin", "gc", "--profile", profile]);
        assert_success(&quiet_gc);
        assert!(!stderr_string(&quiet_gc).contains("pass 1:"));

        // Supplying a candidate budget requests exactly one pass and exposes
        // the opaque cursor instead of the CLI's default completion loop.
        let bounded_gc = harness.run(&[
            "--json",
            "admin",
            "gc",
            "--max-objects",
            "1",
            "--profile",
            profile,
        ]);
        assert_success(&bounded_gc);
        assert!(json_data(&bounded_gc)["next_cursor"]
            .as_str()
            .is_some_and(|cursor| !cursor.is_empty()));

        // Admin failures surface the registry code in both modes.
        let missing = harness.run(&[
            "--json",
            "admin",
            "checkpoint",
            "--name",
            "nightly",
            "--profile",
            profile,
            "--namespace",
            "missing",
        ]);
        assert_failure(&missing);
        assert_eq!(json_error(&missing)["code"], "namespace_not_found");
        // Both modes name the namespace: the CLI mapper mirrors the server
        // handler's scoping.
        assert_eq!(
            json_error(&missing)["message"],
            "namespace `missing` does not exist"
        );

        // The store probe is store-scoped, so it is the one admin command
        // that names no namespace in either mode; both modes still answer
        // with the same report shape.
        let probe = harness.run(&["--json", "admin", "probe-store", "--profile", profile]);
        assert_success(&probe);
        let probe_data = json_data(&probe);
        assert_eq!(probe_data["kind"], "store_probed");
        assert_eq!(
            probe_data["checks"].as_array().expect("checks array").len(),
            13
        );

        shapes_by_mode.push((
            sorted_object_keys(&changes_data),
            sorted_object_keys(&checkpoint_data),
            sorted_object_keys(&retention_data),
            sorted_object_keys(&step_data),
            sorted_object_keys(&gc_data),
            sorted_object_keys(&probe_data),
        ));
    }

    assert_eq!(
        shapes_by_mode[0], shapes_by_mode[1],
        "embedded and remote --json payloads diverged in shape"
    );
}

struct Harness {
    temp_dir: TempDir,
    home_dir: PathBuf,
    config_path: PathBuf,
}

impl Harness {
    fn new() -> Self {
        let temp_dir = tempfile::tempdir().expect("tempdir");
        let home_dir = temp_dir.path().join("home");
        fs::create_dir_all(&home_dir).expect("create temp home");
        Self {
            config_path: home_dir.join(".loonfs").join("config.toml"),
            home_dir,
            temp_dir,
        }
    }

    fn run(&self, args: &[&str]) -> Output {
        self.command().args(args).output().expect("run loonfs")
    }

    /// Runs the CLI with `variables` in its environment, for the config
    /// resolution the environment takes part in.
    fn run_with_env<V: AsRef<std::ffi::OsStr>>(
        &self,
        variables: &[(&str, V)],
        args: &[&str],
    ) -> Output {
        let mut command = self.command();
        for (name, value) in variables {
            command.env(name, value);
        }
        command.args(args).output().expect("run loonfs")
    }

    /// Every invocation starts from the temp home with the config
    /// environment cleared, so a developer's own `XDG_CONFIG_HOME` or
    /// `LOONFS_CONFIG` can never decide which file a test reads.
    fn command(&self) -> Command {
        let mut command = Command::new(loon_binary_path());
        command
            .env("HOME", &self.home_dir)
            .env_remove("XDG_CONFIG_HOME")
            .env_remove("LOONFS_CONFIG");
        command
    }

    /// Runs a command the CLI printed the way a user would: through a shell,
    /// which is what makes the quoting in it load-bearing. Only the `loonfs`
    /// the hint spells is swapped for the binary under test.
    fn replay_in_shell(&self, command: &str) -> Output {
        let arguments = command
            .strip_prefix("loonfs ")
            .expect("a printed command invokes loonfs");
        let binary = loon_binary_path();
        let script = format!("'{}' {arguments}", binary.display());
        Command::new("sh")
            .arg("-c")
            .arg(&script)
            .env("HOME", &self.home_dir)
            .env_remove("XDG_CONFIG_HOME")
            .env_remove("LOONFS_CONFIG")
            .output()
            .expect("replay the printed command")
    }

    /// Runs the CLI with a payload on standard input, which is the one
    /// source whose length is not knowable before it is read.
    fn run_with_stdin(&self, args: &[&str], stdin: &[u8]) -> Output {
        let mut child = self
            .command()
            .args(args)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .expect("spawn loonfs");
        child
            .stdin
            .take()
            .expect("piped stdin")
            .write_all(stdin)
            .expect("write stdin");
        child.wait_with_output().expect("run loonfs")
    }

    fn store_root(&self, name: &str) -> PathBuf {
        self.temp_dir.path().join(format!("{name}-store"))
    }

    fn add_embedded_profile(&self, name: &str) {
        let output = self.run(&[
            "--json",
            "profile",
            "create",
            name,
            "--mode",
            "embedded",
            "--store-kind",
            "local-fs",
            "--root",
            self.store_root(name).to_str().expect("utf-8 path"),
        ]);
        assert_success(&output);
    }

    fn write_cli_config(&self, contents: impl AsRef<[u8]>) {
        fs::create_dir_all(self.config_path.parent().expect("config dir"))
            .expect("create config dir");
        fs::write(&self.config_path, contents).expect("write cli config");
    }

    fn write_server_config(&self, name: &str, key_prefix: &str) -> PathBuf {
        self.write_server_config_with(name, key_prefix, "")
    }

    /// A server config with `extra` appended, for tests that need a table
    /// the default deployment leaves out.
    fn write_server_config_with(&self, name: &str, key_prefix: &str, extra: &str) -> PathBuf {
        let bind = format!("127.0.0.1:{}", available_port());
        let path = self
            .temp_dir
            .path()
            .join(format!("{name}.loonfs-server.toml"));
        let store_root = self.store_root(name);
        let contents = format!(
            r#"
bind = "{bind}"
auth_token = "test-token"
content_token_secret = "test-content-token-secret"
writer_id = "{name}"

[store]
kind = "local-fs"
root = "{}"
key_prefix = "{key_prefix}"
{extra}"#,
            store_root.display()
        );
        fs::write(&path, contents).expect("write server config");
        path
    }

    fn start_external_server(&self, server_config_path: PathBuf) -> ExternalServer {
        for _ in 0..5 {
            let child = Command::new(loonfs_server_binary_path())
                .arg("--config")
                .arg(&server_config_path)
                .spawn()
                .expect("spawn loonfs-server");
            let server_url = server_url_from_config(&server_config_path);
            if wait_for_readiness(&server_url) {
                return ExternalServer { child, server_url };
            }

            let mut child = child;
            let _ = child.kill();
            let _ = child.wait();
            rewrite_server_bind(&server_config_path, available_port());
        }

        unreachable!(
            "timed out waiting for external server from {}",
            server_config_path.display()
        );
    }
}

struct ExternalServer {
    child: Child,
    server_url: String,
}

impl Drop for ExternalServer {
    fn drop(&mut self) {
        let _ = self.child.kill();
        let _ = self.child.wait();
    }
}

fn loon_binary_path() -> PathBuf {
    if let Some(path) = env::var_os("CARGO_BIN_EXE_loonfs") {
        return PathBuf::from(path);
    }

    let current_exe = env::current_exe().expect("current test binary path");
    let debug_dir = current_exe
        .parent()
        .and_then(|path| path.parent())
        .expect("target debug dir");
    let candidate = debug_dir.join(if cfg!(windows) {
        "loonfs.exe"
    } else {
        "loonfs"
    });
    assert!(
        candidate.exists(),
        "expected loonfs binary at {}",
        candidate.display()
    );
    candidate
}

fn loonfs_server_binary_path() -> PathBuf {
    if let Some(path) = env::var_os("CARGO_BIN_EXE_loonfs-server") {
        return PathBuf::from(path);
    }

    let current_exe = env::current_exe().expect("current test binary path");
    let debug_dir = current_exe
        .parent()
        .and_then(|path| path.parent())
        .expect("target debug dir");
    let candidate = debug_dir.join(if cfg!(windows) {
        "loonfs-server.exe"
    } else {
        "loonfs-server"
    });
    assert!(
        candidate.exists(),
        "expected loonfs-server binary at {}",
        candidate.display()
    );
    candidate
}

fn server_url_from_config(path: &Path) -> String {
    let config = fs::read_to_string(path).expect("read server config");
    let bind = config
        .lines()
        .find_map(|line| line.trim().strip_prefix("bind = "))
        .expect("bind line")
        .trim_matches('"')
        .to_owned();
    format!("http://{bind}")
}

// Polls a spawned server binary for readiness; a wall-clock deadline is the
// point, so the timer methods the workspace otherwise disallows are scoped
// to this helper.
#[allow(clippy::disallowed_methods)]
fn wait_for_readiness(server_url: &str) -> bool {
    let deadline = Instant::now() + Duration::from_secs(5);
    while Instant::now() < deadline {
        if ureq::get(&format!("{server_url}/health")).call().is_ok() {
            return true;
        }
        thread::sleep(Duration::from_millis(100));
    }
    false
}

fn rewrite_server_bind(path: &Path, port: u16) {
    let config = fs::read_to_string(path).expect("read server config for bind rewrite");
    let bind = format!("127.0.0.1:{port}");
    let rewritten = config
        .lines()
        .map(|line| {
            if line.trim().starts_with("bind = ") {
                format!("bind = \"{bind}\"")
            } else {
                line.to_owned()
            }
        })
        .collect::<Vec<_>>()
        .join("\n");
    fs::write(path, rewritten).expect("rewrite server bind");
}

fn available_port() -> u16 {
    TcpListener::bind("127.0.0.1:0")
        .expect("bind port")
        .local_addr()
        .expect("local addr")
        .port()
}

fn assert_success(output: &Output) {
    assert!(
        output.status.success(),
        "expected success, got {:?}\nstdout:\n{}\nstderr:\n{}",
        output.status.code(),
        stdout_string(output),
        stderr_string(output)
    );
}

fn assert_failure(output: &Output) {
    assert!(
        !output.status.success(),
        "expected failure, got success\nstdout:\n{}\nstderr:\n{}",
        stdout_string(output),
        stderr_string(output)
    );
}

fn stdout_string(output: &Output) -> String {
    String::from_utf8_lossy(&output.stdout).into_owned()
}

/// The command a `rm` hint spells, taken from between its backticks.
fn hinted_recovery_command(output: &Output) -> String {
    let text = stdout_string(output);
    let hint = text
        .split_once("recover with `")
        .and_then(|(_, rest)| rest.split_once('`'))
        .map(|(command, _)| command.to_owned());
    assert!(
        hint.is_some(),
        "expected a backtick-delimited recovery hint, got:\n{text}"
    );
    hint.expect("checked just above")
}

/// The `RECOVER` cell of the one trash row naming `display_name`.
fn trash_recovery_command(output: &Output, display_name: &str) -> String {
    let table = stdout_string(output);
    let cell = table
        .lines()
        .find(|line| line.split('\t').nth(1) == Some(display_name))
        .and_then(|row| row.split('\t').nth(4))
        .map(ToOwned::to_owned);
    assert!(
        cell.is_some(),
        "expected a trash row for `{display_name}`, got:\n{table}"
    );
    cell.expect("checked just above")
}

fn stderr_string(output: &Output) -> String {
    String::from_utf8_lossy(&output.stderr).into_owned()
}

fn parse_json(bytes: &[u8]) -> Value {
    serde_json::from_slice(bytes).expect("parse json")
}

fn json_data(output: &Output) -> Value {
    parse_json(&output.stdout)["data"].clone()
}

/// The failure envelope, which is the last document on standard error.
///
/// Under `--json` standard error carries a stream of JSON documents, not
/// one: a transfer reports progress there while it runs, and the envelope
/// comes last.
fn json_error(output: &Output) -> Value {
    json_stderr_documents(output)
        .pop()
        .expect("a failure envelope on stderr")["error"]
        .clone()
}

/// Every JSON document standard error carried, in order.
fn json_stderr_documents(output: &Output) -> Vec<Value> {
    serde_json::Deserializer::from_slice(&output.stderr)
        .into_iter::<Value>()
        .collect::<Result<Vec<_>, _>>()
        .expect("parse the json documents on stderr")
}

/// The progress events of one run, in the order they were reported.
fn json_progress_events(output: &Output) -> Vec<Value> {
    json_stderr_documents(output)
        .into_iter()
        .filter(|document| document.get("error").is_none() && document.get("data").is_none())
        .collect()
}

fn sorted_object_keys(value: &Value) -> Vec<String> {
    let mut keys: Vec<String> = value
        .as_object()
        .expect("json object")
        .keys()
        .cloned()
        .collect();
    keys.sort();
    keys
}

/// What an embedded profile serves: the runtime's own capability document
/// (`crates/loonfs/tests/capability_conformance.rs` pins it to the spec
/// text) plus the query plane the CLI composes from `loonfs-grep`, which is
/// how `loonfs grep` and `loonfs admin index-*` reach a store at all.
fn embedded_capability_document() -> loonfs::CapabilityDocument {
    let temp_dir = tempfile::tempdir().expect("tempdir");
    let store = std::sync::Arc::new(
        loonfs_objectstore::local_fs_store::LocalFsStore::new(temp_dir.path()).expect("store"),
    ) as loonfs::SharedObjectStore;
    let reader = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .expect("test runtime")
        .block_on(loonfs::FsReader::builder_with_store(store).build())
        .expect("build reader");
    let mut document = reader.capabilities();
    document
        .profiles
        .push(loonfs_api::PROFILE_QUERY_V0.to_owned());
    document
        .features
        .insert(loonfs_api::FEATURE_QUERY_GREP.to_owned(), true);
    document
}

fn assert_cli_command_path_exists(harness: &Harness, command_path: &[&str]) {
    let mut args = command_path.to_vec();
    args.push("--help");
    let output = harness.run(&args);
    assert!(
        output.status.success(),
        "no CLI command path `loonfs {}`:\n{}",
        command_path.join(" "),
        stderr_string(&output)
    );
}