eidetic-engine 0.15.2

Durable, local-first, explainable memory for coding agents.
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
//! Product-level `ee team` commands over mesh primitives.

use std::io::{BufRead, Write};
use std::path::PathBuf;

use clap::{Parser, Subcommand};
use serde_json::json;

use crate::db::DbConnection;
use crate::mesh::peer_state::MeshDriftThresholds;
use crate::mesh::team::{
    TeamInviteReport, TeamMemberRecord, TeamStatusReport, add_local_team_node, adopt_team_project,
    any_local_team_paused, attest_local_id_token, create_local_team_with_store,
    execute_team_idp_token_poll, execute_team_steward_once, fetch_local_team_body,
    inspect_team_health, inspect_team_port, join_team_with_code_on_store, leave_local_team,
    list_team_activity, list_team_projects, local_team_status, migrate_local_team_port,
    mint_team_invite_with_store, pinned_team_jwks_uri, plan_team_idp_device,
    reconcile_local_team_membership, reconcile_local_team_projects, remove_team_member,
    require_tailnet_attested, resume_pending_invite, revalidate_team_identities,
    revoke_team_invite, revoke_team_invites_before_floor, rotate_local_signing_key,
    serve_one_bootstrap_join_with_store, serve_one_invite_first_sync, set_local_team_paused,
    set_team_oidc_provider, share_team_bodies_represented, share_team_history, share_team_project,
    team_idp_status, unshare_team_bodies,
};
use crate::models::{DomainError, ProcessExitCode};
use crate::output;

use super::{Cli, write_domain_error, write_stdout};

/// Subcommands for `ee team`.
#[derive(Clone, Debug, Eq, PartialEq, Subcommand)]
pub enum TeamCommand {
    /// Create a local team genesis on the origin stream.
    Create(TeamCreateArgs),
    /// Show locally recorded team genesis events.
    Status(TeamStatusArgs),
    /// Mint a single-use invite for the local team.
    Invite(TeamInviteArgs),
    /// Join a team by proving an invite over live TCP.
    Join(TeamJoinArgs),
    /// Revoke a pending invite.
    Revoke(TeamRevokeArgs),
    /// Share origin-owned history as metadata-only origin events.
    #[command(subcommand)]
    Share(TeamShareCommand),
    /// Stop future serving of previously published bodies.
    #[command(subcommand)]
    Unshare(TeamUnshareCommand),
    /// Membership list/remove.
    #[command(subcommand)]
    Members(TeamMembersCommand),
    /// Leave the local team (self removal).
    Leave(TeamLeaveArgs),
    /// Run one mesh sync cycle for the local team.
    Sync(TeamSyncArgs),
    /// Pause team network exchange.
    Pause(TeamPauseArgs),
    /// Resume team network exchange.
    Resume(TeamResumeArgs),
    /// List closed-metadata team activity.
    Activity(TeamActivityArgs),
    /// Mint, adopt, or list team project identities.
    #[command(subcommand)]
    Projects(TeamProjectsCommand),
    /// Fetch a published body from the local hardened cache.
    #[command(subcommand)]
    Fetch(TeamFetchCommand),
    /// Foreground steward pass.
    #[command(subcommand)]
    Steward(TeamStewardCommand),
    /// Read-only team health checks.
    Doctor(TeamDoctorArgs),
    /// Tailnet-attested identity policy.
    #[command(subcommand)]
    Idp(TeamIdpCommand),
    /// Encrypted pair-key and signing-seed backup.
    #[command(subcommand)]
    Credentials(TeamCredentialsCommand),
    /// Inspect or migrate the folded team hello port.
    #[command(subcommand)]
    Port(TeamPortCommand),
}

/// Nested `ee team port` verbs.
#[derive(Clone, Debug, Eq, PartialEq, Subcommand)]
pub enum TeamPortCommand {
    /// Show the folded hello port without rewriting genesis.
    Show(TeamPortShowArgs),
    /// Append a versioned `teamPortMigrated` event and rewrite enrolled locators.
    Migrate(TeamPortMigrateArgs),
}

/// Nested `ee team credentials` verbs.
#[derive(Clone, Debug, Eq, PartialEq, Subcommand)]
pub enum TeamCredentialsCommand {
    /// Write an encrypted credential backup under the workspace keys tree.
    Backup(TeamCredentialsBackupArgs),
    /// Restore pair keys and signing seeds from an encrypted backup.
    Restore(TeamCredentialsRestoreArgs),
}

/// Nested `ee team fetch` verbs.
#[derive(Clone, Debug, Eq, PartialEq, Subcommand)]
pub enum TeamFetchCommand {
    /// Read one published body cache key.
    Body(TeamFetchBodyArgs),
}

/// Nested `ee team steward` verbs.
#[derive(Clone, Debug, Eq, PartialEq, Subcommand)]
pub enum TeamStewardCommand {
    /// Plan and, if triggered, run one mesh sync.
    #[command(name = "once", alias = "run-once")]
    RunOnce(TeamStewardRunOnceArgs),
}

/// Nested `ee team projects` verbs.
#[derive(Clone, Debug, Eq, PartialEq, Subcommand)]
pub enum TeamProjectsCommand {
    /// Mint a team-scoped project id for a local path.
    Share(TeamProjectsShareArgs),
    /// Map an existing project id onto a local path.
    Adopt(TeamProjectsAdoptArgs),
    /// List minted and adopted projects.
    List(TeamProjectsListArgs),
    /// Replay origin project shares onto local rows.
    Reconcile(TeamProjectsReconcileArgs),
}

/// Nested `ee team members` verbs.
#[derive(Clone, Debug, Eq, PartialEq, Subcommand)]
pub enum TeamMembersCommand {
    /// List recorded members.
    List(TeamMembersListArgs),
    /// Remove a non-self member.
    Remove(TeamMembersRemoveArgs),
    /// Bind another local node to the self member.
    AddNode(TeamMembersAddNodeArgs),
    /// Rotate the local signing key.
    RotateKey(TeamMembersRotateKeyArgs),
    /// Replay origin membership events onto local rows.
    Reconcile(TeamMembersReconcileArgs),
    /// Recheck tailnet owners against the recorded IdP policy.
    Revalidate(TeamMembersRevalidateArgs),
}

/// Nested `ee team idp` verbs.
#[derive(Clone, Debug, Eq, PartialEq, Subcommand)]
pub enum TeamIdpCommand {
    /// Require every member node to be owned by a tailnet login.
    Require(TeamIdpRequireArgs),
    /// Show the recorded identity policy.
    Status(TeamIdpStatusArgs),
    /// Pin a secretless-public OIDC issuer from a local discovery document.
    Set(TeamIdpSetArgs),
    /// Plan a local RFC 8628 device ceremony from offline JSON.
    Device(TeamIdpDeviceArgs),
    /// Bind allowlisted ID-token claims to the local self member.
    Attest(TeamIdpAttestArgs),
}

/// Nested `ee team share` verbs.
#[derive(Clone, Debug, Eq, PartialEq, Subcommand)]
pub enum TeamShareCommand {
    /// Preview or project pre-team local memories.
    History(TeamShareHistoryArgs),
    /// Preview or publish origin-owned bodies into the local cache.
    Bodies(TeamShareBodiesArgs),
}

/// Nested `ee team unshare` verbs.
#[derive(Clone, Debug, Eq, PartialEq, Subcommand)]
pub enum TeamUnshareCommand {
    /// Stop future body serving from this node.
    Bodies(TeamUnshareBodiesArgs),
}

/// Arguments for `ee team create`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamCreateArgs {
    /// Human display name for the team.
    #[arg(long)]
    pub name: String,

    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team status`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamStatusArgs {
    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team invite`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamInviteArgs {
    /// Live TCP locator the joiner should contact (IP or IP:port).
    /// When omitted, the local Tailscale IPv4 address is used if present.
    #[arg(long)]
    pub endpoint: Option<String>,

    /// Bind the advertised locator and accept one join before exiting.
    #[arg(long)]
    pub wait: bool,

    /// Resume waiting on an existing pending invite without re-emitting the secret.
    #[arg(long, value_name = "INVITE_ID")]
    pub resume: Option<String>,

    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team join`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamJoinArgs {
    /// `eeteam1-` invite code.
    #[arg(long, required_unless_present = "invite_stdin")]
    pub invite: Option<String>,

    /// Read the invite code from stdin (no-echo TTY, or a pipe for agents).
    #[arg(long)]
    pub invite_stdin: bool,

    /// Display name the inviter should record for this node.
    #[arg(long, default_value = "joiner")]
    pub name: String,

    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team revoke`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamRevokeArgs {
    /// Invite id from `ee team invite`.
    #[arg(long, required_unless_present = "all_before_floor")]
    pub invite_id: Option<String>,

    /// Revoke every pending invite created before the authorization floor.
    #[arg(long)]
    pub all_before_floor: bool,

    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team share bodies`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamShareBodiesArgs {
    /// Publish bearer-approved bodies into the hardened local cache.
    #[arg(long, requires = "token_stdin")]
    pub confirm: bool,

    /// Mint a sensitive `eeap1_` body-approval token on preview.
    #[arg(long, conflicts_with = "confirm")]
    pub issue_token: bool,

    /// Read the body-approval token from bounded stdin. Bearers are never
    /// accepted in process arguments, environment variables, or logs.
    #[arg(long, requires = "confirm")]
    pub token_stdin: bool,

    /// Maximum memories to consider (1–256).
    #[arg(long, default_value_t = 64)]
    pub limit: usize,

    /// Signed body representation. `already_redacted` is allowed; switching an
    /// `exact` publication to `already_redacted` is refused.
    #[arg(long, default_value = "exact")]
    pub representation: String,

    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team unshare bodies`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamUnshareBodiesArgs {
    /// Confirm the non-erasure unshare.
    #[arg(long)]
    pub confirm: bool,

    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team share history`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamShareHistoryArgs {
    /// Project the previewed history onto the origin stream.
    #[arg(long)]
    pub confirm: bool,

    /// Maximum memories to consider (1–256).
    #[arg(long, default_value_t = 64)]
    pub limit: usize,

    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team members list`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamMembersListArgs {
    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team members remove`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamMembersRemoveArgs {
    /// Member id from `ee team status` / `ee team members list`.
    #[arg(long)]
    pub member_id: String,

    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team members add-node`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamMembersAddNodeArgs {
    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team members rotate-key`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamMembersRotateKeyArgs {
    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team members reconcile`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamMembersReconcileArgs {
    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team leave`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamLeaveArgs {
    /// Confirm the irreversible local leave.
    #[arg(long)]
    pub confirm: bool,

    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team sync`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamSyncArgs {
    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team pause`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamPauseArgs {
    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team resume`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamResumeArgs {
    /// Confirm resume after a pause.
    #[arg(long)]
    pub confirm: bool,

    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team activity`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamActivityArgs {
    /// Exclusive member-attested as-of timestamp (RFC 3339).
    #[arg(long)]
    pub as_of: String,

    /// Restrict to this member display name.
    #[arg(long)]
    pub member: Option<String>,

    /// Restrict to this team project display name.
    #[arg(long)]
    pub project: Option<String>,

    /// Inclusive lower bound. JSON requires RFC 3339. Human mode also
    /// accepts a relative duration such as `2h` or `7d`.
    #[arg(long)]
    pub since: Option<String>,

    /// Resume from an `ee.cursor.v1` token. Invalid/stale tokens yield
    /// an empty page plus `cursorError`.
    #[arg(long)]
    pub cursor: Option<String>,

    /// Maximum events to return (1–1000).
    #[arg(long, default_value_t = 100)]
    pub limit: usize,

    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team projects share`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamProjectsShareArgs {
    /// Human project name.
    #[arg(long)]
    pub name: String,

    /// Local path this node binds to the project.
    #[arg(long)]
    pub path: String,

    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team projects adopt`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamProjectsAdoptArgs {
    /// `prj_tm_` project id from another member.
    #[arg(long)]
    pub project_id: String,

    /// Human project name.
    #[arg(long)]
    pub name: String,

    /// Local path this node binds to the project.
    #[arg(long)]
    pub path: String,

    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team projects list`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamProjectsListArgs {
    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team projects reconcile`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamProjectsReconcileArgs {
    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team fetch body`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamFetchBodyArgs {
    /// Body cache key from `ee team share bodies`.
    #[arg(long)]
    pub key: String,

    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team steward once`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamStewardRunOnceArgs {
    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team doctor`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamDoctorArgs {
    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team port show`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamPortShowArgs {
    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team port migrate`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamPortMigrateArgs {
    /// Next non-privileged hello port. Does not rewrite the genesis event.
    #[arg(long = "to", value_name = "PORT")]
    pub to: u16,

    /// Confirm appending `teamPortMigrated` and rewriting enrolled peer locators.
    #[arg(long)]
    pub confirm: bool,

    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team credentials backup`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamCredentialsBackupArgs {
    /// Destination file or directory under the workspace. Defaults to
    /// `<workspace>/.ee/keys/mesh-credential-backup/credentials.backup.v1.json`.
    #[arg(long, value_name = "PATH")]
    pub output: Option<PathBuf>,

    /// Read the passphrase from stdin. Never accepted on argv.
    #[arg(long)]
    pub passphrase_stdin: bool,

    /// Replace an existing backup envelope at the destination.
    #[arg(long)]
    pub overwrite: bool,
}

/// Arguments for `ee team credentials restore`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamCredentialsRestoreArgs {
    /// Encrypted backup envelope. May live outside the workspace.
    #[arg(long, value_name = "PATH")]
    pub input: PathBuf,

    /// Read the passphrase from stdin. Never accepted on argv.
    #[arg(long)]
    pub passphrase_stdin: bool,

    /// Replace existing pair-key and signing-seed slots.
    #[arg(long)]
    pub overwrite: bool,
}

/// Arguments for `ee team idp require`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamIdpRequireArgs {
    /// Bind every member node to the tailnet UserProfile owner.
    #[arg(long)]
    pub tailnet_attested: bool,

    /// Optional login domain restriction, e.g. acme.com.
    #[arg(long)]
    pub domain: Option<String>,

    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team idp status`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamIdpStatusArgs {
    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team idp set`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamIdpSetArgs {
    /// Issuer URL. Must be https.
    #[arg(long)]
    pub issuer: String,

    /// Public client id. Never a client secret.
    #[arg(long)]
    pub client_id: String,

    /// Local OpenID discovery JSON file. No network is used.
    #[arg(long, value_name = "PATH")]
    pub discovery_json: PathBuf,

    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team idp device`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamIdpDeviceArgs {
    /// Local OpenID discovery JSON file. No network is used.
    #[arg(long, value_name = "PATH")]
    pub discovery_json: PathBuf,

    /// Local RFC 8628 device-authorization JSON file.
    #[arg(long, value_name = "PATH")]
    pub authorization_json: PathBuf,

    /// Absolute curl binary. Defaults to /usr/bin/curl.
    #[arg(long, value_name = "PATH", default_value = "/usr/bin/curl")]
    pub curl: PathBuf,

    /// Run one constrained HTTPS token poll. Raw tokens are not printed.
    #[arg(long)]
    pub execute: bool,

    /// Absolute CA bundle used to pin TLS for `--execute`. Never `--insecure`.
    #[arg(long, value_name = "PATH")]
    pub ca_bundle: Option<PathBuf>,

    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team idp attest`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamIdpAttestArgs {
    /// Read the compact ID token from stdin. The only accepted value is `-`;
    /// bearer material is never accepted in process arguments.
    #[arg(long, value_name = "-", value_parser = parse_stdin_sentinel)]
    pub id_token: String,

    /// Configured group to match. Repeatable. Unlisted groups are dropped.
    #[arg(long = "group")]
    pub groups: Vec<String>,

    /// The exact discovery JSON pinned by `ee team idp set`. Its `jwks_uri`
    /// is the only key source authorized for signature verification.
    #[arg(long, value_name = "PATH")]
    pub discovery_json: PathBuf,

    /// Absolute CA bundle used to pin TLS for the discovery-bound JWKS URL.
    #[arg(long, value_name = "PATH")]
    pub ca_bundle: Option<PathBuf>,

    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

/// Arguments for `ee team members revalidate`.
#[derive(Clone, Debug, Eq, Parser, PartialEq)]
pub struct TeamMembersRevalidateArgs {
    /// Database path. Defaults to <workspace>/.ee/ee.db.
    #[arg(long, value_name = "PATH")]
    pub database: Option<PathBuf>,
}

pub fn handle_team<W, E>(
    cli: &Cli,
    command: &TeamCommand,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    match command {
        TeamCommand::Create(args) => handle_team_create(cli, args, stdout, stderr),
        TeamCommand::Status(args) => handle_team_status(cli, args, stdout, stderr),
        TeamCommand::Invite(args) => handle_team_invite(cli, args, stdout, stderr),
        TeamCommand::Join(args) => handle_team_join(cli, args, stdout, stderr),
        TeamCommand::Revoke(args) => handle_team_revoke(cli, args, stdout, stderr),
        TeamCommand::Share(TeamShareCommand::History(args)) => {
            handle_team_share_history(cli, args, stdout, stderr)
        }
        TeamCommand::Share(TeamShareCommand::Bodies(args)) => {
            handle_team_share_bodies(cli, args, stdout, stderr)
        }
        TeamCommand::Unshare(TeamUnshareCommand::Bodies(args)) => {
            handle_team_unshare_bodies(cli, args, stdout, stderr)
        }
        TeamCommand::Members(TeamMembersCommand::List(args)) => {
            handle_team_members_list(cli, args, stdout, stderr)
        }
        TeamCommand::Members(TeamMembersCommand::Remove(args)) => {
            handle_team_members_remove(cli, args, stdout, stderr)
        }
        TeamCommand::Members(TeamMembersCommand::AddNode(args)) => {
            handle_team_members_add_node(cli, args, stdout, stderr)
        }
        TeamCommand::Members(TeamMembersCommand::RotateKey(args)) => {
            handle_team_members_rotate_key(cli, args, stdout, stderr)
        }
        TeamCommand::Members(TeamMembersCommand::Reconcile(args)) => {
            handle_team_members_reconcile(cli, args, stdout, stderr)
        }
        TeamCommand::Members(TeamMembersCommand::Revalidate(args)) => {
            handle_team_members_revalidate(cli, args, stdout, stderr)
        }
        TeamCommand::Idp(TeamIdpCommand::Require(args)) => {
            handle_team_idp_require(cli, args, stdout, stderr)
        }
        TeamCommand::Idp(TeamIdpCommand::Status(args)) => {
            handle_team_idp_status(cli, args, stdout, stderr)
        }
        TeamCommand::Idp(TeamIdpCommand::Set(args)) => {
            handle_team_idp_set(cli, args, stdout, stderr)
        }
        TeamCommand::Idp(TeamIdpCommand::Device(args)) => {
            handle_team_idp_device(cli, args, stdout, stderr)
        }
        TeamCommand::Idp(TeamIdpCommand::Attest(args)) => {
            handle_team_idp_attest(cli, args, stdout, stderr)
        }
        TeamCommand::Leave(args) => handle_team_leave(cli, args, stdout, stderr),
        TeamCommand::Sync(args) => handle_team_sync(cli, args, stdout, stderr),
        TeamCommand::Pause(args) => handle_team_pause(cli, args, stdout, stderr),
        TeamCommand::Resume(args) => handle_team_resume(cli, args, stdout, stderr),
        TeamCommand::Activity(args) => handle_team_activity(cli, args, stdout, stderr),
        TeamCommand::Projects(TeamProjectsCommand::Share(args)) => {
            handle_team_projects_share(cli, args, stdout, stderr)
        }
        TeamCommand::Projects(TeamProjectsCommand::Adopt(args)) => {
            handle_team_projects_adopt(cli, args, stdout, stderr)
        }
        TeamCommand::Projects(TeamProjectsCommand::List(args)) => {
            handle_team_projects_list(cli, args, stdout, stderr)
        }
        TeamCommand::Projects(TeamProjectsCommand::Reconcile(args)) => {
            handle_team_projects_reconcile(cli, args, stdout, stderr)
        }
        TeamCommand::Fetch(TeamFetchCommand::Body(args)) => {
            handle_team_fetch_body(cli, args, stdout, stderr)
        }
        TeamCommand::Steward(TeamStewardCommand::RunOnce(args)) => {
            handle_team_steward_run_once(cli, args, stdout, stderr)
        }
        TeamCommand::Doctor(args) => handle_team_doctor(cli, args, stdout, stderr),
        TeamCommand::Credentials(TeamCredentialsCommand::Backup(args)) => {
            handle_team_credentials_backup(cli, args, stdout, stderr)
        }
        TeamCommand::Credentials(TeamCredentialsCommand::Restore(args)) => {
            handle_team_credentials_restore(cli, args, stdout, stderr)
        }
        TeamCommand::Port(TeamPortCommand::Show(args)) => {
            handle_team_port_show(cli, args, stdout, stderr)
        }
        TeamCommand::Port(TeamPortCommand::Migrate(args)) => {
            handle_team_port_migrate(cli, args, stdout, stderr)
        }
    }
}

fn handle_team_create<W, E>(
    cli: &Cli,
    args: &TeamCreateArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    let (connection, workspace_id) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    let produced_at = chrono::Utc::now().to_rfc3339();
    let workspace_path = cli.resolve_workspace();
    match create_local_team_with_store(
        &connection,
        &workspace_id,
        &args.name,
        &produced_at,
        Some(&workspace_path),
    ) {
        Ok(report) => {
            let human = format!(
                "Team {}: {}\n  team_id: {}\n  origin_node_id: {}\n  hello_port: {}\n  genesis: {}\nNext:\n  {}\n",
                if report.created {
                    "created"
                } else {
                    "already exists"
                },
                report.team.display_name,
                report.team.team_id,
                report.team.origin_node_id,
                report.team.hello_port,
                report.team.genesis_event_id,
                report.next_commands.join("\n  ")
            );
            write_team_report(cli, &report, &human, stdout)
        }
        Err(error) => write_domain_error(
            &DomainError::Storage {
                message: format!("Failed to create team: {error}"),
                repair: Some("ee init --workspace . && ee migrate run --workspace .".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

fn handle_team_status<W, E>(
    cli: &Cli,
    args: &TeamStatusArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    let (connection, _) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    match local_team_status(&connection) {
        Ok(report) => {
            let as_of = chrono::Utc::now();
            let freshness = collect_team_member_freshness(&connection, &report.members, as_of);
            let human = render_team_status_human(&report, &freshness, as_of);
            match inject_team_member_freshness(&report, &freshness) {
                Ok(data) => write_team_report(cli, &data, &human, stdout),
                Err(error) => write_domain_error(
                    &DomainError::Storage {
                        message: format!("Failed to serialize team status: {error}"),
                        repair: Some("ee team status --workspace . --json".to_owned()),
                    },
                    cli.wants_json(),
                    stdout,
                    stderr,
                ),
            }
        }
        Err(error) => write_domain_error(
            &DomainError::Storage {
                message: format!("Failed to read team status: {error}"),
                repair: Some("ee migrate run --workspace .".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

fn wait_for_invite_join<W, E>(
    cli: &Cli,
    connection: &crate::db::DbConnection,
    workspace_id: &str,
    workspace_path: &std::path::Path,
    mut report: TeamInviteReport,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    let Some(bind) = crate::mesh::bootstrap_envelope::parse_live_peer_endpoint(
        &report.endpoint,
        report.hello_port,
    ) else {
        return write_domain_error(
            &DomainError::Storage {
                message: "Invite wait needs a live TCP endpoint".to_owned(),
                repair: Some("ee team invite --endpoint <ip-or-ip:port> --wait".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        );
    };
    let listener = match std::net::TcpListener::bind(bind) {
        Ok(listener) => listener,
        Err(error) => {
            return write_domain_error(
                &DomainError::Storage {
                    message: format!("Failed to bind invite waiter: {error}"),
                    repair: Some("ee mesh hello-responder run --workspace .".to_owned()),
                },
                cli.wants_json(),
                stdout,
                stderr,
            );
        }
    };
    match serve_one_bootstrap_join_with_store(
        connection,
        workspace_id,
        &listener,
        std::time::Duration::from_secs(300),
        Some(workspace_path),
    ) {
        Ok(granted) => report.granted = Some(granted),
        Err(error) => {
            return write_domain_error(
                &DomainError::Storage {
                    message: format!("Invite wait failed: {error}"),
                    repair: Some(
                        "ee team invite --wait --resume <invite-id> --workspace .".to_owned(),
                    ),
                },
                cli.wants_json(),
                stdout,
                stderr,
            );
        }
    }
    if let Ok(_served) = serve_one_invite_first_sync(
        connection,
        workspace_id,
        &listener,
        std::time::Duration::from_secs(15),
    ) {
        report.first_sync_served = true;
        if !report
            .mesh_primitives
            .iter()
            .any(|item| *item == "mesh_sync")
        {
            report.mesh_primitives.push("mesh_sync");
        }
    }
    let human = match &report.granted {
        Some(granted) => format!(
            "Invite redeemed by join\n  invite_id: {}\n  team_id: {}\n  joiner recorded for {}\n  first_sync: {}\n",
            report.invite_id,
            granted.team_id,
            granted.display_name,
            if report.first_sync_served {
                "served"
            } else {
                "joiner did not fetch — start ee mesh hello-responder run"
            }
        ),
        None => format!(
            "Resumed invite waiter\n  invite_id: {}\n  endpoint: {}:{}\n",
            report.invite_id, report.endpoint, report.hello_port
        ),
    };
    write_team_report(cli, &report, &human, stdout)
}

fn handle_team_invite<W, E>(
    cli: &Cli,
    args: &TeamInviteArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    let (connection, workspace_id) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    let produced_at = chrono::Utc::now().to_rfc3339();
    let expires_at = (chrono::Utc::now() + chrono::Duration::days(7)).to_rfc3339();
    let workspace_path = cli.resolve_workspace();
    if let Some(invite_id) = args
        .resume
        .as_deref()
        .map(str::trim)
        .filter(|id| !id.is_empty())
    {
        if !args.wait {
            return write_domain_error(
                &DomainError::Usage {
                    message: "invite --resume requires --wait".to_owned(),
                    repair: Some(
                        "ee team invite --wait --resume <invite-id> --workspace .".to_owned(),
                    ),
                },
                cli.wants_json(),
                stdout,
                stderr,
            );
        }
        return match resume_pending_invite(&connection, invite_id) {
            Ok(report) => wait_for_invite_join(
                cli,
                &connection,
                &workspace_id,
                &workspace_path,
                report,
                stdout,
                stderr,
            ),
            Err(error) => write_domain_error(
                &DomainError::Storage {
                    message: format!("Failed to resume invite: {error}"),
                    repair: Some("ee team status --workspace . --json".to_owned()),
                },
                cli.wants_json(),
                stdout,
                stderr,
            ),
        };
    }
    let endpoint = match args
        .endpoint
        .as_deref()
        .map(str::trim)
        .filter(|value| !value.is_empty())
    {
        Some(explicit) => explicit.to_owned(),
        None => match probe_local_tailscale_for_team().self_tailscale_ip {
            Some(ip) if !ip.is_empty() => ip,
            _ => {
                return write_domain_error(
                    &DomainError::Usage {
                        message: "invite needs --endpoint or a reachable Tailscale self IP"
                            .to_owned(),
                        repair: Some(
                            "ee team invite --endpoint <tailscale-ip> --workspace .".to_owned(),
                        ),
                    },
                    cli.wants_json(),
                    stdout,
                    stderr,
                );
            }
        },
    };
    match mint_team_invite_with_store(
        &connection,
        &endpoint,
        &produced_at,
        &expires_at,
        Some(&workspace_path),
    ) {
        Ok(report) => {
            if args.wait {
                return wait_for_invite_join(
                    cli,
                    &connection,
                    &workspace_id,
                    &workspace_path,
                    report,
                    stdout,
                    stderr,
                );
            }
            write_team_report(
                cli,
                &report,
                &format!(
                    "Invite minted for {}\n  invite_id: {}\n  endpoint: {}:{}\n  expires: {}\n  code: {}\nNext:\n  ee team join --invite <code> --workspace . --json\n  ee team invite --wait --resume {} --workspace .\n",
                    report.team_id,
                    report.invite_id,
                    report.endpoint,
                    report.hello_port,
                    report.expires_at,
                    report.invite_code,
                    report.invite_id
                ),
                stdout,
            )
        }
        Err(error) => write_domain_error(
            &DomainError::Storage {
                message: format!("Failed to mint team invite: {error}"),
                repair: Some("ee team create --name \"<team>\" --workspace .".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

fn handle_team_revoke<W, E>(
    cli: &Cli,
    args: &TeamRevokeArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    let (connection, _) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    let revoked_at = chrono::Utc::now().to_rfc3339();
    if args.all_before_floor {
        return match revoke_team_invites_before_floor(&connection, &revoked_at) {
            Ok(revoked) => {
                let report = json!({
                    "schema": "ee.team.revoke.v1",
                    "command": "team revoke",
                    "allBeforeFloor": true,
                    "revokedCount": revoked,
                    "revokedAt": revoked_at,
                    "meshPrimitives": ["team_pending_invites.revoke", "team_invite_auth_floor"],
                });
                write_team_report(
                    cli,
                    &report,
                    &format!("{revoked} pending invite(s) below the authorization floor revoked\n"),
                    stdout,
                )
            }
            Err(error) => write_domain_error(
                &DomainError::Storage {
                    message: format!("Failed to revoke invites before the floor: {error}"),
                    repair: Some("ee team doctor --workspace . --json".to_owned()),
                },
                cli.wants_json(),
                stdout,
                stderr,
            ),
        };
    }
    let Some(invite_id) = args.invite_id.as_deref() else {
        return write_domain_error(
            &DomainError::Usage {
                message: "invite revoke requires --invite-id or --all-before-floor".to_owned(),
                repair: Some("ee team revoke --invite-id <id> --workspace .".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        );
    };
    match revoke_team_invite(&connection, invite_id, &revoked_at) {
        Ok(true) => {
            let report = json!({
                "schema": "ee.team.revoke.v1",
                "command": "team revoke",
                "inviteId": invite_id,
                "revoked": true,
                "revokedAt": revoked_at,
                "meshPrimitives": ["team_pending_invites.revoke", "team_invite_auth_floor"],
            });
            write_team_report(
                cli,
                &report,
                &format!("Invite {invite_id} revoked\n"),
                stdout,
            )
        }
        Ok(false) => write_domain_error(
            &DomainError::Storage {
                message: format!("Invite {invite_id} is not pending"),
                repair: Some("ee team invite --endpoint <ip> --workspace .".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        ),
        Err(error) => write_domain_error(
            &DomainError::Storage {
                message: format!("Failed to revoke invite: {error}"),
                repair: Some("ee team status --workspace . --json".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

fn handle_team_share_history<W, E>(
    cli: &Cli,
    args: &TeamShareHistoryArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    let (connection, workspace_id) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    let produced_at = chrono::Utc::now().to_rfc3339();
    let workspace_path = cli.resolve_workspace();
    match share_team_history(
        &connection,
        &workspace_id,
        &produced_at,
        args.confirm,
        args.limit,
        Some(&workspace_path),
    ) {
        Ok(report) => {
            let human = if report.confirmed {
                format!(
                    "History projected: {} new, {} already shared\n  team_id: {}\n  consent: {}\n",
                    report.projected_count,
                    report.skipped_count,
                    report.team_id,
                    report.consent_hash
                )
            } else {
                format!(
                    "History preview: {} candidates ({} already shared)\n  team_id: {}\n  consent: {}\nNext:\n  ee team share history --confirm --workspace .\n",
                    report.candidate_count,
                    report.skipped_count,
                    report.team_id,
                    report.consent_hash
                )
            };
            write_team_report(cli, &report, &human, stdout)
        }
        Err(error) => write_domain_error(
            &DomainError::Storage {
                message: format!("Failed to share team history: {error}"),
                repair: Some("ee team create --name \"<team>\" --workspace .".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

fn handle_team_share_bodies<W, E>(
    cli: &Cli,
    args: &TeamShareBodiesArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    let (connection, workspace_id) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    let produced_at = chrono::Utc::now().to_rfc3339();
    let workspace_path = cli.resolve_workspace();
    let stdin_token = if args.token_stdin {
        match crate::mesh::lane_grant::read_bounded_token(&mut std::io::stdin().lock()) {
            Ok(token) => Some(token.expose_bearer()),
            Err(error) => {
                return write_domain_error(
                    &DomainError::Usage {
                        message: format!("Failed to read bounded body token from stdin: {error}"),
                        repair: Some(
                            "ee team share bodies --confirm --token-stdin --workspace .".to_owned(),
                        ),
                    },
                    cli.wants_json(),
                    stdout,
                    stderr,
                );
            }
        }
    } else {
        None
    };
    match share_team_bodies_represented(
        &connection,
        &workspace_id,
        &produced_at,
        args.confirm,
        args.limit,
        Some(&workspace_path),
        args.issue_token,
        stdin_token.as_deref(),
        &args.representation,
    ) {
        Ok(report) => {
            let human = if report.confirmed {
                format!(
                    "Bodies published: {} new, {} already cached\n  team_id: {}\n  representation: {}\n  consent: {}\n",
                    report.published_count,
                    report.skipped_count,
                    report.team_id,
                    report.representation,
                    report.consent_hash
                )
            } else {
                format!(
                    "Body preview: {} candidates ({} already cached)\n  team_id: {}\n  representation: {}\n  consent: {}\nNext:\n  1. Request a bearer with ee team share bodies --issue-token --representation {} --workspace . --json\n  2. Review the same preview, then pipe its approvalToken to ee team share bodies --confirm --token-stdin --representation {} --workspace .\n",
                    report.candidate_count,
                    report.skipped_count,
                    report.team_id,
                    report.representation,
                    report.consent_hash,
                    report.representation,
                    report.representation
                )
            };
            write_team_report(cli, &report, &human, stdout)
        }
        Err(error) => write_domain_error(
            &DomainError::Storage {
                message: format!("Failed to share team bodies: {error}"),
                repair: Some("ee team share history --workspace . --json".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

fn handle_team_unshare_bodies<W, E>(
    cli: &Cli,
    args: &TeamUnshareBodiesArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    if !args.confirm {
        return write_domain_error(
            &DomainError::Storage {
                message: "Unshare bodies requires --confirm".to_owned(),
                repair: Some("ee team unshare bodies --confirm --workspace .".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        );
    }
    let (connection, workspace_id) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    let produced_at = chrono::Utc::now().to_rfc3339();
    match unshare_team_bodies(&connection, &workspace_id, &produced_at) {
        Ok(report) => write_team_report(
            cli,
            &report,
            &format!(
                "Unshared {} body cache row(s) (bytes not erased)\n  team_id: {}\n",
                report.published_count, report.team_id
            ),
            stdout,
        ),
        Err(error) => write_domain_error(
            &DomainError::Storage {
                message: format!("Failed to unshare team bodies: {error}"),
                repair: Some("ee team share bodies --workspace . --json".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

fn handle_team_members_list<W, E>(
    cli: &Cli,
    args: &TeamMembersListArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    handle_team_status(
        cli,
        &TeamStatusArgs {
            database: args.database.clone(),
        },
        stdout,
        stderr,
    )
}

fn handle_team_members_remove<W, E>(
    cli: &Cli,
    args: &TeamMembersRemoveArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    let (connection, workspace_id) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    let produced_at = chrono::Utc::now().to_rfc3339();
    let workspace_path = cli.resolve_workspace();
    match remove_team_member(
        &connection,
        &workspace_id,
        &args.member_id,
        &produced_at,
        Some(&workspace_path),
    ) {
        Ok(report) => write_team_report(
            cli,
            &report,
            &format!(
                "Member {} now {}\n  team_id: {}\n",
                report.member_id, report.state, report.team_id
            ),
            stdout,
        ),
        Err(error) => write_domain_error(
            &DomainError::Storage {
                message: format!("Failed to remove member: {error}"),
                repair: Some("ee team members list --workspace . --json".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

fn handle_team_members_add_node<W, E>(
    cli: &Cli,
    args: &TeamMembersAddNodeArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    let (connection, workspace_id) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    let produced_at = chrono::Utc::now().to_rfc3339();
    let workspace_path = cli.resolve_workspace();
    match add_local_team_node(
        &connection,
        &workspace_id,
        &produced_at,
        Some(&workspace_path),
    ) {
        Ok(report) => write_team_report(
            cli,
            &report,
            &format!(
                "Added node {}\n  team_id: {}\n",
                report.origin_node_id, report.team_id
            ),
            stdout,
        ),
        Err(error) => write_domain_error(
            &DomainError::Storage {
                message: format!("Failed to add node: {error}"),
                repair: Some("ee team create --name \"<team>\" --workspace .".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

fn handle_team_members_rotate_key<W, E>(
    cli: &Cli,
    args: &TeamMembersRotateKeyArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    let (connection, workspace_id) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    let produced_at = chrono::Utc::now().to_rfc3339();
    let workspace_path = cli.resolve_workspace();
    match rotate_local_signing_key(&connection, &workspace_id, &produced_at, &workspace_path) {
        Ok(report) => write_team_report(
            cli,
            &report,
            &format!(
                "Rotated signing key for {}\n  {}\n",
                report.origin_node_id, report.state
            ),
            stdout,
        ),
        Err(error) => write_domain_error(
            &DomainError::Storage {
                message: format!("Failed to rotate signing key: {error}"),
                repair: Some("ee team create --name \"<team>\" --workspace .".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

fn handle_team_members_reconcile<W, E>(
    cli: &Cli,
    args: &TeamMembersReconcileArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    let (connection, workspace_id) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    match reconcile_local_team_membership(&connection, &workspace_id) {
        Ok(report) => write_team_report(
            cli,
            &report,
            &format!(
                "Reconciled {}: {} addition(s), {} removal(s) from {} event(s)\n",
                report.team_id,
                report.applied_additions,
                report.applied_removals,
                report.inspected_events
            ),
            stdout,
        ),
        Err(error) => write_domain_error(
            &DomainError::Storage {
                message: format!("Failed to reconcile membership: {error}"),
                repair: Some("ee team status --workspace . --json".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

fn handle_team_leave<W, E>(
    cli: &Cli,
    args: &TeamLeaveArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    if !args.confirm {
        return write_domain_error(
            &DomainError::Storage {
                message: "Leave requires --confirm".to_owned(),
                repair: Some("ee team leave --confirm --workspace .".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        );
    }
    let (connection, workspace_id) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    let produced_at = chrono::Utc::now().to_rfc3339();
    let workspace_path = cli.resolve_workspace();
    match leave_local_team(
        &connection,
        &workspace_id,
        &produced_at,
        Some(&workspace_path),
    ) {
        Ok(report) => write_team_report(
            cli,
            &report,
            &format!("Left team {}\n", report.team_id),
            stdout,
        ),
        Err(error) => write_domain_error(
            &DomainError::Storage {
                message: format!("Failed to leave team: {error}"),
                repair: Some("ee team status --workspace . --json".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

fn handle_team_sync<W, E>(
    cli: &Cli,
    args: &TeamSyncArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    let (connection, _) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    match any_local_team_paused(&connection) {
        Ok(true) => {
            return write_domain_error(
                &DomainError::Storage {
                    message: "Team is paused".to_owned(),
                    repair: Some("ee team resume --confirm --workspace .".to_owned()),
                },
                cli.wants_json(),
                stdout,
                stderr,
            );
        }
        Ok(false) => {}
        Err(error) => {
            return write_domain_error(
                &DomainError::Storage {
                    message: format!("Failed to read team posture: {error}"),
                    repair: Some("ee team status --workspace . --json".to_owned()),
                },
                cli.wants_json(),
                stdout,
                stderr,
            );
        }
    }
    super::mesh::handle_mesh_sync(
        cli,
        &super::mesh::MeshSyncArgs {
            database: args.database.clone(),
            once: true,
            cadence_ms: 0,
            peer_concurrency: 1,
            body_fetch_budget_bytes: 65_536,
            stale_read_window_ms: 5_000,
            time_budget_ms: crate::mesh::foreground_cli::FOREGROUND_SYNC_TIME_BUDGET_MS,
        },
        stdout,
        stderr,
    )
}

fn handle_team_pause<W, E>(
    cli: &Cli,
    args: &TeamPauseArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    handle_team_posture(cli, args.database.as_deref(), true, stdout, stderr)
}

fn handle_team_resume<W, E>(
    cli: &Cli,
    args: &TeamResumeArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    if !args.confirm {
        return write_domain_error(
            &DomainError::Storage {
                message: "Resume requires --confirm".to_owned(),
                repair: Some("ee team resume --confirm --workspace .".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        );
    }
    handle_team_posture(cli, args.database.as_deref(), false, stdout, stderr)
}

fn resolve_team_activity_since(
    raw: Option<&str>,
    json: bool,
) -> Result<Option<String>, DomainError> {
    let Some(raw) = raw.map(str::trim).filter(|value| !value.is_empty()) else {
        return Ok(None);
    };
    if let Ok(stamp) = chrono::DateTime::parse_from_rfc3339(raw) {
        return Ok(Some(stamp.with_timezone(&chrono::Utc).to_rfc3339()));
    }
    if json {
        return Err(DomainError::Usage {
            message: "JSON --since must be an RFC 3339 timestamp.".to_owned(),
            repair: Some(
                "Use --since 2026-08-13T00:00:00Z. Relative durations such as 2h are human-only."
                    .to_owned(),
            ),
        });
    }
    let now = chrono::Utc::now();
    let resolved = parse_human_activity_since(raw, now)?;
    Ok(Some(resolved.to_rfc3339()))
}

fn parse_human_activity_since(
    raw: &str,
    now: chrono::DateTime<chrono::Utc>,
) -> Result<chrono::DateTime<chrono::Utc>, DomainError> {
    let trimmed = raw.trim().strip_prefix('+').unwrap_or(raw.trim());
    let usage = || DomainError::Usage {
        message: format!("since must be RFC 3339 or a relative duration such as 2h, not {raw:?}"),
        repair: Some("Use 2026-08-13T00:00:00Z, 2h, 30m, or 7d.".to_owned()),
    };
    let (amount, unit) = trimmed.split_at(trimmed.len().saturating_sub(1));
    let amount: i64 = amount.parse().map_err(|_| usage())?;
    if amount < 0 {
        return Err(usage());
    }
    let duration = match unit {
        "s" => chrono::Duration::seconds(amount),
        "m" => chrono::Duration::minutes(amount),
        "h" => chrono::Duration::hours(amount),
        "d" => chrono::Duration::days(amount),
        _ => return Err(usage()),
    };
    now.checked_sub_signed(duration).ok_or_else(usage)
}

fn handle_team_activity<W, E>(
    cli: &Cli,
    args: &TeamActivityArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    let (connection, workspace_id) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    let since = match resolve_team_activity_since(args.since.as_deref(), cli.wants_json()) {
        Ok(since) => since,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    match list_team_activity(
        &connection,
        &workspace_id,
        &args.as_of,
        args.limit,
        args.member.as_deref(),
        args.project.as_deref(),
        since.as_deref(),
        args.cursor.as_deref(),
    ) {
        Ok(report) => write_team_report(
            cli,
            &report,
            &format!(
                "Team activity {}: {} event(s) as-of {}{}\n",
                report.team_id,
                report.event_count,
                report.as_of,
                report
                    .since
                    .as_deref()
                    .map(|since| format!(" since {since}"))
                    .unwrap_or_default()
            ),
            stdout,
        ),
        Err(error) => write_domain_error(
            &DomainError::Storage {
                message: format!("Failed to list team activity: {error}"),
                repair: Some("ee team status --workspace . --json".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

fn handle_team_projects_share<W, E>(
    cli: &Cli,
    args: &TeamProjectsShareArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    let (connection, workspace_id) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    let produced_at = chrono::Utc::now().to_rfc3339();
    let workspace_path = cli.resolve_workspace();
    match share_team_project(
        &connection,
        &workspace_id,
        &args.name,
        &args.path,
        &produced_at,
        Some(&workspace_path),
    ) {
        Ok(report) => write_team_report(
            cli,
            &report,
            &format!(
                "{} project {}\n  team_id: {}\n",
                if report.minted { "Shared" } else { "Existing" },
                report
                    .projects
                    .first()
                    .map(|project| project.project_id.as_str())
                    .unwrap_or("unknown"),
                report.team_id
            ),
            stdout,
        ),
        Err(error) => write_domain_error(
            &DomainError::Storage {
                message: format!("Failed to share project: {error}"),
                repair: Some("ee team create --name \"<team>\" --workspace .".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

fn handle_team_projects_adopt<W, E>(
    cli: &Cli,
    args: &TeamProjectsAdoptArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    let (connection, _) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    let produced_at = chrono::Utc::now().to_rfc3339();
    match adopt_team_project(
        &connection,
        &args.project_id,
        &args.name,
        &args.path,
        &produced_at,
    ) {
        Ok(report) => write_team_report(
            cli,
            &report,
            &format!("Adopted {}\n  path: {}\n", args.project_id, args.path),
            stdout,
        ),
        Err(error) => write_domain_error(
            &DomainError::Storage {
                message: format!("Failed to adopt project: {error}"),
                repair: Some("ee team projects list --workspace . --json".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

fn handle_team_projects_list<W, E>(
    cli: &Cli,
    args: &TeamProjectsListArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    let (connection, _) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    match list_team_projects(&connection) {
        Ok(report) => write_team_report(
            cli,
            &report,
            &format!(
                "Team projects {}: {} project(s)\n",
                report.team_id, report.project_count
            ),
            stdout,
        ),
        Err(error) => write_domain_error(
            &DomainError::Storage {
                message: format!("Failed to list projects: {error}"),
                repair: Some("ee team create --name \"<team>\" --workspace .".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

fn handle_team_projects_reconcile<W, E>(
    cli: &Cli,
    args: &TeamProjectsReconcileArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    let (connection, _) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    match reconcile_local_team_projects(&connection) {
        Ok(report) => write_team_report(
            cli,
            &report,
            &format!(
                "Reconciled {} project row(s) from origin\n",
                report.applied_additions
            ),
            stdout,
        ),
        Err(error) => write_domain_error(
            &DomainError::Storage {
                message: format!("Failed to reconcile projects: {error}"),
                repair: Some("ee team create --name \"<team>\" --workspace .".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

fn handle_team_fetch_body<W, E>(
    cli: &Cli,
    args: &TeamFetchBodyArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    let (connection, workspace_id) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    let workspace_path = cli.resolve_workspace();
    let mut local =
        match fetch_local_team_body(&connection, &workspace_id, &workspace_path, &args.key) {
            Ok(report) => report,
            Err(error) => {
                return write_domain_error(
                    &DomainError::Storage {
                        message: format!("Failed to fetch team body: {error}"),
                        repair: Some("ee team share bodies --workspace . --json".to_owned()),
                    },
                    cli.wants_json(),
                    stdout,
                    stderr,
                );
            }
        };
    if local.body_hex.is_none() {
        let database = args
            .database
            .clone()
            .unwrap_or_else(|| workspace_path.join(".ee").join("ee.db"));
        let _ = crate::mesh::foreground_cli::fetch_pending_team_bodies_from_paths(
            &workspace_path,
            &database,
        );
        if let Ok(refreshed) =
            fetch_local_team_body(&connection, &workspace_id, &workspace_path, &args.key)
        {
            local = refreshed;
        }
    }
    let human = if local.body_hex.is_some() {
        format!(
            "Fetched {} ({} bytes)\n",
            local.body_cache_key, local.size_bytes
        )
    } else {
        format!("Body {} is {}\n", local.body_cache_key, local.cache_status)
    };
    write_team_report(cli, &local, &human, stdout)
}

fn handle_team_steward_run_once<W, E>(
    cli: &Cli,
    args: &TeamStewardRunOnceArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    let (connection, _) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    let workspace_path = cli.resolve_workspace();
    let plan = match execute_team_steward_once(&connection, Some(&workspace_path)) {
        Ok(plan) => plan,
        Err(error) => {
            return write_domain_error(
                &DomainError::Storage {
                    message: format!("Failed to run team steward: {error}"),
                    repair: Some("ee team status --workspace . --json".to_owned()),
                },
                cli.wants_json(),
                stdout,
                stderr,
            );
        }
    };
    if !plan.ran_sync {
        let database = args
            .database
            .clone()
            .unwrap_or_else(|| workspace_path.join(".ee").join("ee.db"));
        let _ = crate::mesh::foreground_cli::fetch_pending_team_bodies_from_paths(
            &workspace_path,
            &database,
        );
        return write_team_report(
            cli,
            &plan,
            &format!(
                "Steward {}: {} (sync skipped)\n  team_id: {}\n",
                plan.outcome, plan.reason, plan.team_id
            ),
            stdout,
        );
    }
    super::mesh::handle_mesh_sync(
        cli,
        &super::mesh::MeshSyncArgs {
            database: args.database.clone(),
            once: true,
            cadence_ms: 0,
            peer_concurrency: 1,
            body_fetch_budget_bytes: 65_536,
            stale_read_window_ms: 5_000,
            time_budget_ms: crate::mesh::foreground_cli::FOREGROUND_SYNC_TIME_BUDGET_MS,
        },
        stdout,
        stderr,
    )
}

fn handle_team_idp_require<W, E>(
    cli: &Cli,
    args: &TeamIdpRequireArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    if !args.tailnet_attested {
        return write_domain_error(
            &DomainError::Usage {
                message: "ee team idp require needs --tailnet-attested".to_owned(),
                repair: Some(
                    "ee team idp require --tailnet-attested [--domain acme.com] --workspace ."
                        .to_owned(),
                ),
            },
            cli.wants_json(),
            stdout,
            stderr,
        );
    }
    let (connection, workspace_id) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    let produced_at = chrono::Utc::now().to_rfc3339();
    let workspace_path = cli.resolve_workspace();
    match require_tailnet_attested(
        &connection,
        &workspace_id,
        args.domain.as_deref(),
        &produced_at,
        Some(&workspace_path),
    ) {
        Ok(report) => write_team_report(
            cli,
            &report,
            &format!(
                "Team IdP policy {} gen {}\n  team_id: {}\n  domain: {}\n",
                report.kind,
                report.policy_generation,
                report.team_id,
                report.allowed_domain.as_deref().unwrap_or("<any>")
            ),
            stdout,
        ),
        Err(error) => write_domain_error(
            &DomainError::Storage {
                message: format!("Failed to require tailnet-attested identity: {error}"),
                repair: Some("ee team create --name \"<team>\" --workspace .".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

fn handle_team_idp_status<W, E>(
    cli: &Cli,
    args: &TeamIdpStatusArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    let (connection, _) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    match team_idp_status(&connection) {
        Ok(report) => write_team_report(
            cli,
            &report,
            &format!(
                "Team IdP policy {} gen {}\n  team_id: {}\n  domain: {}\n",
                report.kind,
                report.policy_generation,
                report.team_id,
                report.allowed_domain.as_deref().unwrap_or("<any>")
            ),
            stdout,
        ),
        Err(error) => write_domain_error(
            &DomainError::Storage {
                message: format!("Failed to read team IdP policy: {error}"),
                repair: Some("ee team create --name \"<team>\" --workspace .".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

fn handle_team_idp_set<W, E>(
    cli: &Cli,
    args: &TeamIdpSetArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    let (connection, _) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    let bytes = match std::fs::read(&args.discovery_json) {
        Ok(bytes) => bytes,
        Err(error) => {
            return write_domain_error(
                &DomainError::Usage {
                    message: format!("Failed to read discovery JSON: {error}"),
                    repair: Some(
                        "ee team idp set --issuer https://idp.example --client-id <id> --discovery-json <file> --workspace ."
                            .to_owned(),
                    ),
                },
                cli.wants_json(),
                stdout,
                stderr,
            );
        }
    };
    let discovery = match serde_json::from_slice(&bytes) {
        Ok(value) => value,
        Err(error) => {
            return write_domain_error(
                &DomainError::Usage {
                    message: format!("Discovery JSON is malformed: {error}"),
                    repair: Some(
                        "provide a local OpenID discovery document; ee does not fetch it"
                            .to_owned(),
                    ),
                },
                cli.wants_json(),
                stdout,
                stderr,
            );
        }
    };
    let set_at = chrono::Utc::now().to_rfc3339();
    match set_team_oidc_provider(
        &connection,
        &args.issuer,
        &args.client_id,
        &discovery,
        &set_at,
    ) {
        Ok(report) => write_team_report(
            cli,
            &report,
            &format!(
                "Team OIDC provider {} ({})\n  team_id: {}\n",
                report.issuer, report.capability, report.team_id
            ),
            stdout,
        ),
        Err(error) => write_domain_error(
            &DomainError::Storage {
                message: format!("Failed to pin OIDC provider: {error}"),
                repair: Some(
                    "ee team idp set --issuer https://idp.example --client-id <id> --discovery-json <file> --workspace ."
                        .to_owned(),
                ),
            },
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

fn handle_team_idp_device<W, E>(
    cli: &Cli,
    args: &TeamIdpDeviceArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    let (connection, _) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    let discovery = match read_json_file(&args.discovery_json) {
        Ok(value) => value,
        Err(error) => {
            return write_domain_error(&error, cli.wants_json(), stdout, stderr);
        }
    };
    let authorization = match read_json_file(&args.authorization_json) {
        Ok(value) => value,
        Err(error) => {
            return write_domain_error(&error, cli.wants_json(), stdout, stderr);
        }
    };
    if args.execute {
        let ca_bundle = args
            .ca_bundle
            .as_ref()
            .map(|path| path.to_string_lossy().into_owned());
        return match execute_team_idp_token_poll(
            &connection,
            &discovery,
            &authorization,
            &args.curl.to_string_lossy(),
            ca_bundle.as_deref(),
        ) {
            Ok(report) => write_team_report(
                cli,
                &report,
                &format!(
                    "Team device poll {}\n  uri: {}\n  exit: {}\n",
                    report.user_code, report.verification_uri, report.curl_exit_code
                ),
                stdout,
            ),
            Err(error) => write_domain_error(
                &DomainError::Storage {
                    message: format!("Failed to execute device poll: {error}"),
                    repair: Some(
                        "ee team idp set then ee team idp device --execute --workspace ."
                            .to_owned(),
                    ),
                },
                cli.wants_json(),
                stdout,
                stderr,
            ),
        };
    }
    match plan_team_idp_device(
        &connection,
        &discovery,
        &authorization,
        &args.curl.to_string_lossy(),
    ) {
        Ok(report) => write_team_report(
            cli,
            &report,
            &format!(
                "Team device ceremony {}\n  uri: {}\n  wait: {}s\n",
                report.user_code,
                report
                    .verification_uri_complete
                    .as_deref()
                    .unwrap_or(&report.verification_uri),
                report.first_wait_secs
            ),
            stdout,
        ),
        Err(error) => write_domain_error(
            &DomainError::Storage {
                message: format!("Failed to plan device ceremony: {error}"),
                repair: Some(
                    "ee team idp device --discovery-json <file> --authorization-json <file> --workspace ."
                        .to_owned(),
                ),
            },
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

fn handle_team_idp_attest<W, E>(
    cli: &Cli,
    args: &TeamIdpAttestArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    let (connection, _) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    let token = if args.id_token == "-" {
        match read_bounded_id_token_from_stdin() {
            Ok(token) => token,
            Err(error) => {
                return write_domain_error(
                    &DomainError::Usage {
                        message: format!("Failed to read id token from stdin: {error}"),
                        repair: Some(
                            "ee team idp attest --id-token - --discovery-json <file> --workspace ."
                                .to_owned(),
                        ),
                    },
                    cli.wants_json(),
                    stdout,
                    stderr,
                );
            }
        }
    } else {
        args.id_token.clone()
    };
    let groups = args.groups.iter().map(String::as_str).collect::<Vec<_>>();
    let checked_at = chrono::Utc::now().to_rfc3339();
    let discovery = match read_json_file(&args.discovery_json) {
        Ok(value) => value,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    let jwks_url = match pinned_team_jwks_uri(&connection, &discovery) {
        Ok(url) => url,
        Err(error) => {
            return write_domain_error(
                &DomainError::Storage {
                    message: format!("Failed to authorize JWKS endpoint: {error}"),
                    repair: Some(
                        "ee team idp set --issuer <https-url> --client-id <id> --discovery-json <file> --workspace ."
                            .to_owned(),
                    ),
                },
                cli.wants_json(),
                stdout,
                stderr,
            );
        }
    };
    let ca = args
        .ca_bundle
        .as_ref()
        .map(|path| path.to_string_lossy().into_owned());
    let jwks =
        match crate::mesh::idp::fetch_jwks_document("/usr/bin/curl", &jwks_url, ca.as_deref()) {
            Ok(value) => value,
            Err(error) => {
                return write_domain_error(
                    &DomainError::Usage {
                        message: format!("Failed to fetch configured JWKS: {error}"),
                        repair: Some(
                            "verify the pinned discovery jwks_uri and --ca-bundle, then retry"
                                .to_owned(),
                        ),
                    },
                    cli.wants_json(),
                    stdout,
                    stderr,
                );
            }
        };
    match attest_local_id_token(
        &connection,
        token.trim(),
        &groups,
        &checked_at,
        &discovery,
        &jwks,
    ) {
        Ok(report) => write_team_report(
            cli,
            &report,
            &format!(
                "Team identity attested\n  member: {}\n  subject: {}\n",
                report.member_id, report.subject
            ),
            stdout,
        ),
        Err(error) => write_domain_error(
            &DomainError::Storage {
                message: format!("Failed to attest identity: {error}"),
                repair: Some(
                    "ee team idp attest --id-token - --discovery-json <file> --workspace ."
                        .to_owned(),
                ),
            },
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

fn read_json_file(path: &std::path::Path) -> Result<serde_json::Value, DomainError> {
    let bytes = std::fs::read(path).map_err(|error| DomainError::Usage {
        message: format!("Failed to read {}: {error}", path.display()),
        repair: Some("pass a local JSON file; ee does not fetch IdP HTTP".to_owned()),
    })?;
    serde_json::from_slice(&bytes).map_err(|error| DomainError::Usage {
        message: format!("JSON is malformed: {error}"),
        repair: Some("pass a local JSON file; ee does not fetch IdP HTTP".to_owned()),
    })
}

fn handle_team_members_revalidate<W, E>(
    cli: &Cli,
    args: &TeamMembersRevalidateArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    let (connection, _) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    let report = probe_local_tailscale_for_team();
    let checked_at = chrono::Utc::now().to_rfc3339();
    match revalidate_team_identities(&connection, &report, &checked_at) {
        Ok(result) => write_team_report(
            cli,
            &result,
            &format!(
                "Team identity revalidate: {} checked, {} attested, {} suspended, {} missing\n  team_id: {}\n",
                result.checked, result.attested, result.suspended, result.missing, result.team_id
            ),
            stdout,
        ),
        Err(error) => write_domain_error(
            &DomainError::Storage {
                message: format!("Failed to revalidate team identities: {error}"),
                repair: Some("ee team idp require --tailnet-attested --workspace .".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

fn probe_local_tailscale_for_team() -> crate::core::tailscale_probe::TailscaleLocalReport {
    use crate::core::tailscale_probe::{
        SystemTailscaleCliProbeRunner, SystemTailscaleSocketProbeRunner, TailscaleCliProbeConfig,
        TailscaleSocketProbeConfig, probe_tailscale_local_with_runners,
    };
    let mut socket_config = TailscaleSocketProbeConfig::mesh_enabled();
    let mut cli_config = TailscaleCliProbeConfig::mesh_enabled();
    socket_config.platform_hint =
        crate::core::tailscale_probe::TailscalePlatform::parse(Some(std::env::consts::OS));
    cli_config.platform_hint = socket_config.platform_hint;
    let mut socket_runner = SystemTailscaleSocketProbeRunner;
    let mut cli_runner = SystemTailscaleCliProbeRunner;
    probe_tailscale_local_with_runners(
        &socket_config,
        &cli_config,
        &mut socket_runner,
        &mut cli_runner,
    )
}

fn handle_team_credentials_backup<W, E>(
    cli: &Cli,
    args: &TeamCredentialsBackupArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    if !args.passphrase_stdin {
        return write_domain_error(
            &DomainError::Usage {
                message: "Passphrase must be read from stdin via --passphrase-stdin.".to_owned(),
                repair: Some(
                    "printf '%s\\n' \"$PASSPHRASE\" | ee team credentials backup --passphrase-stdin --workspace ."
                        .to_owned(),
                ),
            },
            cli.wants_json(),
            stdout,
            stderr,
        );
    }
    let passphrase = match read_invite_code_from_stdin() {
        Ok(value) => value,
        Err(error) => {
            return write_domain_error(
                &DomainError::Usage {
                    message: format!("Failed to read passphrase from stdin: {error}"),
                    repair: Some(
                        "printf '%s\\n' \"$PASSPHRASE\" | ee team credentials backup --passphrase-stdin --workspace ."
                            .to_owned(),
                    ),
                },
                cli.wants_json(),
                stdout,
                stderr,
            );
        }
    };
    let workspace_path = cli.resolve_workspace();
    let (output_dir, file_name) =
        match resolve_credential_backup_output(&workspace_path, args.output.as_deref()) {
            Ok(resolved) => resolved,
            Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
        };
    let created_at = chrono::Utc::now().to_rfc3339();
    match crate::mesh::credential_backup::backup_workspace_credentials(
        &workspace_path,
        &output_dir,
        &file_name,
        &passphrase,
        args.overwrite,
        &created_at,
    ) {
        Ok(report) => {
            let human = format!(
                "Credential backup written\n  path: {}\n  pair_slots: {}\n  signing_slots: {}\n  store_present: {}\n",
                report.path, report.pair_count, report.signing_count, report.store_present
            );
            write_team_report(cli, &report, &human, stdout)
        }
        Err(error) => write_domain_error(
            &credential_backup_domain_error(error),
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

fn handle_team_credentials_restore<W, E>(
    cli: &Cli,
    args: &TeamCredentialsRestoreArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    if !args.passphrase_stdin {
        return write_domain_error(
            &DomainError::Usage {
                message: "Passphrase must be read from stdin via --passphrase-stdin.".to_owned(),
                repair: Some(
                    "printf '%s\\n' \"$PASSPHRASE\" | ee team credentials restore --input <path> --passphrase-stdin --workspace ."
                        .to_owned(),
                ),
            },
            cli.wants_json(),
            stdout,
            stderr,
        );
    }
    let passphrase = match read_invite_code_from_stdin() {
        Ok(value) => value,
        Err(error) => {
            return write_domain_error(
                &DomainError::Usage {
                    message: format!("Failed to read passphrase from stdin: {error}"),
                    repair: Some(
                        "printf '%s\\n' \"$PASSPHRASE\" | ee team credentials restore --input <path> --passphrase-stdin --workspace ."
                            .to_owned(),
                    ),
                },
                cli.wants_json(),
                stdout,
                stderr,
            );
        }
    };
    let workspace_path = cli.resolve_workspace();
    let created_at = chrono::Utc::now().to_rfc3339();
    match crate::mesh::credential_backup::restore_workspace_credentials(
        &workspace_path,
        &args.input,
        &passphrase,
        args.overwrite,
        &created_at,
    ) {
        Ok(report) => {
            let human = format!(
                "Credential backup restored\n  path: {}\n  pair_slots: {}\n  signing_slots: {}\n  overwrite: {}\n",
                report.path, report.pair_count, report.signing_count, report.overwrite
            );
            write_team_report(cli, &report, &human, stdout)
        }
        Err(error) => write_domain_error(
            &credential_backup_domain_error(error),
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

fn resolve_credential_backup_output(
    workspace_path: &std::path::Path,
    output: Option<&std::path::Path>,
) -> Result<(PathBuf, String), DomainError> {
    let default_dir = crate::mesh::credential_backup::mesh_credential_backup_dir(workspace_path);
    let default_name =
        crate::mesh::credential_backup::DEFAULT_CREDENTIAL_BACKUP_FILE_NAME.to_owned();
    let Some(output) = output else {
        return Ok((default_dir, default_name));
    };
    let absolute = if output.is_absolute() {
        output.to_path_buf()
    } else {
        std::env::current_dir()
            .map_err(|error| DomainError::Usage {
                message: format!("Failed to resolve backup output path: {error}"),
                repair: Some("Pass an absolute --output path under the workspace.".to_owned()),
            })?
            .join(output)
    };
    let (dir, name) = if absolute.is_dir()
        || output
            .as_os_str()
            .to_string_lossy()
            .ends_with(std::path::MAIN_SEPARATOR)
    {
        (absolute, default_name)
    } else {
        let name = absolute
            .file_name()
            .and_then(|value| value.to_str())
            .ok_or_else(|| DomainError::Usage {
                message: "Backup output file name is not valid UTF-8.".to_owned(),
                repair: Some("Use a file name such as credentials.backup.v1.json.".to_owned()),
            })?
            .to_owned();
        let dir = absolute
            .parent()
            .map_or_else(|| workspace_path.to_path_buf(), PathBuf::from);
        (dir, name)
    };
    if dir.strip_prefix(workspace_path).is_err() {
        return Err(DomainError::Usage {
            message: format!(
                "Credential backup output {} is outside the workspace {}",
                dir.display(),
                workspace_path.display()
            ),
            repair: Some(
                "Write the encrypted envelope under the workspace (default: .ee/keys/mesh-credential-backup/), then copy the file if you need it elsewhere.".to_owned(),
            ),
        });
    }
    Ok((dir, name))
}

fn credential_backup_domain_error(
    error: crate::mesh::credential_backup::CredentialBackupError,
) -> DomainError {
    use crate::mesh::credential_backup::CredentialBackupError;
    match error {
        CredentialBackupError::Passphrase { message } => DomainError::Usage {
            message,
            repair: Some(
                "Use a passphrase of at least 12 characters on stdin via --passphrase-stdin."
                    .to_owned(),
            ),
        },
        CredentialBackupError::Conflict { message } => DomainError::Usage {
            message,
            repair: Some(
                "ee team credentials restore --input <path> --passphrase-stdin --overwrite --workspace ."
                    .to_owned(),
            ),
        },
        CredentialBackupError::Crypto { message }
        | CredentialBackupError::Malformed { message } => DomainError::Usage {
            message,
            repair: Some(
                "Confirm the passphrase and that the file is an ee.mesh.credentials.backup.v1 envelope."
                    .to_owned(),
            ),
        },
        CredentialBackupError::Io { path, message } => DomainError::Storage {
            message: format!("Credential backup I/O failed at {path}: {message}"),
            repair: Some("ee team doctor --workspace . --json".to_owned()),
        },
        CredentialBackupError::KeyStore(error) => DomainError::Storage {
            message: error.message(),
            repair: Some(error.repair()),
        },
    }
}

fn handle_team_doctor<W, E>(
    cli: &Cli,
    args: &TeamDoctorArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    let (connection, workspace_id) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    let workspace_path = cli.resolve_workspace();
    match inspect_team_health(&connection, &workspace_id, Some(&workspace_path)) {
        Ok(report) => write_team_report(
            cli,
            &report,
            &format!(
                "Team doctor {}: {} check(s)\n",
                report.posture,
                report.checks.len()
            ),
            stdout,
        ),
        Err(error) => write_domain_error(
            &DomainError::Storage {
                message: format!("Failed to inspect team health: {error}"),
                repair: Some("ee team status --workspace . --json".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

fn handle_team_port_show<W, E>(
    cli: &Cli,
    args: &TeamPortShowArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    let (connection, _) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    match inspect_team_port(&connection) {
        Ok(report) => {
            let previous = report
                .previous_hello_port
                .map_or_else(|| "none".to_owned(), |port| port.to_string());
            write_team_report(
                cli,
                &report,
                &format!(
                    "Team hello port\n  team_id: {}\n  current: {}\n  genesis: {}\n  previous: {previous}\n  generation: {}\n  genesis_event_hash: {}\n  configured: {}\n",
                    report.team_id,
                    report.current_hello_port,
                    report.genesis_hello_port,
                    report.port_generation,
                    report.genesis_event_hash,
                    report.configured_hello_port,
                ),
                stdout,
            )
        }
        Err(error) => write_domain_error(
            &DomainError::Storage {
                message: format!("Failed to inspect team hello port: {error}"),
                repair: Some("ee team create --name \"<team>\" --workspace .".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

fn handle_team_port_migrate<W, E>(
    cli: &Cli,
    args: &TeamPortMigrateArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    if !args.confirm {
        return write_domain_error(
            &DomainError::Usage {
                message: "Port migrate requires --confirm".to_owned(),
                repair: Some(format!(
                    "ee team port migrate --to {} --confirm --workspace .",
                    args.to
                )),
            },
            cli.wants_json(),
            stdout,
            stderr,
        );
    }
    let (connection, workspace_id) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    let produced_at = chrono::Utc::now().to_rfc3339();
    let workspace_path = cli.resolve_workspace();
    match migrate_local_team_port(
        &connection,
        &workspace_id,
        args.to,
        &produced_at,
        Some(workspace_path.as_path()),
    ) {
        Ok(report) => {
            let previous = report
                .previous_hello_port
                .map_or_else(|| "none".to_owned(), |port| port.to_string());
            write_team_report(
                cli,
                &report,
                &format!(
                    "Team hello port migrated\n  team_id: {}\n  current: {}\n  previous: {previous}\n  generation: {}\n  genesis_event_hash: {}\n  peer_endpoints_rewritten: {}\n  pair_keys_unchanged: {}\n  grants_unchanged: {}\nNext:\n  ee mesh hello-responder run --workspace .\n  # unset EE_MESH_HELLO_PORT if it still pins the previous port; --port and the env var win over the folded team port\n",
                    report.team_id,
                    report.current_hello_port,
                    report.port_generation,
                    report.genesis_event_hash,
                    report.peer_endpoints_rewritten,
                    report.pair_keys_unchanged,
                    report.grants_unchanged,
                ),
                stdout,
            )
        }
        Err(error) => write_domain_error(
            &DomainError::Storage {
                message: format!("Failed to migrate team hello port: {error}"),
                repair: Some(format!(
                    "ee team port show --workspace . --json; ee team port migrate --to {} --confirm --workspace .",
                    args.to
                )),
            },
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

fn handle_team_posture<W, E>(
    cli: &Cli,
    database: Option<&std::path::Path>,
    paused: bool,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    let (connection, _) = match open_team_store(cli, database) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    let updated_at = chrono::Utc::now().to_rfc3339();
    match set_local_team_paused(&connection, paused, &updated_at) {
        Ok(report) => write_team_report(
            cli,
            &report,
            &format!(
                "Team {} (generation {})\n  team_id: {}\n",
                if report.paused { "paused" } else { "resumed" },
                report.pause_generation,
                report.team_id
            ),
            stdout,
        ),
        Err(error) => write_domain_error(
            &DomainError::Storage {
                message: format!("Failed to update team posture: {error}"),
                repair: Some("ee team create --name \"<team>\" --workspace .".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

fn handle_team_join<W, E>(
    cli: &Cli,
    args: &TeamJoinArgs,
    stdout: &mut W,
    stderr: &mut E,
) -> ProcessExitCode
where
    W: Write,
    E: Write,
{
    let (connection, workspace_id) = match open_team_store(cli, args.database.as_deref()) {
        Ok(opened) => opened,
        Err(error) => return write_domain_error(&error, cli.wants_json(), stdout, stderr),
    };
    let produced_at = chrono::Utc::now().to_rfc3339();
    let invite_code = if args.invite_stdin {
        match read_invite_code_from_stdin() {
            Ok(code) => code,
            Err(error) => {
                return write_domain_error(
                    &DomainError::Storage {
                        message: format!("Failed to read invite from stdin: {error}"),
                        repair: Some("ee team join --invite-stdin --workspace .".to_owned()),
                    },
                    cli.wants_json(),
                    stdout,
                    stderr,
                );
            }
        }
    } else {
        args.invite.clone().unwrap_or_default()
    };
    if invite_code.is_empty() {
        return write_domain_error(
            &DomainError::Storage {
                message: "Join needs --invite or --invite-stdin".to_owned(),
                repair: Some("ee team join --invite-stdin --workspace .".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        );
    }
    let workspace_path = cli.resolve_workspace();
    match join_team_with_code_on_store(
        &connection,
        &workspace_id,
        &invite_code,
        &args.name,
        &produced_at,
        std::time::Duration::from_secs(10),
        Some(&workspace_path),
    ) {
        Ok(report) => {
            let human = format!(
                "Joined {}: {}\n  team_id: {}\n  origin_node_id: {}\n  first_sync: {}\nNext:\n  ee team status --workspace . --json\n  ee mesh hello-responder run --workspace . --json\n  ee mesh sync --once --workspace . --json\n",
                report.team.display_name,
                if report.joined { "ok" } else { "already local" },
                report.team.team_id,
                report.team.origin_node_id,
                if report.first_sync.complete {
                    format!("{} events", report.first_sync.imported_events)
                } else {
                    "incomplete — run ee mesh sync --once".to_owned()
                }
            );
            write_team_report(cli, &report, &human, stdout)
        }
        Err(error) => write_domain_error(
            &DomainError::Storage {
                message: format!("Failed to join team: {error}"),
                repair: Some("ee mesh hello-responder run --workspace .".to_owned()),
            },
            cli.wants_json(),
            stdout,
            stderr,
        ),
    }
}

#[cfg(unix)]
struct StdinEchoGuard;

#[cfg(unix)]
impl Drop for StdinEchoGuard {
    fn drop(&mut self) {
        let _ = std::process::Command::new("stty").arg("echo").status();
    }
}

fn read_invite_code_from_stdin() -> Result<String, String> {
    let tty = std::io::IsTerminal::is_terminal(&std::io::stdin());
    #[cfg(unix)]
    let _guard = if tty {
        std::process::Command::new("stty")
            .arg("-echo")
            .status()
            .map_err(|error| format!("disable stdin echo: {error}"))?;
        Some(StdinEchoGuard)
    } else {
        None
    };
    let mut raw = String::new();
    std::io::stdin()
        .read_line(&mut raw)
        .map_err(|error| error.to_string())?;
    if tty {
        let _ = writeln!(std::io::stderr());
    }
    Ok(raw.trim().to_owned())
}

fn read_bounded_id_token_from_stdin() -> Result<String, String> {
    const MAX_ID_TOKEN_INPUT_BYTES: usize = 64 * 1024;

    let tty = std::io::IsTerminal::is_terminal(&std::io::stdin());
    #[cfg(unix)]
    let _guard = if tty {
        std::process::Command::new("stty")
            .arg("-echo")
            .status()
            .map_err(|error| format!("disable stdin echo: {error}"))?;
        Some(StdinEchoGuard)
    } else {
        None
    };
    let stdin = std::io::stdin();
    let mut reader = stdin.lock();
    let mut bytes = Vec::with_capacity(4096);
    loop {
        let available = reader.fill_buf().map_err(|error| error.to_string())?;
        if available.is_empty() {
            break;
        }
        let consumed = available
            .iter()
            .position(|byte| *byte == b'\n')
            .map_or(available.len(), |index| index.saturating_add(1));
        if bytes.len().saturating_add(consumed) > MAX_ID_TOKEN_INPUT_BYTES {
            return Err(format!(
                "id token exceeds the {MAX_ID_TOKEN_INPUT_BYTES}-byte input limit"
            ));
        }
        bytes.extend_from_slice(&available[..consumed]);
        let found_newline = available.get(consumed.saturating_sub(1)) == Some(&b'\n');
        reader.consume(consumed);
        if found_newline {
            break;
        }
    }
    if tty {
        let _ = writeln!(std::io::stderr());
    }
    String::from_utf8(bytes)
        .map(|raw| raw.trim().to_owned())
        .map_err(|_| "id token input must be UTF-8".to_owned())
}

fn parse_stdin_sentinel(value: &str) -> Result<String, String> {
    if value == "-" {
        Ok(value.to_owned())
    } else {
        Err("pass '-' and provide sensitive token material on stdin".to_owned())
    }
}

fn open_team_store(
    cli: &Cli,
    database: Option<&std::path::Path>,
) -> Result<(DbConnection, String), DomainError> {
    let workspace_path = cli.resolve_workspace();
    let database_path = database
        .map(PathBuf::from)
        .unwrap_or_else(|| workspace_path.join(".ee").join("ee.db"));
    if !database_path.exists() {
        return Err(DomainError::Storage {
            message: format!("Workspace store is missing at {}", database_path.display()),
            repair: Some("ee init --workspace .".to_owned()),
        });
    }
    let connection =
        DbConnection::open_file(&database_path).map_err(|error| DomainError::Storage {
            message: format!("Failed to open team database: {error}"),
            repair: Some("ee doctor --json".to_owned()),
        })?;
    let workspace_id =
        crate::mesh::foreground_cli::resolve_store_workspace_id(&connection, &workspace_path)
            .map_err(|error| DomainError::Storage {
                message: format!("Failed to resolve team workspace: {error}"),
                repair: Some("ee doctor --json".to_owned()),
            })?;
    Ok((connection, workspace_id))
}

const MEMBER_REACHABILITY_SELF: &str = "self";
const MEMBER_REACHABILITY_NEVER_SYNCED: &str = "never_synced";
const MEMBER_REACHABILITY_SYNCED: &str = "synced";
const MEMBER_REACHABILITY_SOFT_STALE: &str = "soft_stale";
const MEMBER_REACHABILITY_HARD_STALE: &str = "hard_stale";

#[derive(Clone, Debug, Eq, PartialEq)]
struct TeamMemberFreshness {
    last_seen_at: Option<String>,
    reachability: &'static str,
}

fn collect_team_member_freshness(
    connection: &DbConnection,
    members: &[TeamMemberRecord],
    as_of: chrono::DateTime<chrono::Utc>,
) -> Vec<TeamMemberFreshness> {
    let thresholds = MeshDriftThresholds::default();
    members
        .iter()
        .map(|member| {
            let last_seen_at = if member.is_self {
                None
            } else {
                latest_peer_last_seen(connection, &member.workspace_id, &member.origin_node_id)
            };
            TeamMemberFreshness {
                reachability: classify_team_member_reachability(
                    member.is_self,
                    last_seen_at.as_deref(),
                    as_of,
                    thresholds,
                ),
                last_seen_at,
            }
        })
        .collect()
}

fn latest_peer_last_seen(
    connection: &DbConnection,
    workspace_id: &str,
    origin_node_id: &str,
) -> Option<String> {
    let peers = connection.list_mesh_peers(workspace_id).ok()?;
    peers
        .into_iter()
        .filter(|peer| {
            peer.origin_node_id == origin_node_id && !peer.last_seen_at.trim().is_empty()
        })
        .max_by(|left, right| last_seen_ord(&left.last_seen_at, &right.last_seen_at))
        .map(|peer| peer.last_seen_at)
}

fn last_seen_ord(left: &str, right: &str) -> std::cmp::Ordering {
    match (parse_rfc3339_utc(left), parse_rfc3339_utc(right)) {
        (Some(left), Some(right)) => left.cmp(&right),
        (Some(_), None) => std::cmp::Ordering::Greater,
        (None, Some(_)) => std::cmp::Ordering::Less,
        (None, None) => left.cmp(right),
    }
}

fn classify_team_member_reachability(
    is_self: bool,
    last_seen_at: Option<&str>,
    as_of: chrono::DateTime<chrono::Utc>,
    thresholds: MeshDriftThresholds,
) -> &'static str {
    if is_self {
        return MEMBER_REACHABILITY_SELF;
    }
    let Some(seen) = last_seen_at.and_then(parse_rfc3339_utc) else {
        return MEMBER_REACHABILITY_NEVER_SYNCED;
    };
    let elapsed = as_of.signed_duration_since(seen).num_seconds();
    if elapsed < 0 {
        return MEMBER_REACHABILITY_SYNCED;
    }
    let elapsed = u64::try_from(elapsed).unwrap_or(u64::MAX);
    if elapsed >= thresholds.hard_stale_after_seconds {
        MEMBER_REACHABILITY_HARD_STALE
    } else if elapsed >= thresholds.soft_stale_after_seconds {
        MEMBER_REACHABILITY_SOFT_STALE
    } else {
        MEMBER_REACHABILITY_SYNCED
    }
}

fn parse_rfc3339_utc(value: &str) -> Option<chrono::DateTime<chrono::Utc>> {
    chrono::DateTime::parse_from_rfc3339(value)
        .ok()
        .map(|stamp| stamp.with_timezone(&chrono::Utc))
}

fn render_team_status_human(
    report: &TeamStatusReport,
    freshness: &[TeamMemberFreshness],
    as_of: chrono::DateTime<chrono::Utc>,
) -> String {
    if report.teams.is_empty() {
        return "No local team genesis recorded.\nNext:\n  ee team create --name \"<team>\" --workspace . --json\n"
            .to_owned();
    }
    let mut lines = vec![format!("Teams: {}", report.team_count)];
    for team in &report.teams {
        lines.push(format!(
            "  {} ({}) port {} genesis {}",
            team.display_name, team.team_id, team.hello_port, team.genesis_event_id
        ));
    }
    if !report.members.is_empty() {
        lines.push(format!("Members: {}", report.members.len()));
        for (member, fresh) in report.members.iter().zip(freshness.iter()) {
            let role = if member.is_self { "self" } else { "peer" };
            let mut line = format!(
                "  {} ({}) {} {}",
                member.display_name, member.member_id, member.bound_via, role
            );
            if let Some(label) = human_member_freshness_label(
                fresh.reachability,
                fresh.last_seen_at.as_deref(),
                as_of,
            ) {
                line.push_str(" · ");
                line.push_str(&label);
            }
            lines.push(line);
        }
    }
    if !report.nodes.is_empty() {
        lines.push(format!("Nodes: {}", report.nodes.len()));
        for node in &report.nodes {
            lines.push(format!(
                "  {} gen {} {}",
                node.node_id, node.signing_key_generation, node.state
            ));
        }
    }
    lines.join("\n") + "\n"
}

fn human_member_freshness_label(
    reachability: &str,
    last_seen_at: Option<&str>,
    as_of: chrono::DateTime<chrono::Utc>,
) -> Option<String> {
    match reachability {
        MEMBER_REACHABILITY_SELF => None,
        MEMBER_REACHABILITY_NEVER_SYNCED => Some("never synced".to_owned()),
        MEMBER_REACHABILITY_SYNCED => Some(format!(
            "synced {} ago",
            human_age_since(last_seen_at, as_of)
        )),
        MEMBER_REACHABILITY_SOFT_STALE => {
            Some(format!("stale {}", human_age_since(last_seen_at, as_of)))
        }
        MEMBER_REACHABILITY_HARD_STALE => Some(format!(
            "unreachable {}",
            human_age_since(last_seen_at, as_of)
        )),
        _ => None,
    }
}

fn human_age_since(last_seen_at: Option<&str>, as_of: chrono::DateTime<chrono::Utc>) -> String {
    let Some(seen) = last_seen_at.and_then(parse_rfc3339_utc) else {
        return "unknown".to_owned();
    };
    let elapsed = as_of.signed_duration_since(seen).num_seconds().max(0);
    let elapsed = u64::try_from(elapsed).unwrap_or(0);
    if elapsed < 60 {
        format!("{elapsed}s")
    } else if elapsed < 3_600 {
        format!("{}m", elapsed / 60)
    } else if elapsed < 86_400 {
        format!("{}h", elapsed / 3_600)
    } else {
        format!("{}d", elapsed / 86_400)
    }
}

fn inject_team_member_freshness(
    report: &TeamStatusReport,
    freshness: &[TeamMemberFreshness],
) -> Result<serde_json::Value, serde_json::Error> {
    let mut data = serde_json::to_value(report)?;
    let Some(members) = data
        .get_mut("members")
        .and_then(serde_json::Value::as_array_mut)
    else {
        return Ok(data);
    };
    for (member, fresh) in members.iter_mut().zip(freshness.iter()) {
        let Some(object) = member.as_object_mut() else {
            continue;
        };
        if let Some(last_seen_at) = fresh.last_seen_at.as_deref() {
            object.insert("lastSeenAt".to_owned(), json!(last_seen_at));
        }
        object.insert("reachability".to_owned(), json!(fresh.reachability));
    }
    Ok(data)
}

fn write_team_report<W, T>(
    cli: &Cli,
    report: &T,
    human_output: &str,
    stdout: &mut W,
) -> ProcessExitCode
where
    W: Write,
    T: serde::Serialize,
{
    match cli.renderer() {
        output::Renderer::Human | output::Renderer::Markdown => write_stdout(stdout, human_output),
        output::Renderer::Toon => {
            let data = match serde_json::to_value(report) {
                Ok(data) => data,
                Err(error) => {
                    return write_stdout(
                        stdout,
                        &format!("error: failed to serialize team report: {error}\n"),
                    );
                }
            };
            write_stdout(
                stdout,
                &(output::render_toon_from_json(&data.to_string()) + "\n"),
            )
        }
        output::Renderer::Json
        | output::Renderer::Jsonl
        | output::Renderer::Compact
        | output::Renderer::Hook => {
            let data = match serde_json::to_value(report) {
                Ok(data) => data,
                Err(error) => {
                    return write_stdout(
                        stdout,
                        &format!("error: failed to serialize team report: {error}\n"),
                    );
                }
            };
            let json = json!({
                "schema": crate::models::RESPONSE_SCHEMA_V2,
                "success": true,
                "data": data,
                "degraded": []
            });
            write_stdout(stdout, &(json.to_string() + "\n"))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db::{
        CreateWorkspaceInput, DbConnection, InsertTeamMemberInput, UpsertMeshPeerInput,
    };
    use crate::mesh::team::create_local_team;

    fn open_db() -> DbConnection {
        let connection = DbConnection::open_memory().expect("open");
        connection.migrate().expect("migrate");
        connection
    }

    #[test]
    fn share_bodies_confirm_requires_bounded_stdin_bearer() {
        assert!(
            TeamShareBodiesArgs::try_parse_from(["bodies", "--confirm"]).is_err(),
            "confirmation without an approval bearer must fail during CLI parsing",
        );
        assert!(
            TeamShareBodiesArgs::try_parse_from(["bodies", "--confirm", "--token", "eeap1_test",])
                .is_err(),
            "argv bearer material must be rejected",
        );
        assert!(
            TeamShareBodiesArgs::try_parse_from(["bodies", "--confirm", "--token-stdin",]).is_ok(),
            "stdin is the supported bearer source for robot confirmation",
        );
        assert!(
            TeamShareBodiesArgs::try_parse_from(["bodies", "--issue-token", "--confirm"]).is_err(),
            "token issuance and confirmation must remain separate commands",
        );
    }

    #[test]
    fn team_idp_attest_requires_pinned_discovery_and_rejects_caller_jwks() {
        let missing = TeamIdpAttestArgs::try_parse_from(["team-idp-attest", "--id-token", "-"])
            .expect_err("missing pinned discovery must be rejected");
        assert_eq!(
            missing.kind(),
            clap::error::ErrorKind::MissingRequiredArgument
        );

        TeamIdpAttestArgs::try_parse_from([
            "team-idp-attest",
            "--id-token",
            "-",
            "--discovery-json",
            "issuer.discovery.json",
        ])
        .expect("pinned discovery source");

        let argv_token = TeamIdpAttestArgs::try_parse_from([
            "team-idp-attest",
            "--id-token",
            "header.claims.signature",
            "--discovery-json",
            "issuer.discovery.json",
        ])
        .expect_err("ID-token bearer in argv must be rejected");
        assert_eq!(argv_token.kind(), clap::error::ErrorKind::ValueValidation);

        let caller_jwks = TeamIdpAttestArgs::try_parse_from([
            "team-idp-attest",
            "--id-token",
            "-",
            "--discovery-json",
            "issuer.discovery.json",
            "--jwks-json",
            "issuer.jwks.json",
        ])
        .expect_err("caller-selected JWKS must be rejected");
        assert_eq!(caller_jwks.kind(), clap::error::ErrorKind::UnknownArgument);
    }

    #[test]
    fn classify_self_and_age_windows() {
        let as_of = parse_rfc3339_utc("2026-08-13T01:00:00Z").expect("as_of");
        let thresholds = MeshDriftThresholds::default();
        assert_eq!(
            classify_team_member_reachability(
                true,
                Some("2026-08-13T00:00:00Z"),
                as_of,
                thresholds
            ),
            MEMBER_REACHABILITY_SELF
        );
        assert_eq!(
            classify_team_member_reachability(false, None, as_of, thresholds),
            MEMBER_REACHABILITY_NEVER_SYNCED
        );
        assert_eq!(
            classify_team_member_reachability(
                false,
                Some("2026-08-13T00:59:00Z"),
                as_of,
                thresholds
            ),
            MEMBER_REACHABILITY_SYNCED
        );
        assert_eq!(
            classify_team_member_reachability(
                false,
                Some("2026-08-13T00:50:00Z"),
                as_of,
                thresholds
            ),
            MEMBER_REACHABILITY_SOFT_STALE
        );
        assert_eq!(
            classify_team_member_reachability(
                false,
                Some("2026-08-12T23:00:00Z"),
                as_of,
                thresholds
            ),
            MEMBER_REACHABILITY_HARD_STALE
        );
        assert_eq!(
            human_member_freshness_label(
                MEMBER_REACHABILITY_HARD_STALE,
                Some("2026-08-10T01:00:00Z"),
                as_of
            )
            .as_deref(),
            Some("unreachable 3d")
        );
        assert_eq!(
            human_member_freshness_label(
                MEMBER_REACHABILITY_SYNCED,
                Some("2026-08-13T00:56:00Z"),
                as_of
            )
            .as_deref(),
            Some("synced 4m ago")
        );
    }

    #[test]
    fn team_status_human_names_peer_sync_freshness() {
        let connection = open_db();
        connection
            .insert_workspace(
                "wsp_statusfresh000000000000001",
                &CreateWorkspaceInput {
                    path: "/tmp/ee-team-status-fresh".to_owned(),
                    name: Some("status-fresh".to_owned()),
                },
            )
            .expect("workspace");
        let created = create_local_team(
            &connection,
            "wsp_statusfresh000000000000001",
            "Analysts",
            "2026-08-13T00:00:00Z",
        )
        .expect("create");
        connection
            .insert_team_member(&InsertTeamMemberInput {
                member_id: "mbr_bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb".to_owned(),
                team_id: created.team.team_id.clone(),
                workspace_id: "wsp_statusfresh000000000000001".to_owned(),
                display_name: "Priya".to_owned(),
                state: "active".to_owned(),
                is_self: false,
                origin_node_id: "node_priya00000000000000000001".to_owned(),
                bound_via: "invite_ceremony".to_owned(),
                joined_at: "2026-08-13T00:56:00Z".to_owned(),
            })
            .expect("priya");
        connection
            .upsert_mesh_peer(&UpsertMeshPeerInput {
                workspace_id: "wsp_statusfresh000000000000001".to_owned(),
                peer_id: "peer_priyafresh000000000000001".to_owned(),
                origin_node_id: "node_priya00000000000000000001".to_owned(),
                display_name: Some("Priya".to_owned()),
                policy_summary_json: None,
                enabled: true,
                last_seen_at: Some("2026-08-13T00:56:00Z".to_owned()),
            })
            .expect("priya peer");
        connection
            .insert_team_member(&InsertTeamMemberInput {
                member_id: "mbr_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_owned(),
                team_id: created.team.team_id.clone(),
                workspace_id: "wsp_statusfresh000000000000001".to_owned(),
                display_name: "Marcus".to_owned(),
                state: "active".to_owned(),
                is_self: false,
                origin_node_id: "node_marcus0000000000000000001".to_owned(),
                bound_via: "invite_ceremony".to_owned(),
                joined_at: "2026-08-13T00:00:00Z".to_owned(),
            })
            .expect("marcus");
        connection
            .upsert_mesh_peer(&UpsertMeshPeerInput {
                workspace_id: "wsp_statusfresh000000000000001".to_owned(),
                peer_id: "peer_stalehana0000000000000001".to_owned(),
                origin_node_id: "node_hanaold000000000000000001".to_owned(),
                display_name: Some("Hana-laptop".to_owned()),
                policy_summary_json: None,
                enabled: true,
                last_seen_at: Some("2026-08-10T01:00:00Z".to_owned()),
            })
            .expect("unused peer");

        let report = local_team_status(&connection).expect("status");
        let as_of = parse_rfc3339_utc("2026-08-13T01:00:00Z").expect("as_of");
        let freshness = collect_team_member_freshness(&connection, &report.members, as_of);
        let human = render_team_status_human(&report, &freshness, as_of);
        let data = inject_team_member_freshness(&report, &freshness).expect("json");

        let self_member = report.members.iter().find(|m| m.is_self).expect("self");
        let priya = report
            .members
            .iter()
            .find(|m| m.display_name == "Priya")
            .expect("priya");
        let marcus = report
            .members
            .iter()
            .find(|m| m.display_name == "Marcus")
            .expect("marcus");
        let by_id = |id: &str| {
            freshness
                .iter()
                .zip(report.members.iter())
                .find(|(_, member)| member.member_id == id)
                .map(|(fresh, _)| fresh)
                .expect("fresh")
        };

        assert_eq!(
            by_id(&self_member.member_id).reachability,
            MEMBER_REACHABILITY_SELF
        );
        assert_eq!(
            by_id(&priya.member_id).reachability,
            MEMBER_REACHABILITY_SYNCED
        );
        assert_eq!(
            by_id(&priya.member_id).last_seen_at.as_deref(),
            Some("2026-08-13T00:56:00Z")
        );
        assert_eq!(
            by_id(&marcus.member_id).reachability,
            MEMBER_REACHABILITY_NEVER_SYNCED
        );
        assert!(
            human.contains("Priya") && human.contains("synced 4m ago"),
            "human must name Priya's last sync: {human}"
        );
        assert!(
            human.contains("Marcus") && human.contains("never synced"),
            "human must say Marcus never synced: {human}"
        );
        assert!(
            !human.contains("unreachable"),
            "an unused old peer must not label the local operator unreachable: {human}"
        );

        let members = data["members"].as_array().expect("members");
        let priya_json = members
            .iter()
            .find(|row| row["displayName"] == "Priya")
            .expect("priya json");
        assert_eq!(priya_json["reachability"], "synced");
        assert_eq!(priya_json["lastSeenAt"], "2026-08-13T00:56:00Z");
        let marcus_json = members
            .iter()
            .find(|row| row["displayName"] == "Marcus")
            .expect("marcus json");
        assert_eq!(marcus_json["reachability"], "never_synced");
        assert!(marcus_json.get("lastSeenAt").is_none());
    }
}