ai-crew-sync 0.7.1

MCP server that lets a team's AI coding agents (Claude Code, Codex, Cursor or any MCP client) exchange messages, coordinate tasks, share presence and keep shared notes, backed by Postgres
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
//! End-to-end tests against a real Postgres and the real HTTP surface.
//!
//! Two MCP clients ("joaquin" and "marta") connect over Streamable HTTP with
//! their own bearer tokens, exactly as two teammates' coding agents
//! would, and are checked for the properties that actually matter: isolation
//! between teams, identity that cannot be spoofed, and task claims that do not
//! hand the same work to two agents.
//!
//! Requires `TEST_DATABASE_URL` (or `DATABASE_URL`); skipped when unset.

use std::sync::Arc;

use ai_crew_sync::{
    MIGRATOR,
    auth::{generate_token, hash_token, token_prefix},
    serve::{ServeOptions, build_router},
};
use rmcp::{
    ServiceExt,
    model::{CallToolRequestParams, ClientConfig},
    service::RunningService,
    transport::{
        StreamableHttpClientTransport, streamable_http_client::StreamableHttpClientTransportConfig,
    },
};
use serde_json::{Value, json};
use sqlx::{PgPool, postgres::PgPoolOptions};
use tokio_util::sync::CancellationToken;
use uuid::Uuid;

fn db_url() -> Option<String> {
    std::env::var("TEST_DATABASE_URL")
        .or_else(|_| std::env::var("DATABASE_URL"))
        .ok()
}

/// Each test gets its own schema so they can run concurrently without
/// tripping over each other's rows.
struct Harness {
    pool: PgPool,
    base: String,
    ct: CancellationToken,
    /// Every axum task started for this harness, including replicas.
    servers: Vec<tokio::task::JoinHandle<()>>,
    /// The schema this harness owns, so replicas can join it.
    schema: String,
    /// The broker this harness's servers can reach, when the test needs
    /// one. `None` is the default installation: Postgres only.
    nats: Option<String>,
}

impl Harness {
    /// Start another bus instance against the SAME database and schema — the
    /// production topology: N processes, one Postgres, each with its own
    /// LISTEN connection and its own in-process event hub.
    async fn add_replica(&mut self) -> String {
        let (base, handle) =
            spawn_server(self.pool.clone(), self.ct.child_token(), self.nats.clone()).await;
        self.servers.push(handle);
        base
    }

    /// Cancel every background task, wait for the servers to actually stop,
    /// then drop the schema and close the pool — a finished test leaves
    /// neither a running task nor a table behind.
    async fn shutdown(mut self) {
        self.ct.cancel();
        let servers = std::mem::take(&mut self.servers);
        for mut handle in servers {
            // Graceful shutdown is wired to the token; the timeout keeps a
            // wedged task from hanging the suite. Dropping the JoinHandle
            // would DETACH the task rather than stop it — the exact leak this
            // harness exists to prevent — so a timeout aborts it explicitly.
            match tokio::time::timeout(std::time::Duration::from_secs(5), &mut handle).await {
                Ok(Ok(())) => {}
                Ok(Err(e)) if e.is_panic() => panic!("a server task panicked: {e}"),
                Ok(Err(_)) => {}
                Err(_) => {
                    handle.abort();
                    panic!("a server task did not stop within 5s of cancellation");
                }
            }
        }
        // Best effort: a failure here must not fail an otherwise green test,
        // and `setup` drops the schema on the way in regardless.
        let _ = sqlx::query(sqlx::AssertSqlSafe(format!(
            "DROP SCHEMA IF EXISTS {} CASCADE",
            self.schema
        )))
        .execute(&self.pool)
        .await;
        self.pool.close().await;
    }
}

impl Drop for Harness {
    /// A panicking test never reaches `shutdown`, and a leaked listener would
    /// keep consuming notifications for the rest of the run.
    fn drop(&mut self) {
        self.ct.cancel();
    }
}

/// Bind an ephemeral port and serve the bus on it. Returns the base URL and
/// the server task, which stops when `ct` is cancelled.
async fn spawn_server(
    pool: PgPool,
    ct: CancellationToken,
    nats: Option<String>,
) -> (String, tokio::task::JoinHandle<()>) {
    spawn_server_with_ping(pool, ct, nats, ai_crew_sync::events::DEFAULT_PING_SECS).await
}

async fn spawn_server_with_ping(
    pool: PgPool,
    ct: CancellationToken,
    nats: Option<String>,
    event_ping_secs: u64,
) -> (String, tokio::task::JoinHandle<()>) {
    let app = build_router(
        pool,
        &ServeOptions {
            bind: String::new(),
            allowed_hosts: vec![],
            allowed_origins: vec![],
            max_request_bytes: ai_crew_sync::serve::DEFAULT_MAX_REQUEST_BYTES,
            // Off by default in tests: the suite hammers the server far faster
            // than any real agent, and the limiter has its own tests.
            rate_limit_per_minute: 0,
            dashboard_secret: b"test-dashboard-secret".to_vec(),
            nats_url: nats,
            nats_credentials: None,
            // The publication tests drive the outbox themselves, one step at
            // a time, so the timing under test is the test's and not a
            // background loop's.
            publication_worker: false,
            event_ping_secs,
        },
        ct.clone(),
    );
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let handle = tokio::spawn(async move {
        let _ = axum::serve(listener, app)
            .with_graceful_shutdown(async move { ct.cancelled().await })
            .await;
    });
    (format!("http://{addr}"), handle)
}

async fn setup(schema: &str) -> Option<Harness> {
    setup_with(schema, None).await
}

/// Same, with a broker the server can reach: for the tests that route a
/// team's conversations off Postgres.
async fn setup_with_broker(schema: &str) -> Option<Harness> {
    let nats = nats_url();
    setup_with(schema, Some(nats)).await
}

async fn setup_with(schema: &str, nats: Option<String>) -> Option<Harness> {
    // Silent unless RUST_LOG asks. A failing test that hides the server's
    // own explanation of why it failed wastes the run.
    let _ = tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .with_test_writer()
        .try_init();
    let url = db_url()?;
    let pool = PgPoolOptions::new()
        .max_connections(8)
        .after_connect({
            let schema = schema.to_owned();
            move |conn, _| {
                let schema = schema.clone();
                Box::pin(async move {
                    sqlx::query(sqlx::AssertSqlSafe(format!("SET search_path TO {schema}")))
                        .execute(&mut *conn)
                        .await?;
                    Ok(())
                })
            }
        })
        .connect(&url)
        .await
        .expect("connect");

    sqlx::query(sqlx::AssertSqlSafe(format!(
        "DROP SCHEMA IF EXISTS {schema} CASCADE"
    )))
    .execute(&pool)
    .await
    .unwrap();
    sqlx::query(sqlx::AssertSqlSafe(format!("CREATE SCHEMA {schema}")))
        .execute(&pool)
        .await
        .unwrap();
    MIGRATOR.run(&pool).await.expect("migrate");

    let ct = CancellationToken::new();
    let (base, handle) = spawn_server(pool.clone(), ct.child_token(), nats.clone()).await;

    Some(Harness {
        pool,
        base,
        ct,
        servers: vec![handle],
        schema: schema.to_owned(),
        nats,
    })
}

/// Create a team + agent + token straight in the database, the way the CLI does.
async fn seed_agent(pool: &PgPool, team: &str, agent: &str) -> String {
    let team_id: (Uuid,) = sqlx::query_as(
        "INSERT INTO teams (slug, name) VALUES ($1, $1)
         ON CONFLICT (slug) DO UPDATE SET name = EXCLUDED.name RETURNING id",
    )
    .bind(team)
    .fetch_one(pool)
    .await
    .unwrap();

    let agent_id: (Uuid,) =
        sqlx::query_as("INSERT INTO agents (team_id, name) VALUES ($1, $2) RETURNING id")
            .bind(team_id.0)
            .bind(agent)
            .fetch_one(pool)
            .await
            .unwrap();

    let raw = generate_token();
    sqlx::query("INSERT INTO api_tokens (agent_id, token_hash, prefix) VALUES ($1, $2, $3)")
        .bind(agent_id.0)
        .bind(hash_token(&raw))
        .bind(token_prefix(&raw))
        .execute(pool)
        .await
        .unwrap();
    raw
}

type Client = RunningService<rmcp::RoleClient, ClientConfig>;

async fn connect(base: &str, token: &str) -> Client {
    let mut config = StreamableHttpClientTransportConfig::with_uri(format!("{base}/mcp"));
    config.auth_header = Some(token.to_string());
    config.allow_stateless = true;
    let transport = StreamableHttpClientTransport::from_config(config);
    ClientConfig::default()
        .serve(transport)
        .await
        .expect("mcp handshake")
}

/// Connect as a named working context — the same token, a different session.
async fn connect_with_session(base: &str, token: &str, session: &str) -> Client {
    let mut config = StreamableHttpClientTransportConfig::with_uri(format!("{base}/mcp"));
    config.auth_header = Some(token.to_string());
    config.allow_stateless = true;
    config.custom_headers.insert(
        ai_crew_sync::auth::SESSION_HEADER.parse().unwrap(),
        session.parse().unwrap(),
    );
    let transport = StreamableHttpClientTransport::from_config(config);
    ClientConfig::default()
        .serve(transport)
        .await
        .expect("mcp handshake")
}

/// Call a tool and return its structured output.
async fn call(client: &Client, name: &str, args: Value) -> Value {
    let args: serde_json::Map<String, Value> = serde_json::from_value(args).unwrap();
    let result = client
        .call_tool(CallToolRequestParams::new(name.to_string()).with_arguments(args))
        .await
        .unwrap_or_else(|e| panic!("{name} failed: {e}"));
    assert_ne!(
        result.is_error,
        Some(true),
        "{name} returned an error: {result:?}"
    );
    result
        .structured_content
        .clone()
        .unwrap_or_else(|| panic!("{name} returned no structured content: {result:?}"))
}

/// Call a tool expecting the server to reject it.
async fn call_expect_error(client: &Client, name: &str, args: Value) -> String {
    let args: serde_json::Map<String, Value> = serde_json::from_value(args).unwrap();
    match client
        .call_tool(CallToolRequestParams::new(name.to_string()).with_arguments(args))
        .await
    {
        Err(e) => e.to_string(),
        Ok(result) => {
            assert_eq!(
                result.is_error,
                Some(true),
                "{name} unexpectedly succeeded: {result:?}"
            );
            format!("{:?}", result.content)
        }
    }
}

/// Same harness, but with the in-process rate limiter enabled — the default
/// setup disables it so the suite can hammer the server.
async fn setup_rate_limited(schema: &str, per_minute: u32) -> Option<Harness> {
    let url = match db_url() {
        Some(url) => url,
        None => {
            assert!(
                !db_required(),
                "AI_CREW_SYNC_REQUIRE_DB is set but TEST_DATABASE_URL is not: \
                 this test would have silently passed without a database"
            );
            return None;
        }
    };
    let pool = PgPoolOptions::new()
        .max_connections(8)
        .after_connect({
            let schema = schema.to_owned();
            move |conn, _| {
                let schema = schema.clone();
                Box::pin(async move {
                    sqlx::query(sqlx::AssertSqlSafe(format!("SET search_path TO {schema}")))
                        .execute(&mut *conn)
                        .await?;
                    Ok(())
                })
            }
        })
        .connect(&url)
        .await
        .expect("connect");
    sqlx::query(sqlx::AssertSqlSafe(format!(
        "DROP SCHEMA IF EXISTS {schema} CASCADE"
    )))
    .execute(&pool)
    .await
    .unwrap();
    sqlx::query(sqlx::AssertSqlSafe(format!("CREATE SCHEMA {schema}")))
        .execute(&pool)
        .await
        .unwrap();
    MIGRATOR.run(&pool).await.expect("migrate");

    let ct = CancellationToken::new();
    let child = ct.child_token();
    let app = build_router(
        pool.clone(),
        &ServeOptions {
            bind: String::new(),
            allowed_hosts: vec![],
            allowed_origins: vec![],
            max_request_bytes: 64 * 1024,
            rate_limit_per_minute: per_minute,
            dashboard_secret: b"test-dashboard-secret".to_vec(),
            nats_url: None,
            nats_credentials: None,
            publication_worker: false,
            event_ping_secs: ai_crew_sync::events::DEFAULT_PING_SECS,
        },
        child.clone(),
    );
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let handle = tokio::spawn(async move {
        let _ = axum::serve(listener, app)
            .with_graceful_shutdown(async move { child.cancelled().await })
            .await;
    });
    Some(Harness {
        pool,
        base: format!("http://{addr}"),
        ct,
        servers: vec![handle],
        schema: schema.to_owned(),
        nats: None,
    })
}

/// Skipping is a convenience for a laptop with no database, and a silent
/// green build everywhere else. `make test` and CI set this, so a broken
/// Postgres setup fails the run instead of passing zero tests.
fn db_required() -> bool {
    std::env::var("AI_CREW_SYNC_REQUIRE_DB").is_ok_and(|v| v != "0")
}

/// Same, for the tests that need the JetStream fixture as well. Missing
/// infrastructure fails visibly: `nats_url()` panics rather than skipping.
macro_rules! require_db_broker {
    ($schema:expr) => {
        match setup_with_broker($schema).await {
            Some(h) => h,
            None => {
                assert!(
                    !db_required(),
                    "AI_CREW_SYNC_REQUIRE_DB is set but TEST_DATABASE_URL is not: \
                     the integration suite would have silently passed without \
                     touching a database"
                );
                eprintln!("skipping: TEST_DATABASE_URL not set");
                return;
            }
        }
    };
}

macro_rules! require_db {
    ($schema:expr) => {
        match setup($schema).await {
            Some(h) => h,
            None => {
                assert!(
                    !db_required(),
                    "AI_CREW_SYNC_REQUIRE_DB is set but TEST_DATABASE_URL is not: \
                     the integration suite would have silently passed without \
                     touching a database"
                );
                eprintln!("skipping: TEST_DATABASE_URL not set");
                return;
            }
        }
    };
}

// ---------------------------------------------------------------------------

#[tokio::test]
async fn unauthenticated_requests_are_rejected() {
    let h = require_db!("t_auth");
    let client = reqwest::Client::new();

    let resp = client
        .post(format!("{}/mcp", h.base))
        .header("Accept", "application/json, text/event-stream")
        .json(&json!({"jsonrpc":"2.0","id":1,"method":"tools/list"}))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 401, "no token must be rejected");

    let resp = client
        .post(format!("{}/mcp", h.base))
        .header("Authorization", "Bearer acs_deadbeef")
        .header("Accept", "application/json, text/event-stream")
        .json(&json!({"jsonrpc":"2.0","id":1,"method":"tools/list"}))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 401, "bogus token must be rejected");

    // Health is deliberately open so load balancers can probe it.
    let resp = client
        .get(format!("{}/health", h.base))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
}

#[tokio::test]
async fn revoked_token_stops_working() {
    let h = require_db!("t_revoke");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    let client = connect(&h.base, &token).await;
    call(&client, "whoami", json!({})).await;
    let _ = client.cancel().await;

    sqlx::query("UPDATE api_tokens SET revoked_at = now()")
        .execute(&h.pool)
        .await
        .unwrap();

    let resp = reqwest::Client::new()
        .post(format!("{}/mcp", h.base))
        .header("Authorization", format!("Bearer {token}"))
        .header("Accept", "application/json, text/event-stream")
        .json(&json!({"jsonrpc":"2.0","id":1,"method":"tools/list"}))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 401);
}

#[tokio::test]
async fn tools_are_advertised_with_schemas() {
    let h = require_db!("t_tools");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    let client = connect(&h.base, &token).await;

    let tools = client.list_all_tools().await.unwrap();
    let names: Vec<&str> = tools.iter().map(|t| t.name.as_ref()).collect();
    for expected in [
        "whoami",
        "post_message",
        "read_messages",
        "list_channels",
        "create_channel",
        "search_messages",
        "ask_agent",
        "attach_file",
        "get_attachment",
        "create_task",
        "claim_task",
        "claim_next_task",
        "complete_task",
        "release_task",
        "renew_task_lease",
        "list_tasks",
        "get_task",
        "heartbeat",
        "list_agents",
        "list_sessions",
        "register_session",
        "resume_session",
        "renew_session",
        "revoke_session",
        "set_note",
        "get_note",
        "list_notes",
        "search_notes",
        "delete_note",
    ] {
        assert!(
            names.contains(&expected),
            "missing tool {expected} in {names:?}"
        );
    }
    for tool in &tools {
        assert!(
            tool.description.as_ref().is_some_and(|d| d.len() > 20),
            "tool {} needs a usable description",
            tool.name
        );
    }

    // A capability that is off is off in the catalogue too. Advertising
    // eighteen tools that every call rejects is a catalogue that lies, and
    // the model reading it spends a turn finding out.
    let optional = [
        "create_conversation",
        "list_conversations",
        "invite_to_conversation",
        "join_conversation",
        "leave_conversation",
        "remove_conversation_member",
        "archive_conversation",
        "transfer_membership",
        "send_conversation_message",
        "read_conversation",
        "get_conversation_message",
        "ack_message",
        "get_message_receipts",
        "fetch_conversation_inbox",
        "confirm_inbox_delivery",
        "conversation_inbox_status",
        "wait_for_conversation_updates",
        "create_project",
        "list_projects",
        "grant_project_access",
        "recover_conversation_history",
    ];
    for hidden in optional {
        assert!(
            !names.contains(&hidden),
            "conversations are off for this team, so {hidden} must not be advertised"
        );
    }
    let refused = call_expect_error(&client, "create_conversation", json!({"title": "no"})).await;
    assert!(
        refused.contains("not enabled"),
        "the per-call check is still the authorization boundary: {refused}"
    );

    enable_conversations(&h.pool, "acme").await;
    let client2 = connect(&h.base, &token).await;
    let names2: Vec<String> = client2
        .list_all_tools()
        .await
        .unwrap()
        .iter()
        .map(|t| t.name.to_string())
        .collect();
    for shown in optional {
        assert!(
            names2.iter().any(|n| n == shown),
            "with the capability on, {shown} is advertised"
        );
    }
    let _ = client2.cancel().await;
    let _ = client.cancel().await;
}

#[tokio::test]
async fn direct_messages_and_channels_flow_between_two_agents() {
    let h = require_db!("t_msg");
    let joaquin_token = seed_agent(&h.pool, "acme", "joaquin").await;
    let marta_token = seed_agent(&h.pool, "acme", "marta").await;
    let joaquin = connect(&h.base, &joaquin_token).await;
    let marta = connect(&h.base, &marta_token).await;

    // Identity comes from the token, not from an argument.
    let me = call(&joaquin, "whoami", json!({})).await;
    assert_eq!(me["agent"], "joaquin");
    assert_eq!(me["team"], "acme");

    // Direct message: only the recipient sees it in their inbox.
    call(
        &joaquin,
        "post_message",
        json!({"to": "marta", "body": "the auth refactor touches your billing module"}),
    )
    .await;

    let inbox = call(&marta, "read_messages", json!({"scope": "inbox"})).await;
    assert_eq!(inbox["messages"].as_array().unwrap().len(), 1);
    assert_eq!(inbox["messages"][0]["from"], "joaquin");
    assert_eq!(inbox["messages"][0]["to"], "marta");

    // The read cursor advanced, so a second read returns nothing new.
    let again = call(&marta, "read_messages", json!({"scope": "inbox"})).await;
    assert_eq!(again["messages"].as_array().unwrap().len(), 0);

    // ...unless we explicitly ask for history.
    let history = call(
        &marta,
        "read_messages",
        json!({"scope": "inbox", "only_new": false}),
    )
    .await;
    assert_eq!(history["messages"].as_array().unwrap().len(), 1);

    // The sender's own inbox stays empty.
    let joaquin_inbox = call(&joaquin, "read_messages", json!({"scope": "inbox"})).await;
    assert_eq!(joaquin_inbox["messages"].as_array().unwrap().len(), 0);

    // Channels are shared by the whole team.
    call(
        &marta,
        "create_channel",
        json!({"name": "#Deploys", "topic": "what is going out"}),
    )
    .await;
    let channels = call(&joaquin, "list_channels", json!({})).await;
    assert_eq!(
        channels["channels"][0]["name"], "deploys",
        "name normalised"
    );

    call(
        &marta,
        "post_message",
        json!({"channel": "deploys", "body": "staging is on 1.4.2"}),
    )
    .await;
    let read = call(&joaquin, "read_messages", json!({"scope": "deploys"})).await;
    assert_eq!(read["messages"][0]["body"], "staging is on 1.4.2");
    assert_eq!(read["messages"][0]["from"], "marta");

    // Full-text search finds it without disturbing cursors.
    let found = call(&joaquin, "search_messages", json!({"query": "staging"})).await;
    assert_eq!(found["messages"].as_array().unwrap().len(), 1);

    // Sending to an unknown agent is a clean, explanatory error.
    let err = call_expect_error(
        &joaquin,
        "post_message",
        json!({"to": "nobody", "body": "hi"}),
    )
    .await;
    assert!(
        err.contains("nobody"),
        "error should name the missing agent: {err}"
    );

    // A message must have exactly one target.
    let err = call_expect_error(&joaquin, "post_message", json!({"body": "hi"})).await;
    assert!(err.to_lowercase().contains("channel"), "got: {err}");

    let _ = joaquin.cancel().await;
    let _ = marta.cancel().await;
}

#[tokio::test]
async fn teams_are_isolated_from_each_other() {
    let h = require_db!("t_isolation");
    let acme = seed_agent(&h.pool, "acme", "joaquin").await;
    let other = seed_agent(&h.pool, "globex", "intruder").await;
    let acme_client = connect(&h.base, &acme).await;
    let other_client = connect(&h.base, &other).await;

    call(&acme_client, "create_channel", json!({"name": "secrets"})).await;
    call(
        &acme_client,
        "post_message",
        json!({"channel": "secrets", "body": "the api key is in vault"}),
    )
    .await;
    call(
        &acme_client,
        "set_note",
        json!({"scope": "api", "key": "vault-path", "value": "secret/prod/api"}),
    )
    .await;
    call(
        &acme_client,
        "create_task",
        json!({"key": "rotate-keys", "title": "rotate the prod keys"}),
    )
    .await;

    // The other team sees none of it.
    let channels = call(&other_client, "list_channels", json!({})).await;
    assert_eq!(channels["channels"].as_array().unwrap().len(), 0);

    let msgs = call(&other_client, "read_messages", json!({"scope": "all"})).await;
    assert_eq!(msgs["messages"].as_array().unwrap().len(), 0);

    let notes = call(&other_client, "list_notes", json!({})).await;
    assert_eq!(notes["notes"].as_array().unwrap().len(), 0);

    let tasks = call(&other_client, "list_tasks", json!({})).await;
    assert_eq!(tasks["tasks"].as_array().unwrap().len(), 0);

    // Not even by name.
    let found = call(&other_client, "search_messages", json!({"query": "vault"})).await;
    assert_eq!(found["messages"].as_array().unwrap().len(), 0);

    let err = call_expect_error(&other_client, "get_task", json!({"key": "rotate-keys"})).await;
    assert!(err.contains("not found"), "got: {err}");

    let agents = call(&other_client, "list_agents", json!({})).await;
    let names: Vec<&str> = agents["agents"]
        .as_array()
        .unwrap()
        .iter()
        .map(|a| a["name"].as_str().unwrap())
        .collect();
    assert_eq!(names, vec!["intruder"]);

    let _ = acme_client.cancel().await;
    let _ = other_client.cancel().await;
}

#[tokio::test]
async fn a_claimed_task_cannot_be_claimed_by_someone_else() {
    let h = require_db!("t_claim");
    let a = seed_agent(&h.pool, "acme", "joaquin").await;
    let b = seed_agent(&h.pool, "acme", "marta").await;
    let joaquin = connect(&h.base, &a).await;
    let marta = connect(&h.base, &b).await;

    call(
        &joaquin,
        "create_task",
        json!({"key": "refactor-auth", "title": "rewrite the token refresh flow"}),
    )
    .await;

    let claim = call(
        &joaquin,
        "claim_task",
        json!({"key": "refactor-auth", "lease_seconds": 600}),
    )
    .await;
    assert_eq!(claim["claimed"], true);
    assert_eq!(claim["task"]["claimed_by"], "joaquin");

    // Marta is refused, and told why rather than getting a bare failure.
    let denied = call(&marta, "claim_task", json!({"key": "refactor-auth"})).await;
    assert_eq!(denied["claimed"], false);
    assert!(
        denied["reason"].as_str().unwrap().contains("joaquin"),
        "reason should name the holder: {denied:?}"
    );

    // Re-claiming your own task is idempotent, not an error.
    let again = call(&joaquin, "claim_task", json!({"key": "refactor-auth"})).await;
    assert_eq!(again["claimed"], true);

    // Marta cannot renew or release a lease she does not hold.
    let err = call_expect_error(&marta, "release_task", json!({"key": "refactor-auth"})).await;
    assert!(err.contains("do not hold"), "got: {err}");
    let err = call_expect_error(&marta, "renew_task_lease", json!({"key": "refactor-auth"})).await;
    assert!(err.contains("do not hold"), "got: {err}");

    // Once released, it is up for grabs again.
    call(&joaquin, "release_task", json!({"key": "refactor-auth"})).await;
    let retry = call(&marta, "claim_task", json!({"key": "refactor-auth"})).await;
    assert_eq!(retry["claimed"], true);
    assert_eq!(retry["task"]["claimed_by"], "marta");

    // Completing records the result and closes the task.
    let done = call(
        &marta,
        "complete_task",
        json!({"key": "refactor-auth", "result": "merged in #421"}),
    )
    .await;
    assert_eq!(done["status"], "done");
    assert_eq!(done["result"], "merged in #421");

    let err = call_expect_error(&joaquin, "complete_task", json!({"key": "refactor-auth"})).await;
    assert!(err.contains("already done"), "got: {err}");

    // The history is a full audit trail.
    let detail = call(&joaquin, "get_task", json!({"key": "refactor-auth"})).await;
    let events: Vec<&str> = detail["history"]
        .as_array()
        .unwrap()
        .iter()
        .map(|e| e["event"].as_str().unwrap())
        .collect();
    assert_eq!(
        events,
        vec![
            "created",
            "claimed",
            "claimed",
            "released",
            "claimed",
            "completed"
        ]
    );

    let _ = joaquin.cancel().await;
    let _ = marta.cancel().await;
}

#[tokio::test]
async fn an_expired_lease_can_be_taken_over() {
    let h = require_db!("t_lease");
    let a = seed_agent(&h.pool, "acme", "joaquin").await;
    let b = seed_agent(&h.pool, "acme", "marta").await;
    let joaquin = connect(&h.base, &a).await;
    let marta = connect(&h.base, &b).await;

    call(
        &joaquin,
        "create_task",
        json!({"key": "long-job", "title": "reindex everything"}),
    )
    .await;
    call(&joaquin, "claim_task", json!({"key": "long-job"})).await;

    // Simulate an agent that died mid-task: the lease lapses.
    sqlx::query("UPDATE tasks SET lease_expires_at = now() - interval '1 minute'")
        .execute(&h.pool)
        .await
        .unwrap();

    let listed = call(&marta, "list_tasks", json!({})).await;
    assert_eq!(listed["tasks"][0]["lease_expired"], true);

    let stolen = call(&marta, "claim_task", json!({"key": "long-job"})).await;
    assert_eq!(
        stolen["claimed"], true,
        "an expired lease must be reclaimable"
    );
    assert_eq!(stolen["task"]["claimed_by"], "marta");

    // Renewing pushes the expiry back out.
    let renewed = call(
        &marta,
        "renew_task_lease",
        json!({"key": "long-job", "lease_seconds": 3600}),
    )
    .await;
    assert_eq!(renewed["lease_expired"], false);

    let _ = joaquin.cancel().await;
    let _ = marta.cancel().await;
}

#[tokio::test]
async fn concurrent_claim_next_never_hands_out_the_same_task_twice() {
    let h = require_db!("t_race");
    let mut clients = Vec::new();
    for i in 0..4 {
        let token = seed_agent(&h.pool, "acme", &format!("agent{i}")).await;
        clients.push(Arc::new(connect(&h.base, &token).await));
    }

    // Four tasks, four agents, all grabbing at once.
    for i in 0..4 {
        call(
            &clients[0],
            "create_task",
            json!({"key": format!("job-{i}"), "title": format!("job {i}")}),
        )
        .await;
    }

    let mut handles = Vec::new();
    for client in &clients {
        let client = Arc::clone(client);
        handles.push(tokio::spawn(async move {
            call(&client, "claim_next_task", json!({})).await
        }));
    }
    let mut keys = Vec::new();
    for handle in handles {
        let result = handle.await.unwrap();
        assert_eq!(result["claimed"], true);
        keys.push(result["task"]["key"].as_str().unwrap().to_owned());
    }
    keys.sort();
    keys.dedup();
    assert_eq!(
        keys.len(),
        4,
        "each agent must get a distinct task: {keys:?}"
    );

    // With nothing left, the pool is empty rather than erroring.
    let empty = call(&clients[0], "claim_next_task", json!({})).await;
    assert_eq!(empty["claimed"], false);
    assert!(empty["reason"].as_str().unwrap().contains("no unclaimed"));
}

#[tokio::test]
async fn presence_expires_and_is_visible_to_the_team() {
    let h = require_db!("t_presence");
    let a = seed_agent(&h.pool, "acme", "joaquin").await;
    let b = seed_agent(&h.pool, "acme", "marta").await;
    let joaquin = connect(&h.base, &a).await;
    let marta = connect(&h.base, &b).await;

    call(
        &joaquin,
        "heartbeat",
        json!({"repo": "acme/api", "branch": "feat/auth", "activity": "rewriting token refresh"}),
    )
    .await;

    let seen = call(&marta, "list_agents", json!({"online_only": true})).await;
    assert_eq!(seen["online_count"], 1);
    assert_eq!(seen["agents"][0]["name"], "joaquin");
    assert_eq!(seen["agents"][0]["activity"], "rewriting token refresh");
    assert_eq!(seen["agents"][0]["repo"], "acme/api");

    // A later heartbeat that omits a field keeps the previous value.
    call(&joaquin, "heartbeat", json!({"status": "blocked"})).await;
    let seen = call(&marta, "list_agents", json!({"online_only": true})).await;
    assert_eq!(seen["agents"][0]["status"], "blocked");
    assert_eq!(seen["agents"][0]["repo"], "acme/api", "repo should persist");

    // When the lease lapses the agent reads as offline, not as stale-but-active.
    sqlx::query("UPDATE agent_presence SET expires_at = now() - interval '1 minute'")
        .execute(&h.pool)
        .await
        .unwrap();
    let seen = call(&marta, "list_agents", json!({})).await;
    assert_eq!(seen["online_count"], 0);
    let joaquin_row = seen["agents"]
        .as_array()
        .unwrap()
        .iter()
        .find(|a| a["name"] == "joaquin")
        .unwrap();
    assert_eq!(joaquin_row["status"], "offline");

    let err = call_expect_error(&joaquin, "heartbeat", json!({"status": "vibing"})).await;
    assert!(err.contains("active"), "got: {err}");

    let _ = joaquin.cancel().await;
    let _ = marta.cancel().await;
}

#[tokio::test]
async fn notes_are_shared_memory_with_history() {
    let h = require_db!("t_notes");
    let a = seed_agent(&h.pool, "acme", "joaquin").await;
    let b = seed_agent(&h.pool, "acme", "marta").await;
    let joaquin = connect(&h.base, &a).await;
    let marta = connect(&h.base, &b).await;

    call(
        &joaquin,
        "set_note",
        json!({
            "scope": "api",
            "key": "why-no-redis",
            "value": "we dropped redis in march; the cache lives in postgres now",
            "tags": ["Infra", "decision"]
        }),
    )
    .await;

    // Marta reads what Joaquin wrote, tags normalised.
    let note = call(
        &marta,
        "get_note",
        json!({"scope": "api", "key": "why-no-redis"}),
    )
    .await;
    assert_eq!(note["found"], true);
    assert_eq!(note["note"]["updated_by"], "joaquin");
    assert_eq!(note["note"]["tags"][0], "infra");

    // Missing notes report found=false instead of erroring.
    let missing = call(&marta, "get_note", json!({"key": "nope"})).await;
    assert_eq!(missing["found"], false);
    assert!(missing["note"].is_null());

    // Overwrites keep a revision trail.
    call(
        &marta,
        "set_note",
        json!({"scope": "api", "key": "why-no-redis", "value": "correction: valkey, not redis"}),
    )
    .await;
    let note = call(
        &joaquin,
        "get_note",
        json!({"scope": "api", "key": "why-no-redis"}),
    )
    .await;
    assert_eq!(note["note"]["updated_by"], "marta");
    let (revisions,): (i64,) = sqlx::query_as("SELECT count(*) FROM note_revisions")
        .fetch_one(&h.pool)
        .await
        .unwrap();
    assert_eq!(revisions, 2, "both versions retained");

    // Scope and tag filtering.
    call(
        &joaquin,
        "set_note",
        json!({"scope": "web", "key": "build", "value": "vite, not webpack", "tags": ["infra"]}),
    )
    .await;
    let api_only = call(&marta, "list_notes", json!({"scope": "api"})).await;
    assert_eq!(api_only["notes"].as_array().unwrap().len(), 1);
    let all = call(&marta, "list_notes", json!({})).await;
    assert_eq!(all["notes"].as_array().unwrap().len(), 2);
    let tagged = call(&marta, "list_notes", json!({"tag": "infra"})).await;
    assert_eq!(tagged["notes"].as_array().unwrap().len(), 1);

    let found = call(&marta, "search_notes", json!({"query": "valkey"})).await;
    assert_eq!(found["notes"].as_array().unwrap().len(), 1);

    let del = call(
        &marta,
        "delete_note",
        json!({"scope": "api", "key": "why-no-redis"}),
    )
    .await;
    assert_eq!(del["ok"], true);
    let del_again = call(
        &marta,
        "delete_note",
        json!({"scope": "api", "key": "why-no-redis"}),
    )
    .await;
    assert_eq!(del_again["ok"], false, "deleting twice is not an error");

    let _ = joaquin.cancel().await;
    let _ = marta.cancel().await;
}

/// A note's scope and key are names, not documents: they ride in the NOTIFY
/// payload that Postgres caps at 8000 bytes, in every listing and on the
/// dashboard. Unbounded, a 9 KB key failed as an opaque "database error"
/// and a 3 KB one was stored and listed everywhere.
#[tokio::test]
async fn a_note_key_is_a_name_not_a_document() {
    let h = require_db!("t_note_key");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    let c = connect(&h.base, &token).await;

    let err = call_expect_error(
        &c,
        "set_note",
        json!({"key": "k".repeat(9000), "value": "x"}),
    )
    .await;
    assert!(err.contains("note key is 9000 bytes"), "{err}");
    assert!(err.contains("256"), "{err}");
    assert!(!err.contains("database error"), "{err}");

    let err = call_expect_error(
        &c,
        "set_note",
        json!({"key": "k".repeat(300), "value": "x"}),
    )
    .await;
    assert!(err.contains("note key is 300 bytes"), "{err}");

    let err = call_expect_error(
        &c,
        "set_note",
        json!({"scope": "s".repeat(65), "key": "fine", "value": "x"}),
    )
    .await;
    assert!(err.contains("note scope is 65 bytes"), "{err}");
    assert!(err.contains("64"), "{err}");

    // The limit is the limit: a 256-byte key is a (long) name.
    let ok = call(
        &c,
        "set_note",
        json!({"scope": "s".repeat(64), "key": "k".repeat(256), "value": "x"}),
    )
    .await;
    assert_eq!(ok["key"].as_str().map(str::len), Some(256), "{ok}");

    let _ = c.cancel().await;
    h.shutdown().await;
}

#[tokio::test]
async fn whoami_reports_pending_work() {
    let h = require_db!("t_whoami");
    let a = seed_agent(&h.pool, "acme", "joaquin").await;
    let b = seed_agent(&h.pool, "acme", "marta").await;
    let joaquin = connect(&h.base, &a).await;
    let marta = connect(&h.base, &b).await;

    call(
        &marta,
        "post_message",
        json!({"to": "joaquin", "body": "ping"}),
    )
    .await;
    call(
        &marta,
        "post_message",
        json!({"to": "joaquin", "body": "ping again"}),
    )
    .await;
    call(
        &joaquin,
        "create_task",
        json!({"key": "t1", "title": "something"}),
    )
    .await;
    call(&joaquin, "claim_task", json!({"key": "t1"})).await;

    let me = call(&joaquin, "whoami", json!({})).await;
    assert_eq!(me["unread_direct_messages"], 2);
    assert_eq!(me["open_claimed_tasks"], 1);

    call(&joaquin, "read_messages", json!({"scope": "inbox"})).await;
    let me = call(&joaquin, "whoami", json!({})).await;
    assert_eq!(me["unread_direct_messages"], 0);

    let _ = joaquin.cancel().await;
    let _ = marta.cancel().await;
}

// ------------------------------------------------------------ v0.2 features --

#[tokio::test]
async fn wait_for_updates_wakes_on_a_teammates_message() {
    let h = require_db!("t_wait");
    let a = seed_agent(&h.pool, "acme", "joaquin").await;
    let b = seed_agent(&h.pool, "acme", "marta").await;
    let joaquin = connect(&h.base, &a).await;
    let marta = connect(&h.base, &b).await;
    call(&joaquin, "create_channel", json!({"name": "dev"})).await;

    // Joaquin blocks waiting; Marta posts shortly after.
    let waiter = {
        let base = h.base.clone();
        let token = a.clone();
        tokio::spawn(async move {
            let client = connect(&base, &token).await;
            let started = std::time::Instant::now();
            let result = call(&client, "wait_for_updates", json!({"timeout_seconds": 20})).await;
            let _ = client.cancel().await;
            (result, started.elapsed())
        })
    };

    tokio::time::sleep(std::time::Duration::from_millis(700)).await;
    call(
        &marta,
        "post_message",
        json!({"channel": "dev", "body": "he subido el fix del parser"}),
    )
    .await;

    let (result, elapsed) = waiter.await.unwrap();
    assert_eq!(result["woke"], true, "must wake on the message: {result:?}");
    assert_eq!(result["timed_out"], false);
    assert!(
        elapsed < std::time::Duration::from_secs(10),
        "woke by event, not by timeout (took {elapsed:?})"
    );
    let summaries = result["events"].as_array().unwrap();
    assert!(
        summaries
            .iter()
            .any(|e| e["summary"].as_str().unwrap().contains("marta")),
        "event should name the sender: {summaries:?}"
    );

    // With unread messages already pending, the wait returns immediately.
    let instant = call(&joaquin, "wait_for_updates", json!({"timeout_seconds": 30})).await;
    assert_eq!(instant["woke"], true);

    let _ = joaquin.cancel().await;
    let _ = marta.cancel().await;
}

#[tokio::test]
async fn ask_agent_returns_the_teammates_answer() {
    let h = require_db!("t_ask");
    let a = seed_agent(&h.pool, "acme", "joaquin").await;
    let b = seed_agent(&h.pool, "acme", "marta").await;
    let joaquin = connect(&h.base, &a).await;
    let marta = connect(&h.base, &b).await;

    // Joaquin asks and blocks; Marta reads the question and replies to it.
    let asker = {
        let base = h.base.clone();
        let token = a.clone();
        tokio::spawn(async move {
            let client = connect(&base, &token).await;
            let started = std::time::Instant::now();
            let result = call(
                &client,
                "ask_agent",
                json!({"to": "marta", "question": "does staging run pg16?", "timeout_seconds": 20}),
            )
            .await;
            let _ = client.cancel().await;
            (result, started.elapsed())
        })
    };

    tokio::time::sleep(std::time::Duration::from_millis(700)).await;
    let inbox = call(&marta, "read_messages", json!({"scope": "inbox"})).await;
    let question = inbox["messages"]
        .as_array()
        .unwrap()
        .last()
        .unwrap()
        .clone();
    assert_eq!(
        question["metadata"]["question"], true,
        "the question DM is marked as such: {question:?}"
    );
    call(
        &marta,
        "post_message",
        json!({"to": "joaquin", "body": "yes, since yesterday", "reply_to": question["id"]}),
    )
    .await;

    let (result, elapsed) = asker.await.unwrap();
    assert_eq!(result["answered"], true, "{result:?}");
    assert_eq!(result["answer"]["from"], "marta");
    assert_eq!(result["answer"]["body"], "yes, since yesterday");
    assert!(
        elapsed < std::time::Duration::from_secs(10),
        "answered by event, not by timeout (took {elapsed:?})"
    );

    // Timeout path: no answer in time, then resume picks up a late answer
    // that was sent without reply_to (lenient matching).
    let timed = call(
        &joaquin,
        "ask_agent",
        json!({"to": "marta", "question": "and prod?", "timeout_seconds": 5}),
    )
    .await;
    assert_eq!(timed["answered"], false, "{timed:?}");
    let qid = timed["question_message_id"].as_i64().unwrap();
    assert!(
        timed["suggestion"]
            .as_str()
            .unwrap()
            .contains(&qid.to_string()),
        "timeout suggestion tells how to resume: {timed:?}"
    );

    call(
        &marta,
        "post_message",
        json!({"to": "joaquin", "body": "prod is still on pg15"}),
    )
    .await;
    let resumed = call(
        &joaquin,
        "ask_agent",
        json!({"to": "marta", "resume_message_id": qid, "timeout_seconds": 5}),
    )
    .await;
    assert_eq!(resumed["answered"], true, "{resumed:?}");
    assert_eq!(resumed["answer"]["body"], "prod is still on pg15");

    // Asking the window you are calling from is refused: nothing would ever
    // read the question, so the call could only ever time out. Asking another
    // of your own sessions is a different thing and is allowed — see
    // one_session_can_ask_another_session_of_the_same_person.
    let err = call_expect_error(
        &joaquin,
        "ask_agent",
        json!({"to": "joaquin", "question": "hi"}),
    )
    .await;
    assert!(err.contains("this session"), "{err}");

    let _ = joaquin.cancel().await;
    let _ = marta.cancel().await;
}

#[tokio::test]
async fn transport_limits_reject_oversized_and_too_frequent_requests() {
    let h = match setup_rate_limited("t_limits", 60).await {
        Some(h) => h,
        None => {
            eprintln!("skipping: TEST_DATABASE_URL not set");
            return;
        }
    };
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    let http = reqwest::Client::new();
    let mcp = format!("{}/mcp", h.base);

    let call_body = |body: String| {
        let http = http.clone();
        let mcp = mcp.clone();
        let token = token.clone();
        async move {
            http.post(&mcp)
                .header("Authorization", format!("Bearer {token}"))
                .header("Content-Type", "application/json")
                .header("Accept", "application/json, text/event-stream")
                .body(body)
                .send()
                .await
                .unwrap()
        }
    };

    // Over the 64 KiB harness limit → 413 with an actionable body, and the
    // request never reaches the tool layer.
    let huge = "x".repeat(200 * 1024);
    let resp = call_body(format!(
        r#"{{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{{"name":"whoami","arguments":{{"pad":"{huge}"}}}}}}"#
    ))
    .await;
    assert_eq!(resp.status(), 413, "oversized body is rejected");
    let text = resp.text().await.unwrap();
    assert!(
        text.contains("too large") && text.contains("attachments"),
        "413 tells the caller what to do: {text}"
    );
    assert!(
        text.contains("65536"),
        "413 states the limit this server is configured with: {text}"
    );

    // Burst past the bucket → 429 with Retry-After and advice.
    let small = r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"whoami","arguments":{}}}"#;
    let mut throttled = None;
    for _ in 0..40 {
        let resp = call_body(small.to_owned()).await;
        if resp.status() == 429 {
            throttled = Some(resp);
            break;
        }
    }
    let resp = throttled.expect("a burst of 40 must exhaust a 60/min bucket");
    let retry_after = resp
        .headers()
        .get("retry-after")
        .and_then(|v| v.to_str().ok())
        .map(str::to_owned);
    let text = resp.text().await.unwrap();
    assert!(
        retry_after.is_some(),
        "429 carries Retry-After: headers missing"
    );
    assert!(
        text.contains("rate limit") && text.contains("wait_for_updates"),
        "429 points at the non-polling alternative: {text}"
    );

    // A different token has its own budget.
    let other = seed_agent(&h.pool, "acme", "marta").await;
    let resp = http
        .post(&mcp)
        .header("Authorization", format!("Bearer {other}"))
        .header("Content-Type", "application/json")
        .header("Accept", "application/json, text/event-stream")
        .body(small)
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200, "another token is unaffected");
}

#[tokio::test]
async fn bounded_fields_reject_oversized_values() {
    let h = require_db!("t_bounds");
    let a = seed_agent(&h.pool, "acme", "joaquin").await;
    let joaquin = connect(&h.base, &a).await;

    let long = "x".repeat(300);
    let err = call_expect_error(
        &joaquin,
        "create_channel",
        json!({"name": "dev", "topic": long.clone()}),
    )
    .await;
    assert!(err.contains("256"), "channel topic bounded: {err}");

    let err = call_expect_error(&joaquin, "heartbeat", json!({"activity": long.clone()})).await;
    assert!(err.contains("256"), "presence activity bounded: {err}");

    let err = call_expect_error(
        &joaquin,
        "set_note",
        json!({"key": "k", "value": "v", "tags": vec!["t"; 20]}),
    )
    .await;
    assert!(err.contains("16"), "tag count bounded: {err}");

    call(&joaquin, "create_task", json!({"key": "dep", "title": "t"})).await;
    let err = call_expect_error(
        &joaquin,
        "create_task",
        json!({"key": "many-deps", "title": "t", "depends_on": vec!["dep"; 40]}),
    )
    .await;
    assert!(err.contains("32"), "dependency count bounded: {err}");

    let _ = joaquin.cancel().await;
}

/// The store layer scopes every query by team and the API tests prove the
/// isolation holds. This one goes underneath both: raw SQL, no helpers, no
/// application code — the database itself must refuse a cross-team reference.
/// The production topology: two bus processes against one database, each with
/// its own LISTEN connection and its own in-process event hub. A wakeup must
/// cross that boundary — an agent long-polling one replica has to hear about a
/// message posted through the other, or `wait_for_updates` is only correct on
/// a single-instance deployment.
#[tokio::test]
async fn a_wait_on_one_replica_wakes_on_the_other_replicas_write() {
    let mut h = require_db!("t_replicas");
    let replica = h.add_replica().await;
    assert_ne!(replica, h.base, "a genuinely separate instance");

    let a = seed_agent(&h.pool, "acme", "joaquin").await;
    let b = seed_agent(&h.pool, "acme", "marta").await;

    // Marta creates the channel through replica two.
    let marta = connect(&replica, &b).await;
    call(&marta, "create_channel", json!({"name": "dev"})).await;

    // Joaquin blocks on replica one.
    let waiter = {
        let base = h.base.clone();
        let token = a.clone();
        tokio::spawn(async move {
            let client = connect(&base, &token).await;
            let started = std::time::Instant::now();
            let result = call(&client, "wait_for_updates", json!({"timeout_seconds": 20})).await;
            let _ = client.cancel().await;
            (result, started.elapsed())
        })
    };

    tokio::time::sleep(std::time::Duration::from_millis(700)).await;
    call(
        &marta,
        "post_message",
        json!({"channel": "dev", "body": "posted through the other replica"}),
    )
    .await;

    let (result, elapsed) = waiter.await.unwrap();
    assert_eq!(
        result["woke"], true,
        "must wake across replicas: {result:?}"
    );
    assert!(
        elapsed < std::time::Duration::from_secs(10),
        "woken by the NOTIFY, not by the timeout (took {elapsed:?})"
    );

    // Reading through either instance returns the same state — no per-process
    // cursor or cache.
    let joaquin = connect(&h.base, &a).await;
    let via_one = call(&joaquin, "read_messages", json!({"scope": "dev"})).await;
    assert_eq!(via_one["messages"].as_array().map(Vec::len), Some(1));

    let _ = joaquin.cancel().await;
    let _ = marta.cancel().await;
    h.shutdown().await;
}

/// The bug this replaces: every replica received the same NOTIFY and every
/// replica POSTed, so a two-replica deployment sent every channel message
/// twice. Enqueueing in a database trigger and claiming with FOR UPDATE SKIP
/// LOCKED makes the count independent of how many processes are running.
#[tokio::test]
async fn webhook_delivery_is_exactly_one_row_per_hook_across_replicas() {
    let mut h = require_db!("t_outbox");
    let _replica = h.add_replica().await;
    let _replica_two = h.add_replica().await;

    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    let client = connect(&h.base, &token).await;
    call(&client, "create_channel", json!({"name": "dev"})).await;

    let team: (Uuid,) = sqlx::query_as("SELECT id FROM teams WHERE slug = 'acme'")
        .fetch_one(&h.pool)
        .await
        .unwrap();
    // A receiver that does not exist: delivery will fail, which is exactly
    // what exercises the retry path. What matters here is the row count.
    sqlx::query(
        "INSERT INTO webhooks (team_id, url, kind, events)
         VALUES ($1, 'http://127.0.0.1:9/hook', 'generic', ARRAY['message','task'])",
    )
    .bind(team.0)
    .execute(&h.pool)
    .await
    .unwrap();

    call(
        &client,
        "post_message",
        json!({"channel": "dev", "body": "one event, three replicas"}),
    )
    .await;

    // Give every replica's dispatcher a chance to have reacted.
    tokio::time::sleep(std::time::Duration::from_millis(1500)).await;

    let (rows,): (i64,) =
        sqlx::query_as("SELECT count(*) FROM webhook_deliveries WHERE kind = 'message'")
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert_eq!(
        rows, 1,
        "one channel message must enqueue exactly one delivery, not one per replica"
    );

    // It failed (nothing is listening on port 9) and was rescheduled rather
    // than dropped — the old code logged a warning and forgot the event.
    let (status, attempts, err): (String, i32, Option<String>) = sqlx::query_as(
        "SELECT status, attempts, last_error FROM webhook_deliveries WHERE kind = 'message'",
    )
    .fetch_one(&h.pool)
    .await
    .unwrap();
    assert!(attempts >= 1, "the delivery was attempted");
    assert!(err.is_some(), "the failure was recorded: {err:?}");
    assert!(
        status == "pending" || status == "failed",
        "a failed delivery is retried or parked, never lost (got {status})"
    );

    // A direct message must not enqueue anything at all.
    let _marta = seed_agent(&h.pool, "acme", "marta").await;
    call(
        &client,
        "post_message",
        json!({"to": "marta", "body": "private"}),
    )
    .await;
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    let (total,): (i64,) = sqlx::query_as("SELECT count(*) FROM webhook_deliveries")
        .fetch_one(&h.pool)
        .await
        .unwrap();
    assert_eq!(total, 1, "a DM must never reach the outbox");

    // A task transition enqueues once too, and a lease renewal does not
    // enqueue at all (it is not a state change).
    call(&client, "create_task", json!({"key": "t1", "title": "t"})).await;
    call(&client, "claim_task", json!({"key": "t1"})).await;
    call(
        &client,
        "renew_task_lease",
        json!({"key": "t1", "lease_seconds": 600}),
    )
    .await;
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;

    let (task_rows,): (i64,) =
        sqlx::query_as("SELECT count(*) FROM webhook_deliveries WHERE kind = 'task'")
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert_eq!(
        task_rows, 2,
        "created + claimed enqueue one each; renewing the lease enqueues none"
    );

    let _ = client.cancel().await;
    h.shutdown().await;
}

/// The digest used to run one tail query per active channel, so a team with
/// 40 channels paid 41 round trips for one digest and the cost grew with the
/// team. This pins the property: the work must not scale with channel count.
///
/// Measured rather than counted, and the measurement is the hard part.
///
/// `pg_stat_statements` would count executions directly, but it needs
/// `shared_preload_libraries`, and a GitHub Actions service container cannot
/// be given a command — so enabling it means running Postgres as a manual
/// step and diverging CI from `make test`. A database-wide counter is noise
/// while the suite runs in parallel, and per-table stats are flushed
/// asynchronously, which trades this test's flakiness for a sleep.
///
/// So: wall clock, with the two things that make wall clock trustworthy.
/// **Minimum** of several runs, because noise only ever adds time — a loaded
/// runner cannot make a query faster than it is. And a **ratio** rather than
/// a constant offset, because a ratio is scale-invariant: a slow machine
/// slows both measurements and the comparison survives.
///
/// The sizes are chosen from measurement, not taste. One MCP round trip costs
/// roughly 9ms here and a database round trip roughly 0.5ms, so at 20 channels
/// an N+1 hides inside the transport: injecting one and running this test at
/// the old sizes **passed**. At 60 channels the extra round trips dominate and
/// the two shapes separate cleanly — measured at 2.0-2.1 for one statement
/// against 4.2-4.3 for a query per channel, which is where the bound below
/// comes from.
#[tokio::test]
async fn the_digest_cost_does_not_grow_with_channel_count() {
    let h = require_db!("t_digest_scale");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    let client = connect(&h.base, &token).await;

    // Seeded straight into the database: 60 channels through post_message is
    // hundreds of MCP calls, and the setup is not what is being measured.
    let seed_channels = |from: i32, to: i32| {
        let pool = h.pool.clone();
        async move {
            // Triggers off for the seed. LISTEN/NOTIFY is database-wide, not
            // schema-scoped, so 360 inserts in one transaction flood every
            // other test's event hub at commit and overflow its broadcast
            // buffer — tests that were passing start waking spuriously. The
            // seed is setup, not the behaviour under measurement, so its
            // notifications are noise by definition. SET LOCAL reverts on
            // commit, so no connection goes back to the pool altered.
            let mut tx = pool.begin().await.expect("begin seed");
            sqlx::query("SET LOCAL session_replication_role = replica")
                .execute(&mut *tx)
                .await
                .expect("suppress seed triggers");
            sqlx::query(sqlx::AssertSqlSafe(
                "WITH team AS (SELECT id FROM teams WHERE slug = 'acme'),
                      me AS (SELECT id FROM agents WHERE name = 'joaquin'),
                      ch AS (
                          INSERT INTO channels (team_id, name, created_by)
                          SELECT team.id, 'chan' || g, me.id
                            FROM generate_series($1, $2 - 1) g, team, me
                          RETURNING id, name
                      )
                 INSERT INTO messages (team_id, channel_id, sender_agent_id, body)
                 SELECT team.id, ch.id, me.id, 'message ' || m || ' in ' || ch.name
                   FROM ch, generate_series(0, 5) m, team, me"
                    .to_owned(),
            ))
            .bind(from)
            .bind(to)
            .execute(&mut *tx)
            .await
            .expect("seed channels");
            tx.commit().await.expect("commit seed");
        }
    };

    // The minimum of several runs. Scheduler noise adds time and never
    // subtracts it, so the smallest observation is the closest to the real
    // cost — which is exactly what a shape assertion wants.
    async fn best_of(client: &Client, runs: usize) -> std::time::Duration {
        let mut best = std::time::Duration::MAX;
        for _ in 0..runs {
            let started = std::time::Instant::now();
            call(client, "team_digest", json!({"hours": 24})).await;
            best = best.min(started.elapsed());
        }
        best
    }

    seed_channels(0, 2).await;
    // Warm the connection and the plan cache before the first measurement.
    call(&client, "team_digest", json!({"hours": 24})).await;

    let small = best_of(&client, 5).await;
    let few = call(&client, "team_digest", json!({"hours": 24})).await;
    assert_eq!(few["channels"].as_array().map(Vec::len), Some(2));

    seed_channels(2, 60).await;
    let large = best_of(&client, 5).await;

    let digest = call(&client, "team_digest", json!({"hours": 24})).await;
    let channels = digest["channels"].as_array().expect("channels");
    assert_eq!(channels.len(), 60, "every channel is reported");
    for c in channels {
        let tail = c["last_messages"].as_array().expect("tail");
        assert!(!tail.is_empty() && tail.len() <= 5, "tail is 1..=5: {c:?}");
        assert_eq!(c["message_count"], 6, "counts survive the rewrite: {c:?}");
        // The tail must be chronological, oldest first — the window function
        // orders by id, and reversing it silently would be easy to miss.
        let first = tail[0]["body"].as_str().unwrap_or("");
        assert!(
            first.contains("message 1"),
            "oldest of the tail first: {tail:?}"
        );
    }

    // Thirty times the channels must not cost thirty times the digest. The
    // bound comes from measuring both shapes rather than taste: one statement
    // runs at 2.0-2.1 here — real growth, 360 rows against 12 — and a query
    // per channel at 4.2-4.3. Three sits between them with room on both
    // sides.
    // The bound has an absolute term as well as a ratio. Two channels can
    // measure well under a millisecond, and the ratio of two sub-millisecond
    // durations on a shared CI runner is mostly scheduler noise — which is
    // how this assertion failed on runs where nothing was wrong. A query per
    // channel costs tens of milliseconds at sixty channels, so the slack
    // does not hide the shape it is here to catch.
    let allowed = small.mul_f64(3.0) + std::time::Duration::from_millis(5);
    assert!(
        large < allowed,
        "digest over 60 channels took {large:?} against {small:?} over 2 \
         (allowed {allowed:?}): the cost is scaling with channel count"
    );

    let _ = client.cancel().await;
    h.shutdown().await;
}

#[tokio::test]
async fn attachment_quotas_are_enforced_per_team() {
    use base64::Engine;
    let b64 = |data: &[u8]| base64::engine::general_purpose::STANDARD.encode(data);

    let h = require_db!("t_quota");
    let a = seed_agent(&h.pool, "acme", "joaquin").await;
    let other = seed_agent(&h.pool, "rival", "spy").await;
    let joaquin = connect(&h.base, &a).await;
    let spy = connect(&h.base, &other).await;
    call(&joaquin, "create_channel", json!({"name": "dev"})).await;
    call(&spy, "create_channel", json!({"name": "dev"})).await;

    // 300 KiB of room for acme; rival stays unlimited.
    sqlx::query("UPDATE teams SET attachment_bytes_limit = $1 WHERE slug = 'acme'")
        .bind(300 * 1024i64)
        .execute(&h.pool)
        .await
        .unwrap();

    let file = |n: usize| json!([{"filename": "f.bin", "data_base64": b64(&vec![b'x'; n])}]);

    // Two 128 KiB files fit.
    for _ in 0..2 {
        call(
            &joaquin,
            "post_message",
            json!({"channel": "dev", "body": "chunk", "attachments": file(128 * 1024)}),
        )
        .await;
    }

    // The third does not, and the error says what to do about it.
    let err = call_expect_error(
        &joaquin,
        "post_message",
        json!({"channel": "dev", "body": "chunk", "attachments": file(128 * 1024)}),
    )
    .await;
    assert!(err.contains("quota"), "names the problem: {err}");
    assert!(
        err.contains("307200") && err.contains("raise the quota"),
        "states the limit and the way out: {err}"
    );

    // The rejection is atomic: the message did not land either.
    let msgs = call(
        &joaquin,
        "read_messages",
        json!({"scope": "dev", "only_new": false}),
    )
    .await;
    assert_eq!(
        msgs["messages"].as_array().map(Vec::len),
        Some(2),
        "a quota rejection must not leave the message behind: {msgs:?}"
    );

    // Another team's quota is its own business.
    call(
        &spy,
        "post_message",
        json!({"channel": "dev", "body": "unbounded", "attachments": file(200 * 1024)}),
    )
    .await;

    // Usage counts only this team's bytes.
    let team: (Uuid,) = sqlx::query_as("SELECT id FROM teams WHERE slug = 'acme'")
        .fetch_one(&h.pool)
        .await
        .unwrap();
    let usage = ai_crew_sync::store::quota::usage(&h.pool, team.0)
        .await
        .expect("usage");
    assert_eq!(usage.attachment_count, 2);
    assert_eq!(usage.attachment_bytes, 256 * 1024);
    assert_eq!(usage.attachment_bytes_limit, Some(300 * 1024));

    // Racing uploads cannot both take the last slot: the check and the insert
    // share a transaction that locks the team row.
    sqlx::query("UPDATE teams SET attachment_bytes_limit = $1 WHERE slug = 'acme'")
        .bind(256 * 1024i64 + 100 * 1024)
        .execute(&h.pool)
        .await
        .unwrap();
    let racers: Vec<_> = (0..4)
        .map(|_| {
            let base = h.base.clone();
            let token = a.clone();
            tokio::spawn(async move {
                let c = connect(&base, &token).await;
                let args: serde_json::Map<String, serde_json::Value> =
                    serde_json::from_value(json!({"channel": "dev", "body": "race",
                           "attachments": [{"filename": "r.bin",
                                            "data_base64": base64::engine::general_purpose::STANDARD
                                                .encode(vec![b'y'; 90 * 1024])}]}))
                    .unwrap();
                let ok = c
                    .call_tool(
                        CallToolRequestParams::new("post_message".to_string()).with_arguments(args),
                    )
                    .await
                    .map(|r| r.is_error != Some(true))
                    .unwrap_or(false);
                let _ = c.cancel().await;
                ok
            })
        })
        .collect();
    let mut accepted = 0;
    for r in racers {
        if r.await.unwrap_or(false) {
            accepted += 1;
        }
    }
    assert_eq!(
        accepted, 1,
        "only one of four racing 90 KiB uploads fits in 100 KiB of room"
    );

    let usage = ai_crew_sync::store::quota::usage(&h.pool, team.0)
        .await
        .expect("usage");
    assert!(
        usage.attachment_bytes <= usage.attachment_bytes_limit.unwrap(),
        "the quota was never exceeded: {} > {:?}",
        usage.attachment_bytes,
        usage.attachment_bytes_limit
    );

    let _ = joaquin.cancel().await;
    let _ = spy.cancel().await;
    h.shutdown().await;
}

/// Retention has to be safe to try: a dry run reports exactly what a real run
/// would remove, and removes nothing.
#[tokio::test]
async fn pruning_is_dry_by_default_and_keeps_durable_state() {
    let h = require_db!("t_prune");
    let a = seed_agent(&h.pool, "acme", "joaquin").await;
    let joaquin = connect(&h.base, &a).await;
    call(&joaquin, "create_channel", json!({"name": "dev"})).await;
    call(
        &joaquin,
        "post_message",
        json!({"channel": "dev", "body": "old"}),
    )
    .await;
    call(&joaquin, "set_note", json!({"key": "k", "value": "v1"})).await;
    call(&joaquin, "set_note", json!({"key": "k", "value": "v2"})).await;
    call(&joaquin, "create_task", json!({"key": "t", "title": "t"})).await;

    // Age everything past the window.
    let team: (Uuid,) = sqlx::query_as("SELECT id FROM teams WHERE slug = 'acme'")
        .fetch_one(&h.pool)
        .await
        .unwrap();
    for sql in [
        "UPDATE messages SET created_at = now() - interval '200 days'",
        "UPDATE note_revisions SET created_at = now() - interval '200 days'",
        "UPDATE task_events SET created_at = now() - interval '200 days'",
    ] {
        sqlx::query(sql).execute(&h.pool).await.unwrap();
    }

    let dry = ai_crew_sync::store::quota::prune(&h.pool, team.0, 90, true)
        .await
        .expect("dry run");
    assert!(dry.dry_run);
    assert_eq!(dry.messages, 1, "reports what it would delete");

    // Nothing actually went away.
    let (still,): (i64,) = sqlx::query_as("SELECT count(*) FROM messages")
        .fetch_one(&h.pool)
        .await
        .unwrap();
    assert_eq!(still, 1, "a dry run deletes nothing");

    let applied = ai_crew_sync::store::quota::prune(&h.pool, team.0, 90, false)
        .await
        .expect("apply");
    assert_eq!(
        applied.messages, dry.messages,
        "the dry run's count was the real one"
    );

    // The durable state survives: the note keeps its current value, the task
    // still exists. Only history was trimmed.
    let note = call(&joaquin, "get_note", json!({"key": "k"})).await;
    assert_eq!(
        note["note"]["value"], "v2",
        "notes are not pruned: {note:?}"
    );
    let task = call(&joaquin, "get_task", json!({"key": "t"})).await;
    assert_eq!(task["task"]["key"], "t", "tasks are not pruned: {task:?}");

    // A nonsensical window is refused rather than deleting everything.
    let err = ai_crew_sync::store::quota::prune(&h.pool, team.0, 0, true).await;
    assert!(err.is_err(), "older_than_days must be at least 1");

    // A day count above i32::MAX used to wrap NEGATIVE, which makes
    // `now() - make_interval(days => -N)` a FUTURE instant — so every row
    // matched and "keep almost everything" became "delete everything".
    let err = ai_crew_sync::store::quota::prune(&h.pool, team.0, 2_147_483_648, true).await;
    assert!(err.is_err(), "a day count above i32::MAX must be refused");
    let (survived,): (i64,) = sqlx::query_as("SELECT count(*) FROM notes")
        .fetch_one(&h.pool)
        .await
        .unwrap();
    assert_eq!(survived, 1, "a refused prune deletes nothing");

    let _ = joaquin.cancel().await;
    h.shutdown().await;
}

/// A dropped harness must not leave an axum task, a listener or a dispatcher
/// behind: the suite runs 20+ tests in one process, and leaked listeners would
/// keep consuming notifications for everyone else.
#[tokio::test]
async fn shutdown_stops_the_server_and_its_background_tasks() {
    let h = require_db!("t_shutdown");
    let base = h.base.clone();
    let pool = h.pool.clone();
    let token = seed_agent(&h.pool, "acme", "joaquin").await;

    // Alive before.
    let http = reqwest::Client::new();
    let resp = http.get(format!("{base}/health")).send().await.unwrap();
    assert_eq!(resp.status(), 200);

    h.shutdown().await;

    // After shutdown the socket is closed: the request fails to connect
    // rather than hanging or being served by a task nobody joined.
    let resp = tokio::time::timeout(
        std::time::Duration::from_secs(5),
        http.get(format!("{base}/health")).send(),
    )
    .await
    .expect("the request must not hang after shutdown");
    assert!(
        resp.is_err(),
        "the server should no longer accept connections"
    );

    // The pool is closed too, so a query through it fails rather than
    // silently opening a fresh connection.
    let seeded = sqlx::query("SELECT 1").execute(&pool).await;
    assert!(
        seeded.is_err(),
        "the harness pool must be closed after shutdown"
    );
    assert!(!token.is_empty(), "the agent was seeded before shutdown");
}

#[tokio::test]
async fn the_database_refuses_cross_team_references() {
    let h = require_db!("t_teamfk");

    // Two teams with one agent each, plus a channel and a task per team.
    let team_a: (Uuid,) =
        sqlx::query_as("INSERT INTO teams (slug, name) VALUES ('a', 'A') RETURNING id")
            .fetch_one(&h.pool)
            .await
            .unwrap();
    let team_b: (Uuid,) =
        sqlx::query_as("INSERT INTO teams (slug, name) VALUES ('b', 'B') RETURNING id")
            .fetch_one(&h.pool)
            .await
            .unwrap();
    let agent_a: (Uuid,) =
        sqlx::query_as("INSERT INTO agents (team_id, name) VALUES ($1, 'a') RETURNING id")
            .bind(team_a.0)
            .fetch_one(&h.pool)
            .await
            .unwrap();
    let agent_b: (Uuid,) =
        sqlx::query_as("INSERT INTO agents (team_id, name) VALUES ($1, 'b') RETURNING id")
            .bind(team_b.0)
            .fetch_one(&h.pool)
            .await
            .unwrap();
    let channel_a: (Uuid,) =
        sqlx::query_as("INSERT INTO channels (team_id, name) VALUES ($1, 'dev') RETURNING id")
            .bind(team_a.0)
            .fetch_one(&h.pool)
            .await
            .unwrap();
    let task_a: (Uuid,) = sqlx::query_as(
        "INSERT INTO tasks (team_id, key, title) VALUES ($1, 'ta', 't') RETURNING id",
    )
    .bind(team_a.0)
    .fetch_one(&h.pool)
    .await
    .unwrap();
    let task_b: (Uuid,) = sqlx::query_as(
        "INSERT INTO tasks (team_id, key, title) VALUES ($1, 'tb', 't') RETURNING id",
    )
    .bind(team_b.0)
    .fetch_one(&h.pool)
    .await
    .unwrap();

    // A sender from the other team.
    let err = sqlx::query(
        "INSERT INTO messages (team_id, channel_id, sender_agent_id, body) VALUES ($1,$2,$3,'x')",
    )
    .bind(team_a.0)
    .bind(channel_a.0)
    .bind(agent_b.0)
    .execute(&h.pool)
    .await;
    assert!(err.is_err(), "a sender from another team must be rejected");

    // A channel belonging to the other team.
    let err = sqlx::query(
        "INSERT INTO messages (team_id, sender_agent_id, channel_id, body) VALUES ($1,$2,$3,'x')",
    )
    .bind(team_b.0)
    .bind(agent_b.0)
    .bind(channel_a.0)
    .execute(&h.pool)
    .await;
    assert!(err.is_err(), "another team's channel must be rejected");

    // A direct message addressed across the team boundary.
    let err = sqlx::query(
        "INSERT INTO messages (team_id, sender_agent_id, recipient_agent_id, body)
         VALUES ($1,$2,$3,'x')",
    )
    .bind(team_a.0)
    .bind(agent_a.0)
    .bind(agent_b.0)
    .execute(&h.pool)
    .await;
    assert!(err.is_err(), "a cross-team DM must be rejected");

    // A lock held by the other team's agent.
    let err = sqlx::query(
        "INSERT INTO locks (team_id, name, holder_agent_id, expires_at)
         VALUES ($1,'x',$2, now() + interval '1 hour')",
    )
    .bind(team_a.0)
    .bind(agent_b.0)
    .execute(&h.pool)
    .await;
    assert!(err.is_err(), "a holder from another team must be rejected");

    // A dependency spanning two teams' tasks.
    let err = sqlx::query("INSERT INTO task_deps (task_id, blocked_by_task_id) VALUES ($1,$2)")
        .bind(task_a.0)
        .bind(task_b.0)
        .execute(&h.pool)
        .await;
    assert!(err.is_err(), "a cross-team dependency must be rejected");

    // An attachment on another team's message.
    let msg_a: (i64,) = sqlx::query_as(
        "INSERT INTO messages (team_id, channel_id, sender_agent_id, body)
         VALUES ($1,$2,$3,'legit') RETURNING id",
    )
    .bind(team_a.0)
    .bind(channel_a.0)
    .bind(agent_a.0)
    .fetch_one(&h.pool)
    .await
    .expect("a same-team message is still accepted");

    let err = sqlx::query(
        "INSERT INTO attachments (team_id, message_id, uploader_agent_id, filename, size_bytes, data)
         VALUES ($1,$2,$3,'f',1,'\\x00')",
    )
    .bind(team_b.0)
    .bind(msg_a.0)
    .bind(agent_b.0)
    .execute(&h.pool)
    .await;
    assert!(
        err.is_err(),
        "an attachment on another team's message must be rejected"
    );
}

#[tokio::test]
async fn oversized_fields_are_rejected_with_their_limit() {
    let h = require_db!("t_caps");
    let a = seed_agent(&h.pool, "acme", "joaquin").await;
    let joaquin = connect(&h.base, &a).await;
    call(&joaquin, "create_channel", json!({"name": "dev"})).await;

    // metadata is a pointer payload, not a document: 16 KiB.
    let fat = "x".repeat(20 * 1024);
    let err = call_expect_error(
        &joaquin,
        "post_message",
        json!({"channel": "dev", "body": "hi", "metadata": {"blob": fat}}),
    )
    .await;
    assert!(err.contains("16384"), "names the metadata limit: {err}");

    let err = call_expect_error(
        &joaquin,
        "create_task",
        json!({"key": "fat-meta", "title": "t", "metadata": {"blob": fat}}),
    )
    .await;
    assert!(err.contains("16384"), "same limit on tasks: {err}");

    // Task text fields.
    let long_title = "t".repeat(600);
    let err = call_expect_error(
        &joaquin,
        "create_task",
        json!({"key": "long-title", "title": long_title}),
    )
    .await;
    assert!(err.contains("512"), "names the title limit: {err}");

    let long_text = "d".repeat(70 * 1024);
    let err = call_expect_error(
        &joaquin,
        "create_task",
        json!({"key": "long-desc", "title": "t", "description": long_text.clone()}),
    )
    .await;
    assert!(err.contains("65536"), "names the description limit: {err}");

    call(
        &joaquin,
        "create_task",
        json!({"key": "capped", "title": "fits"}),
    )
    .await;
    call(&joaquin, "claim_task", json!({"key": "capped"})).await;
    let err = call_expect_error(
        &joaquin,
        "complete_task",
        json!({"key": "capped", "result": long_text}),
    )
    .await;
    assert!(err.contains("65536"), "names the result limit: {err}");

    // Nothing oversized was stored: the task is still claimed, not done.
    let task = call(&joaquin, "get_task", json!({"key": "capped"})).await;
    assert_eq!(task["task"]["status"], "claimed", "{task:?}");

    // A 1 MiB body and note are accepted; one byte over is not.
    let one_mib = "b".repeat(1024 * 1024);
    call(
        &joaquin,
        "post_message",
        json!({"channel": "dev", "body": one_mib.clone()}),
    )
    .await;
    let err = call_expect_error(
        &joaquin,
        "post_message",
        json!({"channel": "dev", "body": format!("{one_mib}x")}),
    )
    .await;
    assert!(err.contains("1048576"), "names the body limit: {err}");

    call(
        &joaquin,
        "set_note",
        json!({"key": "big-note", "value": one_mib.clone()}),
    )
    .await;
    let err = call_expect_error(
        &joaquin,
        "set_note",
        json!({"key": "big-note", "value": format!("{one_mib}x")}),
    )
    .await;
    assert!(err.contains("1048576"), "names the note limit: {err}");

    // Whitespace padding must not smuggle a large payload past the cap.
    let padded = format!("{}fits", " ".repeat(700));
    let err = call_expect_error(
        &joaquin,
        "create_task",
        json!({"key": "padded", "title": padded}),
    )
    .await;
    assert!(
        err.contains("512"),
        "raw size counts, not just trimmed: {err}"
    );

    // And values just under the limits still work.
    call(
        &joaquin,
        "post_message",
        json!({"channel": "dev", "body": "ok", "metadata": {"k": "v"}}),
    )
    .await;
    call(
        &joaquin,
        "create_task",
        json!({"key": "ok-task", "title": "t".repeat(512), "description": "d".repeat(1000)}),
    )
    .await;

    let _ = joaquin.cancel().await;
}

#[tokio::test]
async fn attachments_travel_with_messages_and_tasks() {
    use base64::Engine;
    let b64 = |data: &[u8]| base64::engine::general_purpose::STANDARD.encode(data);

    let h = require_db!("t_attach");
    let a = seed_agent(&h.pool, "acme", "joaquin").await;
    let b = seed_agent(&h.pool, "acme", "marta").await;
    let c = seed_agent(&h.pool, "acme", "pedro").await;
    let joaquin = connect(&h.base, &a).await;
    let marta = connect(&h.base, &b).await;
    let pedro = connect(&h.base, &c).await;

    let diff = "diff --git a/src/lib.rs b/src/lib.rs\n-old\n+new\n";

    // A channel message ships with its file in one call.
    call(&joaquin, "create_channel", json!({"name": "dev"})).await;
    let posted = call(
        &joaquin,
        "post_message",
        json!({
            "channel": "dev", "body": "parser fix attached",
            "attachments": [{
                "filename": "fix.diff", "content_type": "text/plain",
                "data_base64": b64(diff.as_bytes())
            }]
        }),
    )
    .await;
    let att = &posted["message"]["attachments"][0];
    assert_eq!(att["filename"], "fix.diff", "{posted:?}");
    let att_id = att["id"].as_i64().unwrap();

    // A teammate sees the attachment listed and downloads identical bytes.
    let read = call(&marta, "read_messages", json!({"scope": "dev"})).await;
    let msg = read["messages"].as_array().unwrap().last().unwrap().clone();
    assert_eq!(msg["attachments"][0]["id"], att_id, "{msg:?}");
    let got = call(&marta, "get_attachment", json!({"id": att_id})).await;
    assert_eq!(got["data_base64"].as_str().unwrap(), b64(diff.as_bytes()));
    assert_eq!(got["uploaded_by"], "joaquin");

    // DM attachments are invisible to anyone but the two parties.
    let dm = call(
        &joaquin,
        "post_message",
        json!({
            "to": "marta", "body": "the failing log",
            "attachments": [{"filename": "secret.log", "data_base64": b64(b"boom")}]
        }),
    )
    .await;
    let dm_att = dm["message"]["attachments"][0]["id"].as_i64().unwrap();
    call(&marta, "get_attachment", json!({"id": dm_att})).await;
    let err = call_expect_error(&pedro, "get_attachment", json!({"id": dm_att})).await;
    assert!(
        err.contains("not found"),
        "third party must not see it: {err}"
    );

    // Tasks carry attachments too, from any teammate.
    call(
        &joaquin,
        "create_task",
        json!({"key": "fix-parser", "title": "Fix the parser"}),
    )
    .await;
    call(
        &marta,
        "attach_file",
        json!({"task": "fix-parser", "filename": "repro.log", "data_base64": b64(b"repro")}),
    )
    .await;
    let task = call(&pedro, "get_task", json!({"key": "fix-parser"})).await;
    assert_eq!(
        task["task"]["attachments"][0]["filename"], "repro.log",
        "{task:?}"
    );

    // The size cap rejects with an actionable message.
    let big = vec![b'x'; 300 * 1024];
    let err = call_expect_error(
        &joaquin,
        "attach_file",
        json!({"task": "fix-parser", "filename": "big.bin", "data_base64": b64(&big)}),
    )
    .await;
    assert!(err.contains("262144"), "must state the limit: {err}");

    let _ = joaquin.cancel().await;
    let _ = marta.cancel().await;
    let _ = pedro.cancel().await;
}

#[tokio::test]
async fn blocked_tasks_wait_for_their_dependencies() {
    let h = require_db!("t_deps");
    let a = seed_agent(&h.pool, "acme", "joaquin").await;
    let b = seed_agent(&h.pool, "acme", "marta").await;
    let joaquin = connect(&h.base, &a).await;
    let marta = connect(&h.base, &b).await;

    call(
        &joaquin,
        "create_task",
        json!({"key": "migrate-schema", "title": "migrate the users schema"}),
    )
    .await;
    let dependent = call(
        &joaquin,
        "create_task",
        json!({
            "key": "update-clients",
            "title": "update the API clients",
            "depends_on": ["migrate-schema"]
        }),
    )
    .await;
    assert_eq!(dependent["blocked"], true);
    assert_eq!(dependent["depends_on"][0], "migrate-schema");

    // A dependency that does not exist is a clean error.
    let err = call_expect_error(
        &joaquin,
        "create_task",
        json!({"key": "x", "title": "x", "depends_on": ["nope"]}),
    )
    .await;
    assert!(err.contains("nope"), "got: {err}");

    // The blocked task cannot be claimed, with an explanatory reason.
    let denied = call(&marta, "claim_task", json!({"key": "update-clients"})).await;
    assert_eq!(denied["claimed"], false);
    assert!(
        denied["reason"]
            .as_str()
            .unwrap()
            .contains("migrate-schema"),
        "reason should name the blocker: {denied:?}"
    );

    // claim_next_task skips it and hands out the dependency instead.
    let next = call(&marta, "claim_next_task", json!({})).await;
    assert_eq!(next["claimed"], true);
    assert_eq!(next["task"]["key"], "migrate-schema");

    // Finishing the dependency unblocks the dependent task.
    call(&marta, "complete_task", json!({"key": "migrate-schema"})).await;
    let now_free = call(&joaquin, "claim_task", json!({"key": "update-clients"})).await;
    assert_eq!(
        now_free["claimed"], true,
        "unblocked after dep done: {now_free:?}"
    );
    assert_eq!(now_free["task"]["blocked"], false);

    let _ = joaquin.cancel().await;
    let _ = marta.cancel().await;
}

#[tokio::test]
async fn locks_are_exclusive_expiring_and_visible() {
    let h = require_db!("t_locks");
    let a = seed_agent(&h.pool, "acme", "joaquin").await;
    let b = seed_agent(&h.pool, "acme", "marta").await;
    let joaquin = connect(&h.base, &a).await;
    let marta = connect(&h.base, &b).await;

    let got = call(
        &joaquin,
        "acquire_lock",
        json!({"name": "Deploy:Staging", "ttl_seconds": 120, "purpose": "rolling out 1.4.2"}),
    )
    .await;
    assert_eq!(got["acquired"], true);
    assert_eq!(got["lock"]["name"], "deploy:staging", "name normalised");

    // Second acquirer is refused and told who holds it.
    let denied = call(&marta, "acquire_lock", json!({"name": "deploy:staging"})).await;
    assert_eq!(denied["acquired"], false);
    assert!(denied["reason"].as_str().unwrap().contains("joaquin"));

    // Re-acquiring your own lock extends it, not an error.
    let extended = call(
        &joaquin,
        "acquire_lock",
        json!({"name": "deploy:staging", "ttl_seconds": 600}),
    )
    .await;
    assert_eq!(extended["acquired"], true);

    // Visible to the whole team.
    let listed = call(&marta, "list_locks", json!({})).await;
    assert_eq!(listed["locks"][0]["holder"], "joaquin");
    assert_eq!(listed["locks"][0]["purpose"], "rolling out 1.4.2");

    // You cannot release someone else's lock.
    let err = call_expect_error(&marta, "release_lock", json!({"name": "deploy:staging"})).await;
    assert!(err.contains("joaquin"), "got: {err}");

    // Release frees it for the next agent.
    call(&joaquin, "release_lock", json!({"name": "deploy:staging"})).await;
    let now = call(&marta, "acquire_lock", json!({"name": "deploy:staging"})).await;
    assert_eq!(now["acquired"], true);

    // Expired locks are silently taken over.
    sqlx::query("UPDATE locks SET expires_at = now() - interval '1 second'")
        .execute(&h.pool)
        .await
        .unwrap();
    let stolen = call(&joaquin, "acquire_lock", json!({"name": "deploy:staging"})).await;
    assert_eq!(stolen["acquired"], true, "expired lock must be stealable");

    let _ = joaquin.cancel().await;
    let _ = marta.cancel().await;
}

#[tokio::test]
async fn team_digest_summarises_recent_activity() {
    let h = require_db!("t_digest");
    let a = seed_agent(&h.pool, "acme", "joaquin").await;
    let b = seed_agent(&h.pool, "acme", "marta").await;
    let joaquin = connect(&h.base, &a).await;
    let marta = connect(&h.base, &b).await;

    call(&joaquin, "create_channel", json!({"name": "deploys"})).await;
    call(
        &joaquin,
        "post_message",
        json!({"channel": "deploys", "body": "staging lleva la 1.4.2"}),
    )
    .await;
    call(
        &marta,
        "create_task",
        json!({"key": "hotfix", "title": "hotfix the parser"}),
    )
    .await;
    call(&marta, "claim_task", json!({"key": "hotfix"})).await;
    call(
        &marta,
        "complete_task",
        json!({"key": "hotfix", "result": "merged in #99"}),
    )
    .await;
    call(
        &joaquin,
        "set_note",
        json!({"scope": "api", "key": "deploy-runbook", "value": "step 1..."}),
    )
    .await;
    call(&marta, "heartbeat", json!({"activity": "reviewing PRs"})).await;
    // A DM that must NOT leak into the digest.
    call(
        &joaquin,
        "post_message",
        json!({"to": "marta", "body": "esto es privado"}),
    )
    .await;

    let digest = call(&joaquin, "team_digest", json!({"hours": 24})).await;
    assert_eq!(digest["channels"][0]["name"], "deploys");
    assert_eq!(digest["channels"][0]["message_count"], 1);
    let tasks: Vec<&str> = digest["tasks_moved"]
        .as_array()
        .unwrap()
        .iter()
        .map(|t| t["key"].as_str().unwrap())
        .collect();
    assert!(tasks.contains(&"hotfix"));
    assert_eq!(digest["notes_updated"][0]["key"], "deploy-runbook");
    assert!(
        digest["agents_seen"]
            .as_array()
            .unwrap()
            .iter()
            .any(|a| a["name"] == "marta" && a["online"] == true)
    );
    let serialized = serde_json::to_string(&digest).unwrap();
    assert!(
        !serialized.contains("privado"),
        "digest must never contain direct messages"
    );

    let _ = joaquin.cancel().await;
    let _ = marta.cancel().await;
}

#[tokio::test]
async fn webhooks_forward_channel_messages_but_never_dms() {
    let h = require_db!("t_webhooks");
    let a = seed_agent(&h.pool, "acme", "joaquin").await;
    let b = seed_agent(&h.pool, "acme", "marta").await;
    let joaquin = connect(&h.base, &a).await;

    // A local catcher standing in for Slack.
    let received: std::sync::Arc<tokio::sync::Mutex<Vec<Value>>> = Default::default();
    let catcher = {
        let received = received.clone();
        let app = axum::Router::new().route(
            "/hook",
            axum::routing::post(move |axum::Json(v): axum::Json<Value>| {
                let received = received.clone();
                async move {
                    received.lock().await.push(v);
                    "ok"
                }
            }),
        );
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            let _ = axum::serve(listener, app).await;
        });
        addr
    };

    ai_crew_sync::webhooks::webhook_add(
        &h.pool,
        "acme",
        &format!("http://{catcher}/hook"),
        "slack",
        "message,task",
        None,
    )
    .await
    .unwrap();

    call(&joaquin, "create_channel", json!({"name": "deploys"})).await;
    call(
        &joaquin,
        "post_message",
        json!({"channel": "deploys", "body": "canary verde"}),
    )
    .await;
    call(
        &joaquin,
        "post_message",
        json!({"to": "marta", "body": "secreto entre nosotros"}),
    )
    .await;
    call(
        &joaquin,
        "create_task",
        json!({"key": "rotate", "title": "rotate keys"}),
    )
    .await;
    let _ = b; // marta only needs to exist as a DM target

    // Give LISTEN/NOTIFY + dispatch a moment.
    let mut tries = 0;
    loop {
        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
        let got = received.lock().await;
        if got.len() >= 2 || tries > 20 {
            break;
        }
        drop(got);
        tries += 1;
    }

    let got = received.lock().await;
    let texts: Vec<String> = got
        .iter()
        .map(|v| v["text"].as_str().unwrap_or_default().to_owned())
        .collect();
    assert!(
        texts
            .iter()
            .any(|t| t.contains("#deploys") && t.contains("canary verde")),
        "channel message must be forwarded in Slack format: {texts:?}"
    );
    assert!(
        texts.iter().any(|t| t.contains("rotate")),
        "task event must be forwarded: {texts:?}"
    );
    assert!(
        !texts.iter().any(|t| t.contains("secreto")),
        "a DM must NEVER reach a webhook: {texts:?}"
    );

    let _ = joaquin.cancel().await;
}

#[tokio::test]
async fn dashboard_requires_a_token_and_renders_team_state() {
    let h = require_db!("t_dash");
    let a = seed_agent(&h.pool, "acme", "joaquin").await;
    let joaquin = connect(&h.base, &a).await;
    call(&joaquin, "heartbeat", json!({"activity": "smoke testing"})).await;
    call(&joaquin, "create_channel", json!({"name": "dev"})).await;
    call(
        &joaquin,
        "post_message",
        json!({"channel": "dev", "body": "<script>alert(1)</script> it's here"}),
    )
    .await;

    // Redirects are followed manually so the Set-Cookie exchange is visible.
    let http = reqwest::Client::builder()
        .redirect(reqwest::redirect::Policy::none())
        .build()
        .unwrap();
    let base = &h.base;

    // No credential at all → the sign-in page, not the data.
    let resp = http.get(format!("{base}/dashboard")).send().await.unwrap();
    assert_eq!(resp.status(), 401);
    let body = resp.text().await.unwrap();
    assert!(body.contains("<form"), "offers a form to sign in: {body}");
    assert!(!body.contains("smoke testing"), "leaks no team state");

    // A token in the query string is NOT a credential any more.
    let resp = http
        .get(format!("{base}/dashboard?token={a}"))
        .send()
        .await
        .unwrap();
    assert_eq!(
        resp.status(),
        401,
        "query-string tokens must not authenticate"
    );

    // Exchange the token for a session cookie via the form POST.
    let resp = http
        .post(format!("{base}/dashboard/login"))
        .header("Content-Type", "application/x-www-form-urlencoded")
        .body(format!("token={a}"))
        .send()
        .await
        .unwrap();
    assert!(
        resp.status().is_redirection(),
        "successful login redirects: {}",
        resp.status()
    );
    let cookie = resp
        .headers()
        .get("set-cookie")
        .and_then(|v| v.to_str().ok())
        .expect("a session cookie")
        .to_owned();
    assert!(cookie.contains("HttpOnly"), "cookie is HttpOnly: {cookie}");
    assert!(
        cookie.contains("SameSite=Strict"),
        "cookie is SameSite=Strict: {cookie}"
    );
    assert!(
        !cookie.contains(&a),
        "the agent token itself must never be the cookie value"
    );

    let grant = cookie.split(';').next().expect("cookie pair").to_owned();

    // A bad token gets the form back, not a cookie.
    let resp = http
        .post(format!("{base}/dashboard/login"))
        .header("Content-Type", "application/x-www-form-urlencoded")
        .body("token=acs_bogus")
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 401);
    assert!(resp.headers().get("set-cookie").is_none());

    // The cookie renders the page.
    let resp = http
        .get(format!("{base}/dashboard"))
        .header("Cookie", &grant)
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
    assert_eq!(
        resp.headers()
            .get("cache-control")
            .and_then(|v| v.to_str().ok()),
        Some("no-store"),
        "team activity is never cached"
    );
    assert_eq!(
        resp.headers()
            .get("referrer-policy")
            .and_then(|v| v.to_str().ok()),
        Some("no-referrer")
    );
    let body = resp.text().await.unwrap();
    assert!(body.contains("joaquin"), "shows the agent");
    assert!(body.contains("smoke testing"), "shows the activity");
    assert!(
        !body.contains("<script>alert(1)</script>"),
        "message bodies must be HTML-escaped"
    );
    assert!(body.contains("&lt;script&gt;"), "escaped form present");
    assert!(!body.contains("it's here"), "single quotes escaped too");
    assert!(body.contains("it&#39;s here"), "escaped quote present");

    // The grant is read-only: it cannot drive the MCP surface.
    let grant_value = grant.split_once('=').expect("cookie pair").1.to_owned();
    for attempt in [
        http.post(format!("{base}/mcp"))
            .header("Cookie", &grant)
            .header("Accept", "application/json, text/event-stream")
            .json(&json!({"jsonrpc":"2.0","id":1,"method":"tools/list"})),
        http.post(format!("{base}/mcp"))
            .header("Authorization", format!("Bearer {grant_value}"))
            .header("Accept", "application/json, text/event-stream")
            .json(&json!({"jsonrpc":"2.0","id":1,"method":"tools/list"})),
    ] {
        let resp = attempt.send().await.unwrap();
        assert_eq!(
            resp.status(),
            401,
            "a dashboard grant must not authenticate an MCP call"
        );
    }

    // The bearer header still works for scripts, without any cookie exchange.
    let resp = http
        .get(format!("{base}/dashboard"))
        .header("Authorization", format!("Bearer {a}"))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200, "curl/script access keeps working");

    let _ = joaquin.cancel().await;
}

// ------------------------------------------------------------------ sessions --

#[tokio::test]
async fn one_token_carries_several_sessions_without_splitting_identity() {
    let h = require_db!("t_session_ctx");
    let token = seed_agent(&h.pool, "layerv", "joaquin").await;

    let market = connect_with_session(&h.base, &token, "market-data").await;
    let core = connect_with_session(&h.base, &token, "core-manager").await;
    let shared = connect(&h.base, &token).await;

    let m = call(&market, "whoami", json!({})).await;
    let c = call(&core, "whoami", json!({})).await;
    let s = call(&shared, "whoami", json!({})).await;

    // One person: the session never changes who is speaking.
    assert_eq!(m["agent"], "joaquin");
    assert_eq!(m["agent_id"], c["agent_id"]);
    assert_eq!(m["agent_id"], s["agent_id"]);
    assert_eq!(m["team"], "layerv");

    // Three working contexts.
    assert_eq!(m["session"], "market-data");
    assert_eq!(c["session"], "core-manager");
    assert_eq!(
        s["session"],
        Value::Null,
        "no header must report the shared session as null, not as an empty name"
    );

    // Case and padding must not silently create a second session.
    let same = connect_with_session(&h.base, &token, "  Market-Data ").await;
    assert_eq!(
        call(&same, "whoami", json!({})).await["session"],
        "market-data"
    );

    // Presence is per session now, so list_agents must still report one entry
    // per *person* rather than one per session. Grouping the sessions under
    // their agent is the next change in the stack; until it lands, duplicate
    // rows would read as duplicate teammates.
    call(&market, "heartbeat", json!({"repo": "Layer-V/market-data"})).await;
    call(&core, "heartbeat", json!({"repo": "Layer-V/core-manager"})).await;
    let seen = call(&market, "list_agents", json!({})).await;
    let mine = seen["agents"]
        .as_array()
        .unwrap()
        .iter()
        .filter(|a| a["name"] == "joaquin")
        .count();
    assert_eq!(mine, 1, "one entry per teammate: {seen}");
    assert_eq!(seen["online_count"], 1, "two sessions is still one person");

    for client in [market, core, shared, same] {
        let _ = client.cancel().await;
    }
    h.shutdown().await;
}

#[tokio::test]
async fn a_malformed_session_header_is_rejected_before_the_token_is_used() {
    let h = require_db!("t_session_bad");
    let token = seed_agent(&h.pool, "layerv", "joaquin").await;
    let http = reqwest::Client::new();

    let call_with = |session: String| {
        let http = http.clone();
        let base = h.base.clone();
        let token = token.clone();
        async move {
            http.post(format!("{base}/mcp"))
                .header("Authorization", format!("Bearer {token}"))
                .header(ai_crew_sync::auth::SESSION_HEADER, session)
                .header("Accept", "application/json, text/event-stream")
                .json(&json!({"jsonrpc":"2.0","id":1,"method":"tools/list"}))
                .send()
                .await
                .unwrap()
        }
    };

    let resp = call_with("x".repeat(ai_crew_sync::auth::MAX_SESSION_BYTES + 1)).await;
    assert_eq!(
        resp.status(),
        400,
        "an over-long session label is a bad request"
    );
    let body = resp.text().await.unwrap();
    assert!(
        body.contains(&ai_crew_sync::auth::MAX_SESSION_BYTES.to_string()),
        "the error must state the limit so the caller can fix it: {body}"
    );

    // '/' separates agent from session when addressing a message.
    let resp = call_with("joaquin/market-data".to_owned()).await;
    assert_eq!(resp.status(), 400);

    // A valid label on the same token still works, so nothing above rejected
    // the token itself.
    let resp = call_with("market-data".to_owned()).await;
    assert_eq!(resp.status(), 200);

    h.shutdown().await;
}

#[tokio::test]
async fn presence_is_tracked_per_session_not_per_person() {
    let h = require_db!("t_presence_sessions");
    let token = seed_agent(&h.pool, "layerv", "joaquin").await;
    let dani = seed_agent(&h.pool, "layerv", "dani").await;

    let market = connect_with_session(&h.base, &token, "market-data").await;
    let core = connect_with_session(&h.base, &token, "core-manager").await;

    call(
        &market,
        "heartbeat",
        json!({"repo": "Layer-V/market-data", "branch": "devops/scanning"}),
    )
    .await;
    call(
        &core,
        "heartbeat",
        json!({"repo": "Layer-V/core-manager", "branch": "issue-151"}),
    )
    .await;

    // Before this change the second heartbeat overwrote the first, and the
    // board showed one repo flapping between the two.
    let seen = call(&market, "list_agents", json!({})).await;
    let joaquin = seen["agents"]
        .as_array()
        .unwrap()
        .iter()
        .find(|a| a["name"] == "joaquin")
        .expect("joaquin is on the bus");

    let sessions = joaquin["sessions"].as_array().expect("two contexts listed");
    assert_eq!(
        sessions.len(),
        2,
        "one entry per working context: {joaquin}"
    );
    let mut repos: Vec<&str> = sessions
        .iter()
        .map(|s| s["repo"].as_str().unwrap_or_default())
        .collect();
    repos.sort_unstable();
    assert_eq!(repos, ["Layer-V/core-manager", "Layer-V/market-data"]);

    let mut labels: Vec<&str> = sessions
        .iter()
        .map(|s| s["session"].as_str().unwrap_or_default())
        .collect();
    labels.sort_unstable();
    assert_eq!(labels, ["core-manager", "market-data"]);

    // One person, not two: three live sessions across two people is two online.
    let dani_client = connect(&h.base, &dani).await;
    call(
        &dani_client,
        "heartbeat",
        json!({"repo": "Layer-V/core-manager"}),
    )
    .await;
    let seen = call(&market, "list_agents", json!({})).await;
    assert_eq!(
        seen["online_count"], 2,
        "online_count counts teammates, not sessions: {seen}"
    );

    // An agent with a single shared session keeps the flat shape it had before
    // sessions existed. Asserted on the JSON keys rather than on values,
    // because `value["absent"]` and `value["x"] == null` read the same from a
    // test and very differently from a client.
    let dani_row = seen["agents"]
        .as_array()
        .unwrap()
        .iter()
        .find(|a| a["name"] == "dani")
        .unwrap();
    let keys: Vec<&String> = dani_row.as_object().unwrap().keys().collect();
    assert!(
        !keys.iter().any(|k| *k == "session" || *k == "sessions"),
        "the shared session must add no key at all, before or after: {keys:?}"
    );
    assert_eq!(dani_row["repo"], "Layer-V/core-manager");

    // The digest reads presence too, and it is keyed per session now: a person
    // in two repositories must still appear once in the catch-up.
    let digest = call(&market, "team_digest", json!({"hours": 1})).await;
    let joaquins = digest["agents_seen"]
        .as_array()
        .unwrap()
        .iter()
        .filter(|a| a["name"] == "joaquin")
        .count();
    assert_eq!(joaquins, 1, "one line per teammate in a catch-up: {digest}");

    // One session going stale leaves the others alone.
    sqlx::query(
        "UPDATE agent_presence SET expires_at = now() - interval '1 minute' WHERE session = $1",
    )
    .bind("core-manager")
    .execute(&h.pool)
    .await
    .unwrap();
    let seen = call(&market, "list_agents", json!({"online_only": true})).await;
    let joaquin = seen["agents"]
        .as_array()
        .unwrap()
        .iter()
        .find(|a| a["name"] == "joaquin")
        .expect("the live session keeps joaquin online");
    assert_eq!(joaquin["repo"], "Layer-V/market-data");

    for client in [market, core, dani_client] {
        let _ = client.cancel().await;
    }
    h.shutdown().await;
}

#[tokio::test]
async fn a_claim_belongs_to_a_session_not_to_a_person() {
    let h = require_db!("t_session_claims");
    let token = seed_agent(&h.pool, "layerv", "joaquin").await;

    let market = connect_with_session(&h.base, &token, "market-data").await;
    let core = connect_with_session(&h.base, &token, "core-manager").await;

    call(
        &market,
        "create_task",
        json!({"key": "market-data#42", "title": "wire the feed"}),
    )
    .await;

    let first = call(&market, "claim_task", json!({"key": "market-data#42"})).await;
    assert_eq!(first["claimed"], true);
    assert_eq!(first["task"]["claimed_session"], "market-data");

    // The bug this fixes: before, `claimed_by = me` alone satisfied the claim
    // predicate, so this second window was told it held the task too and both
    // did the work.
    let second = call(&core, "claim_task", json!({"key": "market-data#42"})).await;
    assert_eq!(
        second["claimed"], false,
        "another session of the same person must not hold the same claim"
    );
    let reason = second["reason"].as_str().unwrap_or_default();
    assert!(
        reason.contains("market-data") && reason.contains("your own"),
        "the refusal must name the holding session: {reason}"
    );

    // Re-claiming from the holding session is still a lease renewal.
    let renewed = call(&market, "claim_task", json!({"key": "market-data#42"})).await;
    assert_eq!(renewed["claimed"], true, "self-renewal must keep working");

    // Neither renew nor release crosses sessions, and both say who holds it.
    for tool in ["renew_task_lease", "release_task"] {
        let err = call_expect_error(&core, tool, json!({"key": "market-data#42"})).await;
        assert!(
            err.contains("market-data"),
            "{tool} must name the holding session: {err}"
        );
    }
    call(
        &market,
        "renew_task_lease",
        json!({"key": "market-data#42"}),
    )
    .await;

    // "mine" means this session's, the same rule whoami/renew/release use.
    let mine = call(&market, "list_tasks", json!({"mine_only": true})).await;
    assert_eq!(mine["tasks"].as_array().unwrap().len(), 1);
    let theirs = call(&core, "list_tasks", json!({"mine_only": true})).await;
    assert_eq!(
        theirs["tasks"].as_array().unwrap().len(),
        0,
        "another window of the same token does not own this claim: {theirs}"
    );

    // Releasing clears the session with the holder it belongs to; a released
    // task reporting claimed_by null next to a session name would describe an
    // active holder that does not exist.
    let released = call(&market, "release_task", json!({"key": "market-data#42"})).await;
    assert_eq!(released["status"], "open");
    assert_eq!(released["claimed_by"], Value::Null);
    assert!(
        released.get("claimed_session").is_none_or(|v| v.is_null()),
        "the released task must name no holding session: {released}"
    );
    call(&market, "claim_task", json!({"key": "market-data#42"})).await;

    // An expired lease is stealable by anyone, including another session.
    sqlx::query("UPDATE tasks SET lease_expires_at = now() - interval '1 minute'")
        .execute(&h.pool)
        .await
        .unwrap();
    let stolen = call(&core, "claim_task", json!({"key": "market-data#42"})).await;
    assert_eq!(stolen["claimed"], true, "an expired lease is up for grabs");
    assert_eq!(stolen["task"]["claimed_session"], "core-manager");

    for client in [market, core] {
        let _ = client.cancel().await;
    }
    h.shutdown().await;
}

#[tokio::test]
async fn a_lock_belongs_to_a_session_not_to_a_person() {
    let h = require_db!("t_session_locks");
    let token = seed_agent(&h.pool, "layerv", "joaquin").await;

    let market = connect_with_session(&h.base, &token, "market-data").await;
    let core = connect_with_session(&h.base, &token, "core-manager").await;

    let taken = call(&market, "acquire_lock", json!({"name": "deploy:staging"})).await;
    assert_eq!(taken["acquired"], true);
    assert_eq!(taken["lock"]["holder_session"], "market-data");

    // Your other window must not inherit a live deploy lock.
    let blocked = call(&core, "acquire_lock", json!({"name": "deploy:staging"})).await;
    assert_eq!(blocked["acquired"], false);
    assert!(
        blocked["reason"]
            .as_str()
            .unwrap_or_default()
            .contains("market-data"),
        "the refusal must name the holding session: {blocked}"
    );

    // Nor release it.
    let err = call_expect_error(&core, "release_lock", json!({"name": "deploy:staging"})).await;
    assert!(err.contains("market-data"), "{err}");

    // Extending from the holding session still works.
    let again = call(&market, "acquire_lock", json!({"name": "deploy:staging"})).await;
    assert_eq!(
        again["acquired"], true,
        "the holder can extend its own lock"
    );

    call(&market, "release_lock", json!({"name": "deploy:staging"})).await;
    let now_free = call(&core, "acquire_lock", json!({"name": "deploy:staging"})).await;
    assert_eq!(now_free["acquired"], true);

    for client in [market, core] {
        let _ = client.cancel().await;
    }
    h.shutdown().await;
}

#[tokio::test]
async fn a_direct_message_can_address_one_session_of_a_person() {
    let h = require_db!("t_session_dms");
    let token = seed_agent(&h.pool, "layerv", "joaquin").await;
    let dani = seed_agent(&h.pool, "layerv", "dani").await;

    let general = connect_with_session(&h.base, &token, "general").await;
    let market = connect_with_session(&h.base, &token, "market-data").await;
    let core = connect_with_session(&h.base, &token, "core-manager").await;
    let dani_client = connect(&h.base, &dani).await;

    // Addressed to one window of one person.
    let sent = call(
        &general,
        "post_message",
        json!({"to": "joaquin/market-data", "body": "rebase onto main first"}),
    )
    .await;
    assert_eq!(sent["delivered_to"][0], "joaquin/market-data");
    assert_eq!(sent["message"]["to_session"], "market-data");
    assert_eq!(
        sent["message"]["from_session"], "general",
        "a reply needs to know which window asked"
    );

    let inbox = call(&market, "read_messages", json!({"scope": "inbox"})).await;
    assert_eq!(inbox["messages"][0]["body"], "rebase onto main first");

    // The sibling window is not the addressee and does not see it by default.
    let other = call(&core, "read_messages", json!({"scope": "inbox"})).await;
    assert_eq!(
        other["messages"].as_array().unwrap().len(),
        0,
        "a sibling session must not receive another's mail: {other}"
    );
    // But a person can always read their own mail when they ask for it.
    let everything = call(
        &core,
        "read_messages",
        json!({"scope": "inbox", "all_sessions": true, "only_new": false}),
    )
    .await;
    assert_eq!(everything["messages"][0]["body"], "rebase onto main first");

    // Addressing the person still reaches every window, as it always has.
    call(
        &dani_client,
        "post_message",
        json!({"to": "joaquin", "body": "standup in 5"}),
    )
    .await;
    for client in [&market, &core] {
        let seen = call(client, "read_messages", json!({"scope": "inbox"})).await;
        let bodies: Vec<&str> = seen["messages"]
            .as_array()
            .unwrap()
            .iter()
            .map(|m| m["body"].as_str().unwrap_or_default())
            .collect();
        assert!(
            bodies.contains(&"standup in 5"),
            "a message to the person reaches every session: {bodies:?}"
        );
    }

    // Reading in one window must not mark another window's inbox read.
    let again = call(&market, "read_messages", json!({"scope": "inbox"})).await;
    assert_eq!(
        again["messages"].as_array().unwrap().len(),
        0,
        "this window had already read everything addressed to it"
    );

    // Talking to the window you are in is refused with something to do instead.
    let err = call_expect_error(
        &market,
        "post_message",
        json!({"to": "joaquin/market-data", "body": "note to self"}),
    )
    .await;
    assert!(err.contains("set_note"), "{err}");

    for client in [general, market, core, dani_client] {
        let _ = client.cancel().await;
    }
    h.shutdown().await;
}

#[tokio::test]
async fn one_session_can_ask_another_session_of_the_same_person() {
    let h = require_db!("t_session_ask");
    let token = seed_agent(&h.pool, "layerv", "joaquin").await;

    let general = connect_with_session(&h.base, &token, "general").await;
    let market = connect_with_session(&h.base, &token, "market-data").await;

    // The coordinating window asks the one that has the repository open, and
    // blocks. The answer must come back here, not to some other window.
    let asker = tokio::spawn(async move {
        let answer = call(
            &general,
            "ask_agent",
            json!({"to": "joaquin/market-data", "question": "is the suite green?",
                   "timeout_seconds": 20}),
        )
        .await;
        let _ = general.cancel().await;
        answer
    });

    // The addressed window sees the question in its own inbox and replies.
    let mut question_id = None;
    for _ in 0..40 {
        let inbox = call(&market, "read_messages", json!({"scope": "inbox"})).await;
        if let Some(m) = inbox["messages"].as_array().and_then(|a| a.first()) {
            assert_eq!(m["from_session"], "general");
            assert_eq!(m["metadata"]["question"], true);
            question_id = m["id"].as_i64();
            break;
        }
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
    }
    let question_id = question_id.expect("the question reached the addressed session");

    call(
        &market,
        "post_message",
        json!({"to": "joaquin/general", "body": "green, 34 passing",
               "reply_to": question_id}),
    )
    .await;

    let answer = asker.await.unwrap();
    assert_eq!(answer["answered"], true, "{answer}");
    assert_eq!(answer["answer"]["body"], "green, 34 passing");
    assert_eq!(answer["answer"]["from_session"], "market-data");

    let _ = market.cancel().await;
    h.shutdown().await;
}

#[tokio::test]
async fn a_sibling_session_cannot_answer_for_the_one_that_was_asked() {
    let h = require_db!("t_session_ask_sibling");
    let token = seed_agent(&h.pool, "layerv", "joaquin").await;
    let dani = seed_agent(&h.pool, "layerv", "dani").await;

    let general = connect_with_session(&h.base, &token, "general").await;
    let dani_api = connect_with_session(&h.base, &dani, "api").await;
    let dani_web = connect_with_session(&h.base, &dani, "web").await;

    // Ask one specific window of dani's.
    let asker = tokio::spawn(async move {
        let r = call(
            &general,
            "ask_agent",
            json!({"to": "dani/api", "question": "did the migration land?",
                   "timeout_seconds": 8}),
        )
        .await;
        let _ = general.cancel().await;
        r
    });
    tokio::time::sleep(std::time::Duration::from_millis(400)).await;

    // A different window of the same person answers. It must NOT satisfy the
    // wait: the question was addressed to `api`, and `web` cannot see what
    // `api` was asked about.
    call(
        &dani_web,
        "post_message",
        json!({"to": "joaquin/general", "body": "no idea, wrong window"}),
    )
    .await;

    let out = asker.await.unwrap();
    assert_eq!(
        out["answered"], false,
        "a sibling session must not answer for the one that was asked: {out}"
    );
    let qid = out["question_message_id"].as_i64().unwrap();

    // The window that was actually asked answers, and resuming finds it.
    call(
        &dani_api,
        "post_message",
        json!({"to": "joaquin/general", "body": "yes, 0009 applied"}),
    )
    .await;
    let general = connect_with_session(&h.base, &token, "general").await;
    let resumed = call(
        &general,
        "ask_agent",
        json!({"to": "dani/api", "resume_message_id": qid, "timeout_seconds": 5}),
    )
    .await;
    assert_eq!(resumed["answered"], true, "{resumed}");
    assert_eq!(resumed["answer"]["body"], "yes, 0009 applied");

    // Resuming that question against a different address is refused, or a
    // timed-out question could collect another session's answer.
    let err = call_expect_error(
        &general,
        "ask_agent",
        json!({"to": "dani/web", "resume_message_id": qid, "timeout_seconds": 5}),
    )
    .await;
    assert!(err.contains("this session sent"), "{err}");

    for client in [general, dani_api, dani_web] {
        let _ = client.cancel().await;
    }
    h.shutdown().await;
}

#[tokio::test]
async fn wait_for_updates_does_not_wake_a_sibling_session() {
    let h = require_db!("t_session_wait");
    let token = seed_agent(&h.pool, "layerv", "joaquin").await;
    let dani = seed_agent(&h.pool, "layerv", "dani").await;

    let market = connect_with_session(&h.base, &token, "market-data").await;
    let core = connect_with_session(&h.base, &token, "core-manager").await;
    let dani_client = connect(&h.base, &dani).await;

    // core-manager blocks. A question for market-data must not wake it, or
    // every window of a person wakes for work meant for one of them.
    let waiter = tokio::spawn(async move {
        let r = call(
            &core,
            "wait_for_updates",
            json!({"timeout_seconds": 6, "kinds": ["message"]}),
        )
        .await;
        let _ = core.cancel().await;
        r
    });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    call(
        &dani_client,
        "post_message",
        json!({"to": "joaquin/market-data", "body": "only for that window"}),
    )
    .await;

    let woke = waiter.await.unwrap();
    assert_eq!(
        woke["timed_out"], true,
        "a sibling session's mail must not wake this one: {woke}"
    );

    // The addressed window, however, has it waiting immediately.
    let seen = call(
        &market,
        "wait_for_updates",
        json!({"timeout_seconds": 5, "kinds": ["message"]}),
    )
    .await;
    assert_eq!(seen["woke"], true, "{seen}");

    for client in [market, dani_client] {
        let _ = client.cancel().await;
    }
    h.shutdown().await;
}

#[tokio::test]
async fn a_session_posts_to_and_watches_the_channel_named_after_it() {
    let h = require_db!("t_session_channel");
    let token = seed_agent(&h.pool, "layerv", "joaquin").await;
    let dani = seed_agent(&h.pool, "layerv", "dani").await;

    let market = connect_with_session(&h.base, &token, "market-data").await;
    let dani_client = connect(&h.base, &dani).await;

    // No channel of that name yet: the error says what to do about it.
    let err = call_expect_error(&market, "post_message", json!({"body": "hello"})).await;
    assert!(
        err.contains("market-data") && err.contains("create_channel"),
        "the refusal must name the session and the fix: {err}"
    );

    call(&market, "create_channel", json!({"name": "market-data"})).await;
    call(&market, "create_channel", json!({"name": "core-manager"})).await;

    // Now the session has somewhere obvious to post.
    let me = call(&market, "whoami", json!({})).await;
    assert_eq!(me["default_channel"], "market-data");

    let posted = call(&market, "post_message", json!({"body": "feed is wired"})).await;
    assert_eq!(posted["message"]["channel"], "market-data");

    // An explicit channel always wins.
    let elsewhere = call(
        &market,
        "post_message",
        json!({"channel": "core-manager", "body": "fyi"}),
    )
    .await;
    assert_eq!(elsewhere["message"]["channel"], "core-manager");
    // And any channel of the team stays readable.
    let read = call(
        &market,
        "read_messages",
        json!({"scope": "core-manager", "only_new": false}),
    )
    .await;
    assert_eq!(read["messages"][0]["body"], "fyi");

    // The shared session keeps the old contract exactly: no default, and the
    // original error text.
    let shared = connect(&h.base, &token).await;
    let shared_me = call(&shared, "whoami", json!({})).await;
    assert_eq!(shared_me["default_channel"], Value::Null);
    let err = call_expect_error(&shared, "post_message", json!({"body": "hello"})).await;
    assert!(err.contains("set `channel`"), "{err}");

    // The digest follows the same focus: this window's repository by default,
    // the whole team on request.
    let focused = call(&market, "team_digest", json!({"hours": 1})).await;
    let names: Vec<&str> = focused["channels"]
        .as_array()
        .unwrap()
        .iter()
        .map(|c| c["name"].as_str().unwrap_or_default())
        .collect();
    assert_eq!(names, ["market-data"], "the session's own channel only");
    let wide = call(
        &market,
        "team_digest",
        json!({"hours": 1, "all_channels": true}),
    )
    .await;
    assert_eq!(wide["channels"].as_array().unwrap().len(), 2);

    // Noise from another repository must not wake this window.
    let waiter = tokio::spawn(async move {
        let r = call(
            &market,
            "wait_for_updates",
            json!({"timeout_seconds": 6, "kinds": ["message"]}),
        )
        .await;
        let _ = market.cancel().await;
        r
    });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
    call(
        &dani_client,
        "post_message",
        json!({"channel": "core-manager", "body": "unrelated work"}),
    )
    .await;
    let woke = waiter.await.unwrap();
    assert_eq!(
        woke["timed_out"], true,
        "another repository's channel must not wake this session: {woke}"
    );

    // ...but the digest can still be asked for the whole team.
    let focused = call(&shared, "team_digest", json!({"hours": 1})).await;
    let names: Vec<&str> = focused["channels"]
        .as_array()
        .unwrap()
        .iter()
        .map(|c| c["name"].as_str().unwrap_or_default())
        .collect();
    assert!(names.contains(&"core-manager"), "{names:?}");

    for client in [shared, dani_client] {
        let _ = client.cancel().await;
    }
    h.shutdown().await;
}

#[tokio::test]
async fn an_announcement_reaches_a_session_focused_elsewhere() {
    let h = require_db!("t_announce");
    let token = seed_agent(&h.pool, "layerv", "joaquin").await;
    let dani = seed_agent(&h.pool, "layerv", "dani").await;

    let market = connect_with_session(&h.base, &token, "market-data").await;
    let dani_client = connect(&h.base, &dani).await;

    call(&market, "create_channel", json!({"name": "market-data"})).await;
    call(&market, "create_channel", json!({"name": "general"})).await;

    // An ordinary message in another channel must still be ignored — the
    // announcement must not become a hole in the focus rule.
    let quiet = tokio::spawn({
        let market = connect_with_session(&h.base, &token, "market-data").await;
        async move {
            let r = call(
                &market,
                "wait_for_updates",
                json!({"timeout_seconds": 6, "kinds": ["message"]}),
            )
            .await;
            let _ = market.cancel().await;
            r
        }
    });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
    call(
        &dani_client,
        "post_message",
        json!({"channel": "general", "body": "lunch?"}),
    )
    .await;
    assert_eq!(
        quiet.await.unwrap()["timed_out"],
        true,
        "routine chatter elsewhere must still not wake a focused session"
    );

    // The same channel, flagged: this one gets through.
    let waiting = tokio::spawn({
        let market = connect_with_session(&h.base, &token, "market-data").await;
        async move {
            let r = call(
                &market,
                "wait_for_updates",
                json!({"timeout_seconds": 10, "kinds": ["message"]}),
            )
            .await;
            let _ = market.cancel().await;
            r
        }
    });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
    let posted = call(
        &dani_client,
        "post_message",
        json!({"channel": "general", "announce": true,
               "body": "migration 0010 lands in 5 min, stop pushing"}),
    )
    .await;
    assert_eq!(posted["message"]["announce"], true);

    let woke = waiting.await.unwrap();
    assert_eq!(
        woke["woke"], true,
        "an announcement must reach a session focused elsewhere: {woke}"
    );

    // One message in one place — not a copy per channel — so replies work.
    let id = posted["message"]["id"].as_i64().unwrap();
    let seen = call(
        &market,
        "read_messages",
        json!({"scope": "general", "only_new": false}),
    )
    .await;
    let hits = seen["messages"]
        .as_array()
        .unwrap()
        .iter()
        .filter(|m| m["id"].as_i64() == Some(id))
        .count();
    assert_eq!(hits, 1, "an announcement is one message, not a copy each");

    // A focused digest carries it too: a catch-up that omits the migration
    // notice is the same failure one step later.
    let digest = call(&market, "team_digest", json!({"hours": 1})).await;
    let bodies: Vec<String> = digest["channels"]
        .as_array()
        .unwrap()
        .iter()
        .flat_map(|c| c["last_messages"].as_array().cloned().unwrap_or_default())
        .map(|m| m["body"].as_str().unwrap_or_default().to_owned())
        .collect();
    assert!(
        bodies.iter().any(|b| b.contains("stop pushing")),
        "the focused digest must still list announcements: {bodies:?}"
    );

    // The flag is refused on a direct message, which already arrives unfiltered.
    let err = call_expect_error(
        &dani_client,
        "post_message",
        json!({"to": "joaquin", "announce": true, "body": "psst"}),
    )
    .await;
    assert!(err.contains("channel messages"), "{err}");

    for client in [market, dani_client] {
        let _ = client.cancel().await;
    }
    h.shutdown().await;
}

#[tokio::test]
async fn your_own_general_session_can_announce_to_your_other_windows() {
    let h = require_db!("t_announce_self");
    let token = seed_agent(&h.pool, "layerv", "joaquin").await;

    let general = connect_with_session(&h.base, &token, "general").await;
    let market = connect_with_session(&h.base, &token, "market-data").await;
    call(&general, "create_channel", json!({"name": "general"})).await;
    call(&general, "create_channel", json!({"name": "market-data"})).await;

    // Live wake: the coordinating window announces, the repository window is
    // blocked. Same token, so an agent-level "your own messages" guard would
    // discard it and this would time out.
    let waiting = tokio::spawn({
        let market = connect_with_session(&h.base, &token, "market-data").await;
        async move {
            let r = call(
                &market,
                "wait_for_updates",
                json!({"timeout_seconds": 10, "kinds": ["message"]}),
            )
            .await;
            let _ = market.cancel().await;
            r
        }
    });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
    call(
        &general,
        "post_message",
        json!({"channel": "general", "announce": true,
               "body": "0.6.0 goes out in 10, freeze your branches"}),
    )
    .await;
    let woke = waiting.await.unwrap();
    assert_eq!(
        woke["woke"], true,
        "your own general window must be able to reach your other windows: {woke}"
    );

    // Pre-check: the same must be true of the backlog path, which answers
    // before subscribing. Reporting nothing pending here would make the wait
    // look like a hang.
    let pending = call(
        &market,
        "wait_for_updates",
        json!({"timeout_seconds": 5, "kinds": ["message"]}),
    )
    .await;
    assert_eq!(
        pending["woke"], true,
        "the announcement is already waiting for this window: {pending}"
    );

    // The window that sent it is still not woken by its own announcement.
    let quiet = call(
        &general,
        "wait_for_updates",
        json!({"timeout_seconds": 5, "kinds": ["message"]}),
    )
    .await;
    assert_eq!(
        quiet["timed_out"], true,
        "the sending window must not wake on its own message: {quiet}"
    );

    for client in [general, market] {
        let _ = client.cancel().await;
    }
    h.shutdown().await;
}

#[tokio::test]
async fn an_empty_activity_clears_it_and_dead_rows_are_swept() {
    let h = require_db!("t_presence_hygiene");
    let token = seed_agent(&h.pool, "layerv", "joaquin").await;
    let market = connect_with_session(&h.base, &token, "market-data").await;

    call(
        &market,
        "heartbeat",
        json!({"repo": "Layer-V/market-data", "activity": "rewriting the feed"}),
    )
    .await;

    // Omitting the field keeps it: a mid-session ping from the hook must not
    // wipe what the model announced.
    let kept = call(&market, "heartbeat", json!({"branch": "main"})).await;
    assert_eq!(kept["activity"], "rewriting the feed");
    assert_eq!(kept["branch"], "main");

    // An explicit empty string clears it. Without this a session that starts
    // again carries the previous run's line forever, because nothing else ever
    // overwrites an omitted field.
    let cleared = call(&market, "heartbeat", json!({"activity": ""})).await;
    assert_eq!(
        cleared["activity"],
        Value::Null,
        "an empty activity must clear, not store an empty string: {cleared}"
    );
    assert_eq!(
        cleared["repo"], "Layer-V/market-data",
        "clearing the activity must not disturb the other fields"
    );

    // The first heartbeat of a *new* session, which is the path SessionStart
    // actually takes: the clear ran only on conflict, so a fresh row stored an
    // empty string where the update path stored null. The original test only
    // covered clear-after-set and could never have caught it.
    let fresh = connect_with_session(&h.base, &token, "brand-new").await;
    let first = call(&fresh, "heartbeat", json!({"activity": ""})).await;
    assert_eq!(
        first["activity"],
        Value::Null,
        "a new session's first heartbeat must clear, not store '': {first}"
    );
    let _ = fresh.cancel().await;

    // A row from a session that is long gone is swept on the next heartbeat.
    // Nothing else ever deleted one, and a row per distinct label grows without
    // limit once sessions exist.
    sqlx::query(sqlx::AssertSqlSafe(
        "INSERT INTO agent_presence (agent_id, session, status, activity, updated_at, expires_at)
         SELECT id, 'gone', 'active', 'stopping for the day', now() - interval '3 days',
                now() - interval '3 days'
           FROM agents WHERE name = 'joaquin'"
            .to_owned(),
    ))
    .execute(&h.pool)
    .await
    .unwrap();

    let before: (i64,) =
        sqlx::query_as("SELECT count(*) FROM agent_presence WHERE session = 'gone'")
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert_eq!(before.0, 1);

    call(&market, "heartbeat", json!({})).await;

    let after: (i64,) =
        sqlx::query_as("SELECT count(*) FROM agent_presence WHERE session = 'gone'")
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert_eq!(after.0, 0, "a long-dead session row must not live forever");

    // A row that only just expired is kept, so "offline recently" still reads.
    sqlx::query(sqlx::AssertSqlSafe(
        "INSERT INTO agent_presence (agent_id, session, status, updated_at, expires_at)
         SELECT id, 'recent', 'active', now(), now() - interval '1 minute'
           FROM agents WHERE name = 'joaquin'"
            .to_owned(),
    ))
    .execute(&h.pool)
    .await
    .unwrap();
    call(&market, "heartbeat", json!({})).await;
    let recent: (i64,) =
        sqlx::query_as("SELECT count(*) FROM agent_presence WHERE session = 'recent'")
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert_eq!(recent.0, 1, "a just-expired session is still worth showing");

    let _ = market.cancel().await;
    h.shutdown().await;
}

#[tokio::test]
async fn the_summary_projects_a_named_session_over_the_shared_row() {
    let h = require_db!("t_projection");
    let token = seed_agent(&h.pool, "layerv", "dani").await;
    let reader = seed_agent(&h.pool, "layerv", "joaquin").await;

    let shared = connect(&h.base, &token).await;
    let repo = connect_with_session(&h.base, &token, "risk-engine").await;
    let joaquin = connect(&h.base, &reader).await;

    // The shape dani hit: a sessionless row carrying an old activity that
    // keeps refreshing, alongside a real session doing real work.
    call(
        &shared,
        "heartbeat",
        json!({"repo": "Layer-V/old", "activity": "stopping for the day"}),
    )
    .await;
    call(
        &repo,
        "heartbeat",
        json!({"repo": "Layer-V/risk-engine", "activity": "implementing #169"}),
    )
    .await;
    // Refresh the sessionless row last, so "most recently updated" would pick it.
    call(&shared, "heartbeat", json!({})).await;

    let seen = call(&joaquin, "list_agents", json!({})).await;
    let dani = seen["agents"]
        .as_array()
        .unwrap()
        .iter()
        .find(|a| a["name"] == "dani")
        .expect("dani is on the bus");

    assert_eq!(
        dani["activity"], "implementing #169",
        "the summary must project the named session, not the shared row: {dani}"
    );
    assert_eq!(dani["repo"], "Layer-V/risk-engine");
    assert_eq!(dani["session"], "risk-engine");
    // Nothing is hidden: both rows are still listed underneath.
    assert_eq!(dani["sessions"].as_array().unwrap().len(), 2);

    // team_digest reads presence too, and every session reads the digest at
    // start-up — the same wrong row there tells the whole team a stale line.
    let digest = call(&joaquin, "team_digest", json!({"hours": 1})).await;
    let line = digest["agents_seen"]
        .as_array()
        .unwrap()
        .iter()
        .find(|a| a["name"] == "dani")
        .expect("dani in the digest")["activity"]
        .clone();
    assert_eq!(line, "implementing #169", "{digest}");

    // With no named session at all, the shared row is still the answer rather
    // than nothing.
    let solo = seed_agent(&h.pool, "layerv", "carlos").await;
    let carlos = connect(&h.base, &solo).await;
    call(&carlos, "heartbeat", json!({"activity": "triaging"})).await;
    let seen = call(&joaquin, "list_agents", json!({})).await;
    let row = seen["agents"]
        .as_array()
        .unwrap()
        .iter()
        .find(|a| a["name"] == "carlos")
        .unwrap();
    assert_eq!(row["activity"], "triaging");

    for client in [shared, repo, joaquin, carlos] {
        let _ = client.cancel().await;
    }
    h.shutdown().await;
}

#[tokio::test]
async fn the_sweeper_clears_long_dead_shared_rows() {
    let mut h = require_db!("t_presence_sweep");
    let _dani = seed_agent(&h.pool, "layerv", "dani").await;
    let _joaquin = seed_agent(&h.pool, "layerv", "joaquin").await;
    let reader = seed_agent(&h.pool, "layerv", "carlos").await;

    // The 0.6.0 shape: a shared-session row whose owner never heartbeats
    // again, so the lazy per-heartbeat sweep never reaches it. Inserted raw,
    // like a row surviving an upgrade.
    sqlx::query(sqlx::AssertSqlSafe(
        "INSERT INTO agent_presence (agent_id, session, status, activity, updated_at, expires_at)
         SELECT id, '', 'active', 'stopping for the day', now() - interval '3 days',
                now() - interval '3 days'
           FROM agents WHERE name = 'dani'"
            .to_owned(),
    ))
    .execute(&h.pool)
    .await
    .unwrap();
    // A shared row that only just expired must survive: same "offline
    // recently" grace as the heartbeat sweep.
    sqlx::query(sqlx::AssertSqlSafe(
        "INSERT INTO agent_presence (agent_id, session, status, activity, updated_at, expires_at)
         SELECT id, '', 'active', 'still warm', now(), now() - interval '1 minute'
           FROM agents WHERE name = 'joaquin'"
            .to_owned(),
    ))
    .execute(&h.pool)
    .await
    .unwrap();

    // A fresh server on the same schema is what a deploy is; its sweeper's
    // first pass runs immediately. The pass is asynchronous, so poll.
    let _replica = h.add_replica().await;
    let mut swept = false;
    for _ in 0..50 {
        let left: (i64,) = sqlx::query_as(
            "SELECT count(*) FROM agent_presence WHERE session = '' AND activity = 'stopping for the day'",
        )
        .fetch_one(&h.pool)
        .await
        .unwrap();
        if left.0 == 0 {
            swept = true;
            break;
        }
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
    }
    assert!(
        swept,
        "the long-dead shared row must be gone after a restart"
    );

    let warm: (i64,) =
        sqlx::query_as("SELECT count(*) FROM agent_presence WHERE activity = 'still warm'")
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert_eq!(
        warm.0, 1,
        "a recently expired shared row is still worth showing"
    );

    // What the team actually reads no longer carries the stale line.
    let carlos = connect(&h.base, &reader).await;
    let seen = call(&carlos, "list_agents", json!({})).await;
    let dani = seen["agents"]
        .as_array()
        .unwrap()
        .iter()
        .find(|a| a["name"] == "dani")
        .expect("dani is still on the roster");
    assert_eq!(
        dani["activity"],
        Value::Null,
        "the swept row must not project anywhere: {dani}"
    );
    let digest = call(&carlos, "team_digest", json!({"hours": 24})).await;
    assert!(
        !digest.to_string().contains("stopping for the day"),
        "the digest must not resurrect the swept row: {digest}"
    );

    let _ = carlos.cancel().await;
    h.shutdown().await;
}

#[tokio::test]
async fn a_stringified_metadata_object_is_stored_as_an_object() {
    let h = require_db!("t_metadata_shape");
    let a = seed_agent(&h.pool, "layerv", "joaquin").await;
    let b = seed_agent(&h.pool, "layerv", "dani").await;
    let joaquin = connect(&h.base, &a).await;
    let dani = connect(&h.base, &b).await;

    // What some MCP clients actually send: the object serialised. Stored
    // verbatim it is unusable — the Stop drain reads metadata["question"] and
    // finds a string, so the capability the skill documents does not work.
    let sent = call(
        &joaquin,
        "post_message",
        json!({"to": "dani", "body": "is it green?",
               "metadata": "{\"question\": true}"}),
    )
    .await;
    assert_eq!(
        sent["message"]["metadata"]["question"], true,
        "a serialised object must be reconstructed: {}",
        sent["message"]["metadata"]
    );

    // Deliberately narrow: a string that is not an object is what the caller
    // asked for, and rewriting it would be guessing.
    let plain = call(
        &joaquin,
        "post_message",
        json!({"to": "dani", "body": "fyi", "metadata": "just a note"}),
    )
    .await;
    assert_eq!(plain["message"]["metadata"], "just a note");

    // An object still arrives as an object, which was never broken.
    let obj = call(
        &joaquin,
        "post_message",
        json!({"to": "dani", "body": "q", "metadata": {"question": true}}),
    )
    .await;
    assert_eq!(obj["message"]["metadata"]["question"], true);

    // Same normalisation on tasks, which take metadata too.
    let task = call(
        &joaquin,
        "create_task",
        json!({"key": "market-data#7", "title": "wire the feed",
               "metadata": "{\"epic\": \"feeds\"}"}),
    )
    .await;
    assert_eq!(task["metadata"]["epic"], "feeds");

    for client in [joaquin, dani] {
        let _ = client.cancel().await;
    }
    h.shutdown().await;
}

// -------------------------------------------------- administrative credentials --

/// The operator CLI path (bootstrap, agent add, token issue) through the store,
/// exactly as `ai-crew-sync admin bootstrap` / `agent add` / `token issue` run
/// it: credentials resolve, revocation is immediate, the two credential
/// classes never resolve as each other, and the audit trail carries no secret.
#[tokio::test]
async fn administrative_credentials_are_a_separate_class_with_an_audit_trail() {
    use ai_crew_sync::store::admin::{self as store, Actor};

    let h = require_db!("t_admin_store");

    // Bootstrap: a global credential minted with no prior credential.
    let global = store::grant_admin(&h.pool, Actor::Cli, None, Some("laptop".into()))
        .await
        .unwrap();
    assert!(global.token.starts_with("acsa_"), "admin prefix");
    assert!(global.team.is_none(), "bootstrap mints a global credential");
    let ctx = store::resolve_admin(&h.pool, &global.token)
        .await
        .unwrap()
        .expect("fresh credential resolves");
    assert!(ctx.is_global());
    assert_eq!(ctx.id, global.id);

    // The existing operator commands keep working and mint tokens that
    // authenticate on /mcp as exactly the requested agent and team.
    let team = store::create_team(&h.pool, Actor::Cli, "acme", Some("Acme".into()))
        .await
        .unwrap();
    let again = store::create_team(&h.pool, Actor::Cli, "ACME", None)
        .await
        .unwrap();
    assert_eq!(again.id, team.id, "create is idempotent on the slug");
    assert_eq!(again.name, "Acme", "a repeat never renames");
    store::create_agent(&h.pool, Actor::Cli, team.id, "Backend", None)
        .await
        .unwrap();
    // A repeat on an active agent is a no-op and logs nothing; a disable and
    // a re-create are real transitions and log one row each.
    store::create_agent(
        &h.pool,
        Actor::Cli,
        team.id,
        "backend",
        Some("Backend".into()),
    )
    .await
    .unwrap();
    store::disable_agent(&h.pool, Actor::Cli, team.id, "backend")
        .await
        .unwrap();
    store::create_agent(&h.pool, Actor::Cli, team.id, "backend", None)
        .await
        .unwrap();
    assert!(
        store::create_team(&h.pool, Actor::Cli, "evil", Some("Acme\x1b[31m".into()))
            .await
            .is_err(),
        "a team name is display text: no control characters"
    );
    let issued = store::issue_token(
        &h.pool,
        Actor::Cli,
        team.id,
        "backend",
        Some("sesion backend".into()),
    )
    .await
    .unwrap();
    assert_eq!(
        (issued.agent.as_str(), issued.team.as_str()),
        ("backend", "acme")
    );
    let client = connect(&h.base, &issued.token).await;
    let me = call(&client, "whoami", json!({})).await;
    assert_eq!(me["agent"], "backend");
    assert_eq!(me["team"], "acme");
    let _ = client.cancel().await;

    // A team credential lists only its team; the global listing sees both.
    let team_admin = store::grant_admin(&h.pool, Actor::Admin(global.id), Some(team.id), None)
        .await
        .unwrap();
    assert_eq!(team_admin.team.as_deref(), Some("acme"));
    let mine = store::list_admins(&h.pool, Some(team.id)).await.unwrap();
    assert_eq!(
        mine.iter().map(|c| c.id).collect::<Vec<_>>(),
        vec![team_admin.id]
    );
    assert_eq!(store::list_admins(&h.pool, None).await.unwrap().len(), 2);

    // Neither class resolves as the other: same hashing, different tables.
    assert!(
        store::resolve_admin(&h.pool, &issued.token)
            .await
            .unwrap()
            .is_none(),
        "an agent token is not an administrative credential"
    );
    assert!(
        ai_crew_sync::auth::resolve_token(&h.pool, &global.token)
            .await
            .is_err(),
        "an administrative credential is not an agent token"
    );

    // Scoped revocation: a team scope cannot reach a global credential or a
    // token from another team, and reports them as not found.
    let other = store::create_team(&h.pool, Actor::Cli, "other", None)
        .await
        .unwrap();
    store::create_agent(&h.pool, Actor::Cli, other.id, "x", None)
        .await
        .unwrap();
    let foreign = store::issue_token(&h.pool, Actor::Cli, other.id, "x", None)
        .await
        .unwrap();
    assert!(matches!(
        store::revoke_token(
            &h.pool,
            Actor::Admin(team_admin.id),
            Some(team.id),
            foreign.id
        )
        .await,
        Err(ai_crew_sync::error::BusError::NotFound(_))
    ));
    assert!(matches!(
        store::revoke_admin(
            &h.pool,
            Actor::Admin(team_admin.id),
            Some(team.id),
            global.id
        )
        .await,
        Err(ai_crew_sync::error::BusError::NotFound(_))
    ));
    assert!(
        store::resolve_admin(&h.pool, &global.token)
            .await
            .unwrap()
            .is_some(),
        "a failed scoped revoke changes nothing"
    );

    // Revocation is immediate for both classes, and idempotent.
    store::revoke_token(
        &h.pool,
        Actor::Admin(team_admin.id),
        Some(team.id),
        issued.id,
    )
    .await
    .unwrap();
    store::revoke_token(
        &h.pool,
        Actor::Admin(team_admin.id),
        Some(team.id),
        issued.id,
    )
    .await
    .unwrap();
    assert!(
        ai_crew_sync::auth::resolve_token(&h.pool, &issued.token)
            .await
            .is_err()
    );
    store::revoke_admin(&h.pool, Actor::Cli, None, global.id)
        .await
        .unwrap();
    assert!(
        store::resolve_admin(&h.pool, &global.token)
            .await
            .unwrap()
            .is_none()
    );

    // Audit: every mutation logged with its actor, and no secret anywhere.
    let rows: Vec<(String, Option<Uuid>, String, Value)> = sqlx::query_as(
        "SELECT actor_source, actor_admin_id, action, detail FROM admin_audit ORDER BY id",
    )
    .fetch_all(&h.pool)
    .await
    .unwrap();
    let actions: Vec<&str> = rows.iter().map(|r| r.2.as_str()).collect();
    assert_eq!(
        actions,
        vec![
            "admin.grant",
            "team.create",
            "agent.create",
            "agent.disable",
            "agent.enable",
            "token.issue",
            "admin.grant",
            "team.create",
            "agent.create",
            "token.issue",
            "token.revoke",
            "admin.revoke",
        ],
        "one row per real transition, none for the idempotent repeats"
    );
    let by_http: Vec<&(String, Option<Uuid>, String, Value)> =
        rows.iter().filter(|r| r.0 == "http").collect();
    assert_eq!(by_http.len(), 2, "the two actions taken with a credential");
    assert!(
        by_http.iter().all(|r| r.1.is_some()),
        "http rows name their credential"
    );
    assert!(rows.iter().filter(|r| r.0 == "cli").all(|r| r.1.is_none()));
    let dump = serde_json::to_string(&rows.iter().map(|r| &r.3).collect::<Vec<_>>()).unwrap();
    for secret in [
        &global.token,
        &team_admin.token,
        &issued.token,
        &foreign.token,
    ] {
        assert!(
            !dump.contains(secret.as_str()),
            "audit detail carries a secret"
        );
        assert!(
            !dump.contains(&secret[5..]),
            "audit detail carries a secret's body"
        );
    }
    assert!(
        dump.contains(&issued.prefix),
        "the display prefix is what the log keeps"
    );

    h.shutdown().await;
}

/// Revocation is one transition however many callers race for it: the
/// UPDATE is conditional on the row being active, so exactly one caller
/// performs it and exactly one audit row is written; the others succeed as
/// no-ops.
#[tokio::test]
async fn concurrent_revocations_produce_one_transition_and_one_audit_row() {
    use ai_crew_sync::store::admin::{self as store, Actor};

    let h = require_db!("t_admin_revoke_race");
    let team = store::create_team(&h.pool, Actor::Cli, "acme", None)
        .await
        .unwrap();
    store::create_agent(&h.pool, Actor::Cli, team.id, "bot", None)
        .await
        .unwrap();
    let issued = store::issue_token(&h.pool, Actor::Cli, team.id, "bot", None)
        .await
        .unwrap();
    let admin = store::grant_admin(&h.pool, Actor::Cli, Some(team.id), None)
        .await
        .unwrap();

    let mut tasks = Vec::new();
    for _ in 0..8 {
        let pool = h.pool.clone();
        let (tid, token_id, admin_id) = (team.id, issued.id, admin.id);
        tasks.push(tokio::spawn(async move {
            let a = store::revoke_token(&pool, Actor::Admin(admin_id), Some(tid), token_id).await;
            let b = store::revoke_admin(&pool, Actor::Admin(admin_id), Some(tid), admin_id).await;
            (a.is_ok(), b.is_ok())
        }));
    }
    for t in tasks {
        assert_eq!(t.await.unwrap(), (true, true), "every racer succeeds");
    }
    let (revokes,): (i64,) = sqlx::query_as(
        "SELECT count(*) FROM admin_audit WHERE action IN ('token.revoke', 'admin.revoke')",
    )
    .fetch_one(&h.pool)
    .await
    .unwrap();
    assert_eq!(revokes, 2, "one row per transition, not per caller");

    h.shutdown().await;
}

// ------------------------------------------------------- /admin HTTP surface --

/// Minimal client for `/admin/*`: a bearer, a method, a path, a JSON body.
struct Admin {
    http: reqwest::Client,
    base: String,
    token: String,
}

impl Admin {
    fn new(base: &str, token: &str) -> Self {
        Self {
            http: reqwest::Client::new(),
            base: base.to_owned(),
            token: token.to_owned(),
        }
    }

    async fn req(&self, method: reqwest::Method, path: &str, body: Option<Value>) -> (u16, Value) {
        let mut r = self
            .http
            .request(method, format!("{}/admin{path}", self.base))
            .header("Authorization", format!("Bearer {}", self.token));
        if let Some(body) = body {
            r = r.json(&body);
        }
        let resp = r.send().await.unwrap();
        let status = resp.status().as_u16();
        let body: Value = resp.json().await.unwrap_or(Value::Null);
        (status, body)
    }

    async fn get(&self, path: &str) -> (u16, Value) {
        self.req(reqwest::Method::GET, path, None).await
    }
    async fn post(&self, path: &str, body: Value) -> (u16, Value) {
        self.req(reqwest::Method::POST, path, Some(body)).await
    }
    async fn delete(&self, path: &str) -> (u16, Value) {
        self.req(reqwest::Method::DELETE, path, None).await
    }
}

/// A raw `tools/list` on `/mcp` with a bearer, for status checks only.
async fn mcp_status(base: &str, token: &str) -> u16 {
    reqwest::Client::new()
        .post(format!("{base}/mcp"))
        .header("Authorization", format!("Bearer {token}"))
        .header("Accept", "application/json, text/event-stream")
        .json(&json!({"jsonrpc":"2.0","id":1,"method":"tools/list"}))
        .send()
        .await
        .unwrap()
        .status()
        .as_u16()
}

#[tokio::test]
async fn admin_api_refuses_everything_but_an_administrative_credential() {
    let h = require_db!("t_admin_auth");
    let agent_token = seed_agent(&h.pool, "acme", "joaquin").await;

    // No bearer at all.
    let (status, body) = Admin::new(&h.base, "").get("/whoami").await;
    assert_eq!(status, 401);
    assert!(
        body["error"].as_str().unwrap().contains("bootstrap"),
        "{body}"
    );

    // An agent token: refused, and told what to use instead.
    let (status, body) = Admin::new(&h.base, &agent_token).get("/whoami").await;
    assert_eq!(status, 401, "an agent token never administers");
    assert!(
        body["error"].as_str().unwrap().contains("agent token"),
        "{body}"
    );
    // ...on every route, including the ones that mint.
    let agent = Admin::new(&h.base, &agent_token);
    assert_eq!(
        agent
            .post("/teams/acme/tokens", json!({"agent": "joaquin"}))
            .await
            .0,
        401,
        "an agent token cannot mint a token, not even for its own agent"
    );
    assert_eq!(agent.post("/credentials", json!({})).await.0, 401);

    // A well-formed but unknown credential.
    let (status, _) = Admin::new(&h.base, "acsa_deadbeef").get("/whoami").await;
    assert_eq!(status, 401);

    // And an administrative credential is not an agent token on /mcp.
    let global = ai_crew_sync::store::admin::grant_admin(
        &h.pool,
        ai_crew_sync::store::admin::Actor::Cli,
        None,
        None,
    )
    .await
    .unwrap();
    assert_eq!(mcp_status(&h.base, &global.token).await, 401);
    let (status, body) = Admin::new(&h.base, &global.token).get("/whoami").await;
    assert_eq!(status, 200);
    assert_eq!(body["scope"], "global");
    assert!(body["team"].is_null());

    h.shutdown().await;
}

#[tokio::test]
async fn admin_api_global_credential_runs_the_whole_onboarding_remotely() {
    let h = require_db!("t_admin_global");
    let bootstrap = ai_crew_sync::store::admin::grant_admin(
        &h.pool,
        ai_crew_sync::store::admin::Actor::Cli,
        None,
        Some("laptop".into()),
    )
    .await
    .unwrap();
    let admin = Admin::new(&h.base, &bootstrap.token);

    let (status, body) = admin
        .post("/teams", json!({"slug": "RoundCrew", "name": "RoundCrew"}))
        .await;
    assert_eq!(status, 201, "{body}");
    assert_eq!(body["team"]["slug"], "roundcrew", "slugs are normalised");

    let (status, body) = admin
        .post(
            "/teams/roundcrew/agents",
            json!({"name": "backend", "display_name": "RoundCrew backend"}),
        )
        .await;
    assert_eq!(status, 201, "{body}");
    assert_eq!(body["agent"]["name"], "backend");

    let (status, body) = admin
        .post(
            "/teams/roundcrew/tokens",
            json!({"agent": "backend", "label": "sesion backend"}),
        )
        .await;
    assert_eq!(status, 201, "{body}");
    let token = body["token"]["token"].as_str().unwrap().to_owned();
    let token_id = body["token"]["id"].as_str().unwrap().to_owned();
    assert!(token.starts_with("acs_"));
    assert_eq!(body["token"]["agent"], "backend");
    assert_eq!(body["token"]["team"], "roundcrew");
    assert_eq!(body["token"]["label"], "sesion backend");

    // The property that matters: the token IS that agent in that team on /mcp.
    let client = connect(&h.base, &token).await;
    let me = call(&client, "whoami", json!({})).await;
    assert_eq!(me["agent"], "backend");
    assert_eq!(me["team"], "roundcrew");
    let _ = client.cancel().await;

    // Listings show it without the secret.
    let (_, body) = admin.get("/teams/roundcrew/tokens").await;
    let listed = &body["tokens"][0];
    assert_eq!(listed["id"], token_id);
    assert!(
        listed.get("token").is_none(),
        "a listing never carries a secret"
    );
    assert_eq!(listed["prefix"], &token[..12]);
    let (_, body) = admin.get("/teams").await;
    assert_eq!(body["teams"][0]["agents"], 1);

    // Unknown things are 404 with a hint, bad input 400.
    assert_eq!(
        admin
            .post("/teams/nope/agents", json!({"name": "x"}))
            .await
            .0,
        404
    );
    assert_eq!(
        admin
            .post("/teams/roundcrew/tokens", json!({"agent": "ghost"}))
            .await
            .0,
        404
    );
    let (status, body) = admin
        .post("/teams/roundcrew/agents", json!({"name": "has space"}))
        .await;
    assert_eq!(status, 400, "{body}");
    // Extractor rejections wear the same JSON shape as every other error.
    let resp = reqwest::Client::new()
        .post(format!("{}/admin/teams/roundcrew/agents", h.base))
        .header("Authorization", format!("Bearer {}", bootstrap.token))
        .header("Content-Type", "application/json")
        .body("{not json")
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 400);
    let body: Value = resp.json().await.expect("a JSON error body");
    assert!(
        body["error"]
            .as_str()
            .unwrap()
            .contains("invalid JSON body"),
        "{body}"
    );
    let (status, body) = admin.delete("/teams/roundcrew/tokens/not-a-uuid").await;
    assert_eq!(status, 400, "{body}");
    assert!(
        body["error"].as_str().unwrap().contains("path parameter"),
        "{body}"
    );
    let (status, body) = admin.post("/credentials", json!({"team": ""})).await;
    assert_eq!(
        status, 400,
        "an empty team is a mistake, not a global grant: {body}"
    );

    // Revocation stops the token on /mcp immediately.
    let (status, _) = admin
        .delete(&format!("/teams/roundcrew/tokens/{token_id}"))
        .await;
    assert_eq!(status, 200);
    assert_eq!(mcp_status(&h.base, &token).await, 401);

    // Granting: a team credential, then a second global one; each works on
    // /admin/whoami with the right scope, and revoking cuts it off.
    let (status, body) = admin
        .post(
            "/credentials",
            json!({"team": "roundcrew", "label": "dani"}),
        )
        .await;
    assert_eq!(status, 201, "{body}");
    let team_cred = body["credential"]["token"].as_str().unwrap().to_owned();
    let team_cred_id = body["credential"]["id"].as_str().unwrap().to_owned();
    assert!(team_cred.starts_with("acsa_"));
    let (_, body) = Admin::new(&h.base, &team_cred).get("/whoami").await;
    assert_eq!(body["scope"], "team");
    assert_eq!(body["team"], "roundcrew");

    let (status, body) = admin.post("/credentials", json!({})).await;
    assert_eq!(status, 201, "{body}");
    assert!(body["credential"]["team"].is_null(), "no team means global");

    let (_, body) = admin.get("/credentials").await;
    assert_eq!(body["credentials"].as_array().unwrap().len(), 3);
    assert!(
        body["credentials"]
            .as_array()
            .unwrap()
            .iter()
            .all(|c| c.get("token").is_none()),
        "listings never carry a secret"
    );

    let (status, _) = admin.delete(&format!("/credentials/{team_cred_id}")).await;
    assert_eq!(status, 200);
    assert_eq!(
        Admin::new(&h.base, &team_cred).get("/whoami").await.0,
        401,
        "a revoked credential stops authorising at once"
    );

    // Audit: http rows name the credential that acted, and hold no secret.
    let rows: Vec<(String, Option<Uuid>, String, Value)> = sqlx::query_as(
        "SELECT actor_source, actor_admin_id, action, detail FROM admin_audit
         WHERE actor_source = 'http' ORDER BY id",
    )
    .fetch_all(&h.pool)
    .await
    .unwrap();
    let actions: Vec<&str> = rows.iter().map(|r| r.2.as_str()).collect();
    assert_eq!(
        actions,
        vec![
            "team.create",
            "agent.create",
            "token.issue",
            "token.revoke",
            "admin.grant",
            "admin.grant",
            "admin.revoke",
        ]
    );
    assert!(rows.iter().all(|r| r.1 == Some(bootstrap.id)));
    let dump = serde_json::to_string(&rows.iter().map(|r| &r.3).collect::<Vec<_>>()).unwrap();
    assert!(!dump.contains(&token[5..]));
    assert!(!dump.contains(&team_cred[5..]));

    h.shutdown().await;
}

#[tokio::test]
async fn admin_api_team_credential_cannot_leave_its_team_by_any_route() {
    use ai_crew_sync::store::admin::{self as store, Actor};

    let h = require_db!("t_admin_team");
    let acme = store::create_team(&h.pool, Actor::Cli, "acme", None)
        .await
        .unwrap();
    let other = store::create_team(&h.pool, Actor::Cli, "other", None)
        .await
        .unwrap();
    store::create_agent(&h.pool, Actor::Cli, acme.id, "joaquin", None)
        .await
        .unwrap();
    store::create_agent(&h.pool, Actor::Cli, other.id, "marta", None)
        .await
        .unwrap();
    let foreign = store::issue_token(&h.pool, Actor::Cli, other.id, "marta", None)
        .await
        .unwrap();
    let global = store::grant_admin(&h.pool, Actor::Cli, None, None)
        .await
        .unwrap();
    let scoped = store::grant_admin(&h.pool, Actor::Cli, Some(acme.id), None)
        .await
        .unwrap();
    let dani = Admin::new(&h.base, &scoped.token);

    // Inside its team: everything a global credential can do there.
    let (status, body) = dani
        .post("/teams/acme/agents", json!({"name": "dani-codex"}))
        .await;
    assert_eq!(status, 201, "{body}");
    let (status, body) = dani
        .post(
            "/teams/acme/tokens",
            json!({"agent": "dani-codex", "label": "x"}),
        )
        .await;
    assert_eq!(status, 201, "{body}");
    let mine = body["token"]["token"].as_str().unwrap().to_owned();
    let mine_id = body["token"]["id"].as_str().unwrap().to_owned();
    let client = connect(&h.base, &mine).await;
    let me = call(&client, "whoami", json!({})).await;
    assert_eq!(
        (me["agent"].as_str(), me["team"].as_str()),
        (Some("dani-codex"), Some("acme"))
    );
    let _ = client.cancel().await;

    // By slug: another team is forbidden, existing or not, same answer.
    for path in [
        "/teams/other/agents",
        "/teams/other/tokens",
        "/teams/nope/tokens",
    ] {
        let (status, body) = dani.get(path).await;
        assert_eq!(status, 403, "{path}: {body}");
        assert!(body["error"].as_str().unwrap().contains("'acme'"), "{body}");
    }
    assert_eq!(
        dani.post("/teams/other/tokens", json!({"agent": "marta"}))
            .await
            .0,
        403
    );
    // By UUID: a foreign token under its own team's path is simply not found.
    let (status, _) = dani
        .delete(&format!("/teams/acme/tokens/{}", foreign.id))
        .await;
    assert_eq!(status, 404);
    assert_eq!(
        mcp_status(&h.base, &foreign.token).await,
        200,
        "and untouched"
    );
    // Nor can a global credential revoke it through the wrong team's path.
    let (status, _) = Admin::new(&h.base, &global.token)
        .delete(&format!("/teams/acme/tokens/{}", foreign.id))
        .await;
    assert_eq!(status, 404);

    // Global-only actions: create teams, grant credentials.
    let (status, body) = dani.post("/teams", json!({"slug": "mine"})).await;
    assert_eq!(status, 403, "{body}");
    let (status, body) = dani.post("/credentials", json!({"team": "acme"})).await;
    assert_eq!(status, 403, "{body}");
    let (status, _) = dani.post("/credentials", json!({})).await;
    assert_eq!(status, 403, "nor a global one");
    assert_eq!(
        store::list_admins(&h.pool, None).await.unwrap().len(),
        2,
        "nothing was granted"
    );

    // The team roster it sees is exactly its own team.
    let (_, body) = dani.get("/teams").await;
    assert_eq!(body["teams"].as_array().unwrap().len(), 1);
    assert_eq!(body["teams"][0]["slug"], "acme");
    let (_, body) = dani.get("/credentials").await;
    assert_eq!(body["credentials"].as_array().unwrap().len(), 1);
    assert_eq!(body["credentials"][0]["id"], scoped.id.to_string());

    // It cannot revoke the global credential, and can revoke its own team's
    // tokens and — last — itself.
    let (status, _) = dani.delete(&format!("/credentials/{}", global.id)).await;
    assert_eq!(status, 404);
    assert_eq!(
        Admin::new(&h.base, &global.token).get("/whoami").await.0,
        200
    );
    assert_eq!(
        dani.delete(&format!("/teams/acme/tokens/{mine_id}"))
            .await
            .0,
        200
    );
    assert_eq!(mcp_status(&h.base, &mine).await, 401);
    assert_eq!(
        dani.delete(&format!("/credentials/{}", scoped.id)).await.0,
        200
    );
    assert_eq!(dani.get("/whoami").await.0, 401);

    h.shutdown().await;
}

#[tokio::test]
async fn admin_api_caps_active_tokens_per_agent() {
    use ai_crew_sync::store::admin::{self as store, Actor, MAX_ACTIVE_TOKENS_PER_AGENT};

    let h = require_db!("t_admin_cap");
    let acme = store::create_team(&h.pool, Actor::Cli, "acme", None)
        .await
        .unwrap();
    store::create_agent(&h.pool, Actor::Cli, acme.id, "bot", None)
        .await
        .unwrap();
    for _ in 0..MAX_ACTIVE_TOKENS_PER_AGENT {
        store::issue_token(&h.pool, Actor::Cli, acme.id, "bot", None)
            .await
            .unwrap();
    }
    let global = store::grant_admin(&h.pool, Actor::Cli, None, None)
        .await
        .unwrap();
    let admin = Admin::new(&h.base, &global.token);
    let (status, body) = admin
        .post("/teams/acme/tokens", json!({"agent": "bot"}))
        .await;
    assert_eq!(status, 409, "{body}");
    assert!(body["error"].as_str().unwrap().contains("Revoke"), "{body}");

    // Revoking one frees a slot.
    let (_, body) = admin.get("/teams/acme/tokens").await;
    let some_id = body["tokens"][0]["id"].as_str().unwrap().to_owned();
    assert_eq!(
        admin
            .delete(&format!("/teams/acme/tokens/{some_id}"))
            .await
            .0,
        200
    );
    assert_eq!(
        admin
            .post("/teams/acme/tokens", json!({"agent": "bot"}))
            .await
            .0,
        201
    );

    h.shutdown().await;
}

#[tokio::test]
async fn admin_api_has_its_own_lower_rate_limit() {
    use ai_crew_sync::store::admin::{self as store, Actor};

    // 200/min on MCP means 20/min on /admin, with a burst of 10.
    let Some(h) = setup_rate_limited("t_admin_rl", 200).await else {
        assert!(!db_required());
        return;
    };
    let global = store::grant_admin(&h.pool, Actor::Cli, None, None)
        .await
        .unwrap();
    let admin = Admin::new(&h.base, &global.token);
    let mut throttled = None;
    for _ in 0..30 {
        let (status, body) = admin.get("/whoami").await;
        if status == 429 {
            throttled = Some(body);
            break;
        }
    }
    let body = throttled.expect("the admin bucket must run out well before the MCP one would");
    assert!(
        body["error"].as_str().unwrap().contains("retry in"),
        "{body}"
    );

    h.shutdown().await;
}

// ------------------------------------------------------- admin remote CLI --

/// The remote CLI's library functions against the real server and a
/// temporary configuration directory: the full onboarding flow with
/// verification and `--save`, and the failure paths that must leave no
/// trace.
#[tokio::test]
async fn admin_cli_runs_the_remote_flow_end_to_end() {
    use ai_crew_sync::admin_cli::{self, SaveTarget};
    use ai_crew_sync::store::admin::{self as store, Actor};

    let h = require_db!("t_admin_cli");
    let dir = std::env::temp_dir().join(format!("acs-admin-cli-{}", Uuid::new_v4()));
    let bootstrap = store::grant_admin(&h.pool, Actor::Cli, None, None)
        .await
        .unwrap();

    // A bad credential is refused and nothing is written.
    let err = admin_cli::login(&dir, &h.base, "acsa_nope".into())
        .await
        .unwrap_err();
    assert!(format!("{err:#}").contains("nothing was saved"), "{err:#}");
    assert!(!dir.join("admin").exists());

    // Login verifies, then persists with 0600; the URL is normalised.
    let (me, path) = admin_cli::login(&dir, &format!("{}/mcp", h.base), bootstrap.token.clone())
        .await
        .unwrap();
    assert_eq!(me["scope"], "global");
    let text = std::fs::read_to_string(&path).unwrap();
    assert!(text.contains(&format!("url={}\n", h.base)), "{text}");
    assert!(text.contains(&format!("token={}\n", bootstrap.token)));
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        assert_eq!(
            std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
            0o600
        );
    }
    let cfg = admin_cli::load_config(&dir).unwrap();
    assert_eq!(cfg.url, h.base);
    let api = admin_cli::Api::new(cfg);

    // Team, agent, token — and the token is verified before anything else.
    api.create_team("roundcrew", Some("RoundCrew"))
        .await
        .unwrap();
    api.create_agent("roundcrew", "backend", None)
        .await
        .unwrap();

    // The file already has hand-written entries that must survive.
    let tokens = admin_cli::tokens_file(&dir, "roundcrew");
    std::fs::write(
        &tokens,
        "# roundcrew tokens\n_base=acs_base_keep\nweb=acs_web_keep\n",
    )
    .unwrap();
    let issued = api
        .issue_token("roundcrew", "backend", Some("sesion backend"))
        .await
        .unwrap();
    let saved = admin_cli::finish_issue(
        &api,
        &issued,
        "backend",
        "roundcrew",
        Some(&SaveTarget {
            dir: dir.clone(),
            repo: "backend".into(),
        }),
    )
    .await
    .unwrap();
    assert_eq!(saved.as_deref(), Some(tokens.as_path()));
    let text = std::fs::read_to_string(&tokens).unwrap();
    assert_eq!(
        text,
        format!(
            "# roundcrew tokens\n_base=acs_base_keep\nweb=acs_web_keep\nbackend={}\n",
            issued.token
        ),
        "only the backend= line is added; _base and the rest are untouched"
    );
    // The saved token is that agent on /mcp.
    let client = connect(&h.base, &issued.token).await;
    let me = call(&client, "whoami", json!({})).await;
    assert_eq!(
        (me["agent"].as_str(), me["team"].as_str()),
        (Some("backend"), Some("roundcrew"))
    );
    let _ = client.cancel().await;

    // Re-issuing for the same repo replaces the line and does NOT revoke the
    // previous token.
    let second = api.issue_token("roundcrew", "backend", None).await.unwrap();
    admin_cli::finish_issue(
        &api,
        &second,
        "backend",
        "roundcrew",
        Some(&SaveTarget {
            dir: dir.clone(),
            repo: "backend".into(),
        }),
    )
    .await
    .unwrap();
    let text = std::fs::read_to_string(&tokens).unwrap();
    assert!(text.contains(&format!("backend={}\n", second.token)));
    assert!(!text.contains(&issued.token), "one line per repo");
    assert!(text.starts_with("# roundcrew tokens\n_base=acs_base_keep\n"));
    assert_eq!(
        mcp_status(&h.base, &issued.token).await,
        200,
        "the old token still works"
    );

    // Verification failure: a token that authenticates as someone else is
    // revoked, and the file is left exactly as it was.
    api.create_agent("roundcrew", "web", None).await.unwrap();
    let other = api.issue_token("roundcrew", "web", None).await.unwrap();
    let before = std::fs::read_to_string(&tokens).unwrap();
    let err = admin_cli::finish_issue(
        &api,
        &other,
        "backend",
        "roundcrew",
        Some(&SaveTarget {
            dir: dir.clone(),
            repo: "backend".into(),
        }),
    )
    .await
    .unwrap_err();
    let msg = format!("{err:#}");
    assert!(
        msg.contains("web@roundcrew, not backend@roundcrew"),
        "{msg}"
    );
    assert!(msg.contains("has been revoked"), "{msg}");
    assert_eq!(
        std::fs::read_to_string(&tokens).unwrap(),
        before,
        "file untouched"
    );
    assert_eq!(
        mcp_status(&h.base, &other.token).await,
        401,
        "the mismatched token is dead"
    );

    // A save that cannot be written revokes the verified token too: a token
    // that was never printed and never saved must not stay active.
    let unwritable = dir.join("blocked");
    std::fs::write(&unwritable, "not a directory").unwrap();
    let doomed = api.issue_token("roundcrew", "backend", None).await.unwrap();
    let err = admin_cli::finish_issue(
        &api,
        &doomed,
        "backend",
        "roundcrew",
        Some(&SaveTarget {
            dir: unwritable.clone(),
            repo: "backend".into(),
        }),
    )
    .await
    .unwrap_err();
    let msg = format!("{err:#}");
    assert!(msg.contains("could not be saved"), "{msg}");
    assert!(msg.contains("has been revoked"), "{msg}");
    assert_eq!(mcp_status(&h.base, &doomed.token).await, 401);

    // Revoke through the CLI stops the token on /mcp.
    api.revoke_token("roundcrew", second.id).await.unwrap();
    assert_eq!(mcp_status(&h.base, &second.token).await, 401);

    // A team credential logged in on this machine is confined to its team.
    let team_dir = dir.join("dani");
    let granted = api
        .grant_credential(Some("roundcrew"), Some("dani"))
        .await
        .unwrap();
    let team_token = granted["credential"]["token"].as_str().unwrap().to_owned();
    let (me, _) = admin_cli::login(&team_dir, &h.base, team_token)
        .await
        .unwrap();
    assert_eq!(me["team"], "roundcrew");
    let dani = admin_cli::Api::new(admin_cli::load_config(&team_dir).unwrap());
    dani.create_agent("roundcrew", "docs", None).await.unwrap();
    let err = dani.create_agent("other", "docs", None).await.unwrap_err();
    assert!(err.to_string().contains("403"), "{err}");
    assert!(err.to_string().contains("'roundcrew'"), "{err}");
    let err = dani.create_team("mine", None).await.unwrap_err();
    assert!(err.to_string().contains("403"), "{err}");

    // Logout forgets the file and nothing else.
    assert!(admin_cli::remove_config(&team_dir).unwrap());
    assert!(!admin_cli::remove_config(&team_dir).unwrap());
    assert!(admin_cli::load_config(&team_dir).is_err());
    assert!(tokens.exists(), "token files are not login state");

    let _ = std::fs::remove_dir_all(&dir);
    h.shutdown().await;
}

// ------------------------------------------------------------ local context --

/// The resolver against a real bus: a profile plus a token file yields a
/// verified identity with no BUS_TOKEN anywhere; the wrong token behind the
/// right profile, and a revoked one, are refused with a reason.
#[tokio::test]
async fn local_profiles_resolve_and_verify_against_the_bus() {
    use ai_crew_sync::context::{self, Inputs, Profile, Profiles, Source};
    use ai_crew_sync::store::admin::{self as store, Actor};

    let h = require_db!("t_context");
    let dir = std::env::temp_dir().join(format!("acs-context-{}", Uuid::new_v4()));
    std::fs::create_dir_all(&dir).unwrap();

    let acme = store::create_team(&h.pool, Actor::Cli, "acme", None)
        .await
        .unwrap();
    store::create_agent(&h.pool, Actor::Cli, acme.id, "joaquin", None)
        .await
        .unwrap();
    store::create_agent(&h.pool, Actor::Cli, acme.id, "marta", None)
        .await
        .unwrap();
    let mine = store::issue_token(&h.pool, Actor::Cli, acme.id, "joaquin", None)
        .await
        .unwrap();
    let hers = store::issue_token(&h.pool, Actor::Cli, acme.id, "marta", None)
        .await
        .unwrap();

    context::save_profiles(
        &dir,
        &Profiles {
            default: None,
            profiles: std::collections::BTreeMap::from([(
                "acme".to_owned(),
                Profile {
                    url: h.base.clone(),
                    team: "acme".into(),
                    agent: "joaquin".into(),
                    tokens: "tokens-acme".into(),
                    key: None,
                },
            )]),
        },
    )
    .unwrap();
    std::fs::write(
        dir.join("tokens-acme"),
        format!("_base={}\nstolen={}\n", mine.token, hers.token),
    )
    .unwrap();
    let repo = dir.join("repo");
    std::fs::create_dir_all(&repo).unwrap();
    std::fs::write(
        repo.join(context::PROJECT_FILE),
        "profile = \"acme\"\nproject = \"api\"\nchannel = \"api\"\n",
    )
    .unwrap();

    // Two windows in the same repository, no environment: both resolve the
    // project's profile, and each may pick a different entry without
    // touching the file the other reads.
    let base = Inputs {
        config_dir: dir.clone(),
        project_dir: Some(repo.clone()),
        ..Default::default()
    };
    let r = context::resolve(&base).unwrap();
    assert_eq!(r.source, Source::ProjectDefault);
    assert_eq!(
        r.token_key.as_deref(),
        Some("_base"),
        "no 'api' entry, so _base"
    );
    assert_eq!(r.project.as_deref(), Some("api"));
    let v = context::verify(&r).await.unwrap();
    assert_eq!((v.agent.as_str(), v.team.as_str()), ("joaquin", "acme"));

    // The right profile over someone else's token: refused, with the entry
    // named, and the project file untouched.
    let before = std::fs::read_to_string(repo.join(context::PROJECT_FILE)).unwrap();
    std::fs::write(
        repo.join(context::PROJECT_FILE),
        "profile = \"acme\"\nproject = \"api\"\nkey = \"stolen\"\n",
    )
    .unwrap();
    let r = context::resolve(&base).unwrap();
    assert_eq!(r.token_key.as_deref(), Some("stolen"));
    let err = format!("{:#}", context::verify(&r).await.unwrap_err());
    assert!(err.contains("expects joaquin@acme"), "{err}");
    assert!(err.contains("marta@acme"), "{err}");
    assert!(err.contains("'stolen'"), "{err}");
    std::fs::write(repo.join(context::PROJECT_FILE), before).unwrap();

    // A revoked token is reported as such, pointing at the entry to replace.
    store::revoke_token(&h.pool, Actor::Cli, None, mine.id)
        .await
        .unwrap();
    let r = context::resolve(&base).unwrap();
    let err = format!("{:#}", context::verify(&r).await.unwrap_err());
    assert!(err.contains("did not accept the token"), "{err}");
    assert!(err.contains("'_base'"), "{err}");
    assert!(err.contains("admin token issue"), "{err}");

    // Explicit credentials still work exactly as before, and are not
    // checked against any profile.
    let fresh = store::issue_token(&h.pool, Actor::Cli, acme.id, "marta", None)
        .await
        .unwrap();
    let explicit = Inputs {
        explicit_url: Some(format!("{}/mcp", h.base)),
        explicit_token: Some(fresh.token.clone()),
        ..base.clone()
    };
    let r = context::resolve(&explicit).unwrap();
    assert_eq!(r.source, Source::Explicit);
    assert!(r.expected.is_none());
    let v = context::verify(&r).await.unwrap();
    assert_eq!(v.agent, "marta");

    // The project's channel is not decoration: a message with neither
    // --channel nor --to goes there.
    let defaults = ai_crew_sync::client::mapping::Defaults {
        channel: r.channel.clone(),
    };
    let (tool, args) = ai_crew_sync::client::mapping::to_call_with(
        &ai_crew_sync::client::ClientCmd::Send {
            channel: None,
            to: None,
            body: "from the project".into(),
            announce: false,
            reply_to: None,
            file: vec![],
        },
        &defaults,
    )
    .unwrap()
    .expect("send maps to a tool");
    assert_eq!(tool, "post_message");
    assert_eq!(args["channel"], "api", "the .acs.toml channel is used");
    // A direct message stays direct, and an explicit channel still wins.
    let (_, args) = ai_crew_sync::client::mapping::to_call_with(
        &ai_crew_sync::client::ClientCmd::Send {
            channel: None,
            to: Some("marta".into()),
            body: "hi".into(),
            announce: false,
            reply_to: None,
            file: vec![],
        },
        &defaults,
    )
    .unwrap()
    .unwrap();
    assert!(args["channel"].is_null(), "a DM is not redirected: {args}");

    // The secret never appears in the redacted view.
    let shown = serde_json::to_string(&r.redacted()).unwrap();
    assert!(!shown.contains(&fresh.token[5..]));
    assert!(shown.contains(&fresh.token[..12]));

    let _ = std::fs::remove_dir_all(&dir);
    h.shutdown().await;
}

// -------------------------------------------------------- session discovery --

/// Five windows on one token and one repository — implementation, design, a
/// Claude reviewer and two Codex reviewers — are discoverable separately by
/// project and role, keep distinct addresses even when they share both, and
/// a message to one of them reaches that one alone.
#[tokio::test]
async fn sessions_are_discoverable_by_project_and_role_and_addressed_exactly() {
    let h = require_db!("t_sessions");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    let dani_token = seed_agent(&h.pool, "acme", "dani").await;
    let outsider = seed_agent(&h.pool, "other", "eve").await;

    // Opaque session ids, the way a per-conversation proxy would mint them.
    let windows = [
        ("s-1a2b3c4d", "market-data", "implementation"),
        ("s-5e6f7a8b", "market-data", "design"),
        ("s-9c0d1e2f", "market-data", "review"),
        ("s-3a4b5c6d", "market-data", "review"),
        ("s-7e8f9a0b", "market-data", "review"),
    ];
    let mut clients = Vec::new();
    for (session, project, role) in windows {
        let c = connect_with_session(&h.base, &token, session).await;
        let beat = call(
            &c,
            "heartbeat",
            json!({"project": project, "role": role, "repo": "acme/market-data",
                   "activity": format!("{role} window")}),
        )
        .await;
        assert_eq!(beat["project"], project);
        assert_eq!(beat["role"], role);
        clients.push(c);
    }
    // A labelled window of another person on another project, and one with
    // an already expired lease.
    let dani = connect_with_session(&h.base, &dani_token, "s-dani0001").await;
    call(
        &dani,
        "heartbeat",
        json!({"project": "core-manager", "role": "implementation"}),
    )
    .await;
    let stale = connect_with_session(&h.base, &token, "s-stale001").await;
    call(
        &stale,
        "heartbeat",
        json!({"project": "market-data", "role": "review"}),
    )
    .await;
    sqlx::query("UPDATE agent_presence SET expires_at = now() - interval '1 minute' WHERE session = 's-stale001'")
        .execute(&h.pool)
        .await
        .unwrap();

    // Labels are validated as labels, not descriptions.
    let err = call_expect_error(&clients[0], "heartbeat", json!({"role": "code review!"})).await;
    assert!(err.contains("role"), "{err}");

    // Discovery: by project, by role, by both; every window separately.
    let all = call(
        &clients[0],
        "list_sessions",
        json!({"project": "market-data"}),
    )
    .await;
    let addresses: Vec<&str> = all["sessions"]
        .as_array()
        .unwrap()
        .iter()
        .map(|s| s["address"].as_str().unwrap())
        .collect();
    assert_eq!(
        addresses.len(),
        6,
        "five live windows plus the expired one: {addresses:?}"
    );
    for (session, _, _) in windows {
        assert!(addresses.contains(&format!("joaquin/{session}").as_str()));
    }
    assert!(
        !addresses.iter().any(|a| a.starts_with("dani/")),
        "other project"
    );
    let expired = all["sessions"]
        .as_array()
        .unwrap()
        .iter()
        .find(|s| s["session"] == "s-stale001")
        .expect("expired sessions are listed unless online_only");
    assert_eq!(expired["online"], false);
    assert_eq!(expired["status"], "offline");

    let reviewers = call(
        &clients[0],
        "list_sessions",
        json!({"project": "market-data", "role": "review", "online_only": true}),
    )
    .await;
    let mut review_addresses: Vec<String> = reviewers["sessions"]
        .as_array()
        .unwrap()
        .iter()
        .map(|s| s["address"].as_str().unwrap().to_owned())
        .collect();
    review_addresses.sort();
    assert_eq!(
        review_addresses,
        vec![
            "joaquin/s-3a4b5c6d",
            "joaquin/s-7e8f9a0b",
            "joaquin/s-9c0d1e2f"
        ],
        "three reviewers share a role and keep three addresses; the expired one is gone"
    );
    assert_eq!(reviewers["count"], 3);

    let design = call(&clients[0], "list_sessions", json!({"role": "Design"})).await;
    assert_eq!(
        design["sessions"].as_array().unwrap().len(),
        1,
        "labels normalise"
    );
    assert_eq!(design["sessions"][0]["address"], "joaquin/s-5e6f7a8b");

    // whoami and list_agents carry the labels too.
    let me = call(&clients[1], "whoami", json!({})).await;
    assert_eq!(me["project"], "market-data");
    assert_eq!(me["role"], "design");
    // A window that never labelled itself gets the response it always got:
    // the keys are absent, not null.
    let unlabelled = connect_with_session(&h.base, &token, "s-nolabels").await;
    let plain = call(&unlabelled, "whoami", json!({})).await;
    assert!(plain.get("project").is_none(), "{plain}");
    assert!(plain.get("role").is_none(), "{plain}");
    let _ = unlabelled.cancel().await;
    let roster = call(&clients[0], "list_agents", json!({})).await;
    let joaquin = roster["agents"]
        .as_array()
        .unwrap()
        .iter()
        .find(|a| a["name"] == "joaquin")
        .unwrap();
    assert!(
        joaquin["sessions"]
            .as_array()
            .unwrap()
            .iter()
            .any(|s| s["role"] == "design"),
        "{joaquin}"
    );

    // Exact addressing: a message to the design window reaches only it, and
    // a sibling's read neither sees it nor moves its cursor.
    let design_addr = design["sessions"][0]["address"].as_str().unwrap();
    call(
        &clients[0],
        "post_message",
        json!({"to": design_addr, "body": "the header is wrong on mobile"}),
    )
    .await;
    let sibling = call(&clients[2], "read_messages", json!({"scope": "inbox"})).await;
    assert!(
        sibling["messages"].as_array().unwrap().is_empty(),
        "a reviewer window must not see the design window's DM: {sibling}"
    );
    let inbox = call(&clients[1], "read_messages", json!({"scope": "inbox"})).await;
    assert_eq!(inbox["messages"].as_array().unwrap().len(), 1);
    assert_eq!(
        inbox["messages"][0]["body"],
        "the header is wrong on mobile"
    );
    assert_eq!(inbox["messages"][0]["to_session"], "s-5e6f7a8b");
    let again = call(&clients[1], "read_messages", json!({"scope": "inbox"})).await;
    assert!(
        again["messages"].as_array().unwrap().is_empty(),
        "read once, cursor moved"
    );
    let me = call(&clients[1], "whoami", json!({})).await;
    assert_eq!(me["unread_direct_messages"], 0);

    // The default channel follows the project label, not the opaque id.
    call(
        &clients[0],
        "create_channel",
        json!({"name": "market-data"}),
    )
    .await;
    let me = call(&clients[0], "whoami", json!({})).await;
    assert_eq!(me["default_channel"], "market-data");
    let posted = call(
        &clients[0],
        "post_message",
        json!({"body": "posted by default"}),
    )
    .await;
    assert_eq!(posted["message"]["channel"], "market-data");
    // Clearing the project clears the default with it.
    call(&clients[0], "heartbeat", json!({"project": ""})).await;
    let me = call(&clients[0], "whoami", json!({})).await;
    assert!(me["default_channel"].is_null(), "{me}");
    assert!(me["project"].is_null());

    // A shared session mixed with named ones: it is listed, because it is
    // real presence, and it is NOT an exact address. Sending to the bare
    // agent name reaches every window of that agent, which is exactly why
    // `exact` is false — a caller that reads it cannot broadcast a private
    // instruction by accident.
    let shared = connect(&h.base, &dani_token).await;
    call(
        &shared,
        "heartbeat",
        json!({"project": "core-manager", "role": "design"}),
    )
    .await;
    let mixed = call(
        &clients[0],
        "list_sessions",
        json!({"project": "core-manager", "online_only": true}),
    )
    .await;
    let rows = mixed["sessions"].as_array().unwrap();
    let shared_row = rows
        .iter()
        .find(|s| s["session"].is_null())
        .expect("the shared session is listed");
    assert_eq!(shared_row["address"], "dani");
    assert_eq!(
        shared_row["exact"], false,
        "a bare agent name is not one window"
    );
    let named_row = rows
        .iter()
        .find(|s| s["session"] == "s-dani0001")
        .expect("the named session is listed");
    assert_eq!(named_row["address"], "dani/s-dani0001");
    assert_eq!(named_row["exact"], true);

    // Prove the warning: a message to the shared row's address lands in the
    // named window's inbox too.
    call(
        &clients[0],
        "post_message",
        json!({"to": shared_row["address"], "body": "for dani"}),
    )
    .await;
    let named_inbox = call(&dani, "read_messages", json!({"scope": "inbox"})).await;
    assert_eq!(
        named_inbox["messages"][0]["body"], "for dani",
        "the bare name reached the named window as well: {named_inbox}"
    );
    // The exact address of a named window reaches only it.
    call(
        &clients[0],
        "post_message",
        json!({"to": "dani/s-dani0001", "body": "only the named one"}),
    )
    .await;
    let shared_inbox = call(&shared, "read_messages", json!({"scope": "inbox"})).await;
    assert!(
        shared_inbox["messages"]
            .as_array()
            .unwrap()
            .iter()
            .all(|m| m["body"] != "only the named one"),
        "an exact address must not reach the shared session: {shared_inbox}"
    );
    let _ = shared.cancel().await;

    // Another team sees none of it.
    let eve = connect_with_session(&h.base, &outsider, "s-eve").await;
    let theirs = call(&eve, "list_sessions", json!({"project": "market-data"})).await;
    assert_eq!(theirs["count"], 0);
    let err = call_expect_error(
        &eve,
        "post_message",
        json!({"to": design_addr, "body": "hi"}),
    )
    .await;
    assert!(err.contains("no agent"), "{err}");

    for c in clients {
        let _ = c.cancel().await;
    }
    for c in [dani, stale, eve] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

// -------------------------------------------------------------- stdio proxy --

/// A local configuration directory with profiles for the given agents, each
/// with a tokens file holding its token under `_base`.
fn proxy_config_dir(base: &str, profiles: &[(&str, &str, &str, &str)]) -> std::path::PathBuf {
    use ai_crew_sync::context::{Profile, Profiles};
    let dir = std::env::temp_dir().join(format!("acs-proxy-{}", Uuid::new_v4()));
    std::fs::create_dir_all(&dir).unwrap();
    let mut store = Profiles::default();
    for (name, team, agent, token) in profiles {
        let tokens = format!("tokens-{name}");
        std::fs::write(dir.join(&tokens), format!("_base={token}\n")).unwrap();
        store.profiles.insert(
            (*name).to_owned(),
            Profile {
                url: base.to_owned(),
                team: (*team).to_owned(),
                agent: (*agent).to_owned(),
                tokens,
                key: None,
            },
        );
    }
    ai_crew_sync::context::save_profiles(&dir, &store).unwrap();
    dir
}

/// Start the real proxy binary over stdio, with a scrubbed environment so
/// nothing from the developer's shell (a BUS_TOKEN, a Claude session id)
/// leaks into the test.
async fn spawn_proxy(
    config_dir: &std::path::Path,
    project_dir: &std::path::Path,
    args: &[&str],
    env: &[(&str, &str)],
) -> Client {
    use rmcp::transport::{ConfigureCommandExt, TokioChildProcess};
    let bin = env!("CARGO_BIN_EXE_ai-crew-sync");
    let transport = TokioChildProcess::new(tokio::process::Command::new(bin).configure(|cmd| {
        cmd.env_clear()
            .env("PATH", std::env::var("PATH").unwrap_or_default())
            .env("HOME", std::env::var("HOME").unwrap_or_default())
            .env("BUS_CONFIG_DIR", config_dir)
            .env("RUST_LOG", "warn")
            .current_dir(project_dir)
            .args(["mcp", "proxy", "--project-dir"])
            .arg(project_dir)
            .args(args);
        for (k, v) in env {
            cmd.env(k, v);
        }
    }))
    .expect("spawn proxy");
    ClientConfig::default()
        .serve(transport)
        .await
        .expect("proxy initialize")
}

#[tokio::test]
async fn proxy_gives_each_conversation_its_own_session_and_forwards_as_the_profile() {
    let h = require_db!("t_proxy_basic");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    let dir = proxy_config_dir(&h.base, &[("acme", "acme", "joaquin", &token)]);
    let repo = dir.join("market-data");
    std::fs::create_dir_all(&repo).unwrap();
    std::fs::write(
        repo.join(".acs.toml"),
        "profile = \"acme\"\nproject = \"market-data\"\n",
    )
    .unwrap();

    // Two windows, same repository, same token, no environment at all.
    let a = spawn_proxy(&dir, &repo, &["--role", "implementation"], &[]).await;
    let b = spawn_proxy(&dir, &repo, &["--role", "review"], &[]).await;

    let sa = call(&a, "session_status", json!({})).await;
    let sb = call(&b, "session_status", json!({})).await;
    assert_eq!(sa["connected"], true, "{sa}");
    assert_eq!(sa["agent"], "joaquin");
    assert_eq!(sa["team"], "acme");
    assert_eq!(sa["project"], "market-data", "from .acs.toml");
    assert_eq!(sa["role"], "implementation");
    assert_eq!(sb["role"], "review");
    assert_eq!(sa["binding"], "instance");
    assert_ne!(sa["session"], sb["session"], "one session per process");
    assert!(sa["session"].as_str().unwrap().starts_with("s-"));
    assert_eq!(
        sa["address"],
        format!("joaquin/{}", sa["session"].as_str().unwrap())
    );
    assert!(sa.get("token").is_none() && sa.get("credentials").is_none());

    // Forwarded calls carry the session: whoami through each proxy is the
    // same agent in a different session.
    let wa = call(&a, "whoami", json!({})).await;
    let wb = call(&b, "whoami", json!({})).await;
    assert_eq!(wa["agent"], "joaquin");
    assert_eq!(wa["session"], sa["session"]);
    assert_eq!(wb["session"], sb["session"]);
    assert_eq!(
        wa["role"], "implementation",
        "the proxy's heartbeat published it"
    );

    // The local tools sit beside the remote ones here, and nowhere on the
    // bus itself.
    let names: Vec<String> = a
        .list_all_tools()
        .await
        .unwrap()
        .iter()
        .map(|t| t.name.to_string())
        .collect();
    for expected in [
        "configure_session",
        "session_status",
        "whoami",
        "post_message",
        "list_sessions",
    ] {
        assert!(names.contains(&expected.to_owned()), "{names:?}");
    }
    let direct = connect(&h.base, &token).await;
    let remote_names: Vec<String> = direct
        .list_all_tools()
        .await
        .unwrap()
        .iter()
        .map(|t| t.name.to_string())
        .collect();
    assert!(
        !remote_names
            .iter()
            .any(|n| n == "configure_session" || n == "session_status")
    );

    // Discovery sees both windows with their roles and exact addresses.
    let found = call(
        &direct,
        "list_sessions",
        json!({"project": "market-data", "online_only": true}),
    )
    .await;
    let addresses: Vec<&str> = found["sessions"]
        .as_array()
        .unwrap()
        .iter()
        .map(|s| s["address"].as_str().unwrap())
        .collect();
    assert!(
        addresses.contains(&sa["address"].as_str().unwrap()),
        "{addresses:?}"
    );
    assert!(
        addresses.contains(&sb["address"].as_str().unwrap()),
        "{addresses:?}"
    );

    // A DM to window B is read by B only; A's cursor is untouched.
    call(
        &direct,
        "post_message",
        json!({"to": sb["address"], "body": "for the reviewer"}),
    )
    .await;
    let inbox_a = call(&a, "read_messages", json!({"scope": "inbox"})).await;
    assert!(inbox_a["messages"].as_array().unwrap().is_empty());
    let inbox_b = call(&b, "read_messages", json!({"scope": "inbox"})).await;
    assert_eq!(inbox_b["messages"][0]["body"], "for the reviewer");

    // A role change keeps the session and reaches teammates on the next
    // discovery; it touches this window only.
    let changed = call(&b, "configure_session", json!({"role": "design"})).await;
    assert_eq!(changed["status"]["session"], sb["session"]);
    assert_eq!(changed["status"]["role"], "design");
    assert!(changed["previous"].is_null(), "no identity change");
    let design = call(&direct, "list_sessions", json!({"role": "design"})).await;
    assert_eq!(design["count"], 1);
    assert_eq!(design["sessions"][0]["address"], sb["address"]);
    assert_eq!(
        call(&a, "session_status", json!({})).await["role"],
        "implementation"
    );

    for c in [a, b, direct] {
        let _ = c.cancel().await;
    }
    let _ = std::fs::remove_dir_all(&dir);
    h.shutdown().await;
}

#[tokio::test]
async fn proxy_binds_a_conversation_id_to_a_stable_session() {
    use ai_crew_sync::proxy::session_for;

    let h = require_db!("t_proxy_bind");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    let dir = proxy_config_dir(&h.base, &[("acme", "acme", "joaquin", &token)]);
    let repo = dir.join("repo");
    std::fs::create_dir_all(&repo).unwrap();
    std::fs::write(repo.join(".acs.toml"), "profile = \"acme\"\n").unwrap();

    // The same conversation id, twice (a restart, a resume): one session.
    let first = spawn_proxy(&dir, &repo, &["--host-session", "conv-1"], &[]).await;
    let s1 = call(&first, "session_status", json!({})).await;
    let _ = first.cancel().await;
    let again = spawn_proxy(&dir, &repo, &["--host-session", "conv-1"], &[]).await;
    let s1b = call(&again, "session_status", json!({})).await;
    assert_eq!(s1["session"], s1b["session"], "reconnect keeps the session");
    assert_eq!(s1["binding"], "explicit");
    assert_eq!(s1["session"], session_for("conv-1"));
    // A forked conversation has another id and another session.
    let fork = spawn_proxy(&dir, &repo, &[], &[("BUS_HOST_SESSION", "conv-2")]).await;
    let s2 = call(&fork, "session_status", json!({})).await;
    assert_ne!(s2["session"], s1["session"]);
    assert_eq!(s2["session"], session_for("conv-2"));
    // Claude Code's variable binds the same way.
    let claude = spawn_proxy(&dir, &repo, &[], &[("CLAUDE_CODE_SESSION_ID", "conv-1")]).await;
    let s3 = call(&claude, "session_status", json!({})).await;
    assert_eq!(s3["binding"], "claude-code");
    assert_eq!(
        s3["session"], s1["session"],
        "same conversation id, same session"
    );
    // Identity is independent of the binding: still the profile's agent.
    assert_eq!(call(&claude, "whoami", json!({})).await["agent"], "joaquin");
    for c in [again, fork, claude] {
        let _ = c.cancel().await;
    }

    // A host that sends the conversation id in request metadata (Codex):
    // the first id binds, a second one on the same process is refused.
    let meta = spawn_proxy(&dir, &repo, &[], &[]).await;
    let before = call(&meta, "session_status", json!({})).await;
    assert_eq!(before["binding"], "instance");
    let with_thread = |thread: &str| {
        let mut params = CallToolRequestParams::new("whoami");
        let mut m = rmcp::model::JsonObject::new();
        m.insert("threadId".into(), json!(thread));
        params.meta = Some(rmcp::model::RequestMetaObject::from(m));
        params
    };
    let r = meta.call_tool(with_thread("thread-A")).await.unwrap();
    let who = r.structured_content.unwrap();
    assert_eq!(who["session"], session_for("thread-A"));
    let after = call(&meta, "session_status", json!({})).await;
    assert_eq!(after["binding"], "request-meta");
    assert_eq!(after["session"], session_for("thread-A"));
    let err = meta
        .call_tool(with_thread("thread-B"))
        .await
        .unwrap_err()
        .to_string();
    assert!(err.contains("another conversation"), "{err}");
    assert!(
        err.contains("one `ai-crew-sync mcp proxy` per conversation"),
        "{err}"
    );
    // The bound conversation keeps working.
    let r = meta.call_tool(with_thread("thread-A")).await.unwrap();
    assert_eq!(r.is_error, Some(false));
    let _ = meta.cancel().await;

    let _ = std::fs::remove_dir_all(&dir);
    h.shutdown().await;
}

#[tokio::test]
async fn proxy_switches_profiles_only_after_verification_and_never_across_teams() {
    use ai_crew_sync::store::admin::{self as store, Actor};

    let h = require_db!("t_proxy_switch");
    let joaquin = seed_agent(&h.pool, "acme", "joaquin").await;
    let marta = seed_agent(&h.pool, "acme", "marta").await;
    let eve = seed_agent(&h.pool, "other", "eve").await;
    let dir = proxy_config_dir(
        h.base.as_str(),
        &[
            ("me", "acme", "joaquin", &joaquin),
            ("marta", "acme", "marta", &marta),
            ("other", "other", "eve", &eve),
            // Claims to be marta, holds eve's token: verification must catch it.
            ("liar", "acme", "marta", &eve),
        ],
    );
    let repo = dir.join("repo");
    std::fs::create_dir_all(&repo).unwrap();
    std::fs::write(
        repo.join(".acs.toml"),
        "profile = \"me\"\nproject = \"api\"\n",
    )
    .unwrap();

    // This conversation id hashes to the label `s-a7da401d8d70`. The bus
    // quotes it when marta is refused joaquin's lease below, and the proxy
    // once read that "401" as its own credential being rejected.
    let p = spawn_proxy(
        &dir,
        &repo,
        &["--role", "implementation"],
        &[("BUS_HOST_SESSION", "conv-1617")],
    )
    .await;
    let start = call(&p, "session_status", json!({})).await;
    assert_eq!(start["agent"], "joaquin");
    let session = start["session"].as_str().unwrap().to_owned();
    assert_eq!(
        session, "s-a7da401d8d70",
        "the fixture label moved; pick another id"
    );

    // Hold something as joaquin so the switch has something to report.
    call(
        &p,
        "create_task",
        json!({"key": "api#1", "title": "wire it"}),
    )
    .await;
    call(&p, "claim_task", json!({"key": "api#1"})).await;
    call(&p, "acquire_lock", json!({"name": "api:deploy"})).await;

    // A profile that fails verification changes nothing.
    let r = p
        .call_tool(
            CallToolRequestParams::new("configure_session")
                .with_arguments(serde_json::from_value(json!({"profile": "liar"})).unwrap()),
        )
        .await
        .unwrap();
    assert_eq!(r.is_error, Some(true), "{r:?}");
    let text = format!("{:?}", r.content);
    assert!(text.contains("expects marta@acme"), "{text}");
    assert_eq!(
        call(&p, "whoami", json!({})).await["agent"],
        "joaquin",
        "still joaquin"
    );

    // Another team: refused, with the reason.
    let r = p
        .call_tool(
            CallToolRequestParams::new("configure_session")
                .with_arguments(serde_json::from_value(json!({"profile": "other"})).unwrap()),
        )
        .await
        .unwrap();
    assert_eq!(r.is_error, Some(true));
    let text = format!("{:?}", r.content);
    assert!(text.contains("new conversation"), "{text}");
    assert!(text.contains("team 'acme'"), "{text}");
    assert_eq!(call(&p, "whoami", json!({})).await["agent"], "joaquin");

    // A same-team switch while a long poll is in flight: the poll is
    // cancelled, not replayed; the new identity answers afterwards; the old
    // one's claim and lock are reported, not transferred; role and session
    // stay.
    let waiter = {
        let p2 = p.clone();
        tokio::spawn(async move {
            p2.call_tool(
                CallToolRequestParams::new("wait_for_updates").with_arguments(
                    serde_json::from_value(json!({"timeout_seconds": 20})).unwrap(),
                ),
            )
            .await
        })
    };
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
    let switched = call(&p, "configure_session", json!({"profile": "marta"})).await;
    let wait_outcome = tokio::time::timeout(std::time::Duration::from_secs(8), waiter)
        .await
        .expect("the in-flight poll must end at the switch, not at its own timeout")
        .unwrap();
    let err = wait_outcome
        .expect_err("cancelled by the context switch")
        .to_string();
    assert!(err.contains("switched credentials"), "{err}");
    assert_eq!(switched["status"]["agent"], "marta");
    assert_eq!(switched["status"]["team"], "acme");
    assert_eq!(
        switched["status"]["session"], session,
        "session survives the switch"
    );
    assert_eq!(switched["status"]["role"], "implementation");
    assert_eq!(switched["previous"]["agent"], "joaquin");
    assert_eq!(switched["previous"]["open_claims"], json!(["api#1"]));
    assert_eq!(switched["previous"]["held_locks"], json!(["api:deploy"]));

    // The window's own channel is applied to a message that names none, so
    // the default the instructions advertise is the one the bus sees.
    call(&p, "create_channel", json!({"name": "api"})).await;
    let posted = call(&p, "post_message", json!({"body": "from the window"})).await;
    assert_eq!(posted["message"]["channel"], "api");
    // An explicit channel and a direct message are untouched.
    call(&p, "create_channel", json!({"name": "other"})).await;
    let elsewhere = call(
        &p,
        "post_message",
        json!({"channel": "other", "body": "explicit"}),
    )
    .await;
    assert_eq!(elsewhere["message"]["channel"], "other");
    let dm = call(
        &p,
        "post_message",
        json!({"to": "joaquin", "body": "direct"}),
    )
    .await;
    assert!(dm["message"]["channel"].is_null(), "{dm}");

    // A label the bus would reject is refused here too, and changes nothing.
    let before_role = call(&p, "session_status", json!({})).await["role"].clone();
    let r = p
        .call_tool(
            CallToolRequestParams::new("configure_session")
                .with_arguments(serde_json::from_value(json!({"role": "code review!"})).unwrap()),
        )
        .await
        .unwrap();
    assert_eq!(r.is_error, Some(true), "{r:?}");
    assert_eq!(
        call(&p, "session_status", json!({})).await["role"],
        before_role
    );
    assert_eq!(call(&p, "whoami", json!({})).await["agent"], "marta");
    // Ownership stayed with joaquin: marta holds neither the lease nor the
    // lock, so she can renew and release nothing of his.
    let err = call_expect_error(&p, "renew_task_lease", json!({"key": "api#1"})).await;
    assert!(err.contains("joaquin"), "{err}");
    let err = call_expect_error(&p, "release_lock", json!({"name": "api:deploy"})).await;
    assert!(err.contains("joaquin"), "{err}");

    // A revoked token surfaces as an error on the next forwarded call, and a
    // working profile recovers the window.
    let (marta_id,): (Uuid,) = sqlx::query_as(
        "SELECT t.id FROM api_tokens t JOIN agents a ON a.id = t.agent_id WHERE a.name = 'marta'",
    )
    .fetch_one(&h.pool)
    .await
    .unwrap();
    store::revoke_token(&h.pool, Actor::Cli, None, marta_id)
        .await
        .unwrap();
    let err = p
        .call_tool(CallToolRequestParams::new("whoami"))
        .await
        .unwrap_err()
        .to_string();
    assert!(err.contains("revoked or rotated"), "{err}");
    assert!(err.contains("configure_session"), "{err}");
    assert!(err.contains("profile 'marta'"), "{err}");
    let hurt = call(&p, "session_status", json!({})).await;
    assert!(
        hurt["error"]
            .as_str()
            .unwrap_or_default()
            .contains("rejected"),
        "the window reports its own broken credential: {hurt}"
    );
    let back = call(&p, "configure_session", json!({"profile": "me"})).await;
    assert_eq!(back["status"]["agent"], "joaquin");
    assert_eq!(call(&p, "whoami", json!({})).await["session"], session);

    let _ = p.cancel().await;
    let _ = std::fs::remove_dir_all(&dir);
    h.shutdown().await;
}

// ------------------------------------------------- host integration (#86) --

/// Run a plugin hook script the way a host would: payload on stdin, the
/// repository as cwd, and only the environment a hook actually gets. No
/// BUS_TOKEN, no BUS_SESSION — everything is resolved from the profiles and
/// the conversation id in the payload.
async fn run_hook(
    script: &str,
    config_dir: &std::path::Path,
    project_dir: &std::path::Path,
    payload: &str,
    extra_args: &[&str],
) -> String {
    run_hook_env(script, config_dir, project_dir, payload, extra_args, &[]).await
}

/// `run_hook` with extra environment, for the cases where what the
/// operator exported must not win over the window's binding.
async fn run_hook_env(
    script: &str,
    config_dir: &std::path::Path,
    project_dir: &std::path::Path,
    payload: &str,
    extra_args: &[&str],
    env: &[(&str, &str)],
) -> String {
    // The hook talks HTTP to the harness, which runs on this runtime: waiting
    // for the child on this thread deadlocks both. Off to a blocking thread,
    // with a bound so a wedged hook fails the test instead of hanging CI.
    let (script, config_dir, project_dir, payload) = (
        script.to_owned(),
        config_dir.to_path_buf(),
        project_dir.to_path_buf(),
        payload.to_owned(),
    );
    let extra: Vec<String> = extra_args.iter().map(|a| (*a).to_owned()).collect();
    let env: Vec<(String, String)> = env
        .iter()
        .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
        .collect();
    tokio::time::timeout(
        std::time::Duration::from_secs(30),
        tokio::task::spawn_blocking(move || {
            run_hook_blocking(&script, &config_dir, &project_dir, &payload, &extra, &env)
        }),
    )
    .await
    .expect("the hook did not finish within 30s")
    .expect("the hook task panicked")
}

fn run_hook_blocking(
    script: &str,
    config_dir: &std::path::Path,
    project_dir: &std::path::Path,
    payload: &str,
    extra_args: &[String],
    env: &[(String, String)],
) -> String {
    use std::io::Write;
    let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("plugin/scripts")
        .join(script);
    let bin_dir = std::path::Path::new(env!("CARGO_BIN_EXE_ai-crew-sync"))
        .parent()
        .unwrap()
        .to_path_buf();
    let path = format!(
        "{}:{}",
        bin_dir.display(),
        std::env::var("PATH").unwrap_or_default()
    );
    let mut child = std::process::Command::new("sh")
        .arg(&script)
        .args(extra_args.iter().map(String::as_str))
        .current_dir(project_dir)
        .env_clear()
        .env("PATH", path)
        .env("HOME", std::env::var("HOME").unwrap_or_default())
        .env("TMPDIR", config_dir)
        .env("BUS_CONFIG_DIR", config_dir)
        .envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())))
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null())
        .spawn()
        .expect("spawn hook");
    child
        .stdin
        .as_mut()
        .unwrap()
        .write_all(payload.as_bytes())
        .unwrap();
    let out = child.wait_with_output().expect("hook finished");
    String::from_utf8_lossy(&out.stdout).into_owned()
}

/// The workflow the whole stack exists for: five conversations in one
/// repository, on one token, with no per-window export and no new token —
/// implementation, design, a Claude review and two Codex reviews. They find
/// each other, send targeted corrections, and each window's hooks act on its
/// own session only.
#[tokio::test]
async fn five_conversations_share_a_repo_and_stay_separate() {
    let h = require_db!("t_host_integration");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    let dir = proxy_config_dir(&h.base, &[("acme", "acme", "joaquin", &token)]);
    let repo = dir.join("market-data");
    std::fs::create_dir_all(&repo).unwrap();
    std::fs::write(
        repo.join(".acs.toml"),
        "profile = \"acme\"\nproject = \"market-data\"\nchannel = \"market-data\"\n",
    )
    .unwrap();

    // Five windows. Two hosts that expose a conversation id (Claude Code's
    // variable and an explicit flag), and three that expose none.
    let windows = [
        ("impl", "implementation", Some("conv-impl")),
        ("design", "design", Some("conv-design")),
        ("claude-review", "review", None),
        ("codex-review-1", "review", None),
        ("codex-review-2", "review", None),
    ];
    let mut clients = Vec::new();
    let mut ids = Vec::new();
    for (name, role, conv) in windows {
        let env: Vec<(&str, &str)> = match conv {
            Some(c) if name == "impl" => vec![("CLAUDE_CODE_SESSION_ID", c)],
            Some(c) => vec![("BUS_HOST_SESSION", c)],
            None => vec![],
        };
        let c = spawn_proxy(&dir, &repo, &["--role", role], &env).await;
        let st = call(&c, "session_status", json!({})).await;
        assert_eq!(st["connected"], true, "{name}: {st}");
        assert_eq!(st["agent"], "joaquin");
        ids.push((
            name,
            st["session"].as_str().unwrap().to_owned(),
            st["address"].as_str().unwrap().to_owned(),
        ));
        clients.push(c);
    }
    let sessions: std::collections::HashSet<&str> =
        ids.iter().map(|(_, s, _)| s.as_str()).collect();
    assert_eq!(
        sessions.len(),
        5,
        "five conversations, five sessions: {ids:?}"
    );

    // Design discovers the implementation window and sends a correction; the
    // two same-role Codex reviewers stay distinct.
    let design = &clients[1];
    let found = call(
        design,
        "list_sessions",
        json!({"project": "market-data", "role": "implementation", "online_only": true}),
    )
    .await;
    assert_eq!(found["count"], 1);
    let impl_addr = found["sessions"][0]["address"].as_str().unwrap().to_owned();
    assert_eq!(impl_addr, ids[0].2);
    call(
        design,
        "post_message",
        json!({"to": impl_addr, "body": "the empty state needs a spinner"}),
    )
    .await;
    let reviewers = call(
        design,
        "list_sessions",
        json!({"project": "market-data", "role": "review", "online_only": true}),
    )
    .await;
    assert_eq!(
        reviewers["count"], 3,
        "three reviewers share a role, three addresses"
    );

    // The implementation window reads it, replies to the exact sender, and
    // no other window's inbox moved.
    let implementation = &clients[0];
    let inbox = call(implementation, "read_messages", json!({"scope": "inbox"})).await;
    assert_eq!(inbox["messages"].as_array().unwrap().len(), 1);
    let msg = &inbox["messages"][0];
    assert_eq!(msg["body"], "the empty state needs a spinner");
    let from = format!(
        "{}/{}",
        msg["from"].as_str().unwrap(),
        msg["from_session"].as_str().unwrap()
    );
    assert_eq!(from, ids[1].2);
    call(
        implementation,
        "post_message",
        json!({"to": from, "body": "added", "reply_to": msg["id"]}),
    )
    .await;
    let reply = call(design, "read_messages", json!({"scope": "inbox"})).await;
    assert_eq!(reply["messages"][0]["body"], "added");
    for c in clients.iter().skip(2) {
        let quiet = call(c, "read_messages", json!({"scope": "inbox"})).await;
        assert!(
            quiet["messages"].as_array().unwrap().is_empty(),
            "a reviewer saw another window's direct message"
        );
    }

    // The workflow the stack exists for, end to end: design opens a thread
    // with the implementation window and both reviewers, each acknowledges
    // for itself, and the sender can see who acted.
    enable_conversations(&h.pool, "acme").await;
    let convo = call(
        design,
        "create_conversation",
        json!({"title": "the empty state", "private": true,
               "invite": [ids[0].2.clone(), ids[2].2.clone(), ids[3].2.clone()]}),
    )
    .await;
    let cid = convo["id"].as_str().unwrap().to_owned();
    for c in [&clients[0], &clients[2], &clients[3]] {
        call(c, "join_conversation", json!({"conversation_id": cid})).await;
    }
    let asked = call(
        design,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "the empty state needs a spinner",
               "request_id": Uuid::new_v4().to_string()}),
    )
    .await;
    let asked_id = asked["message_id"].as_str().unwrap().to_owned();
    assert_eq!(asked["recipients"].as_array().unwrap().len(), 3);

    // The fifth window was never invited and sees nothing.
    let err = call_expect_error(
        &clients[4],
        "read_conversation",
        json!({"conversation_id": cid}),
    )
    .await;
    assert!(err.contains("no such conversation"), "{err}");

    // Independent observations: implementation resolves, one reviewer only
    // acknowledges, the other has not answered.
    call(
        &clients[0],
        "ack_message",
        json!({"message_id": asked_id, "resolved": true, "note": "added in 4d21f"}),
    )
    .await;
    call(&clients[2], "ack_message", json!({"message_id": asked_id})).await;
    let receipts = call(
        design,
        "get_message_receipts",
        json!({"message_id": asked_id}),
    )
    .await;
    assert_eq!(receipts["total"], 3);
    assert_eq!(receipts["acknowledged"], 2);
    assert_eq!(receipts["resolved"], 1, "{receipts}");
    let pending = receipts["receipts"]
        .as_array()
        .unwrap()
        .iter()
        .find(|r| r["address"] == ids[3].2.as_str())
        .unwrap();
    assert!(
        pending["acknowledged_at"].is_null(),
        "still to answer: {pending}"
    );
    assert!(
        pending["presented_at"].is_null(),
        "unknown presentation stays unknown"
    );

    // A hook of the implementation conversation acts on THAT window: the
    // same conversation id resolves to the same session, so a heartbeat from
    // the hook updates this window's presence and nobody else's.
    run_hook("heartbeat.sh", &dir, &repo, "", &["busy"]).await;
    let after = call(
        design,
        "list_sessions",
        json!({"project": "market-data", "online_only": true}),
    )
    .await;
    assert_eq!(after["count"], 5, "the hook did not create a sixth session");

    // SessionStart for the design conversation injects its own identity,
    // and only after the bus confirmed it.
    let out = run_hook(
        "session-start.sh",
        &dir,
        &repo,
        &json!({"session_id": "conv-design", "cwd": repo.display().to_string()}).to_string(),
        &[],
    )
    .await;
    let injected: Value = serde_json::from_str(out.trim()).expect("hook emitted JSON");
    let context = injected["hookSpecificOutput"]["additionalContext"]
        .as_str()
        .unwrap_or_default();
    assert!(context.contains("agent 'joaquin'"), "{context}");
    assert!(
        context.contains(&ids[1].1),
        "the design window's own session: {context}"
    );
    assert!(context.contains("role 'design'"), "{context}");
    for (name, session, _) in ids.iter().skip(2) {
        assert!(
            !context.contains(session.as_str()),
            "{name}'s session leaked: {context}"
        );
    }

    // A conversation with no bus configured injects nothing at all.
    let empty_cfg = dir.join("no-profiles");
    std::fs::create_dir_all(&empty_cfg).unwrap();
    let out = run_hook(
        "session-start.sh",
        &empty_cfg,
        &repo,
        &json!({"session_id": "conv-nowhere"}).to_string(),
        &[],
    )
    .await;
    assert!(out.trim().is_empty(), "unconfigured session start: {out}");

    // Ending one window leaves the others alone: no idled presence, no
    // drained inbox, no released claim.
    call(
        implementation,
        "create_task",
        json!({"key": "md#1", "title": "spinner"}),
    )
    .await;
    call(implementation, "claim_task", json!({"key": "md#1"})).await;
    let closing = clients.remove(4);
    let _ = closing.cancel().await;
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
    let implementation = &clients[0];
    let mine = call(implementation, "list_tasks", json!({"mine_only": true})).await;
    assert_eq!(mine["tasks"][0]["status"], "claimed");
    assert_eq!(mine["tasks"][0]["claimed_session"], ids[0].1);
    let still = call(
        implementation,
        "list_sessions",
        json!({"project": "market-data", "role": "implementation", "online_only": true}),
    )
    .await;
    assert_eq!(still["count"], 1, "the surviving window is still online");
    assert_eq!(
        call(implementation, "whoami", json!({})).await["session"],
        ids[0].1
    );

    for c in clients {
        let _ = c.cancel().await;
    }
    let _ = std::fs::remove_dir_all(&dir);
    h.shutdown().await;
}

// ------------------------------------------------- authenticated sessions --

/// A session credential proves which window is calling: it is derived from an
/// agent token, cannot mint anything, dies with its parent, expires on its
/// own, and a resume fences the connection it replaced.
#[tokio::test]
async fn session_credentials_prove_a_window_and_die_with_their_parent() {
    let h = require_db!("t_sessions_auth");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    let other = seed_agent(&h.pool, "acme", "marta").await;

    // Registration takes the agent token and derives everything from it.
    let agent = connect_with_session(&h.base, &token, "conv-a").await;
    let cred = call(
        &agent,
        "register_session",
        json!({"session": "conv-a", "ttl_seconds": 3600}),
    )
    .await;
    let session_token = cred["session_token"].as_str().unwrap().to_owned();
    assert!(session_token.starts_with("acss_"), "{cred}");
    assert_eq!(cred["session"], "conv-a");
    assert_eq!(cred["address"], "joaquin/conv-a");
    assert_eq!(cred["epoch"], 1);
    assert!(cred["expires_in_seconds"].as_i64().unwrap() <= 3600);

    // It authenticates as that agent in that session, and says so.
    let window = connect(&h.base, &session_token).await;
    let me = call(&window, "whoami", json!({})).await;
    assert_eq!(me["agent"], "joaquin");
    assert_eq!(me["team"], "acme");
    assert_eq!(me["session"], "conv-a", "the label is proven, not sent");
    assert_eq!(me["session_identity"]["epoch"], 1);
    assert_eq!(me["session_identity"]["session_id"], cred["session_id"]);
    // A plain agent token has no proven identity.
    assert!(call(&agent, "whoami", json!({})).await["session_identity"].is_null());

    // It cannot mint: not another session, not anything else.
    let err = call_expect_error(&window, "register_session", json!({"session": "conv-b"})).await;
    assert!(err.contains("cannot register another session"), "{err}");

    // A header that disagrees with the proof is refused outright, so a
    // session credential can never be widened into another window.
    let resp = reqwest::Client::new()
        .post(format!("{}/mcp", h.base))
        .header("Authorization", format!("Bearer {session_token}"))
        .header("X-Crew-Session", "someone-elses-window")
        .header("Accept", "application/json, text/event-stream")
        .json(&json!({"jsonrpc":"2.0","id":1,"method":"tools/list"}))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 403);
    let body: Value = resp.json().await.unwrap();
    assert!(
        body["error"]
            .as_str()
            .unwrap()
            .contains("authenticates session 'conv-a'"),
        "{body}"
    );
    // The same header, agreeing, is simply redundant.
    assert_eq!(
        mcp_status_with_session(&h.base, &session_token, "conv-a").await,
        200
    );

    // Renewal extends without disturbing the connection: same secret, same
    // epoch, later expiry.
    let renewed = call(&window, "renew_session", json!({"ttl_seconds": 7200})).await;
    assert!(
        renewed["session_token"].is_null(),
        "renewal returns no secret"
    );
    assert_eq!(renewed["epoch"], 1);
    assert!(renewed["expires_in_seconds"].as_i64().unwrap() > 3600);
    assert_eq!(call(&window, "whoami", json!({})).await["agent"], "joaquin");

    // The agent token cannot take a live window: holding it is not proof of
    // being that conversation.
    let err = call_expect_error(&agent, "register_session", json!({"session": "conv-a"})).await;
    assert!(err.contains("already registered and still live"), "{err}");
    assert!(err.contains("resume_session"), "{err}");
    assert_eq!(
        call(&window, "whoami", json!({})).await["session_identity"]["epoch"],
        1,
        "the refused registration changed nothing"
    );

    // A resume rotates the secret and bumps the epoch; the old credential is
    // dead and the old connection is fenced by its stale epoch. The proof is
    // the session's own credential.
    let resumed = call(&window, "resume_session", json!({})).await;
    assert_eq!(resumed["epoch"], 2);
    let resumed_token = resumed["session_token"].as_str().unwrap().to_owned();
    let window_again = connect(&h.base, &resumed_token).await;
    assert_ne!(resumed_token, session_token);
    assert_eq!(
        mcp_status(&h.base, &session_token).await,
        401,
        "old secret is dead"
    );
    assert_eq!(
        mcp_status_with_epoch(&h.base, &resumed_token, 1).await,
        409,
        "a connection carrying the old epoch is stale"
    );
    assert_eq!(mcp_status_with_epoch(&h.base, &resumed_token, 2).await, 200);
    let _ = window.cancel().await;

    // Fencing is not only a pre-dispatch check. The middleware's check runs
    // before the handler, so a request that passed it and then waited on a
    // row lock would otherwise commit into the session that replaced it. The
    // guard re-checks inside the writing transaction, which is where it has
    // to be: here it is exercised directly, with the epoch moved after the
    // transaction opened.
    use ai_crew_sync::store::sessions;
    let stale_ctx = ai_crew_sync::auth::AuthCtx {
        agent_id: sqlx::query_scalar::<_, Uuid>("SELECT id FROM agents WHERE name = 'joaquin'")
            .fetch_one(&h.pool)
            .await
            .unwrap(),
        agent_name: "joaquin".into(),
        team_id: sqlx::query_scalar::<_, Uuid>("SELECT id FROM teams WHERE slug = 'acme'")
            .fetch_one(&h.pool)
            .await
            .unwrap(),
        team_slug: "acme".into(),
        session: "conv-a".into(),
        session_id: Some(
            resumed["session_id"]
                .as_str()
                .unwrap()
                .parse::<Uuid>()
                .unwrap(),
        ),
        // The epoch this connection was admitted with.
        session_epoch: Some(2),
        token_id: None,
    };
    // Same epoch: the write may proceed.
    let mut tx = h.pool.begin().await.unwrap();
    sessions::guard(&mut tx, &stale_ctx)
        .await
        .expect("current epoch passes");
    tx.rollback().await.unwrap();

    // Now the window is resumed by its owner, and the connection admitted at
    // epoch 2 is refused *inside* the transaction rather than committing.
    let bumped = call(&window_again, "resume_session", json!({})).await;
    assert_eq!(bumped["epoch"], 3);
    // The resume rotated the secret again, so later connections use this one.
    let resumed_token = bumped["session_token"].as_str().unwrap().to_owned();
    let _ = window_again.cancel().await;
    let mut tx = h.pool.begin().await.unwrap();
    let err = sessions::guard(&mut tx, &stale_ctx)
        .await
        .expect_err("a replaced connection must not write");
    let err = err.to_string();
    assert!(err.contains("stale"), "{err}");
    assert!(err.contains("Nothing was written"), "{err}");
    tx.rollback().await.unwrap();

    // And a revoked session is refused the same way, not only at the door.
    sqlx::query("UPDATE agent_sessions SET revoked_at = now() WHERE label = 'conv-a'")
        .execute(&h.pool)
        .await
        .unwrap();
    let mut tx = h.pool.begin().await.unwrap();
    let current = ai_crew_sync::auth::AuthCtx {
        session_epoch: Some(3),
        ..stale_ctx.clone()
    };
    let err = sessions::guard(&mut tx, &current)
        .await
        .expect_err("a revoked session must not write")
        .to_string();
    assert!(err.contains("no longer valid"), "{err}");
    tx.rollback().await.unwrap();
    sqlx::query("UPDATE agent_sessions SET revoked_at = NULL WHERE label = 'conv-a'")
        .execute(&h.pool)
        .await
        .unwrap();

    // Two agents, two sessions of the same label: separate rows, separate
    // addresses, no collision.
    let marta = connect(&h.base, &other).await;
    let hers = call(&marta, "register_session", json!({"session": "conv-a"})).await;
    assert_eq!(hers["address"], "marta/conv-a");
    assert_ne!(hers["session_id"], resumed["session_id"]);

    // Revocation: a window can close another window of its own agent, and
    // never one of somebody else's.
    let live = connect(&h.base, &resumed_token).await;
    call(&agent, "register_session", json!({"session": "conv-c"})).await;
    let gone = call(&live, "revoke_session", json!({"session": "conv-c"})).await;
    assert_eq!(gone["revoked_session"], "conv-c");
    let err = call_expect_error(
        &live,
        "revoke_session",
        json!({"session": "conv-a-of-marta"}),
    )
    .await;
    assert!(err.contains("no session"), "{err}");
    assert_eq!(
        call(&marta, "whoami", json!({})).await["agent"],
        "marta",
        "marta's own session is untouched"
    );

    // The parent's revocation is the session's revocation: no sweep needed.
    let (parent_id,): (Uuid,) = sqlx::query_as(
        "SELECT t.id FROM api_tokens t JOIN agents a ON a.id = t.agent_id WHERE a.name = 'joaquin'",
    )
    .fetch_one(&h.pool)
    .await
    .unwrap();
    ai_crew_sync::store::admin::revoke_token(
        &h.pool,
        ai_crew_sync::store::admin::Actor::Cli,
        None,
        parent_id,
    )
    .await
    .unwrap();
    assert_eq!(
        mcp_status(&h.base, &resumed_token).await,
        401,
        "parent revoked"
    );
    assert_eq!(mcp_status(&h.base, &token).await, 401);
    assert_eq!(
        mcp_status(&h.base, &other).await,
        200,
        "another agent is unaffected"
    );

    // An expired credential says what to do rather than just failing.
    let fresh = call(&marta, "register_session", json!({"session": "conv-old"})).await;
    let fresh_token = fresh["session_token"].as_str().unwrap().to_owned();
    sqlx::query("UPDATE agent_sessions SET expires_at = now() - interval '1 minute' WHERE label = 'conv-old'")
        .execute(&h.pool)
        .await
        .unwrap();
    let resp = reqwest::Client::new()
        .post(format!("{}/mcp", h.base))
        .header("Authorization", format!("Bearer {fresh_token}"))
        .header("Accept", "application/json, text/event-stream")
        .json(&json!({"jsonrpc":"2.0","id":1,"method":"tools/list"}))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 401);
    let body: Value = resp.json().await.unwrap();
    assert!(
        body["error"].as_str().unwrap().contains("register_session"),
        "{body}"
    );

    for c in [agent, live, marta] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// `tools/list` with a bearer and a session header, for status checks.
async fn mcp_status_with_session(base: &str, token: &str, session: &str) -> u16 {
    reqwest::Client::new()
        .post(format!("{base}/mcp"))
        .header("Authorization", format!("Bearer {token}"))
        .header("X-Crew-Session", session)
        .header("Accept", "application/json, text/event-stream")
        .json(&json!({"jsonrpc":"2.0","id":1,"method":"tools/list"}))
        .send()
        .await
        .unwrap()
        .status()
        .as_u16()
}

/// `tools/list` with a bearer and an explicit connection epoch.
async fn mcp_status_with_epoch(base: &str, token: &str, epoch: i64) -> u16 {
    reqwest::Client::new()
        .post(format!("{base}/mcp"))
        .header("Authorization", format!("Bearer {token}"))
        .header("X-Crew-Epoch", epoch.to_string())
        .header("Accept", "application/json, text/event-stream")
        .json(&json!({"jsonrpc":"2.0","id":1,"method":"tools/list"}))
        .send()
        .await
        .unwrap()
        .status()
        .as_u16()
}

// ----------------------------------------------------------- conversations --

/// Turn the capability on for a team, the way an operator does.
async fn enable_conversations(pool: &PgPool, team: &str) {
    sqlx::query("UPDATE teams SET conversations_enabled = true WHERE slug = $1")
        .bind(team)
        .execute(pool)
        .await
        .unwrap();
}

/// A fresh request id for each send; reusing one is how a retry is spotted.
fn request_id() -> String {
    Uuid::new_v4().to_string()
}

/// The property the whole feature exists for: two sessions exchange requests
/// privately, each reader has its own receipt, and the sender can see who
/// acknowledged and who resolved. Plus the boundaries: the capability flag,
/// reading not acknowledging, recipients snapshotted at acceptance, and a
/// non-member seeing nothing.
#[tokio::test]
async fn conversations_carry_private_requests_with_per_recipient_receipts() {
    let h = require_db!("t_conversations");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    let dani_token = seed_agent(&h.pool, "acme", "dani").await;
    let outsider = seed_agent(&h.pool, "other", "eve").await;

    // Off by default: the tools refuse before an operator enables them.
    let impl_w = connect_with_session(&h.base, &token, "impl").await;
    let err = call_expect_error(
        &impl_w,
        "create_conversation",
        json!({"title": "too early", "private": true}),
    )
    .await;
    assert!(err.contains("not enabled for this team"), "{err}");
    enable_conversations(&h.pool, "acme").await;

    // Three windows of two people, plus a reviewer who is never invited.
    let design = connect_with_session(&h.base, &dani_token, "design").await;
    let review = connect_with_session(&h.base, &dani_token, "review").await;
    let bystander = connect_with_session(&h.base, &token, "bystander").await;

    // A private thread addressed to two exact windows.
    let convo = call(
        &impl_w,
        "create_conversation",
        json!({"title": "the empty state", "private": true,
               "invite": ["dani/design", "dani/review"]}),
    )
    .await;
    let cid = convo["id"].as_str().unwrap().to_owned();
    assert_eq!(convo["visibility"], "private");
    assert_eq!(convo["membership"]["role"], "owner");
    assert_eq!(convo["members"].as_array().unwrap().len(), 3);

    // An invitation is not membership: until it is accepted, that window is
    // not a recipient.
    let first = call(
        &impl_w,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "what should the empty state say?",
               "request_id": request_id()}),
    )
    .await;
    assert_eq!(first["stored"], true);
    assert_eq!(first["seq"], 1);
    assert!(
        first["recipients"].as_array().unwrap().is_empty(),
        "nobody has accepted yet: {first}"
    );

    // Both accept; only the invited window can, not a sibling.
    let err = call_expect_error(
        &bystander,
        "join_conversation",
        json!({"conversation_id": cid}),
    )
    .await;
    assert!(err.contains("no invitation for this window"), "{err}");
    call(
        &design,
        "join_conversation",
        json!({"conversation_id": cid}),
    )
    .await;
    call(
        &review,
        "join_conversation",
        json!({"conversation_id": cid}),
    )
    .await;

    let second = call(
        &impl_w,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "second attempt, with a spinner",
               "request_id": request_id()}),
    )
    .await;
    let second_id = second["message_id"].as_str().unwrap().to_owned();
    let mut addressed: Vec<&str> = second["recipients"]
        .as_array()
        .unwrap()
        .iter()
        .map(|r| r.as_str().unwrap())
        .collect();
    addressed.sort();
    assert_eq!(addressed, vec!["dani/design", "dani/review"]);

    // Reading is not acknowledging.
    let read = call(
        &design,
        "read_conversation",
        json!({"conversation_id": cid}),
    )
    .await;
    assert_eq!(read["messages"].as_array().unwrap().len(), 2);
    assert!(
        read["messages"][1]["my_receipt"]["acknowledged_at"].is_null(),
        "a read must not acknowledge: {read}"
    );
    let receipts = call(
        &impl_w,
        "get_message_receipts",
        json!({"message_id": second_id}),
    )
    .await;
    assert_eq!(receipts["total"], 2);
    assert_eq!(receipts["acknowledged"], 0);
    assert!(
        receipts["receipts"][0]["stored_at"].is_string(),
        "stored is a fact about persistence: {receipts}"
    );
    assert!(
        receipts["receipts"][0]["presented_at"].is_null(),
        "presentation is unknown, not 'no'"
    );

    // Independent receipts: one reader acknowledges, the other resolves.
    call(
        &design,
        "ack_message",
        json!({"message_id": second_id, "note": "looks right"}),
    )
    .await;
    call(
        &review,
        "ack_message",
        json!({"message_id": second_id, "resolved": true, "note": "shipped in 4d21f"}),
    )
    .await;
    let receipts = call(
        &impl_w,
        "get_message_receipts",
        json!({"message_id": second_id}),
    )
    .await;
    assert_eq!(receipts["acknowledged"], 2);
    assert_eq!(
        receipts["resolved"], 1,
        "only one said it acted: {receipts}"
    );
    let design_receipt = receipts["receipts"]
        .as_array()
        .unwrap()
        .iter()
        .find(|r| r["address"] == "dani/design")
        .unwrap();
    assert!(design_receipt["resolved_at"].is_null());
    assert_eq!(design_receipt["note"], "looks right");

    // A sender does not acknowledge its own message, and a window that was
    // not addressed has nothing to acknowledge.
    let err = call_expect_error(&impl_w, "ack_message", json!({"message_id": second_id})).await;
    assert!(err.contains("not addressed to your window"), "{err}");

    // Idempotency: the same request id returns the original message.
    let rid = request_id();
    let once = call(
        &impl_w,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "retry me", "request_id": rid}),
    )
    .await;
    let twice = call(
        &impl_w,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "retry me", "request_id": rid}),
    )
    .await;
    assert_eq!(once["message_id"], twice["message_id"]);
    assert_eq!(once["seq"], twice["seq"]);
    let err = call_expect_error(
        &impl_w,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "something else", "request_id": rid}),
    )
    .await;
    assert!(err.contains("already sent a different message"), "{err}");

    // A late joiner never enters an older message's denominator.
    call(
        &impl_w,
        "invite_to_conversation",
        json!({"conversation_id": cid, "address": "joaquin/bystander"}),
    )
    .await;
    call(
        &bystander,
        "join_conversation",
        json!({"conversation_id": cid}),
    )
    .await;
    let receipts = call(
        &impl_w,
        "get_message_receipts",
        json!({"message_id": second_id}),
    )
    .await;
    assert_eq!(
        receipts["total"], 2,
        "the denominator is frozen: {receipts}"
    );
    // And sees only what was said after they joined.
    let theirs = call(
        &bystander,
        "read_conversation",
        json!({"conversation_id": cid}),
    )
    .await;
    assert!(
        theirs["messages"]
            .as_array()
            .unwrap()
            .iter()
            .all(|m| m["body"] != "what should the empty state say?"),
        "a late member must not read earlier history: {theirs}"
    );

    // A removal keeps history and receipts, and stops access at once.
    call(
        &impl_w,
        "remove_conversation_member",
        json!({"conversation_id": cid, "address": "dani/design"}),
    )
    .await;
    let err = call_expect_error(
        &design,
        "read_conversation",
        json!({"conversation_id": cid}),
    )
    .await;
    assert!(err.contains("no such conversation"), "{err}");
    let receipts = call(
        &impl_w,
        "get_message_receipts",
        json!({"message_id": second_id}),
    )
    .await;
    assert_eq!(
        receipts["acknowledged"], 2,
        "a removal is not a rewrite: {receipts}"
    );

    // Another team sees nothing, by id or otherwise.
    let eve = connect(&h.base, &outsider).await;
    enable_conversations(&h.pool, "other").await;
    let err = call_expect_error(&eve, "read_conversation", json!({"conversation_id": cid})).await;
    assert!(err.contains("no such conversation"), "{err}");
    let theirs = call(&eve, "list_conversations", json!({})).await;
    assert!(theirs["conversations"].as_array().unwrap().is_empty());

    for c in [impl_w, design, review, bystander, eve] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// The two exceptional paths, and the project boundary. A transfer needs the
/// target to accept and supersedes rather than rewrites; recovery is
/// read-only, needs every window of the agent to be gone, and never invents
/// a receipt. Project access is a grant, not a directory.
#[tokio::test]
async fn transfer_needs_acceptance_and_recovery_is_read_only() {
    let h = require_db!("t_conversations_transfer");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    let dani_token = seed_agent(&h.pool, "acme", "dani").await;
    enable_conversations(&h.pool, "acme").await;

    // A project thread: access is a grant, and a teammate without one sees
    // nothing even though the thread is not private.
    let owner = connect_with_session(&h.base, &token, "market-data").await;
    call(&owner, "create_project", json!({"project": "market-data"})).await;
    let convo = call(
        &owner,
        "create_conversation",
        json!({"title": "feed rewrite", "project": "market-data"}),
    )
    .await;
    let cid = convo["id"].as_str().unwrap().to_owned();
    let first = call(
        &owner,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "starting on the feed", "request_id": request_id()}),
    )
    .await;
    let first_id = first["message_id"].as_str().unwrap().to_owned();

    let dani = connect_with_session(&h.base, &dani_token, "core").await;
    let err = call_expect_error(&dani, "read_conversation", json!({"conversation_id": cid})).await;
    assert!(
        err.contains("no such conversation"),
        "a project grant is required: {err}"
    );
    call(
        &owner,
        "grant_project_access",
        json!({"project": "market-data", "agent": "dani"}),
    )
    .await;
    let seen = call(&dani, "read_conversation", json!({"conversation_id": cid})).await;
    assert_eq!(seen["messages"].as_array().unwrap().len(), 1, "{seen}");
    // Project visibility is reading, not membership: there is nothing for a
    // project reader to acknowledge.
    let err = call_expect_error(&dani, "ack_message", json!({"message_id": first_id})).await;
    assert!(err.contains("active member"), "{err}");
    // And revoking takes effect at once.
    call(
        &owner,
        "grant_project_access",
        json!({"project": "market-data", "agent": "dani", "grant": false}),
    )
    .await;
    let err = call_expect_error(&dani, "read_conversation", json!({"conversation_id": cid})).await;
    assert!(err.contains("no such conversation"), "{err}");

    // Transfer: the owner moves its seat to another window of its own agent.
    let successor = connect_with_session(&h.base, &token, "market-data-2").await;
    let err = call_expect_error(
        &owner,
        "transfer_membership",
        json!({"conversation_id": cid, "to": "dani/core"}),
    )
    .await;
    assert!(
        err.contains("same agent"),
        "a transfer is not an invitation: {err}"
    );

    let proposal = call(
        &owner,
        "transfer_membership",
        json!({"conversation_id": cid, "to": "joaquin/market-data-2"}),
    )
    .await;
    assert_eq!(proposal["state"], "proposed");
    // Nothing has moved yet: the original seat is still active and the
    // successor is only invited.
    let before = call(&owner, "list_conversations", json!({})).await;
    let entry = before["conversations"]
        .as_array()
        .unwrap()
        .iter()
        .find(|c| c["id"] == cid.as_str())
        .unwrap();
    assert_eq!(entry["membership"]["state"], "active");
    assert_eq!(
        entry["members"]
            .as_array()
            .unwrap()
            .iter()
            .find(|m| m["address"] == "joaquin/market-data-2")
            .unwrap()["state"],
        "invited"
    );

    call(
        &successor,
        "join_conversation",
        json!({"conversation_id": cid}),
    )
    .await;
    let after = call(&successor, "list_conversations", json!({})).await;
    let mine = after["conversations"]
        .as_array()
        .unwrap()
        .iter()
        .find(|c| c["id"] == cid.as_str())
        .expect("the successor holds the seat");
    assert_eq!(
        mine["membership"]["role"], "owner",
        "the role travelled: {mine}"
    );
    assert_eq!(mine["membership"]["state"], "active");
    let superseded = mine["members"]
        .as_array()
        .unwrap()
        .iter()
        .find(|m| m["address"] == "joaquin/market-data")
        .unwrap();
    assert_eq!(
        superseded["state"], "left",
        "the old seat is superseded: {superseded}"
    );
    // Authorship is untouched: the first message is still from the old window.
    let msg = call(
        &successor,
        "get_conversation_message",
        json!({"message_id": first_id}),
    )
    .await;
    assert_eq!(msg["from_address"], "joaquin/market-data");

    // Recovery: refused while a window is live, refused with a session
    // credential, and read-only when every window is gone.
    let cred = call(
        &owner,
        "register_session",
        json!({"session": "market-data"}),
    )
    .await;
    let window = connect(&h.base, cred["session_token"].as_str().unwrap()).await;
    let err = call_expect_error(
        &window,
        "recover_conversation_history",
        json!({"conversation_id": cid}),
    )
    .await;
    assert!(err.contains("agent token"), "{err}");
    let err = call_expect_error(
        &owner,
        "recover_conversation_history",
        json!({"conversation_id": cid}),
    )
    .await;
    assert!(err.contains("still live"), "offline is not enough: {err}");

    call(&window, "revoke_session", json!({})).await;
    let recovered = call(
        &owner,
        "recover_conversation_history",
        json!({"conversation_id": cid}),
    )
    .await;
    assert!(!recovered["messages"].as_array().unwrap().is_empty());
    assert!(
        recovered["messages"][0]["my_receipt"].is_null(),
        "recovery observes nothing: {recovered}"
    );
    // It is audited, and it granted nothing.
    let (recoveries,): (i64,) =
        sqlx::query_as("SELECT count(*) FROM conversation_audit WHERE action = 'member.recover'")
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert_eq!(recoveries, 1);

    for c in [owner, dani, successor] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// Three holes the owner reproduced against a real server, and the shape of
/// their fixes: a window's seat needs that window's credential, a private
/// thread is not a project thread, and a receipt is not a way around the
/// history boundary.
#[tokio::test]
async fn a_private_thread_answers_only_to_the_windows_that_are_in_it() {
    let h = require_db!("t_conversation_boundaries");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    let dani_token = seed_agent(&h.pool, "acme", "dani").await;
    let marta_token = seed_agent(&h.pool, "acme", "marta").await;
    enable_conversations(&h.pool, "acme").await;

    // A registered window: the credential, not the label, is what proves it.
    let agent = connect(&h.base, &dani_token).await;
    let cred = call(&agent, "register_session", json!({"session": "review"})).await;
    let window = connect(&h.base, cred["session_token"].as_str().unwrap()).await;
    let owner = connect_with_session(&h.base, &token, "impl").await;

    let convo = call(
        &owner,
        "create_conversation",
        json!({"title": "who is in the room", "private": true, "invite": ["dani/review"]}),
    )
    .await;
    let cid = convo["id"].as_str().unwrap().to_owned();

    // The parent agent token cannot take its own window's seat, even wearing
    // the right label. It is told what to do instead.
    let impostor = connect_with_session(&h.base, &dani_token, "review").await;
    let err = call_expect_error(
        &impostor,
        "join_conversation",
        json!({"conversation_id": cid}),
    )
    .await;
    assert!(err.contains("registered window"), "{err}");
    assert!(err.contains("recover_conversation_history"), "{err}");

    // An invitation is not membership, and it does not read what was said
    // before it was answered.
    let waiting = call(&window, "list_conversations", json!({})).await;
    assert!(
        waiting["conversations"]
            .as_array()
            .unwrap()
            .iter()
            .any(|c| c["id"] == cid.as_str()),
        "an invitee can see that it was invited: {waiting}"
    );
    let err = call_expect_error(
        &window,
        "read_conversation",
        json!({"conversation_id": cid}),
    )
    .await;
    assert!(err.contains("join_conversation first"), "{err}");

    call(
        &window,
        "join_conversation",
        json!({"conversation_id": cid}),
    )
    .await;
    let sent = call(
        &owner,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "the private body", "request_id": request_id()}),
    )
    .await;

    // Now the seat is held by a window. The same agent token with the same
    // label is a different caller and sees nothing.
    let err = call_expect_error(
        &impostor,
        "read_conversation",
        json!({"conversation_id": cid}),
    )
    .await;
    assert!(err.contains("no such conversation"), "{err}");
    let err = call_expect_error(
        &impostor,
        "get_conversation_message",
        json!({"message_id": sent["message_id"]}),
    )
    .await;
    assert!(err.contains("no such conversation"), "{err}");
    // The window itself still reads it.
    let read = call(
        &window,
        "read_conversation",
        json!({"conversation_id": cid}),
    )
    .await;
    assert_eq!(read["messages"][0]["body"], "the private body");

    // Inviting an already active member again does not unbind the seat.
    // The state is preserved, so the binding must be too, or a repeated
    // invitation would quietly hand the label back to the parent token.
    call(
        &owner,
        "invite_to_conversation",
        json!({"conversation_id": cid, "address": "dani/review"}),
    )
    .await;
    let err = call_expect_error(
        &impostor,
        "read_conversation",
        json!({"conversation_id": cid}),
    )
    .await;
    assert!(
        err.contains("no such conversation"),
        "a repeated invitation must not downgrade a protected seat: {err}"
    );
    let read = call(
        &window,
        "read_conversation",
        json!({"conversation_id": cid}),
    )
    .await;
    assert_eq!(
        read["messages"][0]["body"], "the private body",
        "and the window still reads it"
    );

    // Private and project are exclusive, and asking for both is refused
    // rather than quietly resolved one way.
    call(&owner, "create_project", json!({"project": "market-data"})).await;
    let err = call_expect_error(
        &owner,
        "create_conversation",
        json!({"title": "both", "private": true, "project": "market-data"}),
    )
    .await;
    assert!(
        err.contains("either private or visible to a project"),
        "{err}"
    );

    // And a project grant does not reach into a private thread that merely
    // names the project.
    call(
        &owner,
        "grant_project_access",
        json!({"project": "market-data", "agent": "marta"}),
    )
    .await;
    let marta = connect_with_session(&h.base, &marta_token, "review").await;
    sqlx::query(
        "UPDATE conversations SET project_id = (SELECT id FROM projects WHERE name = 'market-data')
          WHERE id = $1",
    )
    .bind(cid.parse::<Uuid>().unwrap())
    .execute(&h.pool)
    .await
    .unwrap();
    let err = call_expect_error(&marta, "read_conversation", json!({"conversation_id": cid})).await;
    assert!(
        err.contains("no such conversation"),
        "a private thread stays private however it is labelled: {err}"
    );

    // A late member is refused the earlier message — and its receipts, which
    // carry recipient addresses and a free-text note that is often the
    // discussion itself.
    call(
        &window,
        "ack_message",
        json!({"message_id": sent["message_id"], "resolved": true,
               "note": "the note is part of the conversation"}),
    )
    .await;
    call(
        &owner,
        "invite_to_conversation",
        json!({"conversation_id": cid, "address": "marta/review"}),
    )
    .await;
    call(&marta, "join_conversation", json!({"conversation_id": cid})).await;
    let err = call_expect_error(
        &marta,
        "get_conversation_message",
        json!({"message_id": sent["message_id"]}),
    )
    .await;
    assert!(
        err.contains("before the point your membership starts"),
        "{err}"
    );
    let err = call_expect_error(
        &marta,
        "get_message_receipts",
        json!({"message_id": sent["message_id"]}),
    )
    .await;
    assert!(
        err.contains("not yours to read either"),
        "the receipts of a message you may not read are not a way around it: {err}"
    );
    // The sender still reads them, of course.
    let receipts = call(
        &owner,
        "get_message_receipts",
        json!({"message_id": sent["message_id"]}),
    )
    .await;
    assert_eq!(receipts["acknowledged"], 1);

    // Revoking the window does not hand its label back. Revocation is a way
    // out, not a way in: the parent token is still refused afterwards, and
    // the audited recovery path is what an agent has instead.
    call(&window, "revoke_session", json!({})).await;
    let err = call_expect_error(
        &impostor,
        "read_conversation",
        json!({"conversation_id": cid}),
    )
    .await;
    assert!(err.contains("no such conversation"), "{err}");
    let err = call_expect_error(
        &impostor,
        "join_conversation",
        json!({"conversation_id": cid}),
    )
    .await;
    assert!(err.contains("registered window"), "{err}");
    assert!(err.contains("does not hand the label back"), "{err}");

    for c in [owner, window, agent, impostor, marta] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

// -------------------------------------------------- backend and the outbox --

/// The failure shape every external store introduces, exercised with
/// Postgres as the only backend: acceptance and persistence are two events,
/// the second can fail, time out, or succeed without the caller hearing.
/// Leases, fencing, bounded retries, idempotency and reconciliation, with no
/// broker installed.
#[tokio::test]
async fn the_outbox_survives_failures_between_acceptance_and_confirmation() {
    use ai_crew_sync::store::backend::{Faults, MessagingBackend, PostgresBackend, Published};
    use ai_crew_sync::store::outbox::{self, Settled};

    let h = require_db!("t_backend_outbox");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    let dani_token = seed_agent(&h.pool, "acme", "dani").await;
    enable_conversations(&h.pool, "acme").await;
    let owner = connect_with_session(&h.base, &token, "impl").await;
    let dani = connect_with_session(&h.base, &dani_token, "review").await;

    let convo = call(
        &owner,
        "create_conversation",
        json!({"title": "async thread", "private": true, "invite": ["dani/review"]}),
    )
    .await;
    let cid = convo["id"].as_str().unwrap().to_owned();
    call(&dani, "join_conversation", json!({"conversation_id": cid})).await;

    // Opt this conversation into asynchronous publication. The default is
    // synchronous and untouched.
    let cuuid: Uuid = cid.parse().unwrap();
    outbox::set_publication(&h.pool, cuuid, true).await.unwrap();

    // Acceptance is not storage, and the caller is told so.
    let rid = request_id();
    let sent = call(
        &owner,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "published later", "request_id": rid}),
    )
    .await;
    assert_eq!(sent["stored"], false, "accepted, not yet stored: {sent}");
    let mid: Uuid = sent["message_id"].as_str().unwrap().parse().unwrap();
    let receipts = call(
        &owner,
        "get_message_receipts",
        json!({"message_id": sent["message_id"]}),
    )
    .await;
    assert!(
        receipts["receipts"][0]["stored_at"].is_null(),
        "stored is not claimed before the backend confirmed: {receipts}"
    );
    let status = outbox::status(&h.pool, team_id(&h.pool, "acme").await)
        .await
        .unwrap();
    assert_eq!(status.pending, 1);
    assert!(status.pending_bytes > 0);

    // A retryable failure backs off and keeps the slot.
    let flaky = PostgresBackend::with_faults(
        h.pool.clone(),
        Faults {
            retryable: 1,
            ..Default::default()
        },
    );
    let outcome = outbox::run_once(&h.pool, &flaky, "worker-a").await.unwrap();
    assert!(
        matches!(outcome, Some(Settled::Retrying { .. })),
        "{outcome:?}"
    );
    let (state,): (String,) =
        sqlx::query_as("SELECT publication_state FROM conversation_messages WHERE id = $1")
            .bind(mid)
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert_eq!(
        state, "pending_publication",
        "a retry does not fabricate stored"
    );

    // A client retry of the same request_id gets the original's real
    // state, not a storage confirmation the first call never got.
    let again = call(
        &owner,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "published later", "request_id": rid}),
    )
    .await;
    assert_eq!(again["message_id"], sent["message_id"]);
    assert_eq!(
        again["stored"], false,
        "the retry reports what the message is, not what a synchronous send would be"
    );

    // And a reader is told what it is looking at. The message keeps its
    // place in the sequence and says it is not stored yet, which is what a
    // cursor needs to not walk over a gap it never knew about.
    let page = call(&dani, "read_conversation", json!({"conversation_id": cid})).await;
    let pending = page["messages"]
        .as_array()
        .unwrap()
        .iter()
        .find(|m| m["message_id"] == sent["message_id"])
        .expect("the message is in the thread, not hidden from it");
    assert_eq!(pending["publication"], "pending_publication");
    let one = call(
        &dani,
        "get_conversation_message",
        json!({"message_id": sent["message_id"]}),
    )
    .await;
    assert_eq!(
        one["publication"], "pending_publication",
        "never reported as stored before the backend says so: {one}"
    );

    // Fencing: a worker whose lease expired settles nothing. Take a lease,
    // let another worker take it over, then try to settle the stale one.
    sqlx::query("UPDATE conversation_outbox SET next_attempt_at = now()")
        .execute(&h.pool)
        .await
        .unwrap();
    let stale = outbox::lease(&h.pool, "worker-stale")
        .await
        .unwrap()
        .unwrap();
    sqlx::query("UPDATE conversation_outbox SET lease_expires_at = now() - interval '1 minute'")
        .execute(&h.pool)
        .await
        .unwrap();
    let fresh = outbox::lease(&h.pool, "worker-b").await.unwrap().unwrap();
    assert!(fresh.generation > stale.generation);
    let fenced = outbox::settle(
        &h.pool,
        &stale,
        Published::Confirmed(ai_crew_sync::store::backend::Locator(mid.to_string())),
    )
    .await
    .unwrap();
    assert_eq!(fenced, Settled::Fenced, "a stale worker must write nothing");
    let (state,): (String,) =
        sqlx::query_as("SELECT publication_state FROM conversation_messages WHERE id = $1")
            .bind(mid)
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert_eq!(state, "pending_publication");

    // Uncertain completion: the body was written and the confirmation lost.
    // Reconciliation asks the backend what it actually holds and settles.
    let losing = PostgresBackend::with_faults(
        h.pool.clone(),
        Faults {
            lose_confirmation: true,
            ..Default::default()
        },
    );
    let outcome = losing
        .publish(ai_crew_sync::store::backend::Envelope {
            message_id: fresh.message_id,
            conversation_id: fresh.conversation_id,
            team_id: fresh.team_id,
            body: fresh.payload.clone(),
            publish_key: fresh.publish_key,
        })
        .await;
    assert!(matches!(outcome, Published::Retryable(_)));
    let plain = PostgresBackend::new(h.pool.clone());
    let settled = outbox::reconcile(&h.pool, &plain, &fresh).await.unwrap();
    assert_eq!(
        settled,
        Settled::Stored,
        "the write did land; reconcile found it"
    );

    // Now it is stored, once, and the receipts say when.
    let (state, locator): (String, Option<String>) = sqlx::query_as(
        "SELECT publication_state, canonical_locator FROM conversation_messages WHERE id = $1",
    )
    .bind(mid)
    .fetch_one(&h.pool)
    .await
    .unwrap();
    assert_eq!(state, "stored");
    assert_eq!(locator.as_deref(), Some(mid.to_string().as_str()));
    let receipts = call(
        &owner,
        "get_message_receipts",
        json!({"message_id": sent["message_id"]}),
    )
    .await;
    assert!(
        receipts["receipts"][0]["stored_at"].is_string(),
        "{receipts}"
    );
    assert!(
        outbox::lease(&h.pool, "worker-c").await.unwrap().is_none(),
        "the slot is gone"
    );

    // Idempotency holds across the async path too: the same request id
    // returns the original message rather than queueing a second.
    let rid = request_id();
    let a = call(
        &owner,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "twice", "request_id": rid}),
    )
    .await;
    let b = call(
        &owner,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "twice", "request_id": rid}),
    )
    .await;
    assert_eq!(a["message_id"], b["message_id"]);
    assert_eq!(a["seq"], b["seq"]);
    let (slots,): (i64,) = sqlx::query_as("SELECT count(*) FROM conversation_outbox")
        .fetch_one(&h.pool)
        .await
        .unwrap();
    assert_eq!(slots, 1, "one logical message, one slot");

    // A fatal failure is explicit and keeps the slot visible, rather than
    // retrying for ever or pretending it stored.
    let doomed = PostgresBackend::with_faults(
        h.pool.clone(),
        Faults {
            fatal: true,
            ..Default::default()
        },
    );
    sqlx::query("UPDATE conversation_outbox SET next_attempt_at = now()")
        .execute(&h.pool)
        .await
        .unwrap();
    let outcome = outbox::run_once(&h.pool, &doomed, "worker-d")
        .await
        .unwrap();
    assert_eq!(outcome, Some(Settled::Failed));
    let team = team_id(&h.pool, "acme").await;
    let status = outbox::status(&h.pool, team).await.unwrap();
    assert_eq!(status.failed, 1);
    assert_eq!(status.pending, 0);
    let mid2: Uuid = a["message_id"].as_str().unwrap().parse().unwrap();
    let (state,): (String,) =
        sqlx::query_as("SELECT publication_state FROM conversation_messages WHERE id = $1")
            .bind(mid2)
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert_eq!(state, "failed", "an explicit failed slot, not a silent gap");

    // Returning to synchronous mode is refused while work is *outstanding*,
    // because a thread would keep a gap nobody drains. A failed slot is
    // settled — explicit, visible, not coming back — so it does not block.
    let pending = call(
        &owner,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "still queued", "request_id": request_id()}),
    )
    .await;
    assert_eq!(pending["stored"], false);
    let err = outbox::set_publication(&h.pool, cuuid, false)
        .await
        .unwrap_err()
        .to_string();
    assert!(err.contains("still awaiting publication"), "{err}");
    sqlx::query("UPDATE conversation_outbox SET next_attempt_at = now() WHERE state = 'pending'")
        .execute(&h.pool)
        .await
        .unwrap();
    assert_eq!(
        outbox::run_once(&h.pool, &plain, "worker-e").await.unwrap(),
        Some(Settled::Stored)
    );
    // The failed slot is still there and still does not block the switch.
    assert_eq!(outbox::status(&h.pool, team).await.unwrap().failed, 1);
    outbox::set_publication(&h.pool, cuuid, false)
        .await
        .unwrap();
    let sync_sent = call(
        &owner,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "back to sync", "request_id": request_id()}),
    )
    .await;
    assert_eq!(sync_sent["stored"], true, "the default path is unchanged");

    for c in [owner, dani] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// A message on an asynchronously published thread whose first publication
/// ended without an answer: its slot is back to pending and the message is
/// marked uncertain, as `mark_uncertain` leaves it.
async fn an_uncertain_publication(h: &Harness, team: &str) -> (Client, Uuid) {
    use ai_crew_sync::store::outbox;

    let token = seed_agent(&h.pool, team, "joaquin").await;
    enable_conversations(&h.pool, team).await;
    let owner = connect_with_session(&h.base, &token, "impl").await;
    let convo = call(
        &owner,
        "create_conversation",
        json!({"title": "async thread", "private": true}),
    )
    .await;
    let cuuid: Uuid = convo["id"].as_str().unwrap().parse().unwrap();
    outbox::set_publication(&h.pool, cuuid, true).await.unwrap();
    let sent = call(
        &owner,
        "send_conversation_message",
        json!({"conversation_id": convo["id"], "body": "published later",
               "request_id": request_id()}),
    )
    .await;
    let mid: Uuid = sent["message_id"].as_str().unwrap().parse().unwrap();
    let lease = outbox::lease(&h.pool, "worker-dead")
        .await
        .unwrap()
        .unwrap();
    assert_eq!(lease.message_id, mid);
    outbox::mark_uncertain(&h.pool, &lease, "the process died")
        .await
        .unwrap();
    (owner, mid)
}

/// A publication that settled `failed` stays failed. The reconciler used to
/// pick every slot whose message was marked uncertain, and a message that
/// became uncertain and then failed keeps the mark: each pass re-leased the
/// terminal slot, and once that lease ran out the ordinary worker published
/// it again (#181).
#[tokio::test]
async fn the_reconciler_leaves_a_failed_publication_failed() {
    use ai_crew_sync::store::backend::{Faults, PostgresBackend};
    use ai_crew_sync::store::outbox::{self, Settled};

    let h = require_db!("t_reconcile_failed");
    let (owner, mid) = an_uncertain_publication(&h, "acme").await;
    let team = team_id(&h.pool, "acme").await;

    // The retry is refused for good: the slot and the message are failed.
    sqlx::query("UPDATE conversation_outbox SET next_attempt_at = now()")
        .execute(&h.pool)
        .await
        .unwrap();
    let doomed = PostgresBackend::with_faults(
        h.pool.clone(),
        Faults {
            fatal: true,
            ..Default::default()
        },
    );
    assert_eq!(
        outbox::run_once(&h.pool, &doomed, "worker-b")
            .await
            .unwrap(),
        Some(Settled::Failed)
    );

    // A reconcile pass leaves it exactly as it is.
    let plain = PostgresBackend::new(h.pool.clone());
    assert_eq!(
        outbox::resolve_uncertain(&h.pool, &plain, team)
            .await
            .unwrap(),
        0
    );
    let (state, holder): (String, Option<String>) =
        sqlx::query_as("SELECT state, leased_by FROM conversation_outbox WHERE message_id = $1")
            .bind(mid)
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert_eq!(state, "failed", "a settled failure was taken again");
    assert!(holder.is_none(), "held by {holder:?}");

    // And no worker is ever handed it, whatever lease it might carry.
    sqlx::query(
        "UPDATE conversation_outbox SET lease_expires_at = now() - interval '1 second'
          WHERE lease_expires_at IS NOT NULL",
    )
    .execute(&h.pool)
    .await
    .unwrap();
    assert!(
        outbox::lease(&h.pool, "worker-c").await.unwrap().is_none(),
        "a failed publication was handed out to be published again"
    );
    let (published,): (String,) =
        sqlx::query_as("SELECT publication_state FROM conversation_messages WHERE id = $1")
            .bind(mid)
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert_eq!(published, "failed");

    let _ = owner.cancel().await;
    h.shutdown().await;
}

/// A slot the reconciler takes and the backend does not hold goes straight
/// back to pending, for the ordinary retry to take at once. It used to stay
/// leased under the reconciler's name for a whole lease, with the comment
/// saying it "stays pending" (#181).
#[tokio::test]
async fn the_reconciler_puts_back_a_slot_the_backend_does_not_hold() {
    use ai_crew_sync::store::backend::{Faults, PostgresBackend};
    use ai_crew_sync::store::outbox;

    let h = require_db!("t_reconcile_unlease");
    let (owner, mid) = an_uncertain_publication(&h, "acme").await;
    let team = team_id(&h.pool, "acme").await;
    let (attempts_before,): (i32,) =
        sqlx::query_as("SELECT attempts FROM conversation_outbox WHERE message_id = $1")
            .bind(mid)
            .fetch_one(&h.pool)
            .await
            .unwrap();

    // A backend that cannot be asked at all: the pass fails, and the slot
    // it took is put back before the error is returned.
    let unreachable = PostgresBackend::with_faults(
        h.pool.clone(),
        Faults {
            fail_reconcile: true,
            ..Default::default()
        },
    );
    assert!(
        outbox::resolve_uncertain(&h.pool, &unreachable, team)
            .await
            .is_err()
    );
    let (state, holder): (String, Option<String>) =
        sqlx::query_as("SELECT state, leased_by FROM conversation_outbox WHERE message_id = $1")
            .bind(mid)
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert_eq!(state, "pending", "left held by {holder:?} after an error");

    let plain = PostgresBackend::new(h.pool.clone());
    assert_eq!(
        outbox::resolve_uncertain(&h.pool, &plain, team)
            .await
            .unwrap(),
        0,
        "the backend holds nothing for it"
    );
    let (state, holder, expires, attempts): (
        String,
        Option<String>,
        Option<chrono::DateTime<chrono::Utc>>,
        i32,
    ) = sqlx::query_as(
        "SELECT state, leased_by, lease_expires_at, attempts
           FROM conversation_outbox WHERE message_id = $1",
    )
    .bind(mid)
    .fetch_one(&h.pool)
    .await
    .unwrap();
    assert_eq!(state, "pending", "left held by {holder:?}");
    assert!(
        holder.is_none() && expires.is_none(),
        "{holder:?} {expires:?}"
    );
    assert_eq!(attempts, attempts_before, "reconciling is not an attempt");
    let (uncertain,): (bool,) =
        sqlx::query_as("SELECT uncertain_at IS NOT NULL FROM conversation_messages WHERE id = $1")
            .bind(mid)
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert!(uncertain, "still unknown until a publish answers");

    // Only the backoff `mark_uncertain` set stands between it and a worker.
    sqlx::query("UPDATE conversation_outbox SET next_attempt_at = now()")
        .execute(&h.pool)
        .await
        .unwrap();
    let retried = outbox::lease(&h.pool, "worker-b").await.unwrap();
    assert_eq!(retried.map(|l| l.message_id), Some(mid));

    let _ = owner.cancel().await;
    h.shutdown().await;
}

/// A reconcile that fails reports its own error, even when the slot it
/// took cannot be put back either: that slot comes back on its own when its
/// lease runs out, and the operator reads why the pass failed (#183 review).
#[tokio::test]
async fn a_reconcile_error_is_not_hidden_by_the_put_back() {
    use ai_crew_sync::store::backend::{Faults, PostgresBackend};
    use ai_crew_sync::store::outbox;

    let h = require_db!("t_reconcile_error_kept");
    let (owner, _mid) = an_uncertain_publication(&h, "acme").await;
    let team = team_id(&h.pool, "acme").await;

    // Putting the slot back fails too.
    sqlx::query(
        "CREATE FUNCTION refuse_unlease() RETURNS trigger LANGUAGE plpgsql AS \
         $$ BEGIN RAISE EXCEPTION 'injected failure'; END $$",
    )
    .execute(&h.pool)
    .await
    .unwrap();
    sqlx::query(
        "CREATE TRIGGER refuse_unlease BEFORE UPDATE ON conversation_outbox
         FOR EACH ROW WHEN (OLD.leased_by = 'reconciler' AND NEW.leased_by IS NULL)
         EXECUTE FUNCTION refuse_unlease()",
    )
    .execute(&h.pool)
    .await
    .unwrap();
    let unreachable = PostgresBackend::with_faults(
        h.pool.clone(),
        Faults {
            fail_reconcile: true,
            ..Default::default()
        },
    );
    let err = outbox::resolve_uncertain(&h.pool, &unreachable, team)
        .await
        .unwrap_err()
        .to_string();
    assert!(
        err.contains("could not be asked"),
        "the reconcile error was replaced: {err}"
    );

    let _ = owner.cancel().await;
    h.shutdown().await;
}

/// A send's acknowledgement agrees with the message record and the receipts,
/// on every path. On an outbox thread a fresh send is accepted before the
/// backend confirms it: the reply says `stored: false` with
/// `publication: "pending_publication"`, which is what a read says too, and a
/// retry with the same `request_id` reports the state the message is in now,
/// stored or failed, never the snapshot the first call got (#185).
#[tokio::test]
async fn a_send_acknowledgement_agrees_with_the_record_and_the_receipts() {
    use ai_crew_sync::store::backend::{Faults, PostgresBackend};
    use ai_crew_sync::store::outbox::{self, Settled};

    let h = require_db!("t_send_ack");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    let dani_token = seed_agent(&h.pool, "acme", "dani").await;
    enable_conversations(&h.pool, "acme").await;
    let owner = connect_with_session(&h.base, &token, "impl").await;
    let dani = connect_with_session(&h.base, &dani_token, "review").await;
    let convo = call(
        &owner,
        "create_conversation",
        json!({"title": "acks", "private": true, "invite": ["dani/review"]}),
    )
    .await;
    let cid = convo["id"].as_str().unwrap().to_owned();
    call(&dani, "join_conversation", json!({"conversation_id": cid})).await;

    // What a read and the receipts say about one message.
    let observed = |mid: String| {
        let owner = &owner;
        async move {
            let msg = call(
                owner,
                "get_conversation_message",
                json!({"message_id": mid}),
            )
            .await;
            let m = msg.get("message").cloned().unwrap_or(msg);
            let receipts = call(owner, "get_message_receipts", json!({"message_id": mid})).await;
            (
                m["publication"].as_str().unwrap_or_default().to_owned(),
                receipts["receipts"][0]["stored_at"].is_string(),
            )
        }
    };
    let send = |rid: String, body: &'static str| {
        let owner = &owner;
        let cid = cid.clone();
        async move {
            call(
                owner,
                "send_conversation_message",
                json!({"conversation_id": cid, "body": body, "request_id": rid}),
            )
            .await
        }
    };

    // Synchronous: the send's commit is the persistence.
    let sync = send(request_id(), "sync").await;
    assert_eq!(sync["stored"], true, "{sync}");
    assert_eq!(sync["publication"], "stored", "{sync}");
    let (publication, stored_at) = observed(sync["message_id"].as_str().unwrap().into()).await;
    assert_eq!((publication.as_str(), stored_at), ("stored", true));

    // Through the outbox: accepted, not yet confirmed, and every surface
    // says the same.
    let cuuid: Uuid = cid.parse().unwrap();
    outbox::set_publication(&h.pool, cuuid, true).await.unwrap();
    let rid = request_id();
    let fresh = send(rid.clone(), "published later").await;
    assert_eq!(fresh["stored"], false, "{fresh}");
    assert_eq!(fresh["publication"], "pending_publication", "{fresh}");
    let mid = fresh["message_id"].as_str().unwrap().to_owned();
    let (publication, stored_at) = observed(mid.clone()).await;
    assert_eq!(
        (publication.as_str(), stored_at),
        ("pending_publication", false)
    );
    let again = send(rid.clone(), "published later").await;
    assert_eq!(again["message_id"], fresh["message_id"]);
    assert_eq!(again["seq"], fresh["seq"]);
    assert_eq!(again["publication"], "pending_publication", "{again}");

    // Once the backend confirms it, a retry says so: the state it is in
    // now, not the one the first call was told.
    let plain = PostgresBackend::new(h.pool.clone());
    assert_eq!(
        outbox::run_once(&h.pool, &plain, "worker").await.unwrap(),
        Some(Settled::Stored)
    );
    let settled = send(rid, "published later").await;
    assert_eq!(settled["message_id"], fresh["message_id"]);
    assert_eq!(settled["stored"], true, "{settled}");
    assert_eq!(settled["publication"], "stored", "{settled}");
    let (publication, stored_at) = observed(mid).await;
    assert_eq!((publication.as_str(), stored_at), ("stored", true));

    // A publication that failed is reported as failed, not as pending.
    let rid = request_id();
    let doomed_send = send(rid.clone(), "never published").await;
    assert_eq!(doomed_send["publication"], "pending_publication");
    let doomed = PostgresBackend::with_faults(
        h.pool.clone(),
        Faults {
            fatal: true,
            ..Default::default()
        },
    );
    assert_eq!(
        outbox::run_once(&h.pool, &doomed, "worker").await.unwrap(),
        Some(Settled::Failed)
    );
    let failed = send(rid, "never published").await;
    assert_eq!(failed["stored"], false, "{failed}");
    assert_eq!(failed["publication"], "failed", "{failed}");
    let (publication, stored_at) =
        observed(doomed_send["message_id"].as_str().unwrap().into()).await;
    assert_eq!((publication.as_str(), stored_at), ("failed", false));

    for c in [owner, dani] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// The team id, for the store-level calls above.
async fn team_id(pool: &PgPool, slug: &str) -> Uuid {
    sqlx::query_scalar::<_, Uuid>("SELECT id FROM teams WHERE slug = $1")
        .bind(slug)
        .fetch_one(pool)
        .await
        .unwrap()
}

// -------------------------------------------------- the JetStream adapter --

/// The broker fixture. Required from phase 4: a skipped broker test proves
/// nothing and reads like a pass, so a missing broker fails visibly.
fn nats_url() -> String {
    match std::env::var("TEST_NATS_URL") {
        Ok(url) if !url.trim().is_empty() => url,
        _ => panic!(
            "TEST_NATS_URL is not set. From phase 4 the real JetStream fixture is required: \
             run `make test`, which starts it, or set TEST_NATS_URL yourself. This is a \
             failure rather than a skip on purpose."
        ),
    }
}

/// The adapter contract against a real broker: publish and await the PubAck,
/// read the body back, refuse another team's locator, deduplicate on the
/// publish key, carry a body at the contract's ceiling, and tell a full
/// stream apart from a timeout.
#[tokio::test]
async fn the_jetstream_adapter_holds_its_contract_against_a_real_broker() {
    use ai_crew_sync::store::backend::{Envelope, Locator, MessagingBackend, Published};
    use ai_crew_sync::store::jetstream::{self, Config, JetStreamBackend};

    // Small ceilings: the fixture's broker has a small store, and the
    // quota behaviour is the same at any size.
    let config = Config::new(nats_url()).with_limits(1_000, 16 * 1024 * 1024);
    let team = Uuid::new_v4();
    let other_team = Uuid::new_v4();
    let conversation = Uuid::new_v4();

    // Provisioning is an operator action, and the runtime path refuses to
    // start against a team that has not had it done.
    let err = match JetStreamBackend::connect(&config, team).await {
        Err(e) => e.to_string(),
        Ok(_) => panic!("connecting to an unprovisioned team must fail"),
    };
    assert!(err.contains("does not exist"), "{err}");
    assert!(err.contains("Provision it first"), "{err}");

    let stream = JetStreamBackend::provision(&config, team).await.unwrap();
    assert_eq!(stream.name, jetstream::stream_name(team));
    assert!(stream.created);
    JetStreamBackend::provision(&config, other_team)
        .await
        .unwrap();
    let backend = JetStreamBackend::connect(&config, team).await.unwrap();
    let theirs = JetStreamBackend::connect(&config, other_team)
        .await
        .unwrap();

    // A publish is stored when the PubAck says so, and the locator reads it
    // back.
    let key = Uuid::new_v4();
    let message_id = Uuid::new_v4();
    let envelope = Envelope {
        message_id,
        conversation_id: conversation,
        team_id: team,
        body: "the empty state needs a spinner".into(),
        publish_key: key,
    };
    let locator = match backend.publish(envelope.clone()).await {
        Published::Confirmed(l) => l,
        other => panic!("expected a PubAck: {other:?}"),
    };
    assert!(locator.0.starts_with("jetstream:"), "{locator:?}");
    assert_eq!(
        backend
            .fetch(&locator, message_id)
            .await
            .unwrap()
            .as_deref(),
        Some("the empty state needs a spinner")
    );

    // Another team cannot read it even holding the locator. Three
    // independent reasons and any of them is a pass: the locator names a
    // stream that is not theirs, that stream would not hold the sequence
    // anyway, and the envelope's team is checked rather than trusted if it
    // ever got that far.
    match theirs.fetch(&locator, message_id).await {
        Ok(None) => {}
        Err(e) => {
            let why = e.to_string();
            assert!(
                why.contains("another stream") || why.contains("another team"),
                "{why}"
            );
        }
        Ok(Some(body)) => panic!("another team read a body it must not see: {body}"),
    }

    // Idempotency: the same publish key inside the dedup window returns the
    // same sequence rather than storing twice.
    let again = match backend.publish(envelope.clone()).await {
        Published::Confirmed(l) => l,
        other => panic!("{other:?}"),
    };
    assert_eq!(again, locator, "a retry must not duplicate the body");
    // Reconciliation answers the uncertain case without inventing a second
    // logical message, and without writing a probe that would take the key
    // the body needs.
    assert_eq!(
        backend.reconcile(&envelope).await.unwrap(),
        Some(locator.clone()),
        "reconcile must find a key the broker has seen"
    );
    // A key it has never seen lands now, under that same key, and answers
    // with where it went. One logical message, and reconciling twice does
    // not make it two.
    let unseen = Envelope {
        message_id: Uuid::new_v4(),
        conversation_id: conversation,
        team_id: team,
        body: "reconciled into existence".into(),
        publish_key: Uuid::new_v4(),
    };
    let landed = backend.reconcile(&unseen).await.unwrap().unwrap();
    assert_eq!(
        backend
            .fetch(&landed, unseen.message_id)
            .await
            .unwrap()
            .as_deref(),
        Some("reconciled into existence"),
        "the locator must name the body, not an empty probe"
    );
    assert_eq!(
        backend.reconcile(&unseen).await.unwrap(),
        Some(landed),
        "reconciling twice is still one message"
    );

    // An envelope for another team is refused rather than written into this
    // team's stream, where the team it belongs to could never read it.
    let stranger = backend
        .publish(Envelope {
            message_id: Uuid::new_v4(),
            conversation_id: conversation,
            team_id: Uuid::new_v4(),
            body: "not mine".into(),
            publish_key: Uuid::new_v4(),
        })
        .await;
    assert!(matches!(stranger, Published::Fatal(_)), "{stranger:?}");

    // A locator for a different message of the same team is refused too. A
    // sequence in the right stream is not proof that it is the right body.
    let err = backend
        .fetch(&locator, Uuid::new_v4())
        .await
        .unwrap_err()
        .to_string();
    assert!(err.contains("another message"), "{err}");

    // A locator naming another stream is refused before it reaches the
    // broker, rather than read as that sequence of this one.
    let forged = Locator(format!("jetstream:ACS_T_{}:1", Uuid::new_v4().simple()));
    let err = backend
        .fetch(&forged, Uuid::new_v4())
        .await
        .unwrap_err()
        .to_string();
    assert!(err.contains("another stream"), "{err}");

    // The 1 MiB body contract still fits once headers and framing are added
    // — but only because the fixture raises the server's own max_payload as
    // well as the stream's ceiling. With the server default of 1 MiB this
    // publish is refused by a couple of hundred bytes of headers, which is
    // why the Makefile passes --max_payload 2MB and the constant says so.
    let big = "x".repeat(1024 * 1024);
    let outcome = backend
        .publish(Envelope {
            message_id: Uuid::new_v4(),
            conversation_id: conversation,
            team_id: team,
            body: big.clone(),
            publish_key: Uuid::new_v4(),
        })
        .await;
    assert!(
        matches!(outcome, Published::Confirmed(_)),
        "a body at the contract's ceiling must fit: {outcome:?}"
    );
    // And one past the broker's limit is fatal, not retried for ever.
    let too_big = "x".repeat(jetstream::MAX_BROKER_MESSAGE_BYTES as usize + 1);
    let outcome = backend
        .publish(Envelope {
            message_id: Uuid::new_v4(),
            conversation_id: conversation,
            team_id: team,
            body: too_big,
            publish_key: Uuid::new_v4(),
        })
        .await;
    assert!(matches!(outcome, Published::Fatal(_)), "{outcome:?}");

    // A sequence this stream does not hold is absent, not an error. A
    // locator naming another stream, or no stream at all, is refused rather
    // than guessed at.
    assert!(
        backend
            .fetch(
                &Locator(format!("jetstream:{}:999999", backend.stream())),
                Uuid::new_v4(),
            )
            .await
            .unwrap()
            .is_none()
    );
    assert!(
        backend
            .fetch(&Locator("jetstream:ACS_T_x:1".into()), Uuid::new_v4())
            .await
            .is_err()
    );
    assert!(
        backend
            .fetch(&Locator("nonsense".into()), Uuid::new_v4())
            .await
            .is_err()
    );

    // A broker that is not there fails retryably rather than hanging.
    let unreachable = Config::new("nats://127.0.0.1:1");
    assert!(
        JetStreamBackend::connect(&unreachable, team).await.is_err(),
        "an unreachable broker must fail, not block"
    );

    // Clean up after ourselves: streams and their bodies are per test.
    JetStreamBackend::deprovision(&config, team).await.unwrap();
    JetStreamBackend::deprovision(&config, other_team)
        .await
        .unwrap();
}

/// The default install does not need a broker: an ordinary team's
/// conversations are Postgres-backed and untouched by anything above.
#[tokio::test]
async fn the_default_backend_stays_postgres_with_no_broker_involved() {
    let h = require_db!("t_default_backend");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    enable_conversations(&h.pool, "acme").await;
    let client = connect_with_session(&h.base, &token, "impl").await;
    let convo = call(
        &client,
        "create_conversation",
        json!({"title": "ordinary", "private": true}),
    )
    .await;
    let (backend, publication): (String, String) =
        sqlx::query_as("SELECT backend, publication FROM conversations WHERE id = $1")
            .bind(convo["id"].as_str().unwrap().parse::<Uuid>().unwrap())
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert_eq!(backend, "postgres");
    assert_eq!(publication, "sync");
    let sent = call(
        &client,
        "send_conversation_message",
        json!({"conversation_id": convo["id"], "body": "no broker here",
               "request_id": request_id()}),
    )
    .await;
    assert_eq!(sent["stored"], true);
    let _ = client.cancel().await;
    h.shutdown().await;
}

/// Phase 5: a conversation routed to JetStream publishes through the outbox
/// to a real broker, reports `stored` only on a PubAck, survives a process
/// death mid-publication, reads its history back by locator, and revalidates
/// access at the moment the body is served.
#[tokio::test]
async fn opted_in_conversations_publish_to_jetstream_and_read_back() {
    use ai_crew_sync::store::jetstream::{Config, JetStreamBackend};
    use ai_crew_sync::store::{conversations as convo_store, outbox};

    let h = require_db_broker!("t_jetstream_publication");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    let dani_token = seed_agent(&h.pool, "acme", "dani").await;
    enable_conversations(&h.pool, "acme").await;
    let team = team_id(&h.pool, "acme").await;

    // Routing is an operator decision, per team, and it only affects
    // conversations created afterwards.
    let before = connect_with_session(&h.base, &token, "before").await;
    let legacy = call(
        &before,
        "create_conversation",
        json!({"title": "postgres thread", "private": true}),
    )
    .await;
    sqlx::query("UPDATE teams SET default_backend = 'jetstream' WHERE id = $1")
        .bind(team)
        .execute(&h.pool)
        .await
        .unwrap();

    let config = Config::new(nats_url()).with_limits(1_000, 16 * 1024 * 1024);
    JetStreamBackend::provision(&config, team).await.unwrap();
    let backend = JetStreamBackend::connect(&config, team).await.unwrap();
    // The same view of the backends the server has, for the reads this test
    // makes directly against the store.
    let backends =
        ai_crew_sync::store::routing::Backends::with_jetstream(h.pool.clone(), config.clone());

    let owner = connect_with_session(&h.base, &token, "impl").await;
    let dani = connect_with_session(&h.base, &dani_token, "review").await;
    let convo = call(
        &owner,
        "create_conversation",
        json!({"title": "jetstream thread", "private": true, "invite": ["dani/review"]}),
    )
    .await;
    let cid = convo["id"].as_str().unwrap().to_owned();
    let cuuid: Uuid = cid.parse().unwrap();
    call(&dani, "join_conversation", json!({"conversation_id": cid})).await;

    // The earlier conversation kept Postgres; the new one is routed.
    let (old_backend,): (String,) =
        sqlx::query_as("SELECT backend FROM conversations WHERE id = $1")
            .bind(legacy["id"].as_str().unwrap().parse::<Uuid>().unwrap())
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert_eq!(old_backend, "postgres", "existing threads are not migrated");
    let (new_backend, publication): (String, String) =
        sqlx::query_as("SELECT backend, publication FROM conversations WHERE id = $1")
            .bind(cuuid)
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert_eq!(
        (new_backend.as_str(), publication.as_str()),
        ("jetstream", "outbox")
    );

    // Acceptance is not storage, and the receipts do not claim it is.
    let sent = call(
        &owner,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "through the broker",
               "request_id": request_id()}),
    )
    .await;
    assert_eq!(sent["stored"], false);
    let mid: Uuid = sent["message_id"].as_str().unwrap().parse().unwrap();
    let receipts = call(
        &owner,
        "get_message_receipts",
        json!({"message_id": sent["message_id"]}),
    )
    .await;
    assert!(receipts["receipts"][0]["stored_at"].is_null(), "{receipts}");

    // A worker dies mid-publication: the outcome is unknown, and that is
    // neither stored nor failed until reconciliation says so.
    let lease = outbox::lease(&h.pool, "worker-dead")
        .await
        .unwrap()
        .unwrap();
    let settled = outbox::mark_uncertain(&h.pool, &lease, "the process died")
        .await
        .unwrap();
    assert!(matches!(settled, outbox::Settled::Retrying { .. }));
    let (state, uncertain): (String, Option<chrono::DateTime<chrono::Utc>>) = sqlx::query_as(
        "SELECT publication_state, uncertain_at FROM conversation_messages WHERE id = $1",
    )
    .bind(mid)
    .fetch_one(&h.pool)
    .await
    .unwrap();
    assert_eq!(state, "pending_publication");
    assert!(
        uncertain.is_some(),
        "an unknown outcome is recorded as unknown"
    );

    // Reconciliation asks the broker under the same key instead of
    // guessing: inside its dedup window that answers with the original
    // sequence, outside it the body lands now. One logical message either
    // way, and only now is it stored.
    assert_eq!(
        outbox::resolve_uncertain(&h.pool, &backend, team)
            .await
            .unwrap(),
        1
    );
    let (uncertain,): (Option<chrono::DateTime<chrono::Utc>>,) =
        sqlx::query_as("SELECT uncertain_at FROM conversation_messages WHERE id = $1")
            .bind(mid)
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert!(
        uncertain.is_none(),
        "an answered question is no longer open"
    );
    let (state, locator): (String, Option<String>) = sqlx::query_as(
        "SELECT publication_state, canonical_locator FROM conversation_messages WHERE id = $1",
    )
    .bind(mid)
    .fetch_one(&h.pool)
    .await
    .unwrap();
    assert_eq!(state, "stored");
    assert!(
        locator.as_deref().unwrap().starts_with("jetstream:"),
        "{locator:?}"
    );
    let receipts = call(
        &owner,
        "get_message_receipts",
        json!({"message_id": sent["message_id"]}),
    )
    .await;
    assert!(
        receipts["receipts"][0]["stored_at"].is_string(),
        "stored once the PubAck arrived, not before: {receipts}"
    );

    // History reads through the ordinary tool, from the broker, with the
    // body's standing stated rather than implied.
    let history = call(&dani, "read_conversation", json!({"conversation_id": cid})).await;
    assert_eq!(history["messages"].as_array().unwrap().len(), 1);
    assert_eq!(history["messages"][0]["publication"], "stored");

    // The temporary local copy is released, and history then reads from the
    // broker by locator.
    assert_eq!(
        outbox::release_published_bodies(
            &h.pool,
            &ai_crew_sync::store::routing::Backends::with_jetstream(h.pool.clone(), config.clone()),
            Some(cuuid),
            0
        )
        .await
        .unwrap(),
        1
    );
    let (local,): (String,) =
        sqlx::query_as("SELECT body FROM conversation_messages WHERE id = $1")
            .bind(mid)
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert!(local.is_empty(), "the body is the broker's now");
    assert_eq!(
        convo_store::body_of(&h.pool, &backends, mid).await.unwrap(),
        "through the broker"
    );

    // One logical message, not two, and its body came from the broker.
    let history = call(&dani, "read_conversation", json!({"conversation_id": cid})).await;
    assert_eq!(
        history["messages"].as_array().unwrap().len(),
        1,
        "a retained body is one message, not a second copy: {history}"
    );
    assert_eq!(history["messages"][0]["body"], "through the broker");

    // A pending publication is neither hidden nor reported as stored, and
    // an earlier pending message does not let a reader walk past it.
    let pending = call(
        &owner,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "still in flight",
               "request_id": request_id()}),
    )
    .await;
    let _later = call(
        &owner,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "sent after it",
               "request_id": request_id()}),
    )
    .await;
    let history = call(&dani, "read_conversation", json!({"conversation_id": cid})).await;
    let msgs = history["messages"].as_array().unwrap();
    assert_eq!(msgs.len(), 3);
    assert_eq!(msgs[1]["publication"], "pending_publication");
    assert_eq!(
        msgs[1]["body"], "still in flight",
        "the body is still local"
    );
    assert!(msgs[1]["seq"].as_i64().unwrap() < msgs[2]["seq"].as_i64().unwrap());
    // And the cursor stops before it. Following the advertised
    // next_after_seq must not step over a sequence that is about to fill.
    let pending_seq = msgs[1]["seq"].as_i64().unwrap();
    let paged = call(
        &dani,
        "read_conversation",
        json!({"conversation_id": cid, "limit": 2}),
    )
    .await;
    assert!(
        paged["next_after_seq"]
            .as_i64()
            .is_none_or(|n| n < pending_seq),
        "the cursor advanced past a message still in flight: {paged}"
    );

    // Out-of-order completion: the later message is published first. The
    // thread keeps its own order, which is the sequence, not the order the
    // broker happened to confirm in.
    let first = outbox::lease(&h.pool, "worker-a").await.unwrap().unwrap();
    let second = outbox::lease(&h.pool, "worker-b").await.unwrap().unwrap();
    assert_eq!(first.message_id.to_string(), pending["message_id"]);
    assert_eq!(
        outbox::publish_leased(&h.pool, &backend, &second)
            .await
            .unwrap(),
        outbox::Settled::Stored
    );
    assert_eq!(
        outbox::publish_leased(&h.pool, &backend, &first)
            .await
            .unwrap(),
        outbox::Settled::Stored
    );
    outbox::release_published_bodies(
        &h.pool,
        &ai_crew_sync::store::routing::Backends::with_jetstream(h.pool.clone(), config.clone()),
        Some(cuuid),
        0,
    )
    .await
    .unwrap();
    let history = call(&dani, "read_conversation", json!({"conversation_id": cid})).await;
    let bodies: Vec<&str> = history["messages"]
        .as_array()
        .unwrap()
        .iter()
        .map(|m| m["body"].as_str().unwrap())
        .collect();
    assert_eq!(
        bodies,
        ["through the broker", "still in flight", "sent after it"],
        "confirmation order is not thread order"
    );

    // An ACL that changes while bodies are on the broker takes effect on
    // the next read, not the next restart: a removed member stops reading.
    call(
        &owner,
        "remove_conversation_member",
        json!({"conversation_id": cid, "address": "dani/review"}),
    )
    .await;
    let refused =
        call_expect_error(&dani, "read_conversation", json!({"conversation_id": cid})).await;
    assert!(refused.contains("no such conversation"), "{refused}");
    let refused = call_expect_error(
        &dani,
        "get_conversation_message",
        json!({"message_id": sent["message_id"]}),
    )
    .await;
    assert!(refused.contains("no such conversation"), "{refused}");

    // A body the backend no longer holds is an explained absence, and the
    // message keeps its place, its recipients and its receipts.
    outbox::tombstone(&h.pool, mid, "retention").await.unwrap();
    let err = convo_store::body_of(&h.pool, &backends, mid)
        .await
        .unwrap_err()
        .to_string();
    assert!(err.contains("no longer held"), "{err}");
    assert!(err.contains("receipts remain"), "{err}");
    let receipts = call(
        &owner,
        "get_message_receipts",
        json!({"message_id": sent["message_id"]}),
    )
    .await;
    assert_eq!(receipts["total"], 1, "the denominator survives a tombstone");
    let history = call(&owner, "read_conversation", json!({"conversation_id": cid})).await;
    assert_eq!(history["messages"][0]["publication"], "tombstoned");
    assert_eq!(history["messages"][0]["body"], "");
    assert!(
        history["messages"][0]["unavailable"]
            .as_str()
            .unwrap()
            .contains("no longer held"),
        "a gap that is explained is not the same as a gap: {history}"
    );
    assert_eq!(
        history["messages"].as_array().unwrap().len(),
        3,
        "a tombstoned body does not remove the message"
    );

    // The Postgres thread is untouched by any of this.
    let legacy_sent = call(
        &before,
        "send_conversation_message",
        json!({"conversation_id": legacy["id"], "body": "still local",
               "request_id": request_id()}),
    )
    .await;
    assert_eq!(legacy_sent["stored"], true);
    assert_eq!(
        convo_store::body_of(
            &h.pool,
            &backends,
            legacy_sent["message_id"].as_str().unwrap().parse().unwrap()
        )
        .await
        .unwrap(),
        "still local"
    );

    JetStreamBackend::deprovision(&config, team).await.unwrap();
    for c in [owner, dani, before] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// Phase 6: every recipient has its own durable inbox. One acknowledgement
/// drains nobody else's, a process that dies between taking a reference and
/// confirming it gets an honest state rather than a fabricated receipt, and
/// a broker that has lost the references does not make the inbox look empty.
#[tokio::test]
async fn each_recipient_holds_its_own_durable_inbox() {
    use ai_crew_sync::store::jetstream::{Config, JetStreamBackend};
    use ai_crew_sync::store::{inbox, outbox};

    let h = require_db_broker!("t_inbox_delivery");
    let owner_token = seed_agent(&h.pool, "acme", "joaquin").await;
    let dani_token = seed_agent(&h.pool, "acme", "dani").await;
    let marta_token = seed_agent(&h.pool, "acme", "marta").await;
    enable_conversations(&h.pool, "acme").await;
    let team = team_id(&h.pool, "acme").await;
    sqlx::query("UPDATE teams SET default_backend = 'jetstream' WHERE id = $1")
        .bind(team)
        .execute(&h.pool)
        .await
        .unwrap();

    let config = Config::new(nats_url()).with_limits(1_000, 16 * 1024 * 1024);
    JetStreamBackend::provision(&config, team).await.unwrap();
    JetStreamBackend::provision_inbox(&config, team)
        .await
        .unwrap();
    let backend = JetStreamBackend::connect(&config, team).await.unwrap();

    let owner = connect_with_session(&h.base, &owner_token, "impl").await;
    let design = connect_with_session(&h.base, &dani_token, "design").await;
    let marta = connect_with_session(&h.base, &marta_token, "review").await;
    // One of the three is a registered window, so the inbox is exercised
    // with a real session credential and not only with a header label.
    let dani_agent = connect(&h.base, &dani_token).await;
    let review_cred = call(
        &dani_agent,
        "register_session",
        json!({"session": "review"}),
    )
    .await;
    let review = connect(&h.base, review_cred["session_token"].as_str().unwrap()).await;

    let convo = call(
        &owner,
        "create_conversation",
        json!({"title": "three inboxes", "private": true,
               "invite": ["dani/review", "dani/design", "marta/review"]}),
    )
    .await;
    let cid = convo["id"].as_str().unwrap().to_owned();
    for client in [&review, &design, &marta] {
        call(client, "join_conversation", json!({"conversation_id": cid})).await;
    }
    let sent = call(
        &owner,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "three of you, three inboxes",
               "request_id": request_id()}),
    )
    .await;
    assert_eq!(sent["recipients"].as_array().unwrap().len(), 3);

    // Nothing is notified before the body is canonical: a reference to a
    // message nobody stored would be a promise of something unreadable.
    assert_eq!(
        inbox::publish_pending(&h.pool, &backend, team, 100)
            .await
            .unwrap(),
        0,
        "no references before the body is stored"
    );
    assert_eq!(
        outbox::run_once(&h.pool, &backend, "worker").await.unwrap(),
        Some(outbox::Settled::Stored)
    );
    assert_eq!(
        inbox::publish_pending(&h.pool, &backend, team, 100)
            .await
            .unwrap(),
        3,
        "one reference per recipient, and no more"
    );

    // Each window takes its own, and only its own.
    let first = call(&review, "fetch_conversation_inbox", json!({})).await;
    assert_eq!(first["references"].as_array().unwrap().len(), 1);
    assert_eq!(first["from_broker"], 1);
    assert_eq!(first["references"][0]["message_id"], sent["message_id"]);
    assert_eq!(first["references"][0]["kind"], "message");
    assert_eq!(first["references"][0]["redelivered"], false);
    assert!(
        first["references"][0].get("body").is_none(),
        "a reference carries no body: {first}"
    );

    // Taking it is not receiving it. Until the holder says it has it
    // durably, nothing is delivered.
    let receipts = call(
        &owner,
        "get_message_receipts",
        json!({"message_id": sent["message_id"]}),
    )
    .await;
    assert!(
        receipts["receipts"]
            .as_array()
            .unwrap()
            .iter()
            .all(|r| r["delivered_at"].is_null()),
        "{receipts}"
    );

    call(
        &review,
        "confirm_inbox_delivery",
        json!({"delivery_ids": [first["references"][0]["delivery_id"]]}),
    )
    .await;
    let delivered = |receipts: &Value, address: &str| -> bool {
        receipts["receipts"]
            .as_array()
            .unwrap()
            .iter()
            .find(|r| r["address"] == address)
            .map(|r| r["delivered_at"].is_string())
            .unwrap_or(false)
    };
    let receipts = call(
        &owner,
        "get_message_receipts",
        json!({"message_id": sent["message_id"]}),
    )
    .await;
    assert!(delivered(&receipts, "dani/review"), "{receipts}");
    assert!(!delivered(&receipts, "dani/design"), "{receipts}");
    assert!(!delivered(&receipts, "marta/review"), "{receipts}");

    // One window's acknowledgement is its own. The other two are not
    // "assumed yes" and not "no": they have not answered.
    call(
        &review,
        "ack_message",
        json!({"message_id": sent["message_id"]}),
    )
    .await;
    let receipts = call(
        &owner,
        "get_message_receipts",
        json!({"message_id": sent["message_id"]}),
    )
    .await;
    assert_eq!(receipts["acknowledged"], 1);
    assert_eq!(receipts["resolved"], 0);
    assert_eq!(receipts["total"], 3);

    // The parent agent token cannot read its own window's inbox, or record
    // a delivery on its behalf. The label in the header is a name.
    let impostor = connect_with_session(&h.base, &dani_token, "review").await;
    let err = call_expect_error(&impostor, "fetch_conversation_inbox", json!({})).await;
    assert!(err.contains("registered window"), "{err}");
    let err = call_expect_error(
        &impostor,
        "confirm_inbox_delivery",
        json!({"delivery_ids": [first["references"][0]["delivery_id"]]}),
    )
    .await;
    assert!(err.contains("registered window"), "{err}");
    let err = call_expect_error(&impostor, "conversation_inbox_status", json!({})).await;
    assert!(err.contains("registered window"), "{err}");

    // A later observation on the same message is a new notification. The
    // sender is told to look again when the recipient resolves it, not only
    // the first time it acknowledged.
    inbox::publish_pending(&h.pool, &backend, team, 100)
        .await
        .unwrap();
    call(
        &review,
        "ack_message",
        json!({"message_id": sent["message_id"], "resolved": true, "note": "and done"}),
    )
    .await;
    assert_eq!(
        inbox::publish_pending(&h.pool, &backend, team, 100)
            .await
            .unwrap(),
        1,
        "resolving after acknowledging is a second thing to tell the sender"
    );
    let (events,): (i64,) = sqlx::query_as(
        "SELECT count(*) FROM inbox_events WHERE kind = 'receipt' AND message_id = $1",
    )
    .bind(
        sent["message_id"]
            .as_str()
            .unwrap()
            .parse::<Uuid>()
            .unwrap(),
    )
    .fetch_one(&h.pool)
    .await
    .unwrap();
    assert_eq!(
        events, 2,
        "acknowledged and resolved are two observations, not one coalesced row"
    );

    // And revoking the window does not open its inbox either. The label was
    // registered once, which is enough: revocation must not turn a
    // protected window into a legacy identity.
    call(&review, "revoke_session", json!({})).await;
    let err = call_expect_error(&impostor, "fetch_conversation_inbox", json!({})).await;
    assert!(err.contains("does not hand the label back"), "{err}");
    let err = call_expect_error(
        &impostor,
        "confirm_inbox_delivery",
        json!({"delivery_ids": [first["references"][0]["delivery_id"]]}),
    )
    .await;
    assert!(err.contains("registered window"), "{err}");

    // A process that takes a reference and dies before confirming: the
    // reference is not lost and no receipt is invented. A second fetch does
    // not hand it over twice while the first hand-out is still in flight,
    // and the state says exactly that.
    let taken = call(&design, "fetch_conversation_inbox", json!({})).await;
    assert_eq!(taken["references"].as_array().unwrap().len(), 1);
    let again = call(&design, "fetch_conversation_inbox", json!({})).await;
    assert_eq!(
        again["references"].as_array().unwrap().len(),
        0,
        "it is already in flight to this window: {again}"
    );
    let state = call(&design, "conversation_inbox_status", json!({})).await;
    assert_eq!(state["address"], "dani/design");
    assert_eq!(state["undelivered"], 1, "the authority still says one");
    assert_eq!(state["handed_out_unconfirmed"], 1);

    // Offered again once that hand-out has gone stale, it is the same
    // reference under the same delivery id. A second row for the same
    // reference used to violate the unique index and fail the whole fetch.
    sqlx::query("UPDATE inbox_deliveries SET handed_at = now() - interval '10 minutes'")
        .execute(&h.pool)
        .await
        .unwrap();
    let redelivered = call(&design, "fetch_conversation_inbox", json!({})).await;
    assert_eq!(redelivered["references"].as_array().unwrap().len(), 1);
    assert_eq!(
        redelivered["references"][0]["delivery_id"], taken["references"][0]["delivery_id"],
        "a redelivery finds the hand-out that is already open: {redelivered}"
    );
    // The confirmation arrives after the restart, with the reference the
    // spool kept. Confirming twice changes nothing.
    let id = taken["references"][0]["delivery_id"].clone();
    let confirmed = call(
        &design,
        "confirm_inbox_delivery",
        json!({"delivery_ids": [id]}),
    )
    .await;
    assert_eq!(confirmed["confirmed"], 1);
    let repeat = call(
        &design,
        "confirm_inbox_delivery",
        json!({"delivery_ids": [id]}),
    )
    .await;
    assert_eq!(repeat["confirmed"], 0, "confirming twice is harmless");
    let receipts = call(
        &owner,
        "get_message_receipts",
        json!({"message_id": sent["message_id"]}),
    )
    .await;
    assert!(delivered(&receipts, "dani/design"), "{receipts}");
    assert!(!delivered(&receipts, "marta/review"));

    // A confirmation from a window that has since been resumed away writes
    // nothing: the reference stays offered to whoever holds the window now.
    // This needs a registered window, because that is what an epoch is.
    let cred = call(&marta, "register_session", json!({"session": "review"})).await;
    let marta_window = connect(&h.base, cred["session_token"].as_str().unwrap()).await;
    let stale = ai_crew_sync::auth::AuthCtx {
        agent_id: sqlx::query_scalar::<_, Uuid>("SELECT id FROM agents WHERE name = 'marta'")
            .fetch_one(&h.pool)
            .await
            .unwrap(),
        agent_name: "marta".into(),
        team_id: team,
        team_slug: "acme".into(),
        session: "review".into(),
        session_id: sqlx::query_scalar::<_, Uuid>(
            "SELECT id FROM agent_sessions WHERE label = 'review' AND agent_id =
                 (SELECT id FROM agents WHERE name = 'marta')",
        )
        .fetch_optional(&h.pool)
        .await
        .unwrap(),
        // The epoch a connection that has since been replaced was admitted
        // with.
        session_epoch: Some(99),
        token_id: None,
    };
    assert!(stale.session_id.is_some(), "the window must be registered");
    let backends =
        ai_crew_sync::store::routing::Backends::with_jetstream(h.pool.clone(), config.clone());
    let marta_batch = call(&marta_window, "fetch_conversation_inbox", json!({})).await;
    let marta_id = marta_batch["references"][0]["delivery_id"]
        .as_str()
        .unwrap()
        .to_owned();
    let err = inbox::confirm(&h.pool, &backends, &stale, std::slice::from_ref(&marta_id))
        .await
        .expect_err("a replaced connection must not confirm")
        .to_string();
    assert!(err.contains("stale"), "{err}");
    let receipts = call(
        &owner,
        "get_message_receipts",
        json!({"message_id": sent["message_id"]}),
    )
    .await;
    assert!(
        !delivered(&receipts, "marta/review"),
        "a fenced confirmation must not write a receipt: {receipts}"
    );

    // The broker loses everything — an expiry, an operator, a deleted
    // consumer. The inbox is not empty: the bus's own records are the
    // authority, and the reference comes back from there.
    JetStreamBackend::deprovision(&config, team).await.unwrap();
    // Immediately after a hand-out the reference is in flight to this
    // window, and a fetch does not hand it over a second time. The state is
    // the honest answer, and it is not "your inbox is empty".
    let inflight = call(&marta_window, "fetch_conversation_inbox", json!({})).await;
    assert_eq!(inflight["references"].as_array().unwrap().len(), 0);
    let state = call(&marta_window, "conversation_inbox_status", json!({})).await;
    assert_eq!(state["undelivered"], 1);
    assert_eq!(state["handed_out_unconfirmed"], 1);
    assert_eq!(
        state["broker_consumer_present"], false,
        "a missing consumer is a fact, not an empty inbox: {state}"
    );

    // Once that hand-out has gone stale — the process holding it never came
    // back — the reference is offered again, from the records that are the
    // authority.
    sqlx::query("UPDATE inbox_deliveries SET handed_at = now() - interval '10 minutes'")
        .execute(&h.pool)
        .await
        .unwrap();
    let rebuilt = call(
        &marta_window,
        "fetch_conversation_inbox",
        json!({"limit": 5}),
    )
    .await;
    let refs = rebuilt["references"].as_array().unwrap();
    assert_eq!(refs.len(), 1, "{rebuilt}");
    assert_eq!(refs[0]["source"], "bus");
    assert_eq!(rebuilt["from_broker"], 0);
    assert!(
        rebuilt["note"].as_str().unwrap().contains("authority"),
        "{rebuilt}"
    );
    call(
        &marta_window,
        "confirm_inbox_delivery",
        json!({"delivery_ids": [refs[0]["delivery_id"]]}),
    )
    .await;
    let receipts = call(
        &owner,
        "get_message_receipts",
        json!({"message_id": sent["message_id"]}),
    )
    .await;
    assert!(delivered(&receipts, "marta/review"), "{receipts}");
    assert_eq!(
        receipts["acknowledged"], 1,
        "delivery is not acknowledgement, on any path"
    );

    // Legacy traffic is untouched by all of this.
    call(&owner, "create_channel", json!({"name": "general"})).await;
    call(
        &owner,
        "post_message",
        json!({"channel": "general", "body": "still here"}),
    )
    .await;
    let read = call(
        &marta_window,
        "read_messages",
        json!({"channel": "general"}),
    )
    .await;
    assert_eq!(read["messages"].as_array().unwrap().len(), 1);

    for c in [
        owner,
        review,
        design,
        marta,
        marta_window,
        dani_agent,
        impostor,
    ] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// Phase 7: a supervised move, a rollback, and an interrupted run that
/// resumes. Bodies, ids, authorship, access and every observed receipt come
/// through unchanged, and nothing is cut over until every body has been read
/// back from the target and matched.
#[tokio::test]
async fn a_conversation_moves_between_backends_and_back_without_losing_anything() {
    use ai_crew_sync::store::jetstream::{Config, JetStreamBackend};
    use ai_crew_sync::store::migrate::{self, Direction};
    use ai_crew_sync::store::outbox;

    let h = require_db_broker!("t_conversation_migration");
    let owner_token = seed_agent(&h.pool, "acme", "joaquin").await;
    let dani_token = seed_agent(&h.pool, "acme", "dani").await;
    enable_conversations(&h.pool, "acme").await;
    let team = team_id(&h.pool, "acme").await;

    let config = Config::new(nats_url()).with_limits(1_000, 16 * 1024 * 1024);
    JetStreamBackend::provision(&config, team).await.unwrap();
    JetStreamBackend::provision_inbox(&config, team)
        .await
        .unwrap();
    let jetstream = JetStreamBackend::connect(&config, team).await.unwrap();

    // A thread that lives entirely in Postgres, with real receipts on it.
    let owner = connect_with_session(&h.base, &owner_token, "impl").await;
    let dani = connect_with_session(&h.base, &dani_token, "review").await;
    let convo = call(
        &owner,
        "create_conversation",
        json!({"title": "moved thread", "private": true, "invite": ["dani/review"]}),
    )
    .await;
    let cid = convo["id"].as_str().unwrap().to_owned();
    let cuuid: Uuid = cid.parse().unwrap();
    call(&dani, "join_conversation", json!({"conversation_id": cid})).await;
    let mut sent = Vec::new();
    for body in ["the first one", "the second one", "the third one"] {
        sent.push(
            call(
                &owner,
                "send_conversation_message",
                json!({"conversation_id": cid, "body": body, "request_id": request_id()}),
            )
            .await,
        );
    }
    call(
        &dani,
        "ack_message",
        json!({"message_id": sent[1]["message_id"], "resolved": true, "note": "done"}),
    )
    .await;
    let before = call(&dani, "read_conversation", json!({"conversation_id": cid})).await;
    let receipts_before = call(
        &owner,
        "get_message_receipts",
        json!({"message_id": sent[1]["message_id"]}),
    )
    .await;

    // A plan changes nothing and says what it would cost.
    let plans = migrate::plan(&h.pool, team, Direction::ToJetStream, &[cuuid])
        .await
        .unwrap();
    assert_eq!(plans.len(), 1);
    assert_eq!(plans[0].messages, 3);
    assert_eq!(plans[0].current_backend, "postgres");
    assert!(plans[0].blocked.is_none());
    assert!(plans[0].bytes > 0);
    let unchanged = call(&dani, "read_conversation", json!({"conversation_id": cid})).await;
    assert_eq!(
        unchanged["messages"], before["messages"],
        "a plan is a read"
    );

    // The move itself.
    let outcome = migrate::run(&h.pool, &jetstream, team, cuuid, Direction::ToJetStream)
        .await
        .unwrap();
    assert_eq!(outcome.copied, 3);
    assert_eq!(outcome.state, "cut_over");

    // Writes are open again, and the thread reads exactly as it did — same
    // ids, same order, same bodies, same authors.
    let after = call(&dani, "read_conversation", json!({"conversation_id": cid})).await;
    assert_eq!(
        after["messages"], before["messages"],
        "the thread is the thread"
    );
    let receipts_after = call(
        &owner,
        "get_message_receipts",
        json!({"message_id": sent[1]["message_id"]}),
    )
    .await;
    assert_eq!(
        receipts_after, receipts_before,
        "a move observes nothing and invents nothing"
    );
    let (backend, locators): (String, i64) = sqlx::query_as(
        "SELECT (SELECT backend FROM conversations WHERE id = $1),
                count(*) FILTER (WHERE canonical_locator IS NOT NULL)
           FROM conversation_messages WHERE conversation_id = $1",
    )
    .bind(cuuid)
    .fetch_one(&h.pool)
    .await
    .unwrap();
    assert_eq!((backend.as_str(), locators), ("jetstream", 3));

    // The source bodies are still there: until cleanup runs, a rollback has
    // something to roll back to.
    let (still_local,): (i64,) = sqlx::query_as(
        "SELECT count(*) FROM conversation_messages WHERE conversation_id = $1 AND body <> ''",
    )
    .bind(cuuid)
    .fetch_one(&h.pool)
    .await
    .unwrap();
    assert_eq!(still_local, 3);
    let (would_drop, _bytes) = migrate::cleanup(&h.pool, team, 168, false).await.unwrap();
    assert_eq!(
        would_drop, 0,
        "nothing is dropped inside the rollback window"
    );
    assert!(
        migrate::cleanup(&h.pool, team, -1, false).await.is_err(),
        "a negative window would point into the future"
    );

    // And the ordinary publication sweep leaves them alone. It releases
    // bodies the outbox staged; a migration source copy is the rollback,
    // and only `conversations cleanup` may drop it.
    assert_eq!(
        outbox::release_published_bodies(
            &h.pool,
            &ai_crew_sync::store::routing::Backends::with_jetstream(h.pool.clone(), config.clone()),
            None,
            0
        )
        .await
        .unwrap(),
        0,
        "the five minute sweep must not eat the rollback source"
    );
    let (still_local,): (i64,) = sqlx::query_as(
        "SELECT count(*) FROM conversation_messages WHERE conversation_id = $1 AND body <> ''",
    )
    .bind(cuuid)
    .fetch_one(&h.pool)
    .await
    .unwrap();
    assert_eq!(still_local, 3);

    // An interrupted run resumes through the same command. The process
    // died holding the pause, and the plan says so instead of skipping the
    // thread and reporting success.
    sqlx::query("UPDATE conversations SET write_paused_at = now() WHERE id = $1")
        .bind(cuuid)
        .execute(&h.pool)
        .await
        .unwrap();
    sqlx::query(
        "INSERT INTO conversation_migrations (team_id, conversation_id, direction, state)
         VALUES ($1, $2, 'to_jetstream', 'copying')",
    )
    .bind(team)
    .bind(cuuid)
    .execute(&h.pool)
    .await
    .unwrap();
    let plans = migrate::plan(&h.pool, team, Direction::ToJetStream, &[cuuid])
        .await
        .unwrap();
    assert!(plans[0].blocked.is_none(), "{:?}", plans[0].blocked);
    assert!(plans[0].resuming, "an open run is resumed, not refused");
    let resumed = migrate::run(&h.pool, &jetstream, team, cuuid, Direction::ToJetStream)
        .await
        .unwrap();
    assert_eq!(resumed.state, "cut_over");
    let (paused,): (Option<chrono::DateTime<chrono::Utc>>,) =
        sqlx::query_as("SELECT write_paused_at FROM conversations WHERE id = $1")
            .bind(cuuid)
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert!(paused.is_none(), "resuming finishes and reopens the thread");

    // New messages go where the thread now lives, and are published like
    // any other: acceptance is not storage.
    let fresh = call(
        &owner,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "written after the move",
               "request_id": request_id()}),
    )
    .await;
    assert_eq!(fresh["stored"], false);
    assert_eq!(
        outbox::run_once(&h.pool, &jetstream, "worker")
            .await
            .unwrap(),
        Some(outbox::Settled::Stored)
    );

    // An interrupted run resumes instead of copying twice. Half the
    // evidence is thrown away and the same move is run again.
    outbox::release_published_bodies(
        &h.pool,
        &ai_crew_sync::store::routing::Backends::with_jetstream(h.pool.clone(), config.clone()),
        Some(cuuid),
        0,
    )
    .await
    .unwrap();
    let back = migrate::run(&h.pool, &jetstream, team, cuuid, Direction::ToPostgres)
        .await
        .unwrap();
    assert_eq!(back.copied, 4, "every body came back off the broker");
    let (backend,): (String,) = sqlx::query_as("SELECT backend FROM conversations WHERE id = $1")
        .bind(cuuid)
        .fetch_one(&h.pool)
        .await
        .unwrap();
    assert_eq!(backend, "postgres");
    let rolled = call(&dani, "read_conversation", json!({"conversation_id": cid})).await;
    let bodies: Vec<&str> = rolled["messages"]
        .as_array()
        .unwrap()
        .iter()
        .map(|m| m["body"].as_str().unwrap())
        .collect();
    assert_eq!(
        bodies,
        [
            "the first one",
            "the second one",
            "the third one",
            "written after the move"
        ],
        "a rollback is a copy back, and it keeps what was written meanwhile"
    );
    let receipts_rolled = call(
        &owner,
        "get_message_receipts",
        json!({"message_id": sent[1]["message_id"]}),
    )
    .await;
    assert_eq!(
        receipts_rolled, receipts_before,
        "receipts survive both ways"
    );

    // A second move, interrupted after two messages and resumed: the run
    // picks up its own evidence rather than starting over.
    let migration = migrate::run(&h.pool, &jetstream, team, cuuid, Direction::ToJetStream)
        .await
        .unwrap();
    sqlx::query(
        "UPDATE conversation_migrations SET state = 'copying', finished_at = NULL WHERE id = $1",
    )
    .bind(migration.migration_id)
    .execute(&h.pool)
    .await
    .unwrap();
    sqlx::query(
        "DELETE FROM conversation_migration_items
          WHERE migration_id = $1 AND message_id IN (
              SELECT id FROM conversation_messages WHERE conversation_id = $2
               ORDER BY seq LIMIT 2)",
    )
    .bind(migration.migration_id)
    .bind(cuuid)
    .execute(&h.pool)
    .await
    .unwrap();
    sqlx::query(
        "UPDATE conversation_messages SET backend = 'postgres'
          WHERE conversation_id = $1 AND seq <= 2",
    )
    .bind(cuuid)
    .execute(&h.pool)
    .await
    .unwrap();
    let resumed = migrate::run(&h.pool, &jetstream, team, cuuid, Direction::ToJetStream)
        .await
        .unwrap();
    assert_eq!(
        resumed.migration_id, migration.migration_id,
        "the same run continued"
    );
    assert_eq!(resumed.copied, 2, "only what was missing was copied again");
    assert_eq!(resumed.skipped, 2, "what was verified was left alone");
    let final_read = call(&dani, "read_conversation", json!({"conversation_id": cid})).await;
    assert_eq!(
        final_read["messages"].as_array().unwrap().len(),
        4,
        "one logical message each, however many times they were copied"
    );

    // Writes are never left paused, whichever way it went.
    let (paused,): (Option<chrono::DateTime<chrono::Utc>>,) =
        sqlx::query_as("SELECT write_paused_at FROM conversations WHERE id = $1")
            .bind(cuuid)
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert!(paused.is_none());

    JetStreamBackend::deprovision(&config, team).await.unwrap();
    for c in [owner, dani] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// A move whose abort cannot finish stays open and resumable. `abort` used
/// to mark the run failed, blank the written-back bodies and lift the pause
/// as three separate writes, so a failure after the first left the thread
/// paused with no run behind the pause: every send refused, and the same
/// command refused too because no move owned the pause (#180).
#[tokio::test]
async fn an_abort_that_cannot_finish_leaves_its_move_resumable() {
    use ai_crew_sync::store::migrate::{self, Direction};

    let h = require_db!("t_abort_atomic");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    enable_conversations(&h.pool, "acme").await;
    let team = team_id(&h.pool, "acme").await;
    let owner = connect_with_session(&h.base, &token, "impl").await;
    let convo = call(
        &owner,
        "create_conversation",
        json!({"title": "moving thread", "private": true}),
    )
    .await;
    let cid = convo["id"].as_str().unwrap().to_owned();
    let cuuid: Uuid = cid.parse().unwrap();

    // A move in flight: the thread paused under an open run, as `run`
    // leaves it while it copies.
    sqlx::query("UPDATE conversations SET write_paused_at = now() WHERE id = $1")
        .bind(cuuid)
        .execute(&h.pool)
        .await
        .unwrap();
    let (migration,): (Uuid,) = sqlx::query_as(
        "INSERT INTO conversation_migrations (team_id, conversation_id, direction, state)
         VALUES ($1, $2, 'to_jetstream', 'copying') RETURNING id",
    )
    .bind(team)
    .bind(cuuid)
    .fetch_one(&h.pool)
    .await
    .unwrap();
    let refused = call_expect_error(
        &owner,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "during the move", "request_id": request_id()}),
    )
    .await;
    assert!(refused.contains("paused"), "{refused}");

    // The abort fails on its last step, the one that reopens the thread.
    sqlx::query(
        "CREATE FUNCTION refuse_reopen() RETURNS trigger LANGUAGE plpgsql AS \
         $$ BEGIN RAISE EXCEPTION 'injected failure'; END $$",
    )
    .execute(&h.pool)
    .await
    .unwrap();
    sqlx::query(
        "CREATE TRIGGER refuse_reopen BEFORE UPDATE OF write_paused_at ON conversations
         FOR EACH ROW WHEN (OLD.write_paused_at IS NOT NULL AND NEW.write_paused_at IS NULL)
         EXECUTE FUNCTION refuse_reopen()",
    )
    .execute(&h.pool)
    .await
    .unwrap();
    assert!(
        migrate::abort(&h.pool, migration, "the copy failed")
            .await
            .is_err()
    );

    // Nothing of it stuck: the run still owns the pause, and the same
    // command resumes it instead of refusing the thread.
    let (state,): (String,) =
        sqlx::query_as("SELECT state FROM conversation_migrations WHERE id = $1")
            .bind(migration)
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert_eq!(
        state, "copying",
        "the run was failed without its pause lifted"
    );
    assert!(migrate::is_paused(&h.pool, cuuid).await.unwrap());
    let plans = migrate::plan(&h.pool, team, Direction::ToJetStream, &[cuuid])
        .await
        .unwrap();
    assert!(plans[0].blocked.is_none(), "{:?}", plans[0].blocked);
    assert!(plans[0].resuming, "an open run is resumed, not refused");

    // With the fault gone, the abort completes all of it at once.
    sqlx::query("DROP TRIGGER refuse_reopen ON conversations")
        .execute(&h.pool)
        .await
        .unwrap();
    migrate::abort(&h.pool, migration, "the copy failed")
        .await
        .unwrap();
    let (state,): (String,) =
        sqlx::query_as("SELECT state FROM conversation_migrations WHERE id = $1")
            .bind(migration)
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert_eq!(state, "failed");
    assert!(!migrate::is_paused(&h.pool, cuuid).await.unwrap());
    let plans = migrate::plan(&h.pool, team, Direction::ToJetStream, &[cuuid])
        .await
        .unwrap();
    assert!(plans[0].blocked.is_none(), "{:?}", plans[0].blocked);
    assert!(!plans[0].resuming);
    call(
        &owner,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "after the abort", "request_id": request_id()}),
    )
    .await;

    let _ = owner.cancel().await;
    h.shutdown().await;
}

/// An abort takes the thread's row before anything else, the order a send
/// and the cutover take, so an abort and a cutover of the same run by two
/// processes queue instead of deadlocking; and it only gives up on a run
/// that is still open (#180 review).
#[tokio::test]
async fn an_abort_takes_the_thread_first_and_leaves_a_settled_run_alone() {
    use ai_crew_sync::store::migrate;

    let h = require_db!("t_abort_lock_order");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    enable_conversations(&h.pool, "acme").await;
    let team = team_id(&h.pool, "acme").await;
    let owner = connect_with_session(&h.base, &token, "impl").await;
    let convo = call(
        &owner,
        "create_conversation",
        json!({"title": "moving thread", "private": true}),
    )
    .await;
    let cuuid: Uuid = convo["id"].as_str().unwrap().parse().unwrap();
    sqlx::query("UPDATE conversations SET write_paused_at = now() WHERE id = $1")
        .bind(cuuid)
        .execute(&h.pool)
        .await
        .unwrap();
    let (migration,): (Uuid,) = sqlx::query_as(
        "INSERT INTO conversation_migrations (team_id, conversation_id, direction, state)
         VALUES ($1, $2, 'to_jetstream', 'copying') RETURNING id",
    )
    .bind(team)
    .bind(cuuid)
    .fetch_one(&h.pool)
    .await
    .unwrap();

    // Someone holds the thread, as a send or a cutover does.
    let mut holder = h.pool.begin().await.unwrap();
    let holder_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")
        .fetch_one(&mut *holder)
        .await
        .unwrap();
    sqlx::query("SELECT id FROM conversations WHERE id = $1 FOR UPDATE")
        .bind(cuuid)
        .fetch_one(&mut *holder)
        .await
        .unwrap();
    let pool = h.pool.clone();
    let aborting =
        tokio::spawn(async move { migrate::abort(&pool, migration, "the copy failed").await });
    let mut parked = false;
    for _ in 0..400 {
        let waiting: bool = sqlx::query_scalar(
            "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE $1 = ANY(pg_blocking_pids(pid)))",
        )
        .bind(holder_pid)
        .fetch_one(&h.pool)
        .await
        .unwrap();
        if waiting {
            parked = true;
            break;
        }
        tokio::time::sleep(std::time::Duration::from_millis(25)).await;
    }
    assert!(parked, "the abort never waited on the thread");

    // Parked on the thread, the abort holds nothing a cutover would need
    // after it: the run's row is free.
    let mut probe = h.pool.begin().await.unwrap();
    let free =
        sqlx::query("SELECT id FROM conversation_migrations WHERE id = $1 FOR UPDATE NOWAIT")
            .bind(migration)
            .fetch_one(&mut *probe)
            .await;
    probe.rollback().await.unwrap();
    holder.rollback().await.unwrap();
    aborting.await.unwrap().unwrap();
    assert!(
        free.is_ok(),
        "the abort took the run before the thread: {:?}",
        free.err()
    );
    assert!(!migrate::is_paused(&h.pool, cuuid).await.unwrap());

    // A run another process already cut over is not failed after the fact.
    let (settled,): (Uuid,) = sqlx::query_as(
        "INSERT INTO conversation_migrations (team_id, conversation_id, direction, state)
         VALUES ($1, $2, 'to_jetstream', 'cut_over') RETURNING id",
    )
    .bind(team)
    .bind(cuuid)
    .fetch_one(&h.pool)
    .await
    .unwrap();
    migrate::abort(&h.pool, settled, "a late failure")
        .await
        .unwrap();
    let (state,): (String,) =
        sqlx::query_as("SELECT state FROM conversation_migrations WHERE id = $1")
            .bind(settled)
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert_eq!(state, "cut_over", "a settled run was rewritten as failed");

    let _ = owner.cancel().await;
    h.shutdown().await;
}

/// A reverse move that is given up on keeps the copies that verified. It
/// used to blank every body it had written back, verified or not, without
/// asking the broker, and a move to Postgres is what runs when the broker
/// is going bad: a verified copy can be the last one (#183 review).
#[tokio::test]
async fn a_reverse_abort_keeps_the_copies_that_verified() {
    use ai_crew_sync::store::migrate;

    let h = require_db!("t_reverse_abort");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    enable_conversations(&h.pool, "acme").await;
    let team = team_id(&h.pool, "acme").await;
    let owner = connect_with_session(&h.base, &token, "impl").await;
    let convo = call(
        &owner,
        "create_conversation",
        json!({"title": "coming home", "private": true}),
    )
    .await;
    let cuuid: Uuid = convo["id"].as_str().unwrap().parse().unwrap();
    let mut ids = Vec::new();
    for body in ["verified on the way back", "written but never verified"] {
        let sent = call(
            &owner,
            "send_conversation_message",
            json!({"conversation_id": convo["id"], "body": body, "request_id": request_id()}),
        )
        .await;
        ids.push(
            sent["message_id"]
                .as_str()
                .unwrap()
                .parse::<Uuid>()
                .unwrap(),
        );
    }

    // Both still broker-authoritative, both written back into their rows by
    // a move to Postgres that stopped before the cutover: one verified,
    // one not.
    sqlx::query("UPDATE conversation_messages SET backend = 'jetstream' WHERE id = ANY($1)")
        .bind(&ids)
        .execute(&h.pool)
        .await
        .unwrap();
    sqlx::query("UPDATE conversations SET write_paused_at = now() WHERE id = $1")
        .bind(cuuid)
        .execute(&h.pool)
        .await
        .unwrap();
    let (migration,): (Uuid,) = sqlx::query_as(
        "INSERT INTO conversation_migrations (team_id, conversation_id, direction, state)
         VALUES ($1, $2, 'to_postgres', 'copying') RETURNING id",
    )
    .bind(team)
    .bind(cuuid)
    .fetch_one(&h.pool)
    .await
    .unwrap();
    for (id, state) in [(ids[0], "verified"), (ids[1], "copied")] {
        sqlx::query(
            "INSERT INTO conversation_migration_items (migration_id, message_id, checksum, bytes, state)
             VALUES ($1, $2, 'sum', 1, $3)",
        )
        .bind(migration)
        .bind(id)
        .bind(state)
        .execute(&h.pool)
        .await
        .unwrap();
    }

    migrate::abort(&h.pool, migration, "the broker went away")
        .await
        .unwrap();
    let body_of = |id: Uuid| {
        let pool = h.pool.clone();
        async move {
            sqlx::query_scalar::<_, String>("SELECT body FROM conversation_messages WHERE id = $1")
                .bind(id)
                .fetch_one(&pool)
                .await
                .unwrap()
        }
    };
    assert_eq!(
        body_of(ids[0]).await,
        "verified on the way back",
        "a verified copy was thrown away"
    );
    assert_eq!(
        body_of(ids[1]).await,
        "",
        "an unverified copy must not be served as the body"
    );

    let _ = owner.cancel().await;
    h.shutdown().await;
}

/// The worker path's last attempt. A backend that keeps the body and never
/// confirms it must not end as `failed`: "we did not hear back" and "it is
/// not there" are different facts, and only one of them is a gap.
#[tokio::test]
async fn a_lost_confirmation_is_not_a_failure_when_the_backend_kept_it() {
    use ai_crew_sync::store::backend::{Faults, MessagingBackend, PostgresBackend};
    use ai_crew_sync::store::outbox::{self, Settled};

    let h = require_db!("t_lost_confirmations");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    let dani_token = seed_agent(&h.pool, "acme", "dani").await;
    enable_conversations(&h.pool, "acme").await;
    let owner = connect_with_session(&h.base, &token, "impl").await;
    let dani = connect_with_session(&h.base, &dani_token, "review").await;

    let convo = call(
        &owner,
        "create_conversation",
        json!({"title": "kept but unconfirmed", "private": true, "invite": ["dani/review"]}),
    )
    .await;
    let cid = convo["id"].as_str().unwrap().to_owned();
    call(&dani, "join_conversation", json!({"conversation_id": cid})).await;
    let cuuid: Uuid = cid.parse().unwrap();
    outbox::set_publication(&h.pool, cuuid, true).await.unwrap();
    let sent = call(
        &owner,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "written, never acknowledged",
               "request_id": request_id()}),
    )
    .await;
    let mid: Uuid = sent["message_id"].as_str().unwrap().parse().unwrap();

    // Every attempt writes the body and reports that it did not.
    let losing = PostgresBackend::with_faults(
        h.pool.clone(),
        Faults {
            lose_confirmation: true,
            ..Default::default()
        },
    );
    let mut last = None;
    for attempt in 1..=outbox::MAX_ATTEMPTS {
        sqlx::query("UPDATE conversation_outbox SET next_attempt_at = now()")
            .execute(&h.pool)
            .await
            .unwrap();
        last = outbox::run_once(&h.pool, &losing, "worker").await.unwrap();
        if attempt < outbox::MAX_ATTEMPTS {
            assert!(
                matches!(last, Some(Settled::Retrying { .. })),
                "attempt {attempt} retries: {last:?}"
            );
        }
    }

    // The last attempt asks instead of assuming. The backend has it, so the
    // message is stored and the receipts say when.
    assert_eq!(
        last,
        Some(Settled::Stored),
        "the backend kept the body; giving up would have recorded a gap that is not there"
    );
    let (state, locator): (String, Option<String>) = sqlx::query_as(
        "SELECT publication_state, canonical_locator FROM conversation_messages WHERE id = $1",
    )
    .bind(mid)
    .fetch_one(&h.pool)
    .await
    .unwrap();
    assert_eq!(state, "stored");
    let plain = PostgresBackend::new(h.pool.clone());
    assert_eq!(
        plain
            .fetch(
                &ai_crew_sync::store::backend::Locator(locator.clone().unwrap()),
                mid
            )
            .await
            .unwrap()
            .as_deref(),
        Some("written, never acknowledged"),
        "and it is the body that was sent"
    );
    let receipts = call(
        &owner,
        "get_message_receipts",
        json!({"message_id": sent["message_id"]}),
    )
    .await;
    assert!(
        receipts["receipts"][0]["stored_at"].is_string(),
        "stored once it was established, not before: {receipts}"
    );

    // A backend that genuinely does not have it still fails, visibly. The
    // fix must not turn every give-up into a success.
    let gone = call(
        &owner,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "never written anywhere",
               "request_id": request_id()}),
    )
    .await;
    let unreachable = PostgresBackend::with_faults(
        h.pool.clone(),
        Faults {
            retryable: outbox::MAX_ATTEMPTS as usize + 1,
            ..Default::default()
        },
    );
    let mut last = None;
    for _ in 1..=outbox::MAX_ATTEMPTS {
        sqlx::query("UPDATE conversation_outbox SET next_attempt_at = now()")
            .execute(&h.pool)
            .await
            .unwrap();
        last = outbox::run_once(&h.pool, &unreachable, "worker")
            .await
            .unwrap();
    }
    assert_eq!(last, Some(Settled::Failed));
    let (state,): (String,) =
        sqlx::query_as("SELECT publication_state FROM conversation_messages WHERE id = $1")
            .bind(
                gone["message_id"]
                    .as_str()
                    .unwrap()
                    .parse::<Uuid>()
                    .unwrap(),
            )
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert_eq!(
        state, "failed",
        "a body nobody has is a gap, and it is shown"
    );

    for c in [owner, dani] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// Losing the broker costs the bodies it holds, for as long as it is away,
/// and nothing else. Reproduced on a real deployment by deleting the
/// broker's volume: the thread stopped reading at all.
#[tokio::test]
async fn a_broker_that_is_gone_does_not_take_the_thread_with_it() {
    use ai_crew_sync::store::jetstream::{Config, JetStreamBackend};
    use ai_crew_sync::store::outbox;

    let h = require_db_broker!("t_broker_gone");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    let dani_token = seed_agent(&h.pool, "acme", "dani").await;
    enable_conversations(&h.pool, "acme").await;
    let team = team_id(&h.pool, "acme").await;

    let owner = connect_with_session(&h.base, &token, "impl").await;
    let dani = connect_with_session(&h.base, &dani_token, "review").await;

    // One thread that stays on Postgres, and one routed to the broker.
    let local = call(
        &owner,
        "create_conversation",
        json!({"title": "en postgres", "private": true}),
    )
    .await;
    call(
        &owner,
        "send_conversation_message",
        json!({"conversation_id": local["id"], "body": "still here", "request_id": request_id()}),
    )
    .await;

    sqlx::query("UPDATE teams SET default_backend = 'jetstream' WHERE id = $1")
        .bind(team)
        .execute(&h.pool)
        .await
        .unwrap();
    let config = Config::new(nats_url()).with_limits(1_000, 16 * 1024 * 1024);
    JetStreamBackend::provision(&config, team).await.unwrap();
    let backend = JetStreamBackend::connect(&config, team).await.unwrap();

    let convo = call(
        &owner,
        "create_conversation",
        json!({"title": "en el broker", "private": true, "invite": ["dani/review"]}),
    )
    .await;
    let cid = convo["id"].as_str().unwrap().to_owned();
    call(&dani, "join_conversation", json!({"conversation_id": cid})).await;
    let sent = call(
        &owner,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "en el broker", "request_id": request_id()}),
    )
    .await;
    assert_eq!(
        outbox::run_once(&h.pool, &backend, "worker").await.unwrap(),
        Some(outbox::Settled::Stored)
    );
    outbox::release_published_bodies(
        &h.pool,
        &ai_crew_sync::store::routing::Backends::with_jetstream(h.pool.clone(), config.clone()),
        Some(cid.parse().unwrap()),
        0,
    )
    .await
    .unwrap();

    // The broker loses everything. Not retention, not a tombstone: gone.
    JetStreamBackend::deprovision(&config, team).await.unwrap();

    // The thread still reads. The message keeps its place, its sender and
    // its sequence, and says why the body is not here.
    let page = call(&dani, "read_conversation", json!({"conversation_id": cid})).await;
    let msgs = page["messages"]
        .as_array()
        .expect("the page is still a page");
    assert_eq!(msgs.len(), 1, "the thread did not vanish: {page}");
    assert_eq!(msgs[0]["message_id"], sent["message_id"]);
    assert_eq!(msgs[0]["seq"], 1);
    assert_eq!(msgs[0]["from_address"], "joaquin/impl");
    assert_eq!(msgs[0]["body"], "");
    assert_eq!(
        msgs[0]["publication"], "stored",
        "it *is* stored; what is missing is this process's way to read it"
    );
    assert!(
        msgs[0]["unavailable"]
            .as_str()
            .unwrap()
            .contains("cannot be reached"),
        "and it says so: {}",
        msgs[0]
    );

    // Its receipts survive, and so does the rest of the bus.
    let receipts = call(
        &owner,
        "get_message_receipts",
        json!({"message_id": sent["message_id"]}),
    )
    .await;
    assert_eq!(receipts["total"], 1, "{receipts}");
    let still = call(
        &owner,
        "read_conversation",
        json!({"conversation_id": local["id"]}),
    )
    .await;
    assert_eq!(
        still["messages"][0]["body"], "still here",
        "a thread on Postgres is untouched by the broker's trouble"
    );

    // And a send is still accepted: it queues, as it does for any outage.
    let after = call(
        &owner,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "después", "request_id": request_id()}),
    )
    .await;
    assert_eq!(after["stored"], false, "{after}");

    for c in [owner, dani] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// A claim has to mean something on the way out too. Found on a deployment:
/// anyone on the team could mark a task done while its holder was still
/// working, and the holder learned about it from a refused renewal.
#[tokio::test]
async fn completing_a_task_respects_whoever_holds_it() {
    let h = require_db!("t_complete_claim");
    let owner = seed_agent(&h.pool, "acme", "joaquin").await;
    let holder = seed_agent(&h.pool, "acme", "marta").await;
    let other = seed_agent(&h.pool, "acme", "dani").await;
    let o = connect(&h.base, &owner).await;
    let m = connect(&h.base, &holder).await;
    let d = connect(&h.base, &other).await;

    call(
        &o,
        "create_task",
        json!({"key": "suya", "title": "el trabajo de marta"}),
    )
    .await;
    let claimed = call(
        &m,
        "claim_task",
        json!({"key": "suya", "lease_seconds": 300}),
    )
    .await;
    assert_eq!(claimed["claimed"], true);

    // The holder is working and the lease is live.
    let err = call_expect_error(&d, "complete_task", json!({"key": "suya"})).await;
    assert!(err.contains("held by marta"), "{err}");
    assert!(
        err.contains("end work somebody else is doing"),
        "and it says why: {err}"
    );
    let still = call(&o, "get_task", json!({"key": "suya"})).await;
    assert_eq!(
        still["task"]["status"], "claimed",
        "nothing was written: {still}"
    );

    // Its holder finishes it.
    let done = call(
        &m,
        "complete_task",
        json!({"key": "suya", "result": "hecho"}),
    )
    .await;
    assert_eq!(done["status"], "done");

    // An unclaimed task is anyone's to finish: nobody's work is ended.
    call(
        &o,
        "create_task",
        json!({"key": "libre", "title": "de nadie"}),
    )
    .await;
    let done = call(&d, "complete_task", json!({"key": "libre"})).await;
    assert_eq!(done["status"], "done", "{done}");

    // And an expired lease is fair game, which is what a lease is for.
    call(
        &o,
        "create_task",
        json!({"key": "caducada", "title": "abandonada"}),
    )
    .await;
    call(
        &m,
        "claim_task",
        json!({"key": "caducada", "lease_seconds": 60}),
    )
    .await;
    sqlx::query(
        "UPDATE tasks SET lease_expires_at = now() - interval '1 minute' WHERE key = 'caducada'",
    )
    .execute(&h.pool)
    .await
    .unwrap();
    let done = call(&d, "complete_task", json!({"key": "caducada"})).await;
    assert_eq!(
        done["status"], "done",
        "a claim nobody renewed does not hold the task for ever: {done}"
    );

    for c in [o, m, d] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// Every task write is fenced by the session epoch, not only the claim.
/// Found in review: a context admitted before a resume could still complete
/// the replacement window's work, because the holder predicate matches the
/// agent and the label, which a resumed window shares.
#[tokio::test]
async fn a_replaced_window_cannot_finish_the_work_of_the_one_that_replaced_it() {
    use ai_crew_sync::store::tasks;

    let h = require_db!("t_task_epoch_fence");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    let agent = connect(&h.base, &token).await;
    let cred = call(&agent, "register_session", json!({"session": "obrero"})).await;
    let window = connect(&h.base, cred["session_token"].as_str().unwrap()).await;

    call(
        &window,
        "create_task",
        json!({"key": "suya", "title": "en curso"}),
    )
    .await;
    let claimed = call(
        &window,
        "claim_task",
        json!({"key": "suya", "lease_seconds": 600}),
    )
    .await;
    assert_eq!(claimed["claimed"], true);

    // The context that connection was admitted with, kept while the window
    // is resumed by the process that took over.
    let stale = ai_crew_sync::auth::AuthCtx {
        agent_id: sqlx::query_scalar::<_, Uuid>("SELECT id FROM agents WHERE name = 'joaquin'")
            .fetch_one(&h.pool)
            .await
            .unwrap(),
        agent_name: "joaquin".into(),
        team_id: team_id(&h.pool, "acme").await,
        team_slug: "acme".into(),
        session: "obrero".into(),
        session_id: Some(cred["session_id"].as_str().unwrap().parse().unwrap()),
        session_epoch: Some(cred["epoch"].as_i64().unwrap()),
        token_id: None,
    };
    let resumed = call(&window, "resume_session", json!({})).await;
    assert_eq!(resumed["epoch"], 2);

    // Same agent, same label, replaced connection. Every write is refused.
    for (name, result) in [
        (
            "complete",
            tasks::complete_task(&h.pool, &stale, "suya", Some("no soy yo".into()))
                .await
                .err(),
        ),
        (
            "renew",
            tasks::renew_lease(&h.pool, &stale, "suya", Some(600))
                .await
                .err(),
        ),
        (
            "release",
            tasks::release_task(&h.pool, &stale, "suya").await.err(),
        ),
        (
            "claim",
            tasks::claim_task(&h.pool, &stale, "suya", Some(600))
                .await
                .err(),
        ),
    ] {
        let err = result
            .unwrap_or_else(|| panic!("{name} accepted a replaced connection"))
            .to_string();
        assert!(err.contains("stale"), "{name}: {err}");
        assert!(err.contains("Nothing was written"), "{name}: {err}");
    }

    // The resume rotated the secret, so the live window is the one holding
    // the new credential.
    let live = connect(&h.base, resumed["session_token"].as_str().unwrap()).await;
    let still = call(&live, "get_task", json!({"key": "suya"})).await;
    assert_eq!(
        still["task"]["status"], "claimed",
        "the task is still the live window's: {still}"
    );

    // And that window finishes it.
    let done = call(
        &live,
        "complete_task",
        json!({"key": "suya", "result": "hecho"}),
    )
    .await;
    assert_eq!(done["status"], "done", "{done}");

    for c in [agent, window, live] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// A path this server does not serve is a path, not a credential problem.
/// Found on the deployment: a mistyped URL answered "missing bearer token",
/// and a mistyped /admin path told an operator holding a perfectly good
/// credential that it was invalid or revoked.
#[tokio::test]
async fn a_mistyped_path_does_not_blame_the_credential() {
    let h = require_db!("t_unknown_paths");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    let client = reqwest::Client::new();

    for (path, bearer) in [
        ("/pepito", None),
        ("/pepito", Some(token.as_str())),
        ("/admin/no-existe", None),
        ("/dashboard/nope", None),
    ] {
        let mut req = client.get(format!("{}{path}", h.base));
        if let Some(b) = bearer {
            req = req.bearer_auth(b);
        }
        let resp = req.send().await.unwrap();
        let status = resp.status();
        let body = resp.text().await.unwrap_or_default();
        assert_eq!(
            status,
            404,
            "{path} (bearer: {}) answered {status}: {body}",
            bearer.is_some()
        );
        assert!(
            !body.contains("bearer") && !body.contains("revoked"),
            "{path} blamed the credential: {body}"
        );
        assert!(
            body.contains("/mcp"),
            "and it says what this server does serve: {body}"
        );
    }

    // A query string can carry a credential, and an error body travels: it
    // is pasted into issues and scraped out of logs. The 404 names the path
    // and nothing else.
    let resp = client
        .get(format!(
            "{}/admin/not-a-route?token=acs_do_not_echo_me&other=keep",
            h.base
        ))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 404);
    let body = resp.text().await.unwrap_or_default();
    assert!(
        !body.contains("do_not_echo_me") && !body.contains("token="),
        "the 404 repeated a query credential: {body}"
    );
    assert!(body.contains("/admin/not-a-route"), "{body}");

    // Anything under /mcp is the MCP endpoint's own namespace, and that one
    // does ask for a token before it says anything at all.
    let resp = client
        .get(format!("{}/mcp/extra", h.base))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 401, "under /mcp, authentication comes first");

    // The real endpoints still guard themselves.
    let resp = client
        .post(format!("{}/mcp", h.base))
        .json(&json!({"jsonrpc":"2.0","id":1,"method":"tools/list"}))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 401, "/mcp without a token is still refused");
    let resp = client
        .post(format!("{}/mcp", h.base))
        .bearer_auth("acs_0000000000000000000000000000000000000000000000000000000000000000")
        .json(&json!({"jsonrpc":"2.0","id":1,"method":"tools/list"}))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 401, "/mcp with a bad token is still refused");

    let c = connect(&h.base, &token).await;
    let me = call(&c, "whoami", json!({})).await;
    assert_eq!(me["agent"], "joaquin", "and a good one still works");
    let _ = c.cancel().await;

    h.shutdown().await;
}

/// The rest of a window's own state is fenced too. A replaced connection
/// cannot put back the lock its replacement holds, cannot advance the live
/// window's read cursor past messages it never saw, and cannot pull
/// references off the live window's inbox.
#[tokio::test]
async fn a_replaced_window_cannot_act_as_the_one_that_replaced_it() {
    use ai_crew_sync::store::{locks, messaging};

    let h = require_db!("t_window_state_fence");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    let dani_token = seed_agent(&h.pool, "acme", "dani").await;
    let agent = connect(&h.base, &token).await;
    let cred = call(&agent, "register_session", json!({"session": "obrero"})).await;
    let window = connect(&h.base, cred["session_token"].as_str().unwrap()).await;
    let dani = connect(&h.base, &dani_token).await;

    let got = call(
        &window,
        "acquire_lock",
        json!({"name": "deploy", "ttl_seconds": 300}),
    )
    .await;
    assert_eq!(got["acquired"], true);
    // A direct message the live window has not read yet.
    call(
        &dani,
        "post_message",
        json!({"to": "joaquin/obrero", "body": "para la ventana viva"}),
    )
    .await;

    let stale = ai_crew_sync::auth::AuthCtx {
        agent_id: sqlx::query_scalar::<_, Uuid>("SELECT id FROM agents WHERE name = 'joaquin'")
            .fetch_one(&h.pool)
            .await
            .unwrap(),
        agent_name: "joaquin".into(),
        team_id: team_id(&h.pool, "acme").await,
        team_slug: "acme".into(),
        session: "obrero".into(),
        session_id: Some(cred["session_id"].as_str().unwrap().parse().unwrap()),
        session_epoch: Some(cred["epoch"].as_i64().unwrap()),
        token_id: None,
    };
    let resumed = call(&window, "resume_session", json!({})).await;
    assert_eq!(resumed["epoch"], 2);

    let err = locks::release_lock(&h.pool, &stale, "deploy")
        .await
        .expect_err("a replaced connection released the live window's lock")
        .to_string();
    assert!(err.contains("stale"), "{err}");

    let err = messaging::read_messages(
        &h.pool,
        &stale,
        messaging::ReadInput {
            scope: String::new(),
            only_new: true,
            limit: 50,
            all_sessions: false,
        },
    )
    .await
    .expect_err("a replaced connection advanced the live window's cursor")
    .to_string();
    assert!(err.contains("stale"), "{err}");

    // The live window still holds the lock and still sees its message.
    let live = connect(&h.base, resumed["session_token"].as_str().unwrap()).await;
    let locks_now = call(&live, "list_locks", json!({})).await;
    assert!(
        locks_now["locks"]
            .as_array()
            .unwrap()
            .iter()
            .any(|l| l["name"] == "deploy"),
        "the lock is gone: {locks_now}"
    );
    let unread = call(&live, "read_messages", json!({})).await;
    assert!(
        unread["messages"]
            .as_array()
            .unwrap()
            .iter()
            .any(|m| m["body"] == "para la ventana viva"),
        "the live window lost a message to a cursor it never moved: {unread}"
    );

    for c in [agent, window, dani, live] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// And the inbox: a replaced connection does not pull the live window's
/// references off the consumer.
#[tokio::test]
async fn a_replaced_window_cannot_fetch_the_inbox_of_the_one_that_replaced_it() {
    use ai_crew_sync::store::jetstream::Config;
    use ai_crew_sync::store::{inbox, routing::Backends};

    let h = require_db_broker!("t_inbox_epoch_fence");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    enable_conversations(&h.pool, "acme").await;
    let agent = connect(&h.base, &token).await;
    let cred = call(&agent, "register_session", json!({"session": "lector"})).await;
    let window = connect(&h.base, cred["session_token"].as_str().unwrap()).await;

    let stale = ai_crew_sync::auth::AuthCtx {
        agent_id: sqlx::query_scalar::<_, Uuid>("SELECT id FROM agents WHERE name = 'joaquin'")
            .fetch_one(&h.pool)
            .await
            .unwrap(),
        agent_name: "joaquin".into(),
        team_id: team_id(&h.pool, "acme").await,
        team_slug: "acme".into(),
        session: "lector".into(),
        session_id: Some(cred["session_id"].as_str().unwrap().parse().unwrap()),
        session_epoch: Some(cred["epoch"].as_i64().unwrap()),
        token_id: None,
    };
    let resumed = call(&window, "resume_session", json!({})).await;
    assert_eq!(resumed["epoch"], 2);

    let backends = Backends::with_jetstream(h.pool.clone(), Config::new(nats_url()));
    let err = inbox::fetch(&h.pool, &backends, &stale, Some(5))
        .await
        .expect_err("a replaced connection fetched the live window's inbox")
        .to_string();
    assert!(err.contains("stale"), "{err}");

    for c in [agent, window] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// The attachment cap is decided under the parent's row lock. Counted
/// outside the transaction, ten uploads racing for the last slots all saw
/// room and all committed.
#[tokio::test]
async fn the_attachment_cap_holds_under_a_race() {
    use base64::Engine;
    let h = require_db!("t_attachment_cap_race");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    let client = Arc::new(connect(&h.base, &token).await);
    call(
        &client,
        "create_task",
        json!({"key": "adjuntos", "title": "muchos"}),
    )
    .await;

    let data = base64::engine::general_purpose::STANDARD.encode(b"x");
    let mut handles = Vec::new();
    for i in 0..12 {
        let c = Arc::clone(&client);
        let data = data.clone();
        handles.push(tokio::spawn(async move {
            let args: serde_json::Map<String, Value> = serde_json::from_value(json!({
                "task": "adjuntos", "filename": format!("f{i}.txt"), "data_base64": data
            }))
            .unwrap();
            c.call_tool(CallToolRequestParams::new("attach_file".to_string()).with_arguments(args))
                .await
                .map(|r| r.is_error != Some(true))
                .unwrap_or(false)
        }));
    }
    let mut ok = 0;
    for h in handles {
        if h.await.unwrap() {
            ok += 1;
        }
    }
    let (stored,): (i64,) = sqlx::query_as("SELECT count(*) FROM attachments")
        .fetch_one(&h.pool)
        .await
        .unwrap();
    assert_eq!(
        stored, 8,
        "the cap is eight, whatever the race: {stored} stored"
    );
    assert_eq!(ok, 8, "and exactly eight callers were told yes");

    let _ = Arc::try_unwrap(client).ok().map(|c| c.cancel());
    h.shutdown().await;
}

/// A live label is refused even when the refusal spells a missing method.
/// The conversation id here hashes to the label `s-32601f03e877`; the bus
/// quotes it when a second process tries to register it without the
/// window's credential, and the proxy once read that "-32601" as "this bus
/// has no register_session" and carried on label-only with the parent
/// token — the one case the conflict exists to stop.
#[tokio::test]
async fn a_live_label_is_refused_even_when_it_spells_a_missing_method() {
    let h = require_db!("t_proxy_32601");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    let profiles = [("acme", "acme", "joaquin", token.as_str())];
    // Two config dirs: the second process has no binding to resume from,
    // so it can only ask the bus to register the label afresh.
    let dir_a = proxy_config_dir(&h.base, &profiles);
    let dir_b = proxy_config_dir(&h.base, &profiles);
    let mut repos = Vec::new();
    for dir in [&dir_a, &dir_b] {
        let repo = dir.join("repo");
        std::fs::create_dir_all(&repo).unwrap();
        std::fs::write(repo.join(".acs.toml"), "profile = \"acme\"\n").unwrap();
        repos.push(repo);
    }

    let holder = spawn_proxy(&dir_a, &repos[0], &["--host-session", "conv-1714608"], &[]).await;
    let s = call(&holder, "session_status", json!({})).await;
    assert_eq!(
        s["session"], "s-32601f03e877",
        "the fixture id moved; pick another: {s}"
    );
    assert_eq!(s["agent"], "joaquin");

    let intruder = spawn_proxy(&dir_b, &repos[1], &["--host-session", "conv-1714608"], &[]).await;
    let s2 = call(&intruder, "session_status", json!({})).await;
    assert!(
        s2["agent"].is_null(),
        "the second process is not connected: {s2}"
    );
    let reason = s2["error"].as_str().unwrap_or_default();
    assert!(reason.contains("still live"), "{s2}");
    let err = call_expect_error(&intruder, "whoami", json!({})).await;
    assert!(err.contains("not connected"), "{err}");

    // The window that owns the label is untouched.
    assert_eq!(call(&holder, "whoami", json!({})).await["agent"], "joaquin");
    for c in [holder, intruder] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// Route a team's new conversations to JetStream the way an operator does:
/// the flag on the team plus provisioned streams. The harness server has the
/// broker configured whenever `require_db_broker!` was used.
async fn route_team_to_jetstream(h: &Harness, team: &str) {
    use ai_crew_sync::store::jetstream::{Config, JetStreamBackend};
    let id = team_id(&h.pool, team).await;
    sqlx::query("UPDATE teams SET default_backend = 'jetstream' WHERE id = $1")
        .bind(id)
        .execute(&h.pool)
        .await
        .unwrap();
    let config = Config::new(nats_url()).with_limits(1_000, 16 * 1024 * 1024);
    JetStreamBackend::provision(&config, id).await.unwrap();
}

/// Re-admitting a removed member is a moderator decision the bus records as
/// 'member.readmit'. The audit table's check never listed that action, so
/// the invitation rolled back with a bare "database error" and the member
/// stayed out (#125). The rule the readmission keeps: nothing said before
/// it comes back, however the inviter asks.
#[tokio::test]
async fn a_removed_member_is_readmitted_without_its_old_history() {
    for backend in ["postgres", "jetstream"] {
        let schema = format!("t_readmit_{backend}");
        let h = require_db_broker!(&schema);
        let token = seed_agent(&h.pool, "acme", "joaquin").await;
        let dani_token = seed_agent(&h.pool, "acme", "dani").await;
        enable_conversations(&h.pool, "acme").await;
        if backend == "jetstream" {
            route_team_to_jetstream(&h, "acme").await;
        }
        let owner = connect_with_session(&h.base, &token, "impl").await;
        let dani = connect_with_session(&h.base, &dani_token, "core").await;

        let convo = call(
            &owner,
            "create_conversation",
            json!({"title": "readmission", "private": true}),
        )
        .await;
        let cid = convo["id"].as_str().unwrap().to_owned();
        let send = |body: &'static str| {
            let owner = &owner;
            let cid = cid.clone();
            async move {
                call(
                    owner,
                    "send_conversation_message",
                    json!({"conversation_id": cid, "body": body, "request_id": request_id()}),
                )
                .await["message_id"]
                    .as_str()
                    .unwrap()
                    .to_owned()
            }
        };
        let before = send("before the removal").await;
        call(
            &owner,
            "invite_to_conversation",
            json!({"conversation_id": cid, "address": "dani/core", "history_from_start": true}),
        )
        .await;
        call(&dani, "join_conversation", json!({"conversation_id": cid})).await;
        let seen = call(
            &dani,
            "get_conversation_message",
            json!({"message_id": before}),
        )
        .await;
        assert_eq!(seen["body"], "before the removal", "[{backend}] {seen}");

        call(
            &owner,
            "remove_conversation_member",
            json!({"conversation_id": cid, "address": "dani/core"}),
        )
        .await;
        let meanwhile = send("said while removed").await;

        // The readmission goes through, whatever history the inviter asks
        // for, and it is recorded as what it is.
        call(
            &owner,
            "invite_to_conversation",
            json!({"conversation_id": cid, "address": "dani/core", "history_from_start": true}),
        )
        .await;
        let cid_uuid: Uuid = cid.parse().unwrap();
        let (state, from_seq): (String, Option<i64>) = sqlx::query_as(
            "SELECT state, history_from_seq FROM conversation_memberships
              WHERE conversation_id = $1 AND session = 'core'",
        )
        .bind(cid_uuid)
        .fetch_one(&h.pool)
        .await
        .unwrap();
        assert_eq!(state, "invited", "[{backend}]");
        assert_eq!(
            from_seq,
            Some(2),
            "[{backend}] a readmission starts here, not at the start"
        );
        let (readmits,): (i64,) = sqlx::query_as(
            "SELECT count(*) FROM conversation_audit
              WHERE conversation_id = $1 AND action = 'member.readmit'",
        )
        .bind(cid_uuid)
        .fetch_one(&h.pool)
        .await
        .unwrap();
        assert_eq!(readmits, 1, "[{backend}] the readmission is audited as one");

        call(&dani, "join_conversation", json!({"conversation_id": cid})).await;
        for hidden in [&before, &meanwhile] {
            let err = call_expect_error(
                &dani,
                "get_conversation_message",
                json!({"message_id": hidden}),
            )
            .await;
            assert!(!err.contains("database error"), "[{backend}] {err}");
        }
        let after = send("after the readmission").await;
        let seen = call(
            &dani,
            "get_conversation_message",
            json!({"message_id": after}),
        )
        .await;
        assert_eq!(seen["body"], "after the readmission", "[{backend}] {seen}");
        let read = call(&dani, "read_conversation", json!({"conversation_id": cid})).await;
        assert_eq!(
            read["messages"].as_array().map(Vec::len),
            Some(1),
            "[{backend}] only what was said after the readmission: {read}"
        );

        for c in [owner, dani] {
            let _ = c.cancel().await;
        }
        h.shutdown().await;
    }
}

/// A moderator admitted without the past cannot hand that past to anyone:
/// not to another agent, not to another window of its own agent. Its grant
/// is clamped to its own floor, for bodies and for receipts alike, and the
/// audit row keeps what was asked. An inviter that can read the start still
/// grants it (#124).
#[tokio::test]
async fn a_late_moderator_cannot_grant_history_it_cannot_read() {
    for backend in ["postgres", "jetstream"] {
        let schema = format!("t_late_moderator_{backend}");
        let h = require_db_broker!(&schema);
        let owner_token = seed_agent(&h.pool, "acme", "joaquin").await;
        let reader_token = seed_agent(&h.pool, "acme", "dani").await;
        let outsider_token = seed_agent(&h.pool, "acme", "marta").await;
        let full_token = seed_agent(&h.pool, "acme", "luis").await;
        enable_conversations(&h.pool, "acme").await;
        if backend == "jetstream" {
            route_team_to_jetstream(&h, "acme").await;
        }
        let owner = connect_with_session(&h.base, &owner_token, "owner").await;
        let reader = connect_with_session(&h.base, &reader_token, "reader").await;
        let outsider = connect_with_session(&h.base, &outsider_token, "outsider").await;
        let sibling = connect_with_session(&h.base, &reader_token, "other").await;
        let full = connect_with_session(&h.base, &full_token, "full").await;

        let convo = call(
            &owner,
            "create_conversation",
            json!({"title": "late moderator", "private": true}),
        )
        .await;
        let cid = convo["id"].as_str().unwrap().to_owned();
        let withheld = call(
            &owner,
            "send_conversation_message",
            json!({"conversation_id": cid, "body": "history withheld from later moderator",
                   "request_id": request_id()}),
        )
        .await["message_id"]
            .as_str()
            .unwrap()
            .to_owned();

        // A moderator, admitted from here on.
        call(
            &owner,
            "invite_to_conversation",
            json!({"conversation_id": cid, "address": "dani/reader", "role": "moderator"}),
        )
        .await;
        call(
            &reader,
            "join_conversation",
            json!({"conversation_id": cid}),
        )
        .await;
        let err = call_expect_error(
            &reader,
            "get_conversation_message",
            json!({"message_id": withheld}),
        )
        .await;
        assert!(!err.contains("database error"), "[{backend}] {err}");

        // It invites another agent and another window of its own agent,
        // asking for the whole history. Both invitations go through, with
        // the moderator's own floor.
        for address in ["marta/outsider", "dani/other"] {
            call(
                &reader,
                "invite_to_conversation",
                json!({"conversation_id": cid, "address": address, "history_from_start": true}),
            )
            .await;
        }
        for (address, window) in [("marta/outsider", &outsider), ("dani/other", &sibling)] {
            call(window, "join_conversation", json!({"conversation_id": cid})).await;
            let err = call_expect_error(
                window,
                "get_conversation_message",
                json!({"message_id": withheld}),
            )
            .await;
            assert!(
                !err.contains("database error"),
                "[{backend}] {address} body: {err}"
            );
            let err = call_expect_error(
                window,
                "get_message_receipts",
                json!({"message_id": withheld}),
            )
            .await;
            assert!(
                !err.contains("database error"),
                "[{backend}] {address} receipts: {err}"
            );
            let read = call(window, "read_conversation", json!({"conversation_id": cid})).await;
            assert_eq!(
                read["messages"].as_array().map(Vec::len),
                Some(0),
                "[{backend}] {address} reads nothing from before the moderator: {read}"
            );
        }
        let cid_uuid: Uuid = cid.parse().unwrap();
        let floors: Vec<(String, Option<i64>)> = sqlx::query_as(
            "SELECT session, history_from_seq FROM conversation_memberships
              WHERE conversation_id = $1 AND session IN ('reader', 'outsider', 'other')
              ORDER BY session",
        )
        .bind(cid_uuid)
        .fetch_all(&h.pool)
        .await
        .unwrap();
        assert!(
            floors.iter().all(|(_, f)| *f == Some(1)),
            "[{backend}] every seat the moderator handed out starts where it did: {floors:?}"
        );
        let (requested,): (i64,) = sqlx::query_as(
            "SELECT count(*) FROM conversation_audit
              WHERE conversation_id = $1 AND action = 'member.invite'
                AND (detail->>'history_from_start_requested')::boolean
                AND (detail->>'history_from_seq')::bigint = 1",
        )
        .bind(cid_uuid)
        .fetch_one(&h.pool)
        .await
        .unwrap();
        assert_eq!(
            requested, 2,
            "[{backend}] the audit keeps what was asked and what was given"
        );

        // The owner can read the start, so the owner can grant it.
        call(
            &owner,
            "invite_to_conversation",
            json!({"conversation_id": cid, "address": "luis/full", "history_from_start": true}),
        )
        .await;
        call(&full, "join_conversation", json!({"conversation_id": cid})).await;
        let seen = call(
            &full,
            "get_conversation_message",
            json!({"message_id": withheld}),
        )
        .await;
        assert_eq!(
            seen["body"], "history withheld from later moderator",
            "[{backend}] {seen}"
        );

        // A seat that had the whole history and left does not get it back
        // from an inviter who cannot read it: the floor is decided now.
        call(&full, "leave_conversation", json!({"conversation_id": cid})).await;
        call(
            &reader,
            "invite_to_conversation",
            json!({"conversation_id": cid, "address": "luis/full", "history_from_start": true}),
        )
        .await;
        call(&full, "join_conversation", json!({"conversation_id": cid})).await;
        let err = call_expect_error(
            &full,
            "get_conversation_message",
            json!({"message_id": withheld}),
        )
        .await;
        assert!(
            !err.contains("database error"),
            "[{backend}] left and back: {err}"
        );
        let (floor,): (Option<i64>,) = sqlx::query_as(
            "SELECT history_from_seq FROM conversation_memberships
              WHERE conversation_id = $1 AND session = 'full'",
        )
        .bind(cid_uuid)
        .fetch_one(&h.pool)
        .await
        .unwrap();
        assert_eq!(
            floor,
            Some(1),
            "[{backend}] the old floor did not come back"
        );

        for c in [owner, reader, outsider, sibling, full] {
            let _ = c.cancel().await;
        }
        h.shutdown().await;
    }
}

/// A transfer to a window that already has a seat changes nothing: it is
/// refused before anything is written, and the target keeps its role, its
/// history boundary and its credential binding while the source stays. A
/// window that holds an invitation, or that was removed, is not a target
/// either. A window that left is, and then the handoff completes (#126).
#[tokio::test]
async fn a_transfer_to_a_window_with_a_seat_changes_nothing() {
    for backend in ["postgres", "jetstream"] {
        let schema = format!("t_transfer_target_{backend}");
        let h = require_db_broker!(&schema);
        let token = seed_agent(&h.pool, "acme", "joaquin").await;
        enable_conversations(&h.pool, "acme").await;
        if backend == "jetstream" {
            route_team_to_jetstream(&h, "acme").await;
        }
        // Two registered windows of the same agent, each with its own
        // credential, plus a third that only ever gets invited.
        let agent = connect(&h.base, &token).await;
        let owner_cred = call(&agent, "register_session", json!({"session": "owner"})).await;
        let owner = connect(&h.base, owner_cred["session_token"].as_str().unwrap()).await;
        let next_cred = call(&agent, "register_session", json!({"session": "next"})).await;
        let next = connect(&h.base, next_cred["session_token"].as_str().unwrap()).await;

        let convo = call(
            &owner,
            "create_conversation",
            json!({"title": "handoff", "private": true}),
        )
        .await;
        let cid = convo["id"].as_str().unwrap().to_owned();
        let cid_uuid: Uuid = cid.parse().unwrap();
        let earlier = call(
            &owner,
            "send_conversation_message",
            json!({"conversation_id": cid, "body": "before the observer arrived",
                   "request_id": request_id()}),
        )
        .await["message_id"]
            .as_str()
            .unwrap()
            .to_owned();
        call(
            &owner,
            "invite_to_conversation",
            json!({"conversation_id": cid, "address": "joaquin/next", "role": "observer"}),
        )
        .await;
        call(&next, "join_conversation", json!({"conversation_id": cid})).await;
        let err = call_expect_error(
            &next,
            "get_conversation_message",
            json!({"message_id": earlier}),
        )
        .await;
        assert!(!err.contains("database error"), "[{backend}] {err}");

        // A message sent while the observer is seated has receipts for the
        // seats of that moment; a refused transfer must leave them as they
        // are, denominator included.
        let seated = call(
            &owner,
            "send_conversation_message",
            json!({"conversation_id": cid, "body": "while the observer is here",
                   "request_id": request_id()}),
        )
        .await["message_id"]
            .as_str()
            .unwrap()
            .to_owned();
        let receipts_before = call(
            &owner,
            "get_message_receipts",
            json!({"message_id": seated}),
        )
        .await;
        assert!(
            receipts_before["total"].as_u64() >= Some(1),
            "[{backend}] {receipts_before}"
        );

        let seat = |session: &'static str| {
            let pool = h.pool.clone();
            async move {
                sqlx::query_as::<_, (String, String, Option<i64>, Option<Uuid>, Option<Uuid>)>(
                    "SELECT role, state, history_from_seq, session_id, superseded_by
                       FROM conversation_memberships
                      WHERE conversation_id = $1 AND session = $2",
                )
                .bind(cid_uuid)
                .bind(session)
                .fetch_one(&pool)
                .await
                .unwrap()
            }
        };
        let next_before = seat("next").await;
        assert_eq!(next_before.0, "observer", "[{backend}]");
        assert_eq!(next_before.2, Some(1), "[{backend}]");
        assert!(
            next_before.3.is_some(),
            "[{backend}] the seat is bound to the window"
        );

        // Already seated: refused, and nothing moved.
        let err = call_expect_error(
            &owner,
            "transfer_membership",
            json!({"conversation_id": cid, "to": "joaquin/next"}),
        )
        .await;
        assert!(err.contains("seat of its own"), "[{backend}] {err}");
        assert!(err.contains("nothing was written"), "[{backend}] {err}");
        assert_eq!(
            seat("next").await,
            next_before,
            "[{backend}] the target is untouched"
        );
        let source = seat("owner").await;
        assert_eq!(
            source.1, "active",
            "[{backend}] the source is not superseded"
        );
        assert!(source.4.is_none(), "[{backend}]");
        let err = call_expect_error(
            &next,
            "get_conversation_message",
            json!({"message_id": earlier}),
        )
        .await;
        assert!(
            !err.contains("database error"),
            "[{backend}] still withheld: {err}"
        );
        let receipts_after = call(
            &owner,
            "get_message_receipts",
            json!({"message_id": seated}),
        )
        .await;
        assert_eq!(
            receipts_after, receipts_before,
            "[{backend}] the receipts and their denominator are untouched"
        );
        let err =
            call_expect_error(&next, "join_conversation", json!({"conversation_id": cid})).await;
        assert!(
            err.contains("already in this conversation"),
            "[{backend}] {err}"
        );

        // Merely invited: refused too.
        call(
            &owner,
            "invite_to_conversation",
            json!({"conversation_id": cid, "address": "joaquin/third"}),
        )
        .await;
        let err = call_expect_error(
            &owner,
            "transfer_membership",
            json!({"conversation_id": cid, "to": "joaquin/third"}),
        )
        .await;
        assert!(
            err.contains("already holds an invitation"),
            "[{backend}] {err}"
        );

        // Removed: a transfer does not undo a removal.
        call(
            &owner,
            "remove_conversation_member",
            json!({"conversation_id": cid, "address": "joaquin/next"}),
        )
        .await;
        let err = call_expect_error(
            &owner,
            "transfer_membership",
            json!({"conversation_id": cid, "to": "joaquin/next"}),
        )
        .await;
        assert!(err.contains("does not undo a removal"), "[{backend}] {err}");
        assert_eq!(seat("next").await.1, "removed", "[{backend}]");

        // Re-admitted, then gone of its own accord: that seat can be offered
        // the handoff, and accepting it completes the transfer.
        call(
            &owner,
            "invite_to_conversation",
            json!({"conversation_id": cid, "address": "joaquin/next"}),
        )
        .await;
        call(&next, "join_conversation", json!({"conversation_id": cid})).await;
        call(&next, "leave_conversation", json!({"conversation_id": cid})).await;
        let proposal = call(
            &owner,
            "transfer_membership",
            json!({"conversation_id": cid, "to": "joaquin/next"}),
        )
        .await;
        assert_eq!(proposal["state"], "proposed", "[{backend}] {proposal}");
        call(&next, "join_conversation", json!({"conversation_id": cid})).await;
        let seen = call(
            &next,
            "get_conversation_message",
            json!({"message_id": earlier}),
        )
        .await;
        assert_eq!(
            seen["body"], "before the observer arrived",
            "[{backend}] the seat's history came with it: {seen}"
        );
        let taken = seat("next").await;
        assert_eq!(
            (taken.0.as_str(), taken.1.as_str(), taken.2),
            ("owner", "active", None),
            "[{backend}]"
        );
        assert!(
            taken.3.is_some(),
            "[{backend}] bound to the window that accepted"
        );
        let source = seat("owner").await;
        assert_eq!(source.1, "left", "[{backend}] the source is superseded");
        assert!(source.4.is_some(), "[{backend}]");

        for c in [agent, owner, next] {
            let _ = c.cancel().await;
        }
        h.shutdown().await;
    }
}

/// A waiter asking for notes, tasks or locks wakes when a teammate writes
/// one. Every wait test before this asked for messages, so the other three
/// kinds were never seen to arrive (#128).
#[tokio::test]
async fn wait_for_updates_wakes_on_notes_tasks_and_locks() {
    let h = require_db!("t_wait_kinds");
    let a = seed_agent(&h.pool, "acme", "joaquin").await;
    let b = seed_agent(&h.pool, "acme", "marta").await;
    let writer = connect(&h.base, &a).await;

    for (kind, tool, args) in [
        (
            "note",
            "set_note",
            json!({"key": "wake-note", "value": "x"}),
        ),
        (
            "task",
            "create_task",
            json!({"key": "wake-task", "title": "t"}),
        ),
        (
            "lock",
            "acquire_lock",
            json!({"name": "wake-lock", "ttl_seconds": 30}),
        ),
    ] {
        let waiter = connect(&h.base, &b).await;
        let wait = tokio::spawn({
            let kind = kind.to_owned();
            async move {
                let r = call(
                    &waiter,
                    "wait_for_updates",
                    json!({"kinds": [kind], "timeout_seconds": 8}),
                )
                .await;
                let _ = waiter.cancel().await;
                r
            }
        });
        tokio::time::sleep(std::time::Duration::from_millis(600)).await;
        call(&writer, tool, args).await;
        let r = wait.await.unwrap();
        assert_eq!(r["woke"], true, "{kind}: {r}");
        assert_eq!(r["events"][0]["kind"], kind, "{kind}: {r}");
    }
    let _ = writer.cancel().await;
    h.shutdown().await;
}

/// A LISTEN connection can die without a word: Swarm's IPVS forgets an idle
/// TCP connection after fifteen minutes and tells neither end, and a bus
/// sat "attached" for hours while no wake arrived (#128). Each replica now
/// pings itself through Postgres; three unanswered pings and the listener is
/// dropped and attached afresh, and `/health` says which state it is in.
#[tokio::test]
async fn a_listener_that_went_deaf_is_noticed_and_reattached() {
    use std::sync::{
        Arc, Mutex,
        atomic::{AtomicBool, Ordering},
    };
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    let mut h = require_db!("t_deaf_listener");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    let marta = seed_agent(&h.pool, "acme", "marta").await;

    // A TCP proxy in front of Postgres that can turn a connection into a
    // black hole: bytes are read and dropped in both directions, the socket
    // stays open, nobody is told. It remembers which connections said
    // LISTEN, because those are the ones the bus can only wait on.
    let url = db_url().unwrap();
    let at = url.rfind('@').unwrap();
    let slash = at + url[at..].find('/').unwrap();
    let upstream = url[at + 1..slash].to_owned();
    let proxy = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let proxied_url = format!(
        "{}@{}{}",
        &url[..at],
        proxy.local_addr().unwrap(),
        &url[slash..]
    );
    let holes: Arc<Mutex<Vec<Arc<AtomicBool>>>> = Arc::default();
    tokio::spawn({
        let holes = holes.clone();
        async move {
            loop {
                let Ok((client, _)) = proxy.accept().await else {
                    break;
                };
                let Ok(server) = tokio::net::TcpStream::connect(&upstream).await else {
                    continue;
                };
                let hole = Arc::new(AtomicBool::new(false));
                let (mut cr, mut cw) = client.into_split();
                let (mut sr, mut sw) = server.into_split();
                tokio::spawn({
                    let hole = hole.clone();
                    let holes = holes.clone();
                    async move {
                        let mut buf = vec![0u8; 16 * 1024];
                        loop {
                            let n = match cr.read(&mut buf).await {
                                Ok(0) | Err(_) => break,
                                Ok(n) => n,
                            };
                            if buf[..n].windows(6).any(|w| w == b"LISTEN") {
                                holes.lock().unwrap().push(hole.clone());
                            }
                            if hole.load(Ordering::SeqCst) {
                                continue;
                            }
                            if sw.write_all(&buf[..n]).await.is_err() {
                                break;
                            }
                        }
                    }
                });
                tokio::spawn(async move {
                    let mut buf = vec![0u8; 16 * 1024];
                    loop {
                        let n = match sr.read(&mut buf).await {
                            Ok(0) | Err(_) => break,
                            Ok(n) => n,
                        };
                        if hole.load(Ordering::SeqCst) {
                            continue;
                        }
                        if cw.write_all(&buf[..n]).await.is_err() {
                            break;
                        }
                    }
                });
            }
        }
    });

    // A second replica whose every connection goes through the proxy, pinging
    // itself every second so the test does not wait minutes.
    let schema = h.schema.clone();
    let proxied = PgPoolOptions::new()
        .max_connections(8)
        .after_connect(move |conn, _| {
            let schema = schema.clone();
            Box::pin(async move {
                sqlx::query(sqlx::AssertSqlSafe(format!("SET search_path TO {schema}")))
                    .execute(&mut *conn)
                    .await?;
                Ok(())
            })
        })
        .connect(&proxied_url)
        .await
        .unwrap();
    let (replica, handle) = spawn_server_with_ping(proxied, h.ct.child_token(), None, 1).await;
    h.servers.push(handle);

    let health = |base: String| async move {
        reqwest::get(format!("{base}/health"))
            .await
            .unwrap()
            .json::<serde_json::Value>()
            .await
            .unwrap()
    };
    let wait_until = |pred: fn(&serde_json::Value) -> bool, what: &'static str| {
        let replica = replica.clone();
        async move {
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
            loop {
                let h = health(replica.clone()).await;
                if pred(&h["events"]) {
                    return h;
                }
                assert!(std::time::Instant::now() < deadline, "{what}: {h}");
                tokio::time::sleep(std::time::Duration::from_millis(200)).await;
            }
        }
    };
    // The first echo is the proof of readiness the log line never was.
    let ready = wait_until(|e| e["echoes"].as_u64() >= Some(1), "first echo").await;
    assert_eq!(ready["events"]["listener"], "live", "{ready}");
    assert_eq!(ready["events"]["attachments"], 1, "{ready}");
    assert_eq!(ready["status"], "ok", "{ready}");

    // A wake through the proxied replica works while its listener hears.
    let wake = |replica: String, writer_base: String, key: &'static str| {
        let token = token.clone();
        let marta = marta.clone();
        async move {
            let waiter = connect(&replica, &marta).await;
            let wait = tokio::spawn(async move {
                let r = call(
                    &waiter,
                    "wait_for_updates",
                    json!({"kinds": ["note"], "timeout_seconds": 10}),
                )
                .await;
                let _ = waiter.cancel().await;
                r
            });
            tokio::time::sleep(std::time::Duration::from_millis(500)).await;
            let writer = connect(&writer_base, &token).await;
            call(&writer, "set_note", json!({"key": key, "value": "x"})).await;
            let _ = writer.cancel().await;
            wait.await.unwrap()
        }
    };
    let woke = wake(replica.clone(), h.base.clone(), "before").await;
    assert_eq!(woke["woke"], true, "{woke}");

    // The socket goes dead without a word. Every LISTEN connection the proxy
    // has seen so far is black-holed; the one the replica opens next is not.
    let dead: Vec<_> = holes.lock().unwrap().drain(..).collect();
    assert!(!dead.is_empty(), "the proxy saw the LISTEN connection");
    for hole in &dead {
        hole.store(true, Ordering::SeqCst);
    }

    // The replica notices on its own, and comes back hearing.
    let back = wait_until(
        |e| e["attachments"].as_u64() >= Some(2) && e["listener"] == "live",
        "reattached",
    )
    .await;
    let echoes_at_reattach = back["events"]["echoes"].as_u64().unwrap();
    wait_until(
        |e| e["listener"] == "live" && e["last_echo_seconds"].as_i64() <= Some(2),
        "hearing again",
    )
    .await;
    let after = health(replica.clone()).await;
    assert!(
        after["events"]["echoes"].as_u64() >= Some(echoes_at_reattach),
        "{after}"
    );
    assert_eq!(after["status"], "ok", "{after}");

    // And wakes work again, on the fresh connection.
    let woke = wake(replica.clone(), h.base.clone(), "after").await;
    assert_eq!(woke["woke"], true, "after the reattach: {woke}");

    h.shutdown().await;
}

/// An owner's seat is only an owner's to change. Re-inviting someone already
/// seated changes their role on the spot, and a moderator used that to
/// demote the owner to observer and then remove it, walking around "only an
/// owner can remove another owner" (#133). The refusal leaves the owner's
/// role, floor and binding exactly as they were; an owner re-inviting a
/// moderator still changes its role.
#[tokio::test]
async fn a_moderator_cannot_demote_an_owner_by_reinviting_it() {
    for backend in ["postgres", "jetstream"] {
        let schema = format!("t_owner_seat_{backend}");
        let h = require_db_broker!(&schema);
        let token = seed_agent(&h.pool, "acme", "joaquin").await;
        let reader_token = seed_agent(&h.pool, "acme", "dani").await;
        enable_conversations(&h.pool, "acme").await;
        if backend == "jetstream" {
            route_team_to_jetstream(&h, "acme").await;
        }
        // The owner is a registered window, so its seat carries a binding
        // the refusal has to leave alone.
        let agent = connect(&h.base, &token).await;
        let cred = call(&agent, "register_session", json!({"session": "owner"})).await;
        let owner = connect(&h.base, cred["session_token"].as_str().unwrap()).await;
        let reader = connect_with_session(&h.base, &reader_token, "reader").await;

        let convo = call(
            &owner,
            "create_conversation",
            json!({"title": "whose seat", "private": true}),
        )
        .await;
        let cid = convo["id"].as_str().unwrap().to_owned();
        let cid_uuid: Uuid = cid.parse().unwrap();
        let first = call(
            &owner,
            "send_conversation_message",
            json!({"conversation_id": cid, "body": "the owner's own thread",
                   "request_id": request_id()}),
        )
        .await["message_id"]
            .as_str()
            .unwrap()
            .to_owned();
        call(
            &owner,
            "invite_to_conversation",
            json!({"conversation_id": cid, "address": "dani/reader", "role": "moderator"}),
        )
        .await;
        call(
            &reader,
            "join_conversation",
            json!({"conversation_id": cid}),
        )
        .await;

        let seat = |session: &'static str| {
            let pool = h.pool.clone();
            async move {
                sqlx::query_as::<_, (String, String, Option<i64>, Option<Uuid>)>(
                    "SELECT role, state, history_from_seq, session_id
                       FROM conversation_memberships
                      WHERE conversation_id = $1 AND session = $2",
                )
                .bind(cid_uuid)
                .bind(session)
                .fetch_one(&pool)
                .await
                .unwrap()
            }
        };
        let owner_seat = seat("owner").await;
        assert_eq!(owner_seat.0, "owner", "[{backend}]");
        assert!(
            owner_seat.3.is_some(),
            "[{backend}] the owner's seat is bound"
        );

        let err = call_expect_error(
            &reader,
            "remove_conversation_member",
            json!({"conversation_id": cid, "address": "joaquin/owner"}),
        )
        .await;
        assert!(
            err.contains("only an owner can remove another owner"),
            "[{backend}] {err}"
        );

        // Every role a moderator could hand out, and the default one.
        for role in [
            Some("observer"),
            Some("participant"),
            Some("moderator"),
            None,
        ] {
            let mut args = json!({"conversation_id": cid, "address": "joaquin/owner"});
            if let Some(role) = role {
                args["role"] = json!(role);
            }
            let err = call_expect_error(&reader, "invite_to_conversation", args).await;
            assert!(
                err.contains("only an owner can change or remove another owner"),
                "[{backend}] role {role:?}: {err}"
            );
            assert!(!err.contains("database error"), "[{backend}] {err}");
            assert_eq!(
                seat("owner").await,
                owner_seat,
                "[{backend}] role {role:?} changed the seat"
            );
            let seen = call(
                &owner,
                "get_conversation_message",
                json!({"message_id": first}),
            )
            .await;
            assert_eq!(seen["body"], "the owner's own thread", "[{backend}] {seen}");
        }
        let err = call_expect_error(
            &reader,
            "remove_conversation_member",
            json!({"conversation_id": cid, "address": "joaquin/owner"}),
        )
        .await;
        assert!(
            err.contains("only an owner can remove another owner"),
            "[{backend}] {err}"
        );
        let read = call(&owner, "read_conversation", json!({"conversation_id": cid})).await;
        assert_eq!(
            read["messages"].as_array().map(Vec::len),
            Some(1),
            "[{backend}] {read}"
        );

        // The ordinary path is untouched: an owner re-inviting a moderator
        // changes its role, and nothing else about its seat.
        let reader_seat = seat("reader").await;
        call(
            &owner,
            "invite_to_conversation",
            json!({"conversation_id": cid, "address": "dani/reader", "role": "observer"}),
        )
        .await;
        let demoted = seat("reader").await;
        assert_eq!(demoted.0, "observer", "[{backend}] {demoted:?}");
        assert_eq!(
            (&demoted.1, demoted.2, demoted.3),
            (&reader_seat.1, reader_seat.2, reader_seat.3),
            "[{backend}] state, floor and binding stay"
        );
        let read = call(
            &reader,
            "read_conversation",
            json!({"conversation_id": cid}),
        )
        .await;
        assert!(read["messages"].is_array(), "[{backend}] {read}");
        call(
            &owner,
            "invite_to_conversation",
            json!({"conversation_id": cid, "address": "dani/reader", "role": "moderator"}),
        )
        .await;

        // A transfer proposal is an owner seat in the `invited` state, and
        // it is not the moderator's to reshape either.
        let cred2 = call(&agent, "register_session", json!({"session": "owner-2"})).await;
        let successor = connect(&h.base, cred2["session_token"].as_str().unwrap()).await;
        let proposal = call(
            &owner,
            "transfer_membership",
            json!({"conversation_id": cid, "to": "joaquin/owner-2"}),
        )
        .await;
        assert_eq!(proposal["state"], "proposed", "[{backend}] {proposal}");
        let proposed_seat = seat("owner-2").await;
        assert_eq!(
            (proposed_seat.0.as_str(), proposed_seat.1.as_str()),
            ("owner", "invited"),
            "[{backend}] {proposed_seat:?}"
        );
        let err = call_expect_error(
            &reader,
            "invite_to_conversation",
            json!({"conversation_id": cid, "address": "joaquin/owner-2", "role": "observer"}),
        )
        .await;
        assert!(
            err.contains("only an owner can change or remove another owner"),
            "[{backend}] {err}"
        );
        assert_eq!(seat("owner-2").await, proposed_seat, "[{backend}]");

        // A storm: the moderator hammers both owner seats from a dozen
        // connections while the owner keeps flipping the moderator's role.
        // Whatever the interleaving, no attempt lands on an owner seat, and
        // none dies of a deadlock, which would surface as "database error".
        let owner_token = cred["session_token"].as_str().unwrap().to_owned();
        let mut storm = Vec::new();
        for i in 0..12usize {
            let base = h.base.clone();
            let reader_token = reader_token.clone();
            let cid = cid.clone();
            storm.push(tokio::spawn(async move {
                let c = connect_with_session(&base, &reader_token, "reader").await;
                let target = if i % 2 == 0 {
                    "joaquin/owner"
                } else {
                    "joaquin/owner-2"
                };
                let role = ["observer", "participant", "moderator"][i % 3];
                let args: serde_json::Map<String, Value> = serde_json::from_value(
                    json!({"conversation_id": cid, "address": target, "role": role}),
                )
                .unwrap();
                let outcome = c
                    .call_tool(
                        CallToolRequestParams::new("invite_to_conversation").with_arguments(args),
                    )
                    .await;
                let _ = c.cancel().await;
                match outcome {
                    Ok(res) if res.is_error != Some(true) => {
                        Err(format!("{target} as {role} went through"))
                    }
                    Ok(res) => Ok(format!("{:?}", res.content)),
                    Err(e) => Ok(e.to_string()),
                }
            }));
        }
        for i in 0..4usize {
            let base = h.base.clone();
            let owner_token = owner_token.clone();
            let cid = cid.clone();
            storm.push(tokio::spawn(async move {
                let c = connect(&base, &owner_token).await;
                let role = if i % 2 == 0 { "observer" } else { "moderator" };
                call(
                    &c,
                    "invite_to_conversation",
                    json!({"conversation_id": cid, "address": "dani/reader", "role": role}),
                )
                .await;
                let _ = c.cancel().await;
                Ok::<String, String>(String::new())
            }));
        }
        for task in storm {
            let outcome = task.await.unwrap();
            let text = outcome.unwrap_or_else(|landed| panic!("[{backend}] {landed}"));
            assert!(!text.contains("database error"), "[{backend}] {text}");
        }
        assert_eq!(
            seat("owner").await,
            owner_seat,
            "[{backend}] the owner's seat survived the storm"
        );
        assert_eq!(
            seat("owner-2").await,
            proposed_seat,
            "[{backend}] so did the proposed one"
        );

        // The proposal still completes for the window it was made to.
        call(
            &successor,
            "join_conversation",
            json!({"conversation_id": cid}),
        )
        .await;
        assert_eq!(seat("owner-2").await.1, "active", "[{backend}]");
        assert_eq!(
            seat("owner").await.1,
            "left",
            "[{backend}] the source is superseded"
        );

        for c in [agent, owner, successor, reader] {
            let _ = c.cancel().await;
        }
        h.shutdown().await;
    }
}

/// A claim whose lease lapsed is open, and every read says so at once: the
/// writers always treated it that way (anyone could claim it), while
/// get_task and list_tasks kept reporting "claimed by marta", the open list
/// left it out and the claimed list kept it (#135).
#[tokio::test]
async fn a_lapsed_lease_reads_as_open_everywhere() {
    let h = require_db!("t_lapsed_lease");
    let a = seed_agent(&h.pool, "acme", "marta").await;
    let b = seed_agent(&h.pool, "acme", "dani").await;
    let marta = connect(&h.base, &a).await;
    let dani = connect(&h.base, &b).await;

    call(
        &marta,
        "create_task",
        json!({"key": "lapse", "title": "long job"}),
    )
    .await;
    call(
        &marta,
        "create_task",
        json!({"key": "still-open", "title": "untouched"}),
    )
    .await;
    let claimed = call(
        &marta,
        "claim_task",
        json!({"key": "lapse", "lease_seconds": 60}),
    )
    .await;
    assert_eq!(claimed["claimed"], true, "{claimed}");

    // Live: claimed by marta, with time left, nobody lapsed.
    let live = call(&dani, "get_task", json!({"key": "lapse"})).await["task"].clone();
    assert_eq!(live["status"], "claimed", "{live}");
    assert_eq!(live["claimed_by"], "marta", "{live}");
    assert_eq!(live["lease_expired"], false, "{live}");
    assert!(live["lapsed_holder"].is_null(), "{live}");
    assert!(
        live["lease_seconds_remaining"].as_i64().unwrap_or(0) > 0,
        "{live}"
    );
    let mine = call(&marta, "list_tasks", json!({"mine_only": true})).await;
    assert_eq!(mine["tasks"].as_array().map(Vec::len), Some(1), "{mine}");
    let listed = call(&dani, "list_tasks", json!({})).await;
    assert_eq!(
        (listed["open"].as_i64(), listed["claimed"].as_i64()),
        (Some(1), Some(1)),
        "{listed}"
    );

    sqlx::query(
        "UPDATE tasks SET lease_expires_at = now() - interval '1 minute' WHERE key = 'lapse'",
    )
    .execute(&h.pool)
    .await
    .unwrap();

    // Lapsed: open, unheld, and honest about who let it go.
    let lapsed = call(&dani, "get_task", json!({"key": "lapse"})).await["task"].clone();
    assert_eq!(lapsed["status"], "open", "{lapsed}");
    assert!(lapsed["claimed_by"].is_null(), "{lapsed}");
    assert!(lapsed["claimed_session"].is_null(), "{lapsed}");
    assert!(lapsed["claimed_at"].is_null(), "{lapsed}");
    assert!(lapsed["lease_expires_at"].is_null(), "{lapsed}");
    assert!(lapsed["lease_seconds_remaining"].is_null(), "{lapsed}");
    assert_eq!(lapsed["lease_expired"], true, "{lapsed}");
    assert_eq!(lapsed["lapsed_holder"], "marta", "{lapsed}");

    let keys = |r: &Value| -> Vec<String> {
        r["tasks"]
            .as_array()
            .unwrap()
            .iter()
            .map(|t| t["key"].as_str().unwrap().to_owned())
            .collect()
    };
    let open = call(&dani, "list_tasks", json!({"status": "open"})).await;
    assert!(
        keys(&open).contains(&"lapse".to_owned()),
        "the open list has it: {open}"
    );
    assert!(
        open["tasks"]
            .as_array()
            .unwrap()
            .iter()
            .all(|t| t["status"] == "open"),
        "and every row in it says open: {open}"
    );
    let claimed = call(&dani, "list_tasks", json!({"status": "claimed"})).await;
    assert!(
        !keys(&claimed).contains(&"lapse".to_owned()),
        "the claimed list does not: {claimed}"
    );
    let all = call(&dani, "list_tasks", json!({})).await;
    let row = all["tasks"]
        .as_array()
        .unwrap()
        .iter()
        .find(|t| t["key"] == "lapse")
        .unwrap();
    assert_eq!(row["status"], "open", "{all}");
    assert_eq!(row["lapsed_holder"], "marta", "{all}");
    assert_eq!(
        (all["open"].as_i64(), all["claimed"].as_i64()),
        (Some(2), Some(0)),
        "counters follow: {all}"
    );
    let mine = call(&marta, "list_tasks", json!({"mine_only": true})).await;
    assert_eq!(
        mine["tasks"].as_array().map(Vec::len),
        Some(0),
        "a lapsed lease is nobody's: {mine}"
    );

    // Renewing what lapsed is refused with the way back in; claiming works,
    // for the former holder as for anyone else.
    let err = call_expect_error(&marta, "renew_task_lease", json!({"key": "lapse"})).await;
    assert!(err.contains("lapsed"), "{err}");
    assert!(err.contains("claim it again"), "{err}");
    let taken = call(&dani, "claim_task", json!({"key": "lapse"})).await;
    assert_eq!(taken["claimed"], true, "{taken}");
    let now = taken["task"].clone();
    assert_eq!(now["status"], "claimed", "{now}");
    assert_eq!(now["claimed_by"], "dani", "{now}");
    assert_eq!(now["lease_expired"], false, "{now}");
    assert!(now["lapsed_holder"].is_null(), "{now}");

    // A claim with no expiry at all (a row from before leases had one) is a
    // live claim: it reads as claimed, counts as its holder's, and never
    // trips the lapse logic.
    sqlx::query("UPDATE tasks SET lease_expires_at = NULL WHERE key = 'lapse'")
        .execute(&h.pool)
        .await
        .unwrap();
    let legacy = call(&dani, "get_task", json!({"key": "lapse"})).await["task"].clone();
    assert_eq!(legacy["status"], "claimed", "{legacy}");
    assert_eq!(legacy["claimed_by"], "dani", "{legacy}");
    assert_eq!(legacy["lease_expired"], false, "{legacy}");
    let mine = call(
        &dani,
        "list_tasks",
        json!({"mine_only": true, "status": "claimed"}),
    )
    .await;
    assert_eq!(mine["tasks"].as_array().map(Vec::len), Some(1), "{mine}");

    for c in [marta, dani] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// Revoking an agent token takes its session credentials with it. Auth
/// already refused them, but their rows still read as live: recovery
/// counted a window that could not answer and the label stayed reserved
/// for a credential that no longer worked, until it expired a day later
/// (#137). A genuinely live window under another token still protects.
#[tokio::test]
async fn a_revoked_token_takes_its_sessions_with_it() {
    use ai_crew_sync::auth::{generate_token, hash_token, token_prefix};
    use ai_crew_sync::store::admin::{self as store, Actor};

    let h = require_db!("t_revoked_parent");
    let token_a = seed_agent(&h.pool, "acme", "joaquin").await;
    enable_conversations(&h.pool, "acme").await;
    // A second credential for the same agent: the replacement.
    let (agent_id,): (Uuid,) = sqlx::query_as("SELECT id FROM agents WHERE name = 'joaquin'")
        .fetch_one(&h.pool)
        .await
        .unwrap();
    let token_b = generate_token();
    sqlx::query("INSERT INTO api_tokens (agent_id, token_hash, prefix) VALUES ($1, $2, $3)")
        .bind(agent_id)
        .bind(hash_token(&token_b))
        .bind(token_prefix(&token_b))
        .execute(&h.pool)
        .await
        .unwrap();
    let (token_a_id,): (Uuid,) = sqlx::query_as("SELECT id FROM api_tokens WHERE token_hash = $1")
        .bind(hash_token(&token_a))
        .fetch_one(&h.pool)
        .await
        .unwrap();

    let a = connect(&h.base, &token_a).await;
    let cred = call(
        &a,
        "register_session",
        json!({"session": "only-window", "ttl_seconds": 3600}),
    )
    .await;
    let window = connect(&h.base, cred["session_token"].as_str().unwrap()).await;
    let convo = call(
        &window,
        "create_conversation",
        json!({"title": "mine alone", "private": true}),
    )
    .await;
    let cid = convo["id"].as_str().unwrap().to_owned();
    call(
        &window,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "before the rotation", "request_id": request_id()}),
    )
    .await;

    // While the window lives, the replacement token recovers nothing.
    let b = connect(&h.base, &token_b).await;
    let err = call_expect_error(
        &b,
        "recover_conversation_history",
        json!({"conversation_id": cid}),
    )
    .await;
    assert!(err.contains("still live"), "{err}");

    // The operator revokes the first token (the CLI and the admin API share
    // this call).
    store::revoke_token(&h.pool, Actor::Cli, None, token_a_id)
        .await
        .unwrap();
    let (detail,): (serde_json::Value,) = sqlx::query_as(
        "SELECT detail FROM admin_audit WHERE action = 'token.revoke' ORDER BY id DESC LIMIT 1",
    )
    .fetch_one(&h.pool)
    .await
    .unwrap();
    assert_eq!(
        detail["sessions_revoked"],
        json!(["only-window"]),
        "{detail}"
    );

    // The window's credential is dead, as before.
    let status = mcp_status(&h.base, cred["session_token"].as_str().unwrap()).await;
    assert_eq!(status, 401, "the child credential is refused");

    // And now the rows agree with authentication: recovery works, the
    // label is free, the old secret stays dead.
    let recovered = call(
        &b,
        "recover_conversation_history",
        json!({"conversation_id": cid}),
    )
    .await;
    assert_eq!(
        recovered["messages"][0]["body"], "before the rotation",
        "{recovered}"
    );
    let again = call(
        &b,
        "register_session",
        json!({"session": "only-window", "ttl_seconds": 3600}),
    )
    .await;
    assert!(again["session_token"].is_string(), "{again}");
    assert_eq!(
        mcp_status(&h.base, cred["session_token"].as_str().unwrap()).await,
        401,
        "re-registering the label does not revive the old secret"
    );

    // A window that is genuinely live, under the replacement token, still
    // blocks recovery: the rule protects windows that can answer.
    let err = call_expect_error(
        &b,
        "recover_conversation_history",
        json!({"conversation_id": cid}),
    )
    .await;
    assert!(err.contains("still live"), "{err}");

    // The races, replayed deterministically at the store: a request that
    // authenticated with token A before the revocation and runs after it.
    use ai_crew_sync::auth::AuthCtx;
    use ai_crew_sync::store::sessions;
    let team = team_id(&h.pool, "acme").await;
    let stale_agent = AuthCtx {
        agent_id,
        agent_name: "joaquin".into(),
        team_id: team,
        team_slug: "acme".into(),
        session: String::new(),
        session_id: None,
        session_epoch: None,
        token_id: Some(token_a_id),
    };
    let err = match sessions::register(&h.pool, &stale_agent, token_a_id, "late-window", None).await
    {
        Ok(_) => panic!("a registration under a revoked token must not land"),
        Err(e) => e,
    };
    assert!(
        err.to_string().contains("revoked while it was in flight"),
        "{err}"
    );
    let (late,): (i64,) = sqlx::query_as(
        "SELECT count(*) FROM agent_sessions WHERE agent_id = $1 AND label = 'late-window'",
    )
    .bind(agent_id)
    .fetch_one(&h.pool)
    .await
    .unwrap();
    assert_eq!(late, 0, "no row was written");

    // And a request that authenticated with the old window's credential,
    // running after B re-registered the label: it must not rotate B's row.
    let (row_id, epoch_now): (Uuid, i64) = sqlx::query_as(
        "SELECT id, epoch FROM agent_sessions WHERE agent_id = $1 AND label = 'only-window'",
    )
    .bind(agent_id)
    .fetch_one(&h.pool)
    .await
    .unwrap();
    let stale_window = AuthCtx {
        agent_id,
        agent_name: "joaquin".into(),
        team_id: team,
        team_slug: "acme".into(),
        session: "only-window".into(),
        session_id: Some(row_id),
        session_epoch: Some(epoch_now - 1),
        token_id: None,
    };
    let err = match sessions::resume(&h.pool, &stale_window, None).await {
        Ok(_) => panic!("a stale connection must not rotate the new window's credential"),
        Err(e) => e,
    };
    assert!(err.to_string().contains("re-registered"), "{err}");
    let err = match sessions::renew(&h.pool, &stale_window, None).await {
        Ok(_) => panic!("a stale connection must not extend the new window's credential"),
        Err(e) => e,
    };
    assert!(err.to_string().contains("revoked"), "{err}");
    assert_eq!(
        mcp_status(&h.base, again["session_token"].as_str().unwrap()).await,
        200,
        "B's window still works"
    );

    // Revocation over the admin API, with a team-scoped credential, sweeps
    // the sessions the same way; another team's credential cannot reach it.
    let token_c = generate_token();
    let (token_c_id,): (Uuid,) = sqlx::query_as(
        "INSERT INTO api_tokens (agent_id, token_hash, prefix) VALUES ($1, $2, $3) RETURNING id",
    )
    .bind(agent_id)
    .bind(hash_token(&token_c))
    .bind(token_prefix(&token_c))
    .fetch_one(&h.pool)
    .await
    .unwrap();
    let c = connect(&h.base, &token_c).await;
    let other = call(&c, "register_session", json!({"session": "other-window"})).await;
    let other_token = other["session_token"].as_str().unwrap().to_owned();
    seed_agent(&h.pool, "rivals", "eve").await;
    let rivals = team_id(&h.pool, "rivals").await;
    let foreign = store::grant_admin(&h.pool, Actor::Cli, Some(rivals), None)
        .await
        .unwrap();
    let (status, _) = Admin::new(&h.base, &foreign.token)
        .delete(&format!("/teams/acme/tokens/{token_c_id}"))
        .await;
    assert_eq!(status, 403, "another team's credential is refused");
    let ours = store::grant_admin(&h.pool, Actor::Cli, Some(team), None)
        .await
        .unwrap();
    let (status, _) = Admin::new(&h.base, &ours.token)
        .delete(&format!("/teams/acme/tokens/{token_c_id}"))
        .await;
    assert_eq!(status, 200);
    assert_eq!(mcp_status(&h.base, &other_token).await, 401);
    let (swept,): (bool,) = sqlx::query_as(
        "SELECT revoked_at IS NOT NULL FROM agent_sessions WHERE agent_id = $1 AND label = 'other-window'",
    )
    .bind(agent_id)
    .fetch_one(&h.pool)
    .await
    .unwrap();
    assert!(swept, "the session row is revoked with its parent");

    for cl in [a, window, b, c] {
        let _ = cl.cancel().await;
    }
    h.shutdown().await;
}

/// The agent lock the lifecycle paths serialise on must not conflict with
/// the key share a foreign key takes. A first heartbeat holds `FOR SHARE`
/// on its session (the epoch guard) and then inserts presence, which needs
/// `FOR KEY SHARE` on the agent; a revocation holding `FOR UPDATE` on the
/// agent and waiting on that session row closed the cycle, and Postgres
/// rolled the revocation back with 40P01. `FOR NO KEY UPDATE` serialises
/// the lifecycle paths without blocking the key share.
#[tokio::test]
async fn a_revocation_does_not_deadlock_with_a_first_heartbeat() {
    use ai_crew_sync::auth::hash_token;
    use ai_crew_sync::store::admin::{self as store, Actor};

    let h = require_db!("t_revoke_vs_heartbeat");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    let (agent_id, token_id): (Uuid, Uuid) = sqlx::query_as(
        "SELECT a.id, t.id FROM api_tokens t JOIN agents a ON a.id = t.agent_id
          WHERE t.token_hash = $1",
    )
    .bind(hash_token(&token))
    .fetch_one(&h.pool)
    .await
    .unwrap();
    let agent = connect(&h.base, &token).await;
    let cred = call(&agent, "register_session", json!({"session": "first"})).await;
    let session_id: Uuid = cred["session_id"].as_str().unwrap().parse().unwrap();

    // The heartbeat's transaction, paused right after the guard.
    let mut heartbeat = h.pool.begin().await.unwrap();
    sqlx::query("SELECT epoch FROM agent_sessions WHERE id = $1 FOR SHARE")
        .bind(session_id)
        .fetch_one(&mut *heartbeat)
        .await
        .unwrap();

    // The revocation takes the agent lock and waits on that session row.
    let revoke = tokio::spawn({
        let pool = h.pool.clone();
        async move { store::revoke_token(&pool, Actor::Cli, None, token_id).await }
    });
    tokio::time::sleep(std::time::Duration::from_millis(400)).await;
    assert!(
        !revoke.is_finished(),
        "the revocation waits for the guarded transaction"
    );

    // The heartbeat inserts presence, which needs a key share on the agent.
    sqlx::query(
        "INSERT INTO agent_presence (agent_id, session, status, updated_at, expires_at)
         VALUES ($1, 'first', 'active', now(), now() + interval '15 minutes')",
    )
    .bind(agent_id)
    .execute(&mut *heartbeat)
    .await
    .expect("the first heartbeat lands while a revocation waits");
    heartbeat.commit().await.unwrap();

    revoke
        .await
        .unwrap()
        .expect("the revocation completes once the heartbeat commits");
    let (revoked,): (bool,) =
        sqlx::query_as("SELECT revoked_at IS NOT NULL FROM agent_sessions WHERE id = $1")
            .bind(session_id)
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert!(revoked, "and it swept the session");

    let _ = agent.cancel().await;
    h.shutdown().await;
}

/// Revoking a project grant takes effect at once, threads being read
/// included: an active seat in a project thread is not a second door. The
/// revoked agent reads nothing new, gets no new receipt or inbox reference,
/// cannot accept a pending invitation, and a project reader without a seat
/// is shut out the same way. Private threads keep their membership rules.
#[tokio::test]
async fn audit_project_revocation_closes_an_active_members_access() {
    let h = require_db!("t_project_revocation");
    let alice_token = seed_agent(&h.pool, "acme", "alice").await;
    let bob_token = seed_agent(&h.pool, "acme", "bob").await;
    let carol_token = seed_agent(&h.pool, "acme", "carol").await;
    let dave_token = seed_agent(&h.pool, "acme", "dave").await;
    enable_conversations(&h.pool, "acme").await;
    let alice = connect_with_session(&h.base, &alice_token, "lead").await;
    // Bob is a registered window, so the inbox path is exercised too.
    let bob_agent = connect(&h.base, &bob_token).await;
    let bob_cred = call(&bob_agent, "register_session", json!({"session": "reader"})).await;
    let bob = connect(&h.base, bob_cred["session_token"].as_str().unwrap()).await;
    let carol = connect_with_session(&h.base, &carol_token, "peek").await;
    let dave = connect_with_session(&h.base, &dave_token, "late").await;

    call(&alice, "create_project", json!({"project": "audit"})).await;
    for who in ["bob", "carol", "dave"] {
        call(
            &alice,
            "grant_project_access",
            json!({"project": "audit", "agent": who}),
        )
        .await;
    }
    let convo = call(
        &alice,
        "create_conversation",
        json!({"title": "audit thread", "project": "audit", "invite": ["bob/reader", "dave/late"]}),
    )
    .await;
    let cid = convo["id"].as_str().unwrap().to_owned();
    call(&bob, "join_conversation", json!({"conversation_id": cid})).await;
    let before = call(
        &alice,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "while Bob still had access", "request_id": request_id()}),
    )
    .await["message_id"]
        .as_str()
        .unwrap()
        .to_owned();
    let seen = call(
        &bob,
        "get_conversation_message",
        json!({"message_id": before}),
    )
    .await;
    assert_eq!(seen["body"], "while Bob still had access", "{seen}");
    let seen = call(
        &carol,
        "get_conversation_message",
        json!({"message_id": before}),
    )
    .await;
    assert_eq!(
        seen["body"], "while Bob still had access",
        "a project reader: {seen}"
    );

    // The revocations.
    for who in ["bob", "carol", "dave"] {
        call(
            &alice,
            "grant_project_access",
            json!({"project": "audit", "agent": who, "grant": false}),
        )
        .await;
    }
    let after = call(
        &alice,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "after Bob lost access", "request_id": request_id()}),
    )
    .await["message_id"]
        .as_str()
        .unwrap()
        .to_owned();

    // The active member reads nothing, new or old, and cannot write.
    for (who, client) in [("bob", &bob), ("carol", &carol)] {
        let err =
            call_expect_error(client, "read_conversation", json!({"conversation_id": cid})).await;
        assert!(!err.contains("database error"), "{who}: {err}");
        for m in [&before, &after] {
            let err =
                call_expect_error(client, "get_conversation_message", json!({"message_id": m}))
                    .await;
            assert!(!err.contains("database error"), "{who}: {err}");
        }
    }
    let err = call_expect_error(
        &bob,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "still here?", "request_id": request_id()}),
    )
    .await;
    assert!(!err.contains("database error"), "{err}");
    let err = call_expect_error(
        &bob,
        "ack_message",
        json!({"conversation_id": cid, "message_id": after, "resolved": false}),
    )
    .await;
    assert!(!err.contains("database error"), "{err}");

    // No new obligation: the message sent after the revocation has no
    // receipt for Bob, and his inbox hands him nothing from this thread.
    let receipts = call(&alice, "get_message_receipts", json!({"message_id": after})).await;
    assert!(
        !receipts["receipts"]
            .as_array()
            .unwrap()
            .iter()
            .any(|r| r["address"].as_str().unwrap_or("").starts_with("bob")),
        "no receipt for the revoked seat: {receipts}"
    );
    let inbox = call(&bob, "fetch_conversation_inbox", json!({})).await;
    assert!(
        inbox["references"]
            .as_array()
            .unwrap()
            .iter()
            .all(|r| r["conversation_id"] != cid.as_str()),
        "nothing from the project thread is handed out: {inbox}"
    );

    // Nor is the seat told anything about the thread: no unread activity
    // to wake on, nothing counted as undelivered.
    let woke = call(
        &bob,
        "wait_for_conversation_updates",
        json!({"timeout_seconds": 1}),
    )
    .await;
    assert!(
        woke["conversations"]
            .as_array()
            .unwrap()
            .iter()
            .all(|c| c["conversation_id"] != cid.as_str()),
        "a revoked seat is not woken: {woke}"
    );
    let status = call(&bob, "conversation_inbox_status", json!({})).await;
    assert_eq!(status["undelivered"], 0, "{status}");

    // A pending invitation cannot be accepted after the revocation.
    let err = call_expect_error(&dave, "join_conversation", json!({"conversation_id": cid})).await;
    assert!(err.contains("revoked"), "{err}");

    // Granting it back reopens the seat: the membership was never removed.
    call(
        &alice,
        "grant_project_access",
        json!({"project": "audit", "agent": "bob"}),
    )
    .await;
    let seen = call(
        &bob,
        "get_conversation_message",
        json!({"message_id": after}),
    )
    .await;
    assert_eq!(seen["body"], "after Bob lost access", "{seen}");

    // A private thread is untouched by project grants.
    let private = call(
        &alice,
        "create_conversation",
        json!({"title": "private", "private": true, "invite": ["bob/reader"]}),
    )
    .await;
    let pid = private["id"].as_str().unwrap().to_owned();
    call(&bob, "join_conversation", json!({"conversation_id": pid})).await;
    call(
        &alice,
        "grant_project_access",
        json!({"project": "audit", "agent": "bob", "grant": false}),
    )
    .await;
    let pm = call(
        &alice,
        "send_conversation_message",
        json!({"conversation_id": pid, "body": "private still works", "request_id": request_id()}),
    )
    .await["message_id"]
        .as_str()
        .unwrap()
        .to_owned();
    let seen = call(&bob, "get_conversation_message", json!({"message_id": pm})).await;
    assert_eq!(seen["body"], "private still works", "{seen}");

    for c in [alice, bob_agent, bob, carol, dave] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// The same promise on the broker path: a reference published to JetStream
/// before the revocation is not handed to the revoked seat, so the
/// guarantee does not depend on which backend holds the thread.
#[tokio::test]
async fn audit_project_revocation_holds_on_the_broker_path() {
    use ai_crew_sync::store::jetstream::{Config, JetStreamBackend};
    use ai_crew_sync::store::{inbox, outbox};
    let h = require_db_broker!("t_project_revocation_js");
    let alice_token = seed_agent(&h.pool, "acme", "alice").await;
    let bob_token = seed_agent(&h.pool, "acme", "bob").await;
    enable_conversations(&h.pool, "acme").await;
    let team = team_id(&h.pool, "acme").await;
    sqlx::query("UPDATE teams SET default_backend = 'jetstream' WHERE id = $1")
        .bind(team)
        .execute(&h.pool)
        .await
        .unwrap();
    let config = Config::new(nats_url()).with_limits(1_000, 16 * 1024 * 1024);
    JetStreamBackend::provision(&config, team).await.unwrap();
    JetStreamBackend::provision_inbox(&config, team)
        .await
        .unwrap();
    let backend = JetStreamBackend::connect(&config, team).await.unwrap();
    // The test server runs no publication worker: the outbox and the inbox
    // references are drained by hand, exactly as the other broker tests do.
    let publish = || async {
        assert_eq!(
            outbox::run_once(&h.pool, &backend, "worker").await.unwrap(),
            Some(outbox::Settled::Stored)
        );
        inbox::publish_pending(&h.pool, &backend, team, 100)
            .await
            .unwrap()
    };
    let alice = connect_with_session(&h.base, &alice_token, "lead").await;
    let bob_agent = connect(&h.base, &bob_token).await;
    let bob_cred = call(&bob_agent, "register_session", json!({"session": "reader"})).await;
    let bob = connect(&h.base, bob_cred["session_token"].as_str().unwrap()).await;

    call(&alice, "create_project", json!({"project": "audit"})).await;
    call(
        &alice,
        "grant_project_access",
        json!({"project": "audit", "agent": "bob"}),
    )
    .await;
    let convo = call(
        &alice,
        "create_conversation",
        json!({"title": "audit thread", "project": "audit", "invite": ["bob/reader"]}),
    )
    .await;
    let cid = convo["id"].as_str().unwrap().to_owned();
    call(&bob, "join_conversation", json!({"conversation_id": cid})).await;

    // A first message proves the broker path is live for this seat.
    call(
        &alice,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "first", "request_id": request_id()}),
    )
    .await;
    assert_eq!(publish().await, 1, "one reference for Bob");
    let batch = call(&bob, "fetch_conversation_inbox", json!({})).await;
    assert_eq!(batch["from_broker"], 1, "{batch}");
    assert_eq!(batch["references"][0]["conversation_id"], cid, "{batch}");
    let ids: Vec<&str> = batch["references"]
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|r| r["delivery_id"].as_str())
        .collect();
    call(&bob, "confirm_inbox_delivery", json!({"delivery_ids": ids})).await;

    // A second message reaches the broker while Bob still has the grant;
    // then the grant goes.
    call(
        &alice,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "second", "request_id": request_id()}),
    )
    .await;
    assert_eq!(publish().await, 1, "the second reference is on the broker");
    call(
        &alice,
        "grant_project_access",
        json!({"project": "audit", "agent": "bob", "grant": false}),
    )
    .await;
    for _ in 0..3 {
        let batch = call(&bob, "fetch_conversation_inbox", json!({})).await;
        assert!(
            batch["references"]
                .as_array()
                .unwrap()
                .iter()
                .all(|r| r["conversation_id"] != cid.as_str()),
            "the broker handed a project reference to a revoked seat: {batch}"
        );
    }
    let status = call(&bob, "conversation_inbox_status", json!({})).await;
    assert_eq!(status["undelivered"], 0, "{status}");

    for c in [alice, bob_agent, bob] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// Listing obeys the same rules as opening: a private seat taken by a
/// registered window is not listed to the parent token wearing its label,
/// a project grant lists project threads only, and a thread that becomes
/// inaccessible between the candidate query and its read is skipped rather
/// than failing the whole listing (#149).
#[tokio::test]
async fn audit_list_skips_an_authenticated_seat_for_parent_label() {
    let h = require_db!("t_list_candidates");
    let alice_token = seed_agent(&h.pool, "acme", "alice").await;
    let bob_token = seed_agent(&h.pool, "acme", "bob").await;
    enable_conversations(&h.pool, "acme").await;
    let alice_agent = connect(&h.base, &alice_token).await;
    let cred = call(
        &alice_agent,
        "register_session",
        json!({"session": "window"}),
    )
    .await;
    let window = connect(&h.base, cred["session_token"].as_str().unwrap()).await;
    let bob = connect_with_session(&h.base, &bob_token, "bob-win").await;

    // A private thread the registered window owns, and a project thread
    // Alice's shared session can list by grant.
    let private = call(
        &window,
        "create_conversation",
        json!({"title": "window's own", "private": true}),
    )
    .await;
    let private_id = private["id"].as_str().unwrap().to_owned();
    call(&window, "create_project", json!({"project": "shared"})).await;
    let project = call(
        &window,
        "create_conversation",
        json!({"title": "project thread", "project": "shared"}),
    )
    .await;
    let project_id = project["id"].as_str().unwrap().to_owned();

    // The parent token wearing the window's label: the private seat is the
    // window's, the project thread is readable by grant. The listing must
    // succeed and omit the seat it cannot open.
    let impostor = connect_with_session(&h.base, &alice_token, "window").await;
    let listed = call(&impostor, "list_conversations", json!({})).await;
    let ids: Vec<&str> = listed["conversations"]
        .as_array()
        .unwrap()
        .iter()
        .map(|c| c["id"].as_str().unwrap())
        .collect();
    assert!(
        !ids.contains(&private_id.as_str()),
        "the window's private seat is not the label's: {listed}"
    );
    assert!(
        ids.contains(&project_id.as_str()),
        "the project thread is listed by grant: {listed}"
    );
    let err = call_expect_error(
        &impostor,
        "read_conversation",
        json!({"conversation_id": private_id}),
    )
    .await;
    assert!(!err.contains("database error"), "{err}");

    // A legacy row that combines a project with private visibility is
    // still private: the grant lists nothing there.
    let legacy = call(
        &window,
        "create_conversation",
        json!({"title": "legacy private", "private": true}),
    )
    .await;
    let legacy_id: Uuid = legacy["id"].as_str().unwrap().parse().unwrap();
    let (project_uuid,): (Uuid,) =
        sqlx::query_as("SELECT project_id FROM conversations WHERE id = $1")
            .bind(project_id.parse::<Uuid>().unwrap())
            .fetch_one(&h.pool)
            .await
            .unwrap();
    sqlx::query("UPDATE conversations SET project_id = $2 WHERE id = $1")
        .bind(legacy_id)
        .bind(project_uuid)
        .execute(&h.pool)
        .await
        .unwrap();
    call(
        &window,
        "grant_project_access",
        json!({"project": "shared", "agent": "bob"}),
    )
    .await;
    let listed = call(&bob, "list_conversations", json!({})).await;
    let ids: Vec<&str> = listed["conversations"]
        .as_array()
        .unwrap()
        .iter()
        .map(|c| c["id"].as_str().unwrap())
        .collect();
    assert!(ids.contains(&project_id.as_str()), "{listed}");
    assert!(
        !ids.contains(&legacy_id.to_string().as_str()),
        "a private thread naming a project stays private: {listed}"
    );

    // Access lost between candidates and reads does not fail the listing:
    // Bob's grant is revoked while he holds an invitation to the project
    // thread, and the listing still returns what he may see.
    call(
        &window,
        "invite_to_conversation",
        json!({"conversation_id": project_id, "address": "bob/bob-win"}),
    )
    .await;
    call(
        &window,
        "grant_project_access",
        json!({"project": "shared", "agent": "bob", "grant": false}),
    )
    .await;
    let listed = call(&bob, "list_conversations", json!({})).await;
    assert!(
        listed["conversations"].is_array(),
        "the listing answers: {listed}"
    );
    assert!(
        !listed["conversations"]
            .as_array()
            .unwrap()
            .iter()
            .any(|c| c["id"] == project_id.as_str()),
        "a project thread is not listed without the project: {listed}"
    );

    for c in [alice_agent, window, impostor, bob] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// A cursor read drains the backlog oldest first. Taking the newest page
/// and moving the cursor past it lost every unread message older than the
/// page, in every scope (#146). History reads keep returning the last N.
#[tokio::test]
async fn audit_only_new_pagination_does_not_skip_unread_messages() {
    let h = require_db!("t_only_new_pages");
    let alice_token = seed_agent(&h.pool, "acme", "alice").await;
    let bob_token = seed_agent(&h.pool, "acme", "bob").await;
    let alice = connect(&h.base, &alice_token).await;
    let bob = connect(&h.base, &bob_token).await;
    let bodies = |r: &Value| -> Vec<String> {
        r["messages"]
            .as_array()
            .unwrap()
            .iter()
            .map(|m| m["body"].as_str().unwrap().to_owned())
            .collect()
    };

    // Inbox: three DMs, pages of two.
    for body in ["oldest", "middle", "newest"] {
        call(&alice, "post_message", json!({"to": "bob", "body": body})).await;
    }
    let page = call(
        &bob,
        "read_messages",
        json!({"scope": "inbox", "only_new": true, "limit": 2}),
    )
    .await;
    assert_eq!(bodies(&page), ["oldest", "middle"], "{page}");
    assert_eq!(page["truncated"], true, "{page}");
    // A message that arrives between pages lands on a later page, not lost.
    call(
        &alice,
        "post_message",
        json!({"to": "bob", "body": "latest"}),
    )
    .await;
    let page = call(
        &bob,
        "read_messages",
        json!({"scope": "inbox", "only_new": true, "limit": 2}),
    )
    .await;
    assert_eq!(bodies(&page), ["newest", "latest"], "{page}");
    let page = call(
        &bob,
        "read_messages",
        json!({"scope": "inbox", "only_new": true, "limit": 2}),
    )
    .await;
    assert!(bodies(&page).is_empty(), "drained: {page}");
    // History still means the last N, oldest first within the page.
    let last = call(
        &bob,
        "read_messages",
        json!({"scope": "inbox", "only_new": false, "limit": 2}),
    )
    .await;
    assert_eq!(bodies(&last), ["newest", "latest"], "{last}");

    // Channel and all scopes: five messages, pages of two, nothing skipped.
    call(&alice, "create_channel", json!({"name": "pages"})).await;
    for i in 1..=5 {
        call(
            &alice,
            "post_message",
            json!({"channel": "pages", "body": format!("c{i}")}),
        )
        .await;
    }
    let mut seen = Vec::new();
    for _ in 0..3 {
        let page = call(
            &bob,
            "read_messages",
            json!({"scope": "pages", "only_new": true, "limit": 2}),
        )
        .await;
        seen.extend(bodies(&page));
    }
    assert_eq!(
        seen,
        ["c1", "c2", "c3", "c4", "c5"],
        "every channel message, in order"
    );
    // Another window of Bob has its own cursor and starts from the top.
    let other = connect_with_session(&h.base, &bob_token, "other").await;
    let page = call(
        &other,
        "read_messages",
        json!({"scope": "pages", "only_new": true, "limit": 2}),
    )
    .await;
    assert_eq!(bodies(&page), ["c1", "c2"], "independent cursor: {page}");
    // The cross-session view keeps its own cursor too.
    let all = call(
        &bob,
        "read_messages",
        json!({"scope": "all", "only_new": true, "all_sessions": true, "limit": 3}),
    )
    .await;
    assert_eq!(bodies(&all).len(), 3, "{all}");
    assert_eq!(all["truncated"], true, "{all}");
    let all_first = bodies(&all);
    let all2 = call(
        &bob,
        "read_messages",
        json!({"scope": "all", "only_new": true, "all_sessions": true, "limit": 3}),
    )
    .await;
    assert!(
        bodies(&all2).iter().all(|b| !all_first.contains(b)),
        "the next page is new: {all2}"
    );

    for c in [alice, bob, other] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// revoke_session is fenced like resume and renew: a request admitted with
/// a credential that was rotated before it ran must not close the window
/// that replaced it, nor a sibling, while an agent token still closes a
/// dead window and the label registers again afterwards (#148).
#[tokio::test]
async fn audit_a_stale_session_cannot_revoke_its_replacement() {
    use ai_crew_sync::auth::{AuthCtx, hash_token};
    use ai_crew_sync::store::sessions;

    let h = require_db!("t_stale_revoke");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    let (agent_id, token_id): (Uuid, Uuid) = sqlx::query_as(
        "SELECT a.id, t.id FROM api_tokens t JOIN agents a ON a.id = t.agent_id WHERE t.token_hash = $1",
    )
    .bind(hash_token(&token))
    .fetch_one(&h.pool)
    .await
    .unwrap();
    let team = team_id(&h.pool, "acme").await;
    let agent = connect(&h.base, &token).await;
    let first = call(&agent, "register_session", json!({"session": "window"})).await;
    let sibling = call(&agent, "register_session", json!({"session": "sibling"})).await;
    let session_id: Uuid = first["session_id"].as_str().unwrap().parse().unwrap();
    // The context middleware built at epoch 1, kept while the window rotates.
    let stale = AuthCtx {
        agent_id,
        agent_name: "joaquin".into(),
        team_id: team,
        team_slug: "acme".into(),
        session: "window".into(),
        session_id: Some(session_id),
        session_epoch: Some(1),
        token_id: None,
    };
    let old = connect(&h.base, first["session_token"].as_str().unwrap()).await;
    let resumed = call(&old, "resume_session", json!({})).await;
    assert_eq!(resumed["epoch"], 2, "{resumed}");
    let current = resumed["session_token"].as_str().unwrap().to_owned();

    // The stale request runs now: refused, and the replacement still works.
    let err = match sessions::revoke(&h.pool, &stale, None).await {
        Ok(label) => panic!("a stale request revoked '{label}'"),
        Err(e) => e.to_string(),
    };
    assert!(err.contains("stale"), "{err}");
    assert_eq!(
        mcp_status(&h.base, &current).await,
        200,
        "the replacement is untouched"
    );
    let err = match sessions::revoke(&h.pool, &stale, Some("sibling")).await {
        Ok(label) => panic!("a stale request revoked the sibling '{label}'"),
        Err(e) => e.to_string(),
    };
    assert!(err.contains("stale"), "{err}");
    assert_eq!(
        mcp_status(&h.base, sibling["session_token"].as_str().unwrap()).await,
        200,
        "the sibling is untouched"
    );

    // The live credential revokes itself; the agent token closes the
    // sibling; the labels register again afterwards.
    let live = connect(&h.base, &current).await;
    call(&live, "revoke_session", json!({})).await;
    assert_eq!(mcp_status(&h.base, &current).await, 401);
    call(&agent, "revoke_session", json!({"session": "sibling"})).await;
    assert_eq!(
        mcp_status(&h.base, sibling["session_token"].as_str().unwrap()).await,
        401
    );
    let again = call(&agent, "register_session", json!({"session": "window"})).await;
    assert!(again["session_token"].is_string(), "{again}");
    let _ = token_id;

    for c in [agent, old, live] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// An unconfirmed reference handed out again after the window resumed is
/// handed to the window as it is now, at its current epoch: kept at the
/// epoch of the first hand-out, the delivery could never be confirmed
/// again, because confirmation is fenced on the epoch the row carries
/// (#147). The replaced process still cannot confirm it.
#[tokio::test]
async fn audit_postgres_redelivery_after_resume_can_be_confirmed() {
    let h = require_db!("t_redelivery_epoch");
    let alice_token = seed_agent(&h.pool, "acme", "alice").await;
    let bob_token = seed_agent(&h.pool, "acme", "bob").await;
    enable_conversations(&h.pool, "acme").await;
    let alice = connect_with_session(&h.base, &alice_token, "lead").await;
    let bob_agent = connect(&h.base, &bob_token).await;
    let first = call(&bob_agent, "register_session", json!({"session": "reader"})).await;
    let bob1 = connect(&h.base, first["session_token"].as_str().unwrap()).await;

    let convo = call(
        &alice,
        "create_conversation",
        json!({"title": "redelivery", "private": true, "invite": ["bob/reader"]}),
    )
    .await;
    let cid = convo["id"].as_str().unwrap().to_owned();
    call(&bob1, "join_conversation", json!({"conversation_id": cid})).await;
    let mid = call(
        &alice,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "hold this", "request_id": request_id()}),
    )
    .await["message_id"]
        .as_str()
        .unwrap()
        .to_owned();

    // Fetched at epoch 1 and left unconfirmed.
    let batch = call(&bob1, "fetch_conversation_inbox", json!({})).await;
    let delivery = batch["references"][0]["delivery_id"]
        .as_str()
        .unwrap()
        .to_owned();
    assert_eq!(batch["references"][0]["message_id"], mid, "{batch}");

    // The window resumes: new secret, epoch 2. The grace period elapses.
    let resumed = call(&bob1, "resume_session", json!({})).await;
    assert_eq!(resumed["epoch"], 2, "{resumed}");
    let bob2 = connect(&h.base, resumed["session_token"].as_str().unwrap()).await;
    sqlx::query(
        "UPDATE inbox_deliveries SET handed_at = now() - interval '6 minutes' WHERE id = $1",
    )
    .bind(delivery.parse::<Uuid>().unwrap())
    .execute(&h.pool)
    .await
    .unwrap();

    // Redelivered to the current window, and confirmable by it.
    let again = call(&bob2, "fetch_conversation_inbox", json!({})).await;
    assert_eq!(
        again["references"][0]["delivery_id"], delivery,
        "the same delivery: {again}"
    );
    let (epoch,): (Option<i64>,) =
        sqlx::query_as("SELECT epoch FROM inbox_deliveries WHERE id = $1")
            .bind(delivery.parse::<Uuid>().unwrap())
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert_eq!(epoch, Some(2), "the row now belongs to epoch 2");
    let done = call(
        &bob2,
        "confirm_inbox_delivery",
        json!({"delivery_ids": [delivery]}),
    )
    .await;
    assert_eq!(done["confirmed"], 1, "{done}");
    let receipts = call(&alice, "get_message_receipts", json!({"message_id": mid})).await;
    assert!(
        receipts["receipts"][0]["delivered_at"].is_string(),
        "{receipts}"
    );

    // A second message: handed out at epoch 2, and the replaced process
    // (epoch 1's credential is dead; its context would be stale) cannot
    // confirm what the live window holds.
    let mid2 = call(
        &alice,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "and this", "request_id": request_id()}),
    )
    .await["message_id"]
        .as_str()
        .unwrap()
        .to_owned();
    let batch = call(&bob2, "fetch_conversation_inbox", json!({})).await;
    let delivery2 = batch["references"][0]["delivery_id"]
        .as_str()
        .unwrap()
        .to_owned();
    assert_eq!(batch["references"][0]["message_id"], mid2, "{batch}");
    let status = mcp_status(&h.base, first["session_token"].as_str().unwrap()).await;
    assert_eq!(
        status, 401,
        "the replaced credential is refused before it can confirm"
    );
    let done = call(
        &bob2,
        "confirm_inbox_delivery",
        json!({"delivery_ids": [delivery2]}),
    )
    .await;
    assert_eq!(done["confirmed"], 1, "{done}");

    for c in [alice, bob_agent, bob1, bob2] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// The proxy's inbox fetch always answers with the fetch, never with the
/// confirmation it sends on the side, and a confirmation replayed after a
/// lost local record converges: the bus lists what it committed and what it
/// had already, and the spool settles on both (#150).
#[tokio::test]
async fn audit_proxy_inbox_keeps_fetch_schema_after_lost_confirmation() {
    let h = require_db!("t_proxy_inbox_replay");
    let alice_token = seed_agent(&h.pool, "acme", "alice").await;
    let bob_token = seed_agent(&h.pool, "acme", "bob").await;
    enable_conversations(&h.pool, "acme").await;
    let dir = proxy_config_dir(&h.base, &[("acme", "acme", "bob", &bob_token)]);
    let repo = dir.join("repo");
    std::fs::create_dir_all(&repo).unwrap();
    std::fs::write(repo.join(".acs.toml"), "profile = \"acme\"\n").unwrap();
    let bob = spawn_proxy(&dir, &repo, &["--host-session", "conv-inbox"], &[]).await;
    let status = call(&bob, "session_status", json!({})).await;
    let address = status["address"].as_str().unwrap().to_owned();
    let alice = connect_with_session(&h.base, &alice_token, "lead").await;
    let convo = call(
        &alice,
        "create_conversation",
        json!({"title": "spool", "private": true, "invite": [address]}),
    )
    .await;
    let cid = convo["id"].as_str().unwrap().to_owned();
    call(&bob, "join_conversation", json!({"conversation_id": cid})).await;
    let send = |body: &'static str| {
        let alice = &alice;
        let cid = cid.clone();
        async move {
            call(
                alice,
                "send_conversation_message",
                json!({"conversation_id": cid, "body": body, "request_id": request_id()}),
            )
            .await["message_id"]
                .as_str()
                .unwrap()
                .to_owned()
        }
    };
    let first = send("first").await;

    // Fetched through the proxy: the reply is the fetch, and the proxy
    // confirms behind the scenes and records it in its spool.
    let batch = call(&bob, "fetch_conversation_inbox", json!({})).await;
    assert_eq!(batch["references"][0]["message_id"], first, "{batch}");
    let spool = std::fs::read_dir(dir.join("inbox"))
        .unwrap()
        .filter_map(|e| e.ok())
        .map(|e| e.path())
        .find(|p| p.extension().is_some_and(|x| x == "jsonl"))
        .expect("the proxy wrote a spool");
    let confirmed_line = |path: &std::path::Path| -> Vec<bool> {
        std::fs::read_to_string(path)
            .unwrap()
            .lines()
            .filter(|l| !l.trim().is_empty())
            .map(|l| {
                serde_json::from_str::<Value>(l).unwrap()["confirmed"]
                    .as_bool()
                    .unwrap()
            })
            .collect()
    };
    assert_eq!(
        confirmed_line(&spool),
        vec![true],
        "confirmed after the first fetch"
    );

    // The crash window: the bus committed the confirmation, the local
    // rewrite was lost. Replay the fetch.
    let text = std::fs::read_to_string(&spool)
        .unwrap()
        .replace("\"confirmed\":true", "\"confirmed\":false");
    std::fs::write(&spool, text).unwrap();
    assert_eq!(confirmed_line(&spool), vec![false]);
    let again = call(&bob, "fetch_conversation_inbox", json!({})).await;
    assert!(
        again.get("references").is_some(),
        "the fetch keeps its schema: {again}"
    );
    assert!(
        again.get("confirmed").is_none(),
        "the confirmation reply never leaks: {again}"
    );
    assert_eq!(
        confirmed_line(&spool),
        vec![true],
        "the replay converged on already_confirmed"
    );

    // A pending old entry mixed with a fresh one: both settle in one call.
    let second = send("second").await;
    let text = std::fs::read_to_string(&spool)
        .unwrap()
        .replace("\"confirmed\":true", "\"confirmed\":false");
    std::fs::write(&spool, text).unwrap();
    let batch = call(&bob, "fetch_conversation_inbox", json!({})).await;
    assert_eq!(batch["references"][0]["message_id"], second, "{batch}");
    assert_eq!(
        confirmed_line(&spool),
        vec![true, true],
        "old and new both settled"
    );

    // The bus itself lists what it settled, scoped to the caller.
    let direct = connect_with_session(&h.base, &alice_token, "lead").await;
    let ids: Vec<String> = std::fs::read_to_string(&spool)
        .unwrap()
        .lines()
        .filter(|l| !l.trim().is_empty())
        .map(|l| {
            serde_json::from_str::<Value>(l).unwrap()["delivery_id"]
                .as_str()
                .unwrap()
                .to_owned()
        })
        .collect();
    let foreign = call(
        &direct,
        "confirm_inbox_delivery",
        json!({"delivery_ids": ids}),
    )
    .await;
    assert_eq!(foreign["confirmed"], 0, "{foreign}");
    assert_eq!(
        foreign["already_confirmed"],
        json!([]),
        "somebody else's settled ids are not the caller's: {foreign}"
    );

    let _ = bob.cancel().await;
    for c in [alice, direct] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// An inbox fetch that was admitted holds the session row for the whole
/// hand-out: a resume waits for it, and once the resume has committed a
/// fetch still carrying the old epoch is refused inside its own transaction
/// rather than stamping the old epoch over the live window's delivery.
#[tokio::test]
async fn audit_an_admitted_fetch_cannot_move_a_delivery_backwards() {
    use ai_crew_sync::store::{inbox, routing::Backends, sessions};
    let h = require_db!("t_fetch_epoch_fence");
    let alice_token = seed_agent(&h.pool, "acme", "alice").await;
    let bob_token = seed_agent(&h.pool, "acme", "bob").await;
    enable_conversations(&h.pool, "acme").await;
    let alice = connect_with_session(&h.base, &alice_token, "lead").await;
    let bob_agent = connect(&h.base, &bob_token).await;
    let first = call(&bob_agent, "register_session", json!({"session": "reader"})).await;
    let bob1 = connect(&h.base, first["session_token"].as_str().unwrap()).await;
    let convo = call(
        &alice,
        "create_conversation",
        json!({"title": "fence", "private": true, "invite": ["bob/reader"]}),
    )
    .await;
    let cid = convo["id"].as_str().unwrap().to_owned();
    call(&bob1, "join_conversation", json!({"conversation_id": cid})).await;
    let mid = call(
        &alice,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "hold this", "request_id": request_id()}),
    )
    .await["message_id"]
        .as_str()
        .unwrap()
        .to_owned();
    let bob_epoch1 = ai_crew_sync::auth::AuthCtx {
        agent_id: sqlx::query_scalar::<_, Uuid>("SELECT id FROM agents WHERE name = 'bob'")
            .fetch_one(&h.pool)
            .await
            .unwrap(),
        agent_name: "bob".into(),
        team_id: team_id(&h.pool, "acme").await,
        team_slug: "acme".into(),
        session: "reader".into(),
        session_id: Some(
            first["session_id"]
                .as_str()
                .unwrap()
                .parse::<Uuid>()
                .unwrap(),
        ),
        session_epoch: Some(1),
        token_id: None,
    };

    // An admitted fetch, paused before its hand-out: the guard it passed
    // holds the session row, so the resume cannot commit underneath it.
    let mut admitted = h.pool.begin().await.unwrap();
    sessions::guard(&mut admitted, &bob_epoch1).await.unwrap();
    let resume = {
        let bob1 = connect(&h.base, first["session_token"].as_str().unwrap()).await;
        tokio::spawn(async move {
            let out = call(&bob1, "resume_session", json!({})).await;
            let _ = bob1.cancel().await;
            out
        })
    };
    tokio::time::sleep(std::time::Duration::from_millis(800)).await;
    assert!(
        !resume.is_finished(),
        "the resume must wait for the admitted fetch to finish"
    );
    admitted.rollback().await.unwrap();
    let resumed = tokio::time::timeout(std::time::Duration::from_secs(10), resume)
        .await
        .expect("the resume proceeds once the fetch is done")
        .unwrap();
    assert_eq!(resumed["epoch"], 2, "{resumed}");
    let bob2 = connect(&h.base, resumed["session_token"].as_str().unwrap()).await;

    // The live window takes the delivery at epoch 2.
    let batch = call(&bob2, "fetch_conversation_inbox", json!({})).await;
    let delivery = batch["references"][0]["delivery_id"]
        .as_str()
        .unwrap()
        .to_owned();
    assert_eq!(batch["references"][0]["message_id"], mid, "{batch}");

    // A fetch still carrying epoch 1, admitted at the door and reaching the
    // store after the resume: refused inside its transaction, and the row
    // keeps epoch 2 for the window that holds it.
    let backends = Backends::postgres_only(h.pool.clone());
    let err = match inbox::fetch(&h.pool, &backends, &bob_epoch1, None).await {
        Ok(_) => panic!("a stale fetch must not hand anything out"),
        Err(e) => e.to_string(),
    };
    assert!(err.contains("stale"), "{err}");
    let (epoch,): (Option<i64>,) =
        sqlx::query_as("SELECT epoch FROM inbox_deliveries WHERE id = $1")
            .bind(delivery.parse::<Uuid>().unwrap())
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert_eq!(epoch, Some(2), "the delivery stays with the live window");

    // The statement itself refuses to go backwards, guard or no guard: a
    // hand-out at epoch 1 run straight against the store leaves the row at
    // epoch 2 and hands nothing out.
    let membership_id: Uuid = sqlx::query_scalar(
        "SELECT id FROM conversation_memberships WHERE conversation_id = $1 AND agent_id = $2",
    )
    .bind(cid.parse::<Uuid>().unwrap())
    .bind(bob_epoch1.agent_id)
    .fetch_one(&h.pool)
    .await
    .unwrap();
    let key = inbox::recipient_key(bob_epoch1.agent_id, "reader");
    let mut unguarded = h.pool.begin().await.unwrap();
    let handed = inbox::hand_out_message(
        &mut unguarded,
        &bob_epoch1,
        &key,
        mid.parse::<Uuid>().unwrap(),
        membership_id,
        cid.parse::<Uuid>().unwrap(),
    )
    .await
    .unwrap();
    unguarded.commit().await.unwrap();
    assert!(
        handed.is_none(),
        "an older epoch must not take the delivery over"
    );
    let (epoch,): (Option<i64>,) =
        sqlx::query_as("SELECT epoch FROM inbox_deliveries WHERE id = $1")
            .bind(delivery.parse::<Uuid>().unwrap())
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert_eq!(epoch, Some(2), "still the live window's");
    let done = call(
        &bob2,
        "confirm_inbox_delivery",
        json!({"delivery_ids": [delivery]}),
    )
    .await;
    assert_eq!(done["confirmed"], 1, "{done}");

    for c in [alice, bob_agent, bob1, bob2] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// A proxy renews its session credential before it expires, busy or idle,
/// without rotating secret or epoch, and records the new expiry in its
/// binding; a revoked credential is refused at renewal and reported, never
/// replaced by another identity (#153).
#[tokio::test]
async fn audit_proxy_renews_its_credential_before_expiry() {
    let h = require_db!("t_proxy_renewal");
    let bob_token = seed_agent(&h.pool, "acme", "bob").await;
    let dir = proxy_config_dir(&h.base, &[("acme", "acme", "bob", &bob_token)]);
    let repo = dir.join("repo");
    std::fs::create_dir_all(&repo).unwrap();
    std::fs::write(repo.join(".acs.toml"), "profile = \"acme\"\n").unwrap();
    // A 60 s credential renewed 50 s before it expires: the first renewal is
    // due 10 s in, and retries are 12 s apart.
    let knobs = [
        ("BUS_SESSION_TTL_SECS", "60"),
        ("BUS_SESSION_RENEW_LEAD_SECS", "50"),
    ];
    let busy = spawn_proxy(&dir, &repo, &["--host-session", "conv-busy"], &knobs).await;
    let idle = spawn_proxy(&dir, &repo, &["--host-session", "conv-idle"], &knobs).await;
    let started = std::time::Instant::now();
    let session_of = |status: Value| status["session"].as_str().unwrap().to_owned();
    let busy_label = session_of(call(&busy, "session_status", json!({})).await);
    let idle_label = session_of(call(&idle, "session_status", json!({})).await);
    let row = |label: String| {
        let pool = h.pool.clone();
        async move {
            sqlx::query_as::<_, (i64, Vec<u8>, chrono::DateTime<chrono::Utc>)>(
                "SELECT epoch, token_hash, expires_at FROM agent_sessions WHERE label = $1 AND revoked_at IS NULL",
            )
            .bind(label)
            .fetch_one(&pool)
            .await
            .unwrap()
        }
    };
    let (busy_epoch, busy_hash, busy_expiry) = row(busy_label.clone()).await;
    let (idle_epoch, idle_hash, idle_expiry) = row(idle_label.clone()).await;
    assert!(
        (busy_expiry - chrono::Utc::now()).num_seconds() <= 60,
        "the proxy asked for the short lifetime: {busy_expiry}"
    );

    // Busy: keeps calling. Idle: nothing but its keepalive. Both must be
    // renewed by the time the first deadline plus a retry has passed.
    let deadline = started + std::time::Duration::from_secs(40);
    loop {
        let me = call(&busy, "whoami", json!({})).await;
        assert_eq!(me["agent"], "bob", "{me}");
        let (_, _, b) = row(busy_label.clone()).await;
        let (_, _, i) = row(idle_label.clone()).await;
        if b > busy_expiry && i > idle_expiry {
            break;
        }
        assert!(
            std::time::Instant::now() < deadline,
            "no renewal within 40 s: busy {b} (was {busy_expiry}), idle {i} (was {idle_expiry})"
        );
        tokio::time::sleep(std::time::Duration::from_secs(2)).await;
    }
    let (epoch, hash, expiry) = row(busy_label.clone()).await;
    assert_eq!(
        (epoch, &hash),
        (busy_epoch, &busy_hash),
        "renewal rotates nothing"
    );
    assert!(expiry > busy_expiry);
    let (epoch, hash, expiry) = row(idle_label.clone()).await;
    assert_eq!(
        (epoch, &hash),
        (idle_epoch, &idle_hash),
        "renewal rotates nothing"
    );
    assert!(expiry > idle_expiry);
    // The binding carries the renewed expiry, so a hook of this window
    // reads the same lifetime the bus holds.
    let binding = std::fs::read_to_string(ai_crew_sync::context::binding_path(&dir, "conv-idle"))
        .expect("the idle window has a binding");
    let recorded = serde_json::from_str::<Value>(&binding).unwrap()["expires_at"]
        .as_str()
        .unwrap()
        .to_owned();
    let recorded = chrono::DateTime::parse_from_rfc3339(&recorded)
        .unwrap()
        .with_timezone(&chrono::Utc);
    assert!(
        recorded > idle_expiry,
        "binding stamped: {recorded} vs {idle_expiry}"
    );
    let status = call(&idle, "session_status", json!({})).await;
    assert!(status["error"].is_null(), "{status}");

    // Revocation wins: the parent revokes the idle window by label; its
    // next renewal is refused and the proxy says so instead of switching
    // identities.
    let parent = connect(&h.base, &bob_token).await;
    call(&parent, "revoke_session", json!({"session": idle_label})).await;
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(40);
    loop {
        let status = call(&idle, "session_status", json!({})).await;
        if status["error"]
            .as_str()
            .is_some_and(|e| e.contains("rejected the credential"))
        {
            break;
        }
        assert!(
            std::time::Instant::now() < deadline,
            "the refusal was never reported: {status}"
        );
        tokio::time::sleep(std::time::Duration::from_secs(1)).await;
    }
    let (_, _, still) = row(busy_label).await;
    assert!(still > busy_expiry, "the other window is unaffected");

    let _ = busy.cancel().await;
    let _ = idle.cancel().await;
    let _ = parent.cancel().await;
    h.shutdown().await;
}

/// The renewal schedule follows the connected context, not the presence
/// tick: a credential established after startup (configure_session on a
/// proxy that started without a profile) is renewed on time, and after a
/// refusal a context established anew is renewed again.
#[tokio::test]
async fn audit_proxy_renewal_follows_a_context_established_later() {
    let h = require_db!("t_proxy_renewal_late");
    let bob_token = seed_agent(&h.pool, "acme", "bob").await;
    let dir = proxy_config_dir(&h.base, &[("acme", "acme", "bob", &bob_token)]);
    // No .acs.toml and no default profile: the proxy starts disconnected.
    let repo = dir.join("repo");
    std::fs::create_dir_all(&repo).unwrap();
    let knobs = [
        ("BUS_SESSION_TTL_SECS", "60"),
        ("BUS_SESSION_RENEW_LEAD_SECS", "50"),
    ];
    let proxy = spawn_proxy(&dir, &repo, &["--host-session", "conv-late"], &knobs).await;
    let status = call(&proxy, "session_status", json!({})).await;
    assert_eq!(status["connected"], false, "{status}");
    let label = status["session"].as_str().unwrap().to_owned();
    let row = |label: String| {
        let pool = h.pool.clone();
        async move {
            sqlx::query_as::<_, (i64, chrono::DateTime<chrono::Utc>)>(
                "SELECT epoch, expires_at FROM agent_sessions WHERE label = $1 AND revoked_at IS NULL",
            )
            .bind(label)
            .fetch_one(&pool)
            .await
            .unwrap()
        }
    };
    let renewed_after = |label: String, since: chrono::DateTime<chrono::Utc>| {
        let row = &row;
        async move {
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(40);
            loop {
                let (_, expiry) = row(label.clone()).await;
                if expiry > since {
                    return expiry;
                }
                assert!(
                    std::time::Instant::now() < deadline,
                    "no renewal within 40 s of {since}"
                );
                tokio::time::sleep(std::time::Duration::from_secs(2)).await;
            }
        }
    };

    // Configured after startup: the keepalive must pick the credential up
    // now, not on its next five-minute presence tick.
    let switched = call(&proxy, "configure_session", json!({"profile": "acme"})).await;
    assert_eq!(switched["status"]["connected"], true, "{switched}");
    let (_, first_expiry) = row(label.clone()).await;
    renewed_after(label.clone(), first_expiry).await;

    // Refused, then established anew: the refusal's backoff belongs to the
    // old context, and the new credential is scheduled at once.
    let parent = connect(&h.base, &bob_token).await;
    call(&parent, "revoke_session", json!({"session": label})).await;
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(40);
    loop {
        let status = call(&proxy, "session_status", json!({})).await;
        if status["error"]
            .as_str()
            .is_some_and(|e| e.contains("rejected the credential"))
        {
            break;
        }
        assert!(
            std::time::Instant::now() < deadline,
            "the refusal was never reported: {status}"
        );
        tokio::time::sleep(std::time::Duration::from_secs(1)).await;
    }
    let again = call(&proxy, "configure_session", json!({"profile": "acme"})).await;
    assert_eq!(again["status"]["connected"], true, "{again}");
    assert!(again["status"]["error"].is_null(), "{again}");
    let (_, second_expiry) = row(label.clone()).await;
    renewed_after(label.clone(), second_expiry).await;

    let _ = proxy.cancel().await;
    let _ = parent.cancel().await;
    h.shutdown().await;
}

/// Every writer of a binding record takes the configuration lock: a proxy
/// starting while another holder has it waits to publish its record rather
/// than replacing it underneath a renewal's ownership check.
#[tokio::test]
async fn audit_binding_writers_share_the_config_lock() {
    let h = require_db!("t_binding_lock");
    let bob_token = seed_agent(&h.pool, "acme", "bob").await;
    let dir = proxy_config_dir(&h.base, &[("acme", "acme", "bob", &bob_token)]);
    let repo = dir.join("repo");
    std::fs::create_dir_all(&repo).unwrap();
    std::fs::write(repo.join(".acs.toml"), "profile = \"acme\"\n").unwrap();

    // Hold the directory's lock for three seconds, as a sibling writer would.
    let lock_path = dir.join(".lock");
    let held = std::fs::OpenOptions::new()
        .create(true)
        .truncate(false)
        .write(true)
        .open(&lock_path)
        .unwrap();
    let holder = tokio::task::spawn_blocking(move || {
        held.lock().unwrap();
        std::thread::sleep(std::time::Duration::from_secs(3));
        held.unlock().unwrap();
    });
    tokio::time::sleep(std::time::Duration::from_millis(200)).await;

    // The proxy registers its session and then publishes its binding, which
    // waits for the lock: it cannot answer before the holder lets go.
    let started = std::time::Instant::now();
    let proxy = spawn_proxy(&dir, &repo, &["--host-session", "conv-locked"], &[]).await;
    let status = call(&proxy, "session_status", json!({})).await;
    let waited = started.elapsed();
    assert_eq!(status["connected"], true, "{status}");
    assert!(
        waited >= std::time::Duration::from_secs(2),
        "the proxy published its binding without waiting for the lock ({waited:?})"
    );
    holder.await.unwrap();
    let binding = std::fs::read_to_string(ai_crew_sync::context::binding_path(&dir, "conv-locked"))
        .expect("the binding was written once the lock was free");
    assert!(
        binding.contains(status["session"].as_str().unwrap()),
        "{binding}"
    );

    let _ = proxy.cancel().await;
    h.shutdown().await;
}

/// The Stop drain of a bound window reads that window's inbox whatever the
/// environment exports: with a parent BUS_TOKEN and a conflicting
/// BUS_SESSION, with the conflicting session alone, and after a same-team
/// profile switch. A conversation with no binding keeps the legacy path,
/// which is what proves the environment really pointed elsewhere (#152).
#[tokio::test]
async fn audit_stop_drain_reads_the_bound_window_whatever_the_environment_says() {
    let h = require_db!("t_stop_drain_binding");
    let bob_token = seed_agent(&h.pool, "acme", "bob").await;
    let bobby_token = seed_agent(&h.pool, "acme", "bobby").await;
    let alice_token = seed_agent(&h.pool, "acme", "alice").await;
    let dir = proxy_config_dir(
        h.base.as_str(),
        &[
            ("acme", "acme", "bob", &bob_token),
            ("acme-bobby", "acme", "bobby", &bobby_token),
        ],
    );
    let repo = dir.join("repo");
    std::fs::create_dir_all(&repo).unwrap();
    std::fs::write(repo.join(".acs.toml"), "profile = \"acme\"\n").unwrap();
    let window = spawn_proxy(&dir, &repo, &["--host-session", "audit-hook-window"], &[]).await;
    let label = call(&window, "session_status", json!({})).await["session"]
        .as_str()
        .unwrap()
        .to_owned();
    // The other window really exists: bob's legacy label has announced itself.
    let legacy = connect_with_session(&h.base, &bob_token, "legacy-other").await;
    call(&legacy, "heartbeat", json!({"status": "active"})).await;
    let alice = connect_with_session(&h.base, &alice_token, "lead").await;
    let ask = |to: String, body: &'static str| {
        let alice = &alice;
        async move {
            call(
                alice,
                "post_message",
                json!({"to": to, "body": body, "metadata": {"question": true}}),
            )
            .await
        }
    };
    ask(
        "bob/legacy-other".to_owned(),
        "ONLY THE OTHER WINDOW SHOULD SEE THIS QUESTION",
    )
    .await;

    let mcp_url = format!("{}/mcp", h.base);
    let conflicting = [
        ("BUS_URL", mcp_url.as_str()),
        ("BUS_TOKEN", bob_token.as_str()),
        ("BUS_SESSION", "legacy-other"),
    ];
    let bound = r#"{"session_id":"audit-hook-window"}"#;

    // Bound window, parent token and conflicting session exported: nothing
    // to block on, because the other window's question is not this one's.
    let out = run_hook_env("stop-drain.sh", &dir, &repo, bound, &[], &conflicting).await;
    assert_eq!(
        out.trim(),
        "",
        "the bound drain injected the other window's question: {out}"
    );
    // The same without a token: the binding, not BUS_SESSION, still decides.
    let out = run_hook_env("stop-drain.sh", &dir, &repo, bound, &[], &conflicting[2..]).await;
    assert_eq!(out.trim(), "", "{out}");
    // Positive control: with no binding at all (no session_id in the
    // payload) the legacy path reads exactly what the environment says.
    let out = run_hook_env("stop-drain.sh", &dir, &repo, "{}", &[], &conflicting).await;
    assert!(
        out.contains("ONLY THE OTHER WINDOW"),
        "the legacy path did not see the other window's question: {out}"
    );

    // A question for the bound window is raised, with the token exported
    // and without it.
    ask(
        format!("bob/{label}"),
        "FOR THE BOUND WINDOW, WITH A TOKEN EXPORTED",
    )
    .await;
    let out = run_hook_env("stop-drain.sh", &dir, &repo, bound, &[], &conflicting).await;
    assert!(
        out.contains("\"decision\": \"block\"") || out.contains("\"decision\":\"block\""),
        "{out}"
    );
    assert!(
        out.contains("WITH A TOKEN EXPORTED") && !out.contains("ONLY THE OTHER WINDOW"),
        "{out}"
    );
    ask(format!("bob/{label}"), "FOR THE BOUND WINDOW, NO TOKEN").await;
    let out = run_hook_env("stop-drain.sh", &dir, &repo, bound, &[], &conflicting[2..]).await;
    assert!(
        out.contains("NO TOKEN") && !out.contains("ONLY THE OTHER WINDOW"),
        "{out}"
    );

    // Same-team profile switch: the window is now bobby's, and the drain
    // follows the binding to bobby's inbox, with bob's token still exported.
    let switched = call(
        &window,
        "configure_session",
        json!({"profile": "acme-bobby"}),
    )
    .await;
    assert_eq!(switched["status"]["agent"], "bobby", "{switched}");
    ask(format!("bobby/{label}"), "FOR BOBBY AFTER THE SWITCH").await;
    ask(
        format!("bob/{label}"),
        "FOR BOB, WHO NO LONGER HAS THIS WINDOW",
    )
    .await;
    let out = run_hook_env("stop-drain.sh", &dir, &repo, bound, &[], &conflicting).await;
    assert!(out.contains("FOR BOBBY AFTER THE SWITCH"), "{out}");
    assert!(
        !out.contains("NO LONGER HAS THIS WINDOW") && !out.contains("ONLY THE OTHER WINDOW"),
        "{out}"
    );

    // The call event cannot be turned against the window it serves: a
    // hook asking to resume the session is refused before the bus is
    // contacted, prints no secret, and the proxy stays authenticated at
    // its epoch.
    let (epoch_before,): (i64,) = sqlx::query_as(
        "SELECT epoch FROM agent_sessions WHERE label = $1 AND revoked_at IS NULL
          ORDER BY created_at DESC LIMIT 1",
    )
    .bind(&label)
    .fetch_one(&h.pool)
    .await
    .unwrap();
    let bin = env!("CARGO_BIN_EXE_ai-crew-sync").to_owned();
    let cfg = dir.clone();
    let attempt = tokio::task::spawn_blocking(move || {
        std::process::Command::new(bin)
            .args([
                "context",
                "hook",
                "--binding",
                "audit-hook-window",
                "--event",
                "call",
                "--tool",
                "resume_session",
                "--args",
                "{}",
            ])
            .env_clear()
            .env("PATH", std::env::var("PATH").unwrap_or_default())
            .env("HOME", std::env::var("HOME").unwrap_or_default())
            .env("BUS_CONFIG_DIR", cfg)
            .output()
            .expect("the binary runs")
    })
    .await
    .unwrap();
    let stdout = String::from_utf8_lossy(&attempt.stdout);
    let stderr = String::from_utf8_lossy(&attempt.stderr);
    assert_eq!(stdout.trim(), "", "a refused call prints nothing: {stdout}");
    assert!(stderr.contains("not a hook operation"), "{stderr}");
    assert!(
        !stdout.contains("acss_") && !stderr.contains("acss_"),
        "no secret in any output"
    );
    let (epoch_after,): (i64,) = sqlx::query_as(
        "SELECT epoch FROM agent_sessions WHERE label = $1 AND revoked_at IS NULL
          ORDER BY created_at DESC LIMIT 1",
    )
    .bind(&label)
    .fetch_one(&h.pool)
    .await
    .unwrap();
    assert_eq!(epoch_after, epoch_before, "the window's epoch is untouched");
    let me = call(&window, "whoami", json!({})).await;
    assert_eq!(
        me["agent"], "bobby",
        "the proxy is still authenticated: {me}"
    );
    let status = call(&window, "session_status", json!({})).await;
    assert!(status["error"].is_null(), "{status}");

    let _ = window.cancel().await;
    for c in [legacy, alice] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// The listing's race guard, exercised for real: a revocation that commits
/// between candidate selection and the per-conversation read leaves the
/// project thread out and the private thread in, with no error (#167).
#[tokio::test]
async fn audit_listing_skips_a_grant_revoked_after_candidate_selection() {
    use ai_crew_sync::store::conversations as convo_store;
    let h = require_db!("t_listing_race");
    let alice_token = seed_agent(&h.pool, "acme", "alice").await;
    let bob_token = seed_agent(&h.pool, "acme", "bob").await;
    enable_conversations(&h.pool, "acme").await;
    let alice = connect_with_session(&h.base, &alice_token, "lead").await;
    let bob_agent = connect(&h.base, &bob_token).await;
    let cred = call(&bob_agent, "register_session", json!({"session": "reader"})).await;
    let bob = connect(&h.base, cred["session_token"].as_str().unwrap()).await;
    call(&alice, "create_project", json!({"project": "audit"})).await;
    call(
        &alice,
        "grant_project_access",
        json!({"project": "audit", "agent": "bob"}),
    )
    .await;
    let project_thread = call(
        &alice,
        "create_conversation",
        json!({"title": "project", "project": "audit", "invite": ["bob/reader"]}),
    )
    .await["id"]
        .as_str()
        .unwrap()
        .parse::<Uuid>()
        .unwrap();
    let private_thread = call(
        &alice,
        "create_conversation",
        json!({"title": "private", "private": true, "invite": ["bob/reader"]}),
    )
    .await["id"]
        .as_str()
        .unwrap()
        .parse::<Uuid>()
        .unwrap();
    for id in [project_thread, private_thread] {
        call(&bob, "join_conversation", json!({"conversation_id": id})).await;
    }
    let bob_ctx = ai_crew_sync::auth::AuthCtx {
        agent_id: sqlx::query_scalar::<_, Uuid>("SELECT id FROM agents WHERE name = 'bob'")
            .fetch_one(&h.pool)
            .await
            .unwrap(),
        agent_name: "bob".into(),
        team_id: team_id(&h.pool, "acme").await,
        team_slug: "acme".into(),
        session: "reader".into(),
        session_id: Some(
            cred["session_id"]
                .as_str()
                .unwrap()
                .parse::<Uuid>()
                .unwrap(),
        ),
        session_epoch: Some(1),
        token_id: None,
    };

    // Candidates chosen while the grant stands: both threads.
    let candidates = convo_store::list_candidates(&h.pool, &bob_ctx, false)
        .await
        .unwrap();
    assert!(candidates.contains(&project_thread), "{candidates:?}");
    assert!(candidates.contains(&private_thread), "{candidates:?}");

    // The revocation commits in the window between the two halves.
    call(
        &alice,
        "grant_project_access",
        json!({"project": "audit", "agent": "bob", "grant": false}),
    )
    .await;

    // The second half copes: the project thread is skipped, the private
    // one is listed, and nothing errors.
    let listed = convo_store::list_conversations_among(&h.pool, &bob_ctx, candidates)
        .await
        .expect("a revoked candidate must not fail the listing");
    let ids: Vec<String> = listed.iter().map(|c| c.id.clone()).collect();
    assert!(ids.contains(&private_thread.to_string()), "{ids:?}");
    assert!(!ids.contains(&project_thread.to_string()), "{ids:?}");

    // The tool agrees once the candidate query itself runs after the revoke.
    let through_api = call(&bob, "list_conversations", json!({})).await;
    let api_ids: Vec<&str> = through_api["conversations"]
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|c| c["id"].as_str())
        .collect();
    assert_eq!(
        api_ids,
        vec![private_thread.to_string().as_str()],
        "{through_api}"
    );

    for c in [alice, bob_agent, bob] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// A receipt event handed out from the bus's own records is rehanded at the
/// fetching window's epoch after a resume, exactly as a message reference
/// is, the live window confirms it, and a context still at the old epoch
/// cannot (#167). The Postgres reconciliation also tops up a batch while
/// the broker is healthy; here the team's streams are deleted, so the
/// reference can only have come from Postgres.
#[tokio::test]
async fn audit_receipt_event_redelivery_after_resume_on_the_postgres_path() {
    use ai_crew_sync::store::jetstream::{Config, JetStreamBackend};
    use ai_crew_sync::store::{inbox, outbox};
    let h = require_db_broker!("t_receipt_redelivery");
    let alice_token = seed_agent(&h.pool, "acme", "alice").await;
    let bob_token = seed_agent(&h.pool, "acme", "bob").await;
    enable_conversations(&h.pool, "acme").await;
    let team = team_id(&h.pool, "acme").await;
    sqlx::query("UPDATE teams SET default_backend = 'jetstream' WHERE id = $1")
        .bind(team)
        .execute(&h.pool)
        .await
        .unwrap();
    let config = Config::new(nats_url()).with_limits(1_000, 16 * 1024 * 1024);
    JetStreamBackend::provision(&config, team).await.unwrap();
    JetStreamBackend::provision_inbox(&config, team)
        .await
        .unwrap();
    let backend = JetStreamBackend::connect(&config, team).await.unwrap();
    let publish = || async {
        assert_eq!(
            outbox::run_once(&h.pool, &backend, "worker").await.unwrap(),
            Some(outbox::Settled::Stored)
        );
        inbox::publish_pending(&h.pool, &backend, team, 100)
            .await
            .unwrap()
    };
    // Both sides are registered windows: the sender's inbox is where the
    // receipt event lands, and only a window has an inbox.
    let alice_agent = connect(&h.base, &alice_token).await;
    let alice_cred = call(&alice_agent, "register_session", json!({"session": "lead"})).await;
    let alice1 = connect(&h.base, alice_cred["session_token"].as_str().unwrap()).await;
    let bob_agent = connect(&h.base, &bob_token).await;
    let bob_cred = call(&bob_agent, "register_session", json!({"session": "reader"})).await;
    let bob = connect(&h.base, bob_cred["session_token"].as_str().unwrap()).await;

    let cid = call(
        &alice1,
        "create_conversation",
        json!({"title": "receipts", "private": true, "invite": ["bob/reader"]}),
    )
    .await["id"]
        .as_str()
        .unwrap()
        .to_owned();
    call(&bob, "join_conversation", json!({"conversation_id": cid})).await;
    let mid = call(
        &alice1,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "look again", "request_id": request_id()}),
    )
    .await["message_id"]
        .as_str()
        .unwrap()
        .to_owned();
    assert_eq!(publish().await, 1, "one reference for Bob");
    let batch = call(&bob, "fetch_conversation_inbox", json!({})).await;
    let bob_delivery = batch["references"][0]["delivery_id"]
        .as_str()
        .unwrap()
        .to_owned();
    call(
        &bob,
        "confirm_inbox_delivery",
        json!({"delivery_ids": [bob_delivery]}),
    )
    .await;
    // The acknowledgement queues Alice's receipt event; publishing it marks
    // it `published`, which is what the Postgres hand-out reconciles from.
    call(
        &bob,
        "ack_message",
        json!({"conversation_id": cid, "message_id": mid, "resolved": false}),
    )
    .await;
    assert_eq!(
        inbox::publish_pending(&h.pool, &backend, team, 100)
            .await
            .unwrap(),
        1,
        "Alice's receipt event is published"
    );

    // The team's streams are deleted (not a broker outage: the resources
    // are gone), so the broker read fails and what Alice is owed can only
    // come from the bus's records.
    JetStreamBackend::deprovision(&config, team).await.unwrap();
    let batch = call(&alice1, "fetch_conversation_inbox", json!({})).await;
    let refs = batch["references"].as_array().unwrap();
    assert_eq!(refs.len(), 1, "{batch}");
    assert_eq!(refs[0]["kind"], "receipt", "{batch}");
    assert_eq!(refs[0]["source"], "bus", "{batch}");
    assert_eq!(refs[0]["message_id"], mid, "{batch}");
    assert_eq!(batch["from_broker"], 0, "{batch}");
    assert!(
        batch["note"]
            .as_str()
            .is_some_and(|n| n.contains("could not be read")),
        "the fetch says the broker was not the source: {batch}"
    );
    let delivery = refs[0]["delivery_id"].as_str().unwrap().to_owned();

    // Fetched at epoch 1 and left unconfirmed; the window resumes and the
    // hand-out grace elapses.
    let resumed = call(&alice1, "resume_session", json!({})).await;
    assert_eq!(resumed["epoch"], 2, "{resumed}");
    let alice2 = connect(&h.base, resumed["session_token"].as_str().unwrap()).await;
    sqlx::query(
        "UPDATE inbox_deliveries SET handed_at = now() - interval '6 minutes' WHERE id = $1",
    )
    .bind(delivery.parse::<Uuid>().unwrap())
    .execute(&h.pool)
    .await
    .unwrap();

    // Rehanded to the live window at its epoch, and confirmable by it.
    let again = call(&alice2, "fetch_conversation_inbox", json!({})).await;
    assert_eq!(
        again["references"][0]["delivery_id"], delivery,
        "the same delivery: {again}"
    );
    assert_eq!(again["references"][0]["kind"], "receipt", "{again}");
    let (epoch,): (Option<i64>,) =
        sqlx::query_as("SELECT epoch FROM inbox_deliveries WHERE id = $1")
            .bind(delivery.parse::<Uuid>().unwrap())
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert_eq!(epoch, Some(2), "the row now belongs to epoch 2");

    // A context still at epoch 1 cannot confirm what the live window holds:
    // the store refuses it as stale before touching the row.
    let stale = ai_crew_sync::auth::AuthCtx {
        agent_id: sqlx::query_scalar::<_, Uuid>("SELECT id FROM agents WHERE name = 'alice'")
            .fetch_one(&h.pool)
            .await
            .unwrap(),
        agent_name: "alice".into(),
        team_id: team,
        team_slug: "acme".into(),
        session: "lead".into(),
        session_id: Some(
            alice_cred["session_id"]
                .as_str()
                .unwrap()
                .parse::<Uuid>()
                .unwrap(),
        ),
        session_epoch: Some(1),
        token_id: None,
    };
    let backends =
        ai_crew_sync::store::routing::Backends::with_jetstream(h.pool.clone(), config.clone());
    let err =
        match inbox::confirm(&h.pool, &backends, &stale, std::slice::from_ref(&delivery)).await {
            Ok(_) => panic!("a stale context must not confirm the live window's delivery"),
            Err(e) => e.to_string(),
        };
    assert!(err.contains("stale"), "{err}");
    let (still,): (Option<chrono::DateTime<chrono::Utc>>,) =
        sqlx::query_as("SELECT confirmed_at FROM inbox_deliveries WHERE id = $1")
            .bind(delivery.parse::<Uuid>().unwrap())
            .fetch_one(&h.pool)
            .await
            .unwrap();
    assert!(
        still.is_none(),
        "nothing was confirmed by the stale context"
    );

    let done = call(
        &alice2,
        "confirm_inbox_delivery",
        json!({"delivery_ids": [delivery]}),
    )
    .await;
    assert_eq!(done["confirmed"], 1, "{done}");

    for c in [alice_agent, alice1, alice2, bob_agent, bob] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// The body sweep must not drop the only readable copy of a body while its
/// backend cannot confirm it still holds it. Postgres is the last copy
/// during a broker outage and after the broker lost its stream; releasing
/// it there turns a recoverable outage into an unreadable thread, and a
/// lost stream into permanent loss. A healthy broker still releases, and
/// releasing resumes by itself once the broker is back (#170).
#[tokio::test]
async fn the_sweep_keeps_a_body_its_backend_cannot_confirm() {
    use ai_crew_sync::store::jetstream::{Config, JetStreamBackend};
    use ai_crew_sync::store::outbox;
    use ai_crew_sync::store::routing::Backends;

    let h = require_db_broker!("t_sweep_guard");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    let dani_token = seed_agent(&h.pool, "acme", "dani").await;
    enable_conversations(&h.pool, "acme").await;
    let team = team_id(&h.pool, "acme").await;
    let owner = connect_with_session(&h.base, &token, "impl").await;
    let dani = connect_with_session(&h.base, &dani_token, "review").await;
    sqlx::query("UPDATE teams SET default_backend = 'jetstream' WHERE id = $1")
        .bind(team)
        .execute(&h.pool)
        .await
        .unwrap();
    let config = Config::new(nats_url()).with_limits(1_000, 16 * 1024 * 1024);
    JetStreamBackend::provision(&config, team).await.unwrap();
    let backend = JetStreamBackend::connect(&config, team).await.unwrap();
    let healthy = Backends::with_jetstream(h.pool.clone(), config.clone());
    let convo = call(
        &owner,
        "create_conversation",
        json!({"title": "on the broker", "private": true, "invite": ["dani/review"]}),
    )
    .await;
    let cid = convo["id"].as_str().unwrap().to_owned();
    let cuuid: Uuid = cid.parse().unwrap();
    call(&dani, "join_conversation", json!({"conversation_id": cid})).await;
    let send = |body: &'static str| {
        let owner = &owner;
        let cid = cid.clone();
        async move {
            call(
                owner,
                "send_conversation_message",
                json!({"conversation_id": cid, "body": body, "request_id": request_id()}),
            )
            .await["message_id"]
                .as_str()
                .unwrap()
                .to_owned()
        }
    };
    let local_body = |mid: String| {
        let pool = h.pool.clone();
        async move {
            sqlx::query_scalar::<_, String>("SELECT body FROM conversation_messages WHERE id = $1")
                .bind(mid.parse::<Uuid>().unwrap())
                .fetch_one(&pool)
                .await
                .unwrap()
        }
    };

    // 1. The broker is unreachable (a process that is down): nothing is
    //    released, whatever the flags say.
    let first = send("keep me").await;
    assert_eq!(
        outbox::run_once(&h.pool, &backend, "worker").await.unwrap(),
        Some(outbox::Settled::Stored)
    );
    let unreachable = Backends::with_jetstream(
        h.pool.clone(),
        Config::new("nats://127.0.0.1:1").with_limits(1_000, 16 * 1024 * 1024),
    );
    assert_eq!(
        outbox::release_published_bodies(&h.pool, &unreachable, Some(cuuid), 0)
            .await
            .unwrap(),
        0,
        "the sweep released a body while the broker was unreachable"
    );
    assert_eq!(local_body(first.clone()).await, "keep me");

    // 2. The broker is back: the same body is confirmed and released, with
    //    no operator action in between, and history reads it by locator.
    assert_eq!(
        outbox::release_published_bodies(&h.pool, &healthy, Some(cuuid), 0)
            .await
            .unwrap(),
        1,
        "a healthy broker still releases"
    );
    assert_eq!(local_body(first.clone()).await, "");
    let page = call(&dani, "read_conversation", json!({"conversation_id": cid})).await;
    assert_eq!(page["messages"][0]["body"], "keep me", "{page}");

    // 3. The broker loses the stream BEFORE the sweep runs on a second
    //    body. Postgres still holds it: that copy is now the only one there
    //    is, and the sweep leaves it alone.
    let second = send("and me").await;
    assert_eq!(
        outbox::run_once(&h.pool, &backend, "worker").await.unwrap(),
        Some(outbox::Settled::Stored)
    );
    JetStreamBackend::deprovision(&config, team).await.unwrap();
    assert_eq!(
        outbox::release_published_bodies(&h.pool, &healthy, Some(cuuid), 0)
            .await
            .unwrap(),
        0,
        "the sweep released a body while its backend could not confirm holding it"
    );
    assert_eq!(
        local_body(second.clone()).await,
        "and me",
        "the last readable copy of the body was destroyed by the bus itself"
    );
    let page = call(&dani, "read_conversation", json!({"conversation_id": cid})).await;
    assert_eq!(page["messages"][1]["body"], "and me", "{page}");
    // The body released while healthy and then lost still reads as
    // unavailable, with its receipts intact: this path is unchanged.
    assert_eq!(page["messages"][0]["body"], "");
    assert_eq!(page["messages"][0]["publication"], "stored");
    assert!(page["messages"][0]["unavailable"].is_string(), "{page}");
    let receipts = call(&owner, "get_message_receipts", json!({"message_id": first})).await;
    assert_eq!(receipts["total"], 1, "{receipts}");

    // 4. A stream re-created empty (a restore older than the publication)
    //    answers, but not with this body: still kept.
    JetStreamBackend::provision(&config, team).await.unwrap();
    assert_eq!(
        outbox::release_published_bodies(&h.pool, &healthy, Some(cuuid), 0)
            .await
            .unwrap(),
        0,
        "a stream that does not hold the body confirms nothing"
    );
    assert_eq!(local_body(second).await, "and me");

    // The fixture broker is shared: give the re-created stream back.
    let _ = JetStreamBackend::deprovision(&config, team).await;
    for c in [owner, dani] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// An unreadable body cannot be mistaken for an empty message: the schema
/// says so (`unavailable` is always present, `null` when the body is real),
/// the tool descriptions say so, and the reason carries one classification
/// and none of the broker's internals (#171).
#[tokio::test]
async fn an_unreadable_body_is_labelled_for_the_model() {
    use ai_crew_sync::store::jetstream::{Config, JetStreamBackend};
    use ai_crew_sync::store::outbox;
    use ai_crew_sync::store::routing::Backends;

    let h = require_db_broker!("t_unavailable_label");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;
    let dani_token = seed_agent(&h.pool, "acme", "dani").await;
    enable_conversations(&h.pool, "acme").await;
    let team = team_id(&h.pool, "acme").await;
    let owner = connect_with_session(&h.base, &token, "impl").await;
    let dani = connect_with_session(&h.base, &dani_token, "review").await;

    // What a model reads before its first call already says it.
    let tools = dani.list_all_tools().await.unwrap();
    for name in ["read_conversation", "get_conversation_message"] {
        let tool = tools.iter().find(|t| t.name == name).unwrap();
        let description = tool.description.as_deref().unwrap_or_default();
        assert!(
            description.contains("`unavailable`"),
            "{name}: {description}"
        );
        assert!(description.contains("placeholder"), "{name}: {description}");
        assert!(
            description.contains("never stored") && description.contains("no longer held"),
            "the permanent cases are named too: {name}: {description}"
        );
        assert!(
            description.contains("Never quote or summarise"),
            "both tools carry the same instruction: {name}: {description}"
        );
    }

    sqlx::query("UPDATE teams SET default_backend = 'jetstream' WHERE id = $1")
        .bind(team)
        .execute(&h.pool)
        .await
        .unwrap();
    let config = Config::new(nats_url()).with_limits(1_000, 16 * 1024 * 1024);
    JetStreamBackend::provision(&config, team).await.unwrap();
    let backend = JetStreamBackend::connect(&config, team).await.unwrap();
    let cid = call(
        &owner,
        "create_conversation",
        json!({"title": "labelled", "private": true, "invite": ["dani/review"]}),
    )
    .await["id"]
        .as_str()
        .unwrap()
        .to_owned();
    call(&dani, "join_conversation", json!({"conversation_id": cid})).await;
    let mid = call(
        &owner,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "real text", "request_id": request_id()}),
    )
    .await["message_id"]
        .as_str()
        .unwrap()
        .to_owned();
    assert_eq!(
        outbox::run_once(&h.pool, &backend, "worker").await.unwrap(),
        Some(outbox::Settled::Stored)
    );
    outbox::release_published_bodies(
        &h.pool,
        &Backends::with_jetstream(h.pool.clone(), config.clone()),
        Some(cid.parse().unwrap()),
        0,
    )
    .await
    .unwrap();

    // Healthy: the field is there and says null, so its absence is never
    // something a model has to infer.
    let page = call(&dani, "read_conversation", json!({"conversation_id": cid})).await;
    let message = &page["messages"][0];
    assert_eq!(message["body"], "real text", "{page}");
    assert!(
        message.get("unavailable").is_some_and(|v| v.is_null()),
        "unavailable must be present and null on a healthy read: {page}"
    );
    let one = call(
        &dani,
        "get_conversation_message",
        json!({"message_id": mid}),
    )
    .await;
    assert!(one.get("unavailable").is_some_and(|v| v.is_null()), "{one}");

    // The broker loses the stream: the body is a placeholder with a reason
    // that has exactly one class and none of the broker's codes.
    JetStreamBackend::deprovision(&config, team).await.unwrap();
    for read in [
        call(&dani, "read_conversation", json!({"conversation_id": cid})).await["messages"][0]
            .clone(),
        call(
            &dani,
            "get_conversation_message",
            json!({"message_id": mid}),
        )
        .await,
    ] {
        assert_eq!(read["body"], "", "{read}");
        assert_eq!(read["seq"], 1, "{read}");
        assert_eq!(read["from"], "joaquin", "{read}");
        assert_eq!(read["publication"], "stored", "{read}");
        let reason = read["unavailable"].as_str().expect("a reason");
        assert_eq!(reason.matches("conflict:").count(), 1, "{reason}");
        assert!(!reason.contains("invalid input"), "{reason}");
        assert!(!reason.contains("jetstream error"), "{reason}");
        assert!(!reason.contains("code"), "{reason}");
        assert!(reason.contains("not lost"), "{reason}");
    }
    let receipts = call(&owner, "get_message_receipts", json!({"message_id": mid})).await;
    assert_eq!(receipts["total"], 1, "{receipts}");

    // A permanent absence reads as one: a tombstoned body says it is no
    // longer held, not that the backend is away right now.
    ai_crew_sync::store::outbox::tombstone(&h.pool, mid.parse().unwrap(), "retention")
        .await
        .unwrap();
    let gone = call(
        &dani,
        "get_conversation_message",
        json!({"message_id": mid}),
    )
    .await;
    assert_eq!(gone["publication"], "tombstoned", "{gone}");
    let reason = gone["unavailable"].as_str().expect("a reason");
    assert!(reason.contains("no longer held"), "{reason}");
    assert!(
        !reason.contains("right now"),
        "a permanent gap is not retryable: {reason}"
    );

    for c in [owner, dani] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// Small teams fit on a small broker: three teams provisioned with explicit
/// quotas on the fixture's 512 MiB store, each stream carrying exactly the
/// limits asked for, and a quota the store cannot reserve refused with the
/// arithmetic spelled out rather than "insufficient storage resources"
/// (#169).
#[tokio::test]
async fn small_quotas_let_several_teams_share_a_bounded_broker() {
    use ai_crew_sync::admin::{StreamQuotas, team_stream};
    use ai_crew_sync::store::jetstream::{self, Config, JetStreamBackend};
    let h = require_db_broker!("t_stream_quotas");
    let mib = 1024 * 1024;
    let small = StreamQuotas {
        max_bytes: 32 * mib,
        max_messages: 5_000,
        inbox_max_bytes: 4 * mib,
        inbox_max_messages: 2_000,
    };
    let context = async_nats::jetstream::new(
        async_nats::connect(nats_url())
            .await
            .expect("the fixture broker"),
    );
    let mut ids = Vec::new();
    for slug in ["small-a", "small-b", "small-c"] {
        seed_agent(&h.pool, slug, "x").await;
        team_stream(&h.pool, slug, &nats_url(), None, false, small, false)
            .await
            .expect("a small team provisions");
        let id = team_id(&h.pool, slug).await;
        ids.push(id);
        let mut bodies = context
            .get_stream(jetstream::stream_name(id))
            .await
            .unwrap();
        let info = bodies.info().await.unwrap();
        assert_eq!(info.config.max_bytes, 32 * mib, "{slug} bodies");
        assert_eq!(info.config.max_messages, 5_000, "{slug} bodies");
        let mut inbox = context
            .get_stream(jetstream::inbox_stream_name(id))
            .await
            .unwrap();
        let info = inbox.info().await.unwrap();
        assert_eq!(info.config.max_bytes, 4 * mib, "{slug} inbox");
        assert_eq!(info.config.max_messages, 2_000, "{slug} inbox");
    }

    // The fixture's store is 512 MiB; 3 × 36 MiB are reserved. Asking for
    // 480 MiB more is refused by the broker, and the error says why in
    // terms an operator can act on.
    seed_agent(&h.pool, "greedy", "x").await;
    let greedy = StreamQuotas {
        max_bytes: 480 * mib,
        ..small
    };
    let err = team_stream(&h.pool, "greedy", &nats_url(), None, false, greedy, false)
        .await
        .expect_err("the store cannot reserve that much")
        .to_string();
    assert!(err.contains("cannot reserve"), "{err}");
    assert!(err.contains("max_file_store"), "{err}");
    assert!(err.contains("already reserved"), "{err}");
    assert!(err.contains("actually used"), "{err}");
    assert!(err.contains("--max-bytes"), "{err}");

    // Nonsense is refused before the broker is asked.
    let tiny = StreamQuotas {
        max_bytes: 1024,
        ..small
    };
    let err = team_stream(&h.pool, "greedy", &nats_url(), None, false, tiny, false)
        .await
        .expect_err("a body stream must hold one body")
        .to_string();
    assert!(err.contains("--max-bytes must be at least"), "{err}");

    for id in ids {
        let config = Config::new(nats_url());
        JetStreamBackend::deprovision(&config, id).await.unwrap();
    }
    h.shutdown().await;
}

/// A routine `team stream` on a team that already has its streams keeps
/// their limits whatever it is asked for, and says so. Changing them is
/// explicit, refused below what a stream holds, and never touches bodies
/// or references (#169).
#[tokio::test]
async fn existing_quotas_are_kept_unless_updated_explicitly() {
    use ai_crew_sync::admin::{StreamQuotas, team_stream};
    use ai_crew_sync::store::jetstream::{self, Config, JetStreamBackend, StreamKind};
    use ai_crew_sync::store::{inbox, outbox};
    let h = require_db_broker!("t_stream_quota_update");
    let mib = 1024 * 1024;
    let owner_token = seed_agent(&h.pool, "acme", "joaquin").await;
    let dani_token = seed_agent(&h.pool, "acme", "dani").await;
    enable_conversations(&h.pool, "acme").await;
    let team = team_id(&h.pool, "acme").await;
    let first = StreamQuotas {
        max_bytes: 16 * mib,
        max_messages: 1_000,
        inbox_max_bytes: 4 * mib,
        inbox_max_messages: 1_000,
    };
    team_stream(&h.pool, "acme", &nats_url(), None, false, first, false)
        .await
        .unwrap();
    sqlx::query("UPDATE teams SET default_backend = 'jetstream' WHERE id = $1")
        .bind(team)
        .execute(&h.pool)
        .await
        .unwrap();
    let config = Config::new(nats_url()).with_limits(1_000, 16 * mib);
    let backend = JetStreamBackend::connect(&config, team).await.unwrap();

    // Two bodies on the stream and one reference in the inbox.
    let owner = connect_with_session(&h.base, &owner_token, "impl").await;
    let dani_agent = connect(&h.base, &dani_token).await;
    let cred = call(
        &dani_agent,
        "register_session",
        json!({"session": "review"}),
    )
    .await;
    let dani = connect(&h.base, cred["session_token"].as_str().unwrap()).await;
    let cid = call(
        &owner,
        "create_conversation",
        json!({"title": "quotas", "private": true, "invite": ["dani/review"]}),
    )
    .await["id"]
        .as_str()
        .unwrap()
        .to_owned();
    call(&dani, "join_conversation", json!({"conversation_id": cid})).await;
    for body in ["one", "two"] {
        call(
            &owner,
            "send_conversation_message",
            json!({"conversation_id": cid, "body": body, "request_id": request_id()}),
        )
        .await;
        assert_eq!(
            outbox::run_once(&h.pool, &backend, "worker").await.unwrap(),
            Some(outbox::Settled::Stored)
        );
    }
    assert_eq!(
        inbox::publish_pending(&h.pool, &backend, team, 100)
            .await
            .unwrap(),
        2
    );
    let context = async_nats::jetstream::new(async_nats::connect(nats_url()).await.unwrap());
    let limits = |name: String| {
        let context = context.clone();
        async move {
            let mut stream = context.get_stream(name).await.unwrap();
            let info = stream.info().await.unwrap();
            (
                info.config.max_messages,
                info.config.max_bytes,
                info.state.messages,
            )
        }
    };
    assert_eq!(
        limits(jetstream::stream_name(team)).await,
        (1_000, 16 * mib, 2),
        "the bodies are on the stream"
    );

    // A retry with other numbers changes nothing.
    let other = StreamQuotas {
        max_bytes: 64 * mib,
        max_messages: 9_000,
        inbox_max_bytes: 8 * mib,
        inbox_max_messages: 9_000,
    };
    team_stream(&h.pool, "acme", &nats_url(), None, false, other, false)
        .await
        .unwrap();
    assert_eq!(
        limits(jetstream::stream_name(team)).await,
        (1_000, 16 * mib, 2),
        "kept"
    );
    assert_eq!(
        limits(jetstream::inbox_stream_name(team)).await,
        (1_000, 4 * mib, 2),
        "kept"
    );

    // An explicit update below what the stream holds is refused, with the
    // count, and nothing changes.
    let too_small = StreamQuotas {
        max_messages: 1,
        ..first
    };
    let err = team_stream(&h.pool, "acme", &nats_url(), None, false, too_small, true)
        .await
        .expect_err("two bodies do not fit a ceiling of one")
        .to_string();
    assert!(err.contains("holds 2 messages"), "{err}");
    assert!(err.contains("nothing was changed"), "{err}");
    assert_eq!(
        limits(jetstream::stream_name(team)).await,
        (1_000, 16 * mib, 2)
    );
    // Three large bodies push the stream past 2 MiB, the smallest quota
    // the command accepts; a byte ceiling below the contents is refused
    // just like a count.
    for _ in 0..3 {
        call(
            &owner,
            "send_conversation_message",
            json!({"conversation_id": cid, "body": "x".repeat(800 * 1024), "request_id": request_id()}),
        )
        .await;
        assert_eq!(
            outbox::run_once(&h.pool, &backend, "worker").await.unwrap(),
            Some(outbox::Settled::Stored)
        );
    }
    let err = JetStreamBackend::update_quotas(
        &Config::new(nats_url()).with_limits(10, 2 * mib),
        team,
        StreamKind::Bodies,
    )
    .await
    .expect_err("a byte ceiling below the contents is refused too")
    .to_string();
    assert!(err.contains("more than the requested ceiling"), "{err}");
    assert!(err.contains("MiB"), "{err}");
    assert_eq!(
        limits(jetstream::stream_name(team)).await,
        (1_000, 16 * mib, 5)
    );

    // A change the broker cannot reserve leaves the team as it was: the
    // fixture's store is 512 MiB, and 480 MiB for the inbox on top of
    // 64 MiB for bodies does not fit. The fixture's account has no budget
    // of its own, so the refusal comes from the broker when the inbox is
    // updated, after the body stream was; the command restores the body
    // stream and says so. Both keep their limits.
    let too_much = StreamQuotas {
        inbox_max_bytes: 480 * mib,
        ..other
    };
    let err = team_stream(&h.pool, "acme", &nats_url(), None, false, too_much, true)
        .await
        .expect_err("the store cannot reserve that much")
        .to_string();
    assert!(err.contains("nothing was changed"), "{err}");
    assert!(err.contains("Restored"), "{err}");
    assert!(err.contains("could not update"), "{err}");
    assert!(err.contains("already reserved"), "{err}");
    assert_eq!(
        limits(jetstream::stream_name(team)).await,
        (1_000, 16 * mib, 5),
        "the body stream was not changed on its own"
    );
    assert_eq!(
        limits(jetstream::inbox_stream_name(team)).await,
        (1_000, 4 * mib, 2)
    );

    // An explicit update to larger limits applies, and everything stored
    // is still there.
    team_stream(&h.pool, "acme", &nats_url(), None, false, other, true)
        .await
        .unwrap();
    assert_eq!(
        limits(jetstream::stream_name(team)).await,
        (9_000, 64 * mib, 5),
        "updated"
    );
    assert_eq!(
        limits(jetstream::inbox_stream_name(team)).await,
        (9_000, 8 * mib, 2),
        "updated"
    );
    let page = call(&dani, "read_conversation", json!({"conversation_id": cid})).await;
    let bodies: Vec<&str> = page["messages"]
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|m| m["body"].as_str())
        .collect();
    assert_eq!(bodies.len(), 5, "{page}");
    assert_eq!(&bodies[..2], ["one", "two"], "{page}");
    let batch = call(&dani, "fetch_conversation_inbox", json!({})).await;
    assert_eq!(batch["from_broker"], 2, "the references survived: {batch}");

    // The fixture broker is shared by every test in the run: give the
    // reservation back.
    for c in [owner, dani_agent, dani] {
        let _ = c.cancel().await;
    }
    JetStreamBackend::deprovision(&config, team).await.unwrap();
    h.shutdown().await;
}

/// A body the backend cannot confirm holds up nothing else: the pass steps
/// over it and releases what comes after, and a team whose stream is gone
/// does not keep another team's bodies staged. A migration in flight is
/// left alone entirely (#170).
#[tokio::test]
async fn an_unconfirmable_body_does_not_hold_up_the_sweep() {
    use ai_crew_sync::store::jetstream::{Config, JetStreamBackend};
    use ai_crew_sync::store::outbox;
    use ai_crew_sync::store::routing::Backends;

    let h = require_db_broker!("t_sweep_fairness");
    let config = Config::new(nats_url()).with_limits(1_000, 16 * 1024 * 1024);
    let backends = Backends::with_jetstream(h.pool.clone(), config.clone());
    let local_body = |mid: String| {
        let pool = h.pool.clone();
        async move {
            sqlx::query_scalar::<_, String>("SELECT body FROM conversation_messages WHERE id = $1")
                .bind(mid.parse::<Uuid>().unwrap())
                .fetch_one(&pool)
                .await
                .unwrap()
        }
    };

    // Two teams, both routed to the broker, each with its own stream.
    let mut sent = Vec::new();
    let mut clients = Vec::new();
    for slug in ["alpha", "beta"] {
        let token = seed_agent(&h.pool, slug, "joaquin").await;
        enable_conversations(&h.pool, slug).await;
        let team = team_id(&h.pool, slug).await;
        sqlx::query("UPDATE teams SET default_backend = 'jetstream' WHERE id = $1")
            .bind(team)
            .execute(&h.pool)
            .await
            .unwrap();
        JetStreamBackend::provision(&config, team).await.unwrap();
        let backend = JetStreamBackend::connect(&config, team).await.unwrap();
        let client = connect_with_session(&h.base, &token, "impl").await;
        let cid = call(
            &client,
            "create_conversation",
            json!({"title": slug, "private": true}),
        )
        .await["id"]
            .as_str()
            .unwrap()
            .to_owned();
        // Two bodies per team, oldest first.
        let mut ids = Vec::new();
        for body in ["first", "second"] {
            let mid = call(
                &client,
                "send_conversation_message",
                json!({"conversation_id": cid, "body": body, "request_id": request_id()}),
            )
            .await["message_id"]
                .as_str()
                .unwrap()
                .to_owned();
            assert_eq!(
                outbox::run_once(&h.pool, &backend, "worker").await.unwrap(),
                Some(outbox::Settled::Stored)
            );
            ids.push(mid);
        }
        sent.push((slug, team, cid, ids));
        clients.push(client);
    }

    // Alpha's oldest body can never be confirmed: the digest recorded for
    // it does not match what the broker holds. It must not keep alpha's
    // newer body staged behind it.
    let (_, alpha_team, _, alpha_ids) = &sent[0];
    sqlx::query("UPDATE conversation_messages SET body_sha256 = $2 WHERE id = $1")
        .bind(alpha_ids[0].parse::<Uuid>().unwrap())
        .bind("0".repeat(64))
        .execute(&h.pool)
        .await
        .unwrap();
    // And beta's stream is gone entirely: its bodies stay, and that must
    // not stop alpha's from being released. Beta's messages are backdated
    // so the broken backend is the one this pass meets FIRST: a sweep that
    // gave up on the first failure would never reach alpha.
    let (_, beta_team, _, beta_ids) = &sent[1];
    for id in beta_ids {
        sqlx::query(
            "UPDATE conversation_messages SET created_at = now() - interval '1 day' WHERE id = $1",
        )
        .bind(id.parse::<Uuid>().unwrap())
        .execute(&h.pool)
        .await
        .unwrap();
    }
    JetStreamBackend::deprovision(&config, *beta_team)
        .await
        .unwrap();

    let released = outbox::release_published_bodies(&h.pool, &backends, None, 0)
        .await
        .unwrap();
    assert_eq!(released, 1, "exactly alpha's confirmable body");
    assert_eq!(
        local_body(alpha_ids[0].clone()).await,
        "first",
        "a body whose digest does not match stays"
    );
    assert_eq!(
        local_body(alpha_ids[1].clone()).await,
        "",
        "the body behind it was released in the same pass"
    );
    for id in beta_ids {
        assert!(
            !local_body(id.clone()).await.is_empty(),
            "beta's stream is gone; its bodies stay"
        );
    }

    // A message a migration is working on is not a candidate at all: the
    // move writes the body back into the row before its cutover.
    let (_, _, gamma_cid, gamma_ids) = {
        let token = seed_agent(&h.pool, "gamma", "joaquin").await;
        enable_conversations(&h.pool, "gamma").await;
        let team = team_id(&h.pool, "gamma").await;
        sqlx::query("UPDATE teams SET default_backend = 'jetstream' WHERE id = $1")
            .bind(team)
            .execute(&h.pool)
            .await
            .unwrap();
        JetStreamBackend::provision(&config, team).await.unwrap();
        let backend = JetStreamBackend::connect(&config, team).await.unwrap();
        let client = connect_with_session(&h.base, &token, "impl").await;
        let cid = call(
            &client,
            "create_conversation",
            json!({"title": "moving", "private": true}),
        )
        .await["id"]
            .as_str()
            .unwrap()
            .to_owned();
        let mid = call(
            &client,
            "send_conversation_message",
            json!({"conversation_id": cid, "body": "mid move", "request_id": request_id()}),
        )
        .await["message_id"]
            .as_str()
            .unwrap()
            .to_owned();
        assert_eq!(
            outbox::run_once(&h.pool, &backend, "worker").await.unwrap(),
            Some(outbox::Settled::Stored)
        );
        clients.push(client);
        ("gamma", team, cid, vec![mid])
    };
    let migration: Uuid = sqlx::query_scalar(
        "INSERT INTO conversation_migrations (team_id, conversation_id, direction, state)
         VALUES ((SELECT team_id FROM conversations WHERE id = $1), $1, 'to_postgres', 'copying')
         RETURNING id",
    )
    .bind(gamma_cid.parse::<Uuid>().unwrap())
    .fetch_one(&h.pool)
    .await
    .unwrap();
    sqlx::query(
        "INSERT INTO conversation_migration_items (migration_id, message_id, checksum, bytes)
         VALUES ($1, $2, 'x', 8)",
    )
    .bind(migration)
    .bind(gamma_ids[0].parse::<Uuid>().unwrap())
    .execute(&h.pool)
    .await
    .unwrap();
    assert_eq!(
        outbox::release_published_bodies(&h.pool, &backends, Some(gamma_cid.parse().unwrap()), 0)
            .await
            .unwrap(),
        0,
        "a body a migration is copying back must not be cleared"
    );
    assert_eq!(local_body(gamma_ids[0].clone()).await, "mid move");

    for team in [*alpha_team, *beta_team] {
        let _ = JetStreamBackend::deprovision(&config, team).await;
    }
    let _ = JetStreamBackend::deprovision(&config, team_id(&h.pool, "gamma").await).await;
    for c in clients {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// A broker that cannot be read is reported to the MODEL in the inbox's
/// `note`, and that note is LLM-facing text like the `unavailable` reason
/// #171 cleaned: one class of problem, no broker internals, and nothing that
/// asks an agent to run an operator command it has no access to (#175).
#[tokio::test]
async fn the_inbox_note_carries_no_broker_internals() {
    use ai_crew_sync::store::jetstream::{Config, JetStreamBackend};
    use ai_crew_sync::store::outbox;

    let h = require_db_broker!("t_inbox_note");
    let owner_token = seed_agent(&h.pool, "acme", "joaquin").await;
    let dani_token = seed_agent(&h.pool, "acme", "dani").await;
    enable_conversations(&h.pool, "acme").await;
    let team = team_id(&h.pool, "acme").await;
    sqlx::query("UPDATE teams SET default_backend = 'jetstream' WHERE id = $1")
        .bind(team)
        .execute(&h.pool)
        .await
        .unwrap();
    let config = Config::new(nats_url()).with_limits(1_000, 16 * 1024 * 1024);
    JetStreamBackend::provision(&config, team).await.unwrap();
    JetStreamBackend::provision_inbox(&config, team)
        .await
        .unwrap();
    let backend = JetStreamBackend::connect(&config, team).await.unwrap();

    let owner = connect_with_session(&h.base, &owner_token, "impl").await;
    let dani_agent = connect(&h.base, &dani_token).await;
    let cred = call(
        &dani_agent,
        "register_session",
        json!({"session": "review"}),
    )
    .await;
    let review = connect(&h.base, cred["session_token"].as_str().unwrap()).await;

    let convo = call(
        &owner,
        "create_conversation",
        json!({"title": "inbox note", "private": true, "invite": ["dani/review"]}),
    )
    .await;
    let cid = convo["id"].as_str().unwrap().to_owned();
    call(
        &review,
        "join_conversation",
        json!({"conversation_id": cid}),
    )
    .await;
    call(
        &owner,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "still owed", "request_id": request_id()}),
    )
    .await;
    assert_eq!(
        outbox::run_once(&h.pool, &backend, "worker").await.unwrap(),
        Some(outbox::Settled::Stored)
    );

    // The broker loses the team's streams. The inbox must still answer from
    // Postgres — that part already works — and say so in a way a model can use.
    JetStreamBackend::deprovision(&config, team).await.unwrap();

    let batch = call(&review, "fetch_conversation_inbox", json!({})).await;
    assert_eq!(
        batch["references"].as_array().unwrap().len(),
        1,
        "the reference is still owed, from Postgres"
    );
    let note = batch["note"]
        .as_str()
        .expect("a broker failure is explained");
    assert_clean_broker_note(note);

    for c in [owner, dani_agent, review] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// The other failure branch: the bodies stream is there, so the backend
/// opens, and reading the team's inbox stream is what fails. Same contract
/// for the note (#175). Every failure inside `fetch_references` lands here,
/// and this is the one a test can reach: the durable consumer's name is
/// derived from hex, so no caller input can make opening or reading it fail.
#[tokio::test]
async fn the_inbox_note_is_clean_when_the_inbox_stream_is_gone() {
    use ai_crew_sync::store::jetstream::{Config, JetStreamBackend};
    use ai_crew_sync::store::outbox;

    let h = require_db_broker!("t_inbox_note_consumer");
    let owner_token = seed_agent(&h.pool, "acme", "joaquin").await;
    let dani_token = seed_agent(&h.pool, "acme", "dani").await;
    enable_conversations(&h.pool, "acme").await;
    let team = team_id(&h.pool, "acme").await;
    sqlx::query("UPDATE teams SET default_backend = 'jetstream' WHERE id = $1")
        .bind(team)
        .execute(&h.pool)
        .await
        .unwrap();
    let config = Config::new(nats_url()).with_limits(1_000, 16 * 1024 * 1024);
    // Bodies only: `connect` succeeds and reading the inbox is what fails,
    // which is the state a half-finished provisioning leaves behind. The
    // operator text it produces names a CLI command, which is exactly what
    // must not reach the model.
    JetStreamBackend::provision(&config, team).await.unwrap();
    let backend = JetStreamBackend::connect(&config, team).await.unwrap();

    let owner = connect_with_session(&h.base, &owner_token, "impl").await;
    let dani_agent = connect(&h.base, &dani_token).await;
    let cred = call(
        &dani_agent,
        "register_session",
        json!({"session": "review"}),
    )
    .await;
    let review = connect(&h.base, cred["session_token"].as_str().unwrap()).await;
    let cid = call(
        &owner,
        "create_conversation",
        json!({"title": "no inbox stream", "private": true, "invite": ["dani/review"]}),
    )
    .await["id"]
        .as_str()
        .unwrap()
        .to_owned();
    call(
        &review,
        "join_conversation",
        json!({"conversation_id": cid}),
    )
    .await;
    call(
        &owner,
        "send_conversation_message",
        json!({"conversation_id": cid, "body": "owed as well", "request_id": request_id()}),
    )
    .await;
    assert_eq!(
        outbox::run_once(&h.pool, &backend, "worker").await.unwrap(),
        Some(outbox::Settled::Stored)
    );

    let batch = call(&review, "fetch_conversation_inbox", json!({})).await;
    assert_eq!(
        batch["from_broker"], 0,
        "the broker supplied nothing: {batch}"
    );
    assert_eq!(
        batch["references"].as_array().unwrap().len(),
        1,
        "and the reference still arrives from Postgres: {batch}"
    );
    let note = batch["note"]
        .as_str()
        .expect("a broker failure is explained");
    assert_clean_broker_note(note);
    assert!(
        !note.contains("inbox:") && !note.contains("consumer"),
        "no broker vocabulary either: {note}"
    );

    let _ = JetStreamBackend::deprovision(&config, team).await;
    for c in [owner, dani_agent, review] {
        let _ = c.cancel().await;
    }
    h.shutdown().await;
}

/// What an inbox note may say when the broker fails: one class of problem,
/// what the agent should do, and nothing an operator would need.
fn assert_clean_broker_note(note: &str) {
    for internal in [
        "error code",
        "code 404",
        "jetstream error",
        "10059",
        "request error",
        "ACS_T_",
        "ACS_I_",
        "credential",
    ] {
        assert!(
            !note.contains(internal),
            "the inbox note leaks broker internals ({internal:?}): {note}"
        );
    }
    assert!(
        !note.contains("team stream"),
        "the inbox note tells an agent to run an operator command: {note}"
    );
    assert!(
        !note.starts_with("invalid input"),
        "a valid call is not invalid input: {note}"
    );
    assert!(
        note.contains("could not be read") && note.contains("page is complete"),
        "the note says what happened and that the page is whole: {note}"
    );
    assert!(
        !note.contains("team stream --provision"),
        "and never an operator command: {note}"
    );
}

/// Call a tool and return the raw `ErrorData` it failed with, so a test can
/// compare codes and messages instead of a rendering of them.
async fn call_error_data(client: &Client, name: &str, args: Value) -> rmcp::model::ErrorData {
    let args: serde_json::Map<String, Value> = serde_json::from_value(args).unwrap();
    match client
        .call_tool(CallToolRequestParams::new(name.to_string()).with_arguments(args))
        .await
    {
        Err(rmcp::service::ServiceError::McpError(data)) => data,
        Err(other) => panic!("{name} failed outside MCP: {other}"),
        Ok(result) => panic!("{name} unexpectedly succeeded: {result:?}"),
    }
}

/// An error the bus writes for the model reaches the model through the
/// proxy exactly as a direct call gets it: same code, same words. The proxy
/// used to re-code it as an internal error and prefix rmcp's rendering of a
/// JSON-RPC code ("get_task: Mcp error: -32602: …") (#177).
#[tokio::test]
async fn the_proxy_forwards_the_bus_error_unchanged() {
    let h = require_db!("t_proxy_error_passthrough");
    let token = seed_agent(&h.pool, "acme", "bob").await;
    let dir = proxy_config_dir(&h.base, &[("acme", "acme", "bob", &token)]);
    let repo = dir.join("repo");
    std::fs::create_dir_all(&repo).unwrap();
    std::fs::write(repo.join(".acs.toml"), "profile = \"acme\"\n").unwrap();
    let proxy = spawn_proxy(&dir, &repo, &["--host-session", "conv-passthrough"], &[]).await;
    let direct = connect(&h.base, &token).await;

    let missing = json!({"key": format!("nope-{}", Uuid::new_v4().simple())});
    let from_bus = call_error_data(&direct, "get_task", missing.clone()).await;
    let via_proxy = call_error_data(&proxy, "get_task", missing).await;
    assert_eq!(
        via_proxy.code, from_bus.code,
        "the bus's code, not an internal error"
    );
    assert_eq!(
        via_proxy.message, from_bus.message,
        "the bus's words, untouched"
    );
    for noise in ["Mcp error", "-32602", "get_task:"] {
        assert!(
            !via_proxy.message.contains(noise),
            "transport rendering reached the model ({noise:?}): {}",
            via_proxy.message
        );
    }

    let _ = proxy.cancel().await;
    let _ = direct.cancel().await;
    h.shutdown().await;
}

/// A proxy that loses the bus says so once, in the caller's terms, and
/// without the transport's internals: no URL, no OS error, no rmcp error
/// type. What the caller needs to act safely is that the call may or may
/// not have run (#177).
#[tokio::test]
async fn a_proxy_that_loses_the_bus_says_so_without_transport_detail() {
    let h = require_db!("t_proxy_lost_bus");
    let token = seed_agent(&h.pool, "acme", "bob").await;
    let dir = proxy_config_dir(&h.base, &[("acme", "acme", "bob", &token)]);
    let repo = dir.join("repo");
    std::fs::create_dir_all(&repo).unwrap();
    std::fs::write(repo.join(".acs.toml"), "profile = \"acme\"\n").unwrap();
    let proxy = spawn_proxy(&dir, &repo, &["--host-session", "conv-lost-bus"], &[]).await;
    let me = call(&proxy, "whoami", json!({})).await;
    assert_eq!(
        me["agent"], "bob",
        "connected before the bus goes away: {me}"
    );

    // The bus goes away under a connected proxy.
    h.shutdown().await;

    let lost = call_error_data(&proxy, "get_task", json!({"key": "anything"})).await;
    assert_eq!(
        lost.code,
        rmcp::model::ErrorCode::INTERNAL_ERROR,
        "{lost:?}"
    );
    assert!(
        lost.message.contains("could not reach the bus"),
        "{}",
        lost.message
    );
    assert!(
        lost.message.contains("may or may not have run"),
        "{}",
        lost.message
    );
    for internal in [
        "Transport",
        "error sending request",
        "http://",
        "onnection refused",
        "Mcp error",
    ] {
        assert!(
            !lost.message.contains(internal),
            "transport internals reached the model ({internal:?}): {}",
            lost.message
        );
    }

    let _ = proxy.cancel().await;
}

/// A registration the bus refuses is reported by `session_status` in the
/// bus's own words, which say what to do, and without rmcp's rendering of
/// the JSON-RPC code around them (#177).
#[tokio::test]
async fn session_status_reports_a_registration_refusal_in_the_bus_words() {
    let h = require_db!("t_proxy_register_refused");
    let token = seed_agent(&h.pool, "acme", "bob").await;
    let dir = proxy_config_dir(&h.base, &[("acme", "acme", "bob", &token)]);
    let repo = dir.join("repo");
    std::fs::create_dir_all(&repo).unwrap();
    std::fs::write(repo.join(".acs.toml"), "profile = \"acme\"\n").unwrap();

    // Someone holding the agent token already registered the label this
    // conversation maps to, so the proxy's own registration is refused.
    let label = ai_crew_sync::context::session_for_host("conv-taken");
    let agent = connect(&h.base, &token).await;
    let taken = call(&agent, "register_session", json!({"session": label})).await;
    assert!(taken["session_token"].is_string(), "{taken}");

    let proxy = spawn_proxy(&dir, &repo, &["--host-session", "conv-taken"], &[]).await;
    let status = call(&proxy, "session_status", json!({})).await;
    assert_eq!(status["connected"], false, "{status}");
    let error = status["error"].as_str().expect("the refusal is reported");
    assert!(
        error.contains("already registered and still live"),
        "the bus's own words reach the model: {error}"
    );
    for noise in ["Mcp error", "-32602", "-32600"] {
        assert!(
            !error.contains(noise),
            "transport rendering reached the model ({noise:?}): {error}"
        );
    }

    let _ = proxy.cancel().await;
    let _ = agent.cancel().await;
    h.shutdown().await;
}

/// A request the bus refuses over HTTP before running anything (here the
/// body limit, 64 KiB in this harness) reaches the model through the proxy
/// in the bus's own words, and says the call did not run. rmcp hands such
/// an answer back as a transport error, which the proxy used to report as
/// a lost connection where "may or may not have run" sent the model off to
/// check for a post that never happened (#178 review).
#[tokio::test]
async fn a_proxy_forwards_the_bus_http_refusal_and_says_nothing_ran() {
    let h = match setup_rate_limited("t_proxy_http_refusal", 0).await {
        Some(h) => h,
        None => {
            eprintln!("skipping: TEST_DATABASE_URL not set");
            return;
        }
    };
    let token = seed_agent(&h.pool, "acme", "bob").await;
    let dir = proxy_config_dir(&h.base, &[("acme", "acme", "bob", &token)]);
    let repo = dir.join("repo");
    std::fs::create_dir_all(&repo).unwrap();
    std::fs::write(repo.join(".acs.toml"), "profile = \"acme\"\n").unwrap();
    let proxy = spawn_proxy(&dir, &repo, &["--host-session", "conv-refused"], &[]).await;

    let huge = "x".repeat(100 * 1024);
    let refused = call_error_data(
        &proxy,
        "post_message",
        json!({"channel": "general", "body": huge}),
    )
    .await;
    assert_eq!(
        refused.code,
        rmcp::model::ErrorCode::INVALID_REQUEST,
        "{refused:?}"
    );
    assert!(
        refused.message.contains("request body is too large") && refused.message.contains("65536"),
        "the bus's own words reach the model: {}",
        refused.message
    );
    assert!(
        refused.message.contains("before running it"),
        "the model is told nothing ran: {}",
        refused.message
    );
    for noise in [
        "may or may not have run",
        "could not reach the bus",
        "HTTP 413",
        "Transport",
        "http://",
    ] {
        assert!(
            !refused.message.contains(noise),
            "a refusal read as a lost connection ({noise:?}): {}",
            refused.message
        );
    }
    let (posted,): (i64,) = sqlx::query_as("SELECT count(*) FROM messages")
        .fetch_one(&h.pool)
        .await
        .unwrap();
    assert_eq!(posted, 0, "the refusal is true: nothing was posted");
    // The proxy is still connected; the refusal was not a lost bus.
    assert_eq!(call(&proxy, "whoami", json!({})).await["agent"], "bob");

    let _ = proxy.cancel().await;
    h.shutdown().await;
}

/// The same refusal at connect time: a token already throttled when the
/// proxy starts is reported by `session_status` in the bus's words, not as
/// a connection that failed, and without the bus's URL (#178 review).
#[tokio::test]
async fn session_status_reports_an_http_refusal_at_connect_in_the_bus_words() {
    let h = match setup_rate_limited("t_proxy_connect_refused", 1).await {
        Some(h) => h,
        None => {
            eprintln!("skipping: TEST_DATABASE_URL not set");
            return;
        }
    };
    let token = seed_agent(&h.pool, "acme", "bob").await;
    let dir = proxy_config_dir(&h.base, &[("acme", "acme", "bob", &token)]);
    let repo = dir.join("repo");
    std::fs::create_dir_all(&repo).unwrap();
    std::fs::write(repo.join(".acs.toml"), "profile = \"acme\"\n").unwrap();

    // Spend the token's burst so the proxy's first request is throttled.
    let http = reqwest::Client::new();
    let mut throttled = false;
    for _ in 0..40 {
        let resp = http
            .post(format!("{}/mcp", h.base))
            .header("Authorization", format!("Bearer {token}"))
            .header("Accept", "application/json, text/event-stream")
            .json(&json!({"jsonrpc":"2.0","id":1,"method":"tools/call",
                          "params":{"name":"whoami","arguments":{}}}))
            .send()
            .await
            .unwrap();
        if resp.status() == 429 {
            throttled = true;
            break;
        }
    }
    assert!(throttled, "a burst of 40 must exhaust a 1/min bucket");

    let proxy = spawn_proxy(&dir, &repo, &["--host-session", "conv-throttled"], &[]).await;
    let status = call(&proxy, "session_status", json!({})).await;
    assert_eq!(status["connected"], false, "{status}");
    let error = status["error"].as_str().expect("the refusal is reported");
    assert!(
        error.contains("rate limit exceeded"),
        "the bus's own words reach the model: {error}"
    );
    for noise in [
        "failed before an answer came back",
        "HTTP 429",
        "Transport",
        "http://",
        h.base.as_str(),
    ] {
        assert!(
            !error.contains(noise),
            "a refusal read as a lost connection ({noise:?}): {error}"
        );
    }

    let _ = proxy.cancel().await;
    h.shutdown().await;
}

/// Wait until some backend is blocked behind `blocker_pid`, so the call
/// under test is parked exactly where the test holds it open. Keyed on the
/// blocker's pid, so a lock wait in another test's schema never counts.
async fn wait_until_blocked_by(pool: &PgPool, blocker_pid: i32) {
    for _ in 0..400 {
        let waiting: bool = sqlx::query_scalar(
            "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE $1 = ANY(pg_blocking_pids(pid)))",
        )
        .bind(blocker_pid)
        .fetch_one(pool)
        .await
        .unwrap();
        if waiting {
            return;
        }
        tokio::time::sleep(std::time::Duration::from_millis(25)).await;
    }
    panic!("nothing ever waited on the blocking transaction");
}

/// Make every insert into `table` in this test's schema fail, optionally
/// only for rows matching `when` (a trigger WHEN condition on NEW).
async fn inject_insert_failure(pool: &PgPool, table: &str, when: Option<&str>) {
    sqlx::query(
        "CREATE OR REPLACE FUNCTION injected_failure() RETURNS trigger LANGUAGE plpgsql AS \
         $$ BEGIN RAISE EXCEPTION 'injected failure'; END $$",
    )
    .execute(pool)
    .await
    .unwrap();
    let when = when.map(|w| format!("WHEN ({w})")).unwrap_or_default();
    sqlx::query(sqlx::AssertSqlSafe(format!(
        "CREATE TRIGGER injected_failure BEFORE INSERT ON {table} FOR EACH ROW {when} \
         EXECUTE FUNCTION injected_failure()"
    )))
    .execute(pool)
    .await
    .unwrap();
}

async fn lift_insert_failure(pool: &PgPool, table: &str) {
    sqlx::query(sqlx::AssertSqlSafe(format!(
        "DROP TRIGGER injected_failure ON {table}"
    )))
    .execute(pool)
    .await
    .unwrap();
}

/// A task declared with `depends_on` is never claimable before its
/// dependencies are recorded. `create_task` used to commit the task row and
/// then write its `task_deps` rows one by one, so in between the task was
/// open and dependency-free and both claim paths handed it out (#179). The
/// window is held open from another transaction: EXCLUSIVE on `task_deps`
/// parks the dependency insert (ROW EXCLUSIVE) but not the claims'
/// `NOT EXISTS` read (ACCESS SHARE).
#[tokio::test]
async fn a_task_is_never_claimable_before_its_dependencies_are_recorded() {
    let h = require_db!("t_deps_atomic");
    let a = seed_agent(&h.pool, "acme", "joaquin").await;
    let b = seed_agent(&h.pool, "acme", "marta").await;
    let joaquin = connect(&h.base, &a).await;
    let marta = connect(&h.base, &b).await;

    call(
        &joaquin,
        "create_task",
        json!({"key": "migrate-schema", "title": "migrate the users schema"}),
    )
    .await;
    // Held, so claim_next_task has nothing older to hand out first.
    let held = call(&joaquin, "claim_task", json!({"key": "migrate-schema"})).await;
    assert_eq!(held["claimed"], true, "{held}");

    let mut blocker = h.pool.begin().await.unwrap();
    let blocker_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")
        .fetch_one(&mut *blocker)
        .await
        .unwrap();
    sqlx::query("LOCK TABLE task_deps IN EXCLUSIVE MODE")
        .execute(&mut *blocker)
        .await
        .unwrap();

    let creator = tokio::spawn(async move {
        let created = call(
            &joaquin,
            "create_task",
            json!({"key": "update-clients", "title": "update the API clients",
                   "depends_on": ["migrate-schema"]}),
        )
        .await;
        (joaquin, created)
    });
    wait_until_blocked_by(&h.pool, blocker_pid).await;

    // The create is parked on its dependency insert. Whatever the task looks
    // like from outside now, it must not be claimable.
    let next = call(&marta, "claim_next_task", json!({})).await;
    let named = marta
        .call_tool(
            CallToolRequestParams::new("claim_task")
                .with_arguments(serde_json::from_value(json!({"key": "update-clients"})).unwrap()),
        )
        .await;

    blocker.rollback().await.unwrap();
    let (joaquin, created) = creator.await.unwrap();

    assert_eq!(
        next["claimed"], false,
        "claim_next_task handed out a task before its dependency was recorded: {next}"
    );
    match named {
        // Not visible yet: the task does not exist for anyone until its
        // dependencies do.
        Err(e) => assert!(e.to_string().contains("not found"), "{e}"),
        Ok(r) if r.is_error == Some(true) => {
            let said = format!("{:?}", r.content);
            assert!(said.contains("not found"), "{said}");
        }
        // Visible: then it must already be refused on its dependency.
        Ok(r) => {
            let v = r.structured_content.unwrap_or_default();
            assert_eq!(
                v["claimed"], false,
                "claim_task took a task before its dependency was recorded: {v}"
            );
            assert!(
                v["reason"]
                    .as_str()
                    .unwrap_or_default()
                    .contains("migrate-schema"),
                "{v}"
            );
        }
    }

    // Once the create returns, the task carries its dependency and stays
    // blocked on it.
    assert_eq!(created["depends_on"][0], "migrate-schema", "{created}");
    assert_eq!(created["blocked"], true, "{created}");
    let denied = call(&marta, "claim_task", json!({"key": "update-clients"})).await;
    assert_eq!(denied["claimed"], false, "{denied}");
    assert!(
        denied["reason"]
            .as_str()
            .unwrap_or_default()
            .contains("migrate-schema"),
        "{denied}"
    );

    let _ = joaquin.cancel().await;
    let _ = marta.cancel().await;
    h.shutdown().await;
}

/// A create that fails after the task row is written leaves nothing behind:
/// no task, no event, so the same call retried succeeds instead of hitting
/// "already exists" on an orphan that was claimable with no dependencies
/// (#179).
#[tokio::test]
async fn a_failed_create_leaves_no_task_behind_and_a_retry_succeeds() {
    let h = require_db!("t_create_rollback");
    let a = seed_agent(&h.pool, "acme", "joaquin").await;
    let joaquin = connect(&h.base, &a).await;
    call(
        &joaquin,
        "create_task",
        json!({"key": "migrate-schema", "title": "migrate the users schema"}),
    )
    .await;
    let events_before: i64 = sqlx::query_scalar("SELECT count(*) FROM task_events")
        .fetch_one(&h.pool)
        .await
        .unwrap();

    let request = json!({"key": "update-clients", "title": "update the API clients",
                         "depends_on": ["migrate-schema"]});
    inject_insert_failure(&h.pool, "task_deps", None).await;
    let err = call_expect_error(&joaquin, "create_task", request.clone()).await;
    assert!(err.contains("database error"), "{err}");

    let left: i64 = sqlx::query_scalar("SELECT count(*) FROM tasks WHERE key = 'update-clients'")
        .fetch_one(&h.pool)
        .await
        .unwrap();
    assert_eq!(left, 0, "a failed create left its task behind");
    let events_after: i64 = sqlx::query_scalar("SELECT count(*) FROM task_events")
        .fetch_one(&h.pool)
        .await
        .unwrap();
    assert_eq!(events_after, events_before, "and no history for it");

    lift_insert_failure(&h.pool, "task_deps").await;
    let created = call(&joaquin, "create_task", request).await;
    assert_eq!(created["depends_on"][0], "migrate-schema", "{created}");
    assert_eq!(created["blocked"], true, "{created}");

    let _ = joaquin.cancel().await;
    h.shutdown().await;
}

/// A claim whose history entry cannot be written does not stand. The
/// `claimed` event used to be written after the claim committed, so the
/// caller was told "database error" while holding the lease (#179).
#[tokio::test]
async fn a_claim_whose_event_cannot_be_recorded_does_not_stand() {
    let h = require_db!("t_claim_event_atomic");
    let a = seed_agent(&h.pool, "acme", "joaquin").await;
    let joaquin = connect(&h.base, &a).await;
    call(
        &joaquin,
        "create_task",
        json!({"key": "deploy-api", "title": "deploy the API"}),
    )
    .await;

    inject_insert_failure(&h.pool, "task_events", Some("NEW.event = 'claimed'")).await;
    let err = call_expect_error(&joaquin, "claim_task", json!({"key": "deploy-api"})).await;
    assert!(err.contains("database error"), "{err}");
    let task = call(&joaquin, "get_task", json!({"key": "deploy-api"})).await;
    assert_eq!(
        task["task"]["status"], "open",
        "a claim reported as failed stood: {task}"
    );
    assert!(task["task"]["claimed_by"].is_null(), "{task}");

    // The other claim path, on the same task.
    let err = call_expect_error(&joaquin, "claim_next_task", json!({})).await;
    assert!(err.contains("database error"), "{err}");
    let task = call(&joaquin, "get_task", json!({"key": "deploy-api"})).await;
    assert_eq!(task["task"]["status"], "open", "{task}");

    lift_insert_failure(&h.pool, "task_events").await;
    let claimed = call(&joaquin, "claim_task", json!({"key": "deploy-api"})).await;
    assert_eq!(claimed["claimed"], true, "{claimed}");

    let _ = joaquin.cancel().await;
    h.shutdown().await;
}

/// A note write that cannot record its revision changes nothing: the value
/// and its revision used to commit separately, so a failure between them
/// left an overwrite with no revision to recover the old value from (#179).
#[tokio::test]
async fn a_note_write_that_cannot_record_its_revision_changes_nothing() {
    let h = require_db!("t_note_revision_atomic");
    let a = seed_agent(&h.pool, "acme", "joaquin").await;
    let joaquin = connect(&h.base, &a).await;
    let note = json!({"scope": "api", "key": "cache-backend"});
    call(
        &joaquin,
        "set_note",
        json!({"scope": "api", "key": "cache-backend", "value": "valkey"}),
    )
    .await;

    inject_insert_failure(&h.pool, "note_revisions", None).await;
    let err = call_expect_error(
        &joaquin,
        "set_note",
        json!({"scope": "api", "key": "cache-backend", "value": "memcached"}),
    )
    .await;
    assert!(err.contains("database error"), "{err}");

    let read = call(&joaquin, "get_note", note.clone()).await;
    assert_eq!(read["note"]["value"], "valkey", "{read}");
    let revisions: i64 = sqlx::query_scalar("SELECT count(*) FROM note_revisions")
        .fetch_one(&h.pool)
        .await
        .unwrap();
    assert_eq!(revisions, 1, "only the first write has a revision");

    lift_insert_failure(&h.pool, "note_revisions").await;
    call(
        &joaquin,
        "set_note",
        json!({"scope": "api", "key": "cache-backend", "value": "memcached"}),
    )
    .await;
    let read = call(&joaquin, "get_note", note).await;
    assert_eq!(read["note"]["value"], "memcached", "{read}");
    let revisions: i64 = sqlx::query_scalar("SELECT count(*) FROM note_revisions")
        .fetch_one(&h.pool)
        .await
        .unwrap();
    assert_eq!(revisions, 2, "{revisions}");

    let _ = joaquin.cancel().await;
    h.shutdown().await;
}

/// Two creates of one key race to the same conflict the sequential case
/// gets. The existence check used to be a separate read, so the loser
/// passed it, then hit the unique index and answered "database error"
/// (#179).
#[tokio::test]
async fn two_creates_of_one_key_race_to_a_conflict() {
    let h = require_db!("t_create_race");
    let a = seed_agent(&h.pool, "acme", "joaquin").await;
    let joaquin = connect(&h.base, &a).await;
    let team_id: Uuid = sqlx::query_scalar("SELECT id FROM teams WHERE slug = 'acme'")
        .fetch_one(&h.pool)
        .await
        .unwrap();

    // The winner, still in flight.
    let mut winner = h.pool.begin().await.unwrap();
    let winner_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")
        .fetch_one(&mut *winner)
        .await
        .unwrap();
    sqlx::query("INSERT INTO tasks (team_id, key, title) VALUES ($1, 'deploy-api', 'first')")
        .bind(team_id)
        .execute(&mut *winner)
        .await
        .unwrap();

    let loser = tokio::spawn(async move {
        let err = call_expect_error(
            &joaquin,
            "create_task",
            json!({"key": "deploy-api", "title": "second"}),
        )
        .await;
        (joaquin, err)
    });
    wait_until_blocked_by(&h.pool, winner_pid).await;
    winner.commit().await.unwrap();
    let (joaquin, err) = loser.await.unwrap();

    assert!(err.contains("already exists"), "{err}");
    assert!(!err.contains("database error"), "{err}");

    let _ = joaquin.cancel().await;
    h.shutdown().await;
}

#[tokio::test]
async fn the_handshake_names_the_bus_and_its_version() {
    let h = require_db!("t_handshake_version");
    let token = seed_agent(&h.pool, "acme", "joaquin").await;

    // Any client — the 0.6.1 plugin's direct HTTP shape included — learns
    // the real server and version from `initialize`, not the framework's
    // name. This is what lets a failure later point at version skew
    // instead of starting the search at the token and the TLS (#187).
    let client = connect(&h.base, &token).await;
    let info = client.peer_info().expect("initialize result");
    let si = info
        .server_info
        .as_ref()
        .expect("serverInfo is present in the handshake");
    assert_eq!(si.name, "ai-crew-sync");
    assert_eq!(si.version, env!("CARGO_PKG_VERSION"));

    let _ = client.cancel().await;
    h.shutdown().await;
}

#[tokio::test]
async fn verify_failure_names_url_and_credential_provenance() {
    let h = require_db!("t_verify_provenance");
    let _ = seed_agent(&h.pool, "acme", "joaquin").await;

    // A leftover environment token from a previous release: the bus refuses
    // it, and the error must say where the credential and the URL came
    // from — without printing the credential.
    let bad = "acs_0000000000000000000000000000000000000000000000000000000000000000";
    let resolved = ai_crew_sync::context::Resolved {
        mcp_url: format!("{}/mcp", h.base),
        token: bad.to_owned(),
        source: ai_crew_sync::context::Source::Explicit,
        profile: None,
        expected: None,
        tokens_file: None,
        token_key: None,
        project: None,
        channel: None,
        project_root: None,
        session: None,
        token_origin: Some(ai_crew_sync::context::Origin::Environment),
        url_origin: Some(ai_crew_sync::context::Origin::Environment),
        warnings: Vec::new(),
    };
    let err = format!(
        "{:#}",
        ai_crew_sync::context::verify(&resolved)
            .await
            .expect_err("a wrong token must not verify")
    );
    assert!(err.contains(&format!("{}/mcp", h.base)), "{err}");
    assert!(err.contains("BUS_TOKEN (environment)"), "{err}");
    assert!(err.contains("BUS_URL (environment)"), "{err}");
    assert!(!err.contains(bad), "the credential never crosses: {err}");

    // The same refusal through a profile names the entry and the file the
    // operator has to fix, still never the secret.
    let resolved = ai_crew_sync::context::Resolved {
        mcp_url: format!("{}/mcp", h.base),
        token: bad.to_owned(),
        source: ai_crew_sync::context::Source::UserDefault,
        profile: Some("acme".into()),
        expected: Some(("acme".into(), "joaquin".into())),
        tokens_file: Some(std::path::PathBuf::from("/tmp/tokens-acme")),
        token_key: Some("_base".into()),
        project: None,
        channel: None,
        project_root: None,
        session: None,
        token_origin: None,
        url_origin: None,
        warnings: Vec::new(),
    };
    let err = format!(
        "{:#}",
        ai_crew_sync::context::verify(&resolved)
            .await
            .expect_err("a wrong token must not verify")
    );
    assert!(err.contains("entry '_base'"), "{err}");
    assert!(err.contains("tokens-acme"), "{err}");
    assert!(err.contains("profile 'acme'"), "{err}");
    assert!(!err.contains(bad), "{err}");

    h.shutdown().await;
}