quorum-rs 0.7.0-rc.6

Rust SDK and CLI for multi-agent deliberation systems — ships the `quorum` binary (run / status / trace / tui / init) plus the underlying agent, LLM, tool, prompt, and worker library.
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
use super::*;
use crate::agents::AgentConfig;
use crate::status::new_shared_status;
use crate::workers::buffer::AckHandle;
use axum::body::Body;
use axum::http::StatusCode;
use http_body_util::BodyExt;
use std::sync::atomic::Ordering;
use tower::ServiceExt;

/// Shared no-op ack handle for test buffer entries.
struct NoopAck;
#[async_trait::async_trait]
impl AckHandle for NoopAck {
    async fn ack(&self) -> anyhow::Result<()> {
        Ok(())
    }
}

/// Build a test app state with two agents.
fn test_state() -> MultiAppState {
    let mut statuses = HashMap::new();
    let mut configs = HashMap::new();

    // Agent ALPHA
    let alpha_status =
        new_shared_status("ALPHA".into(), "MiniMax-M2.5".into(), "together_ai".into());
    statuses.insert("ALPHA".to_string(), alpha_status);
    configs.insert(
        "ALPHA".to_string(),
        Arc::new(RwLock::new(AgentConfig {
            name: "ALPHA".into(),
            provider_id: "together_ai".into(),
            model_name: "MiniMax-M2.5".into(),
            temperature: 0.7,
            max_tokens: 8192,
            ..Default::default()
        })),
    );

    // Agent BETA
    let beta_status = new_shared_status("BETA".into(), "llama3.2".into(), "ollama_local".into());
    statuses.insert("BETA".to_string(), beta_status);
    configs.insert(
        "BETA".to_string(),
        Arc::new(RwLock::new(AgentConfig {
            name: "BETA".into(),
            provider_id: "ollama_local".into(),
            model_name: "llama3.2".into(),
            temperature: 0.5,
            max_tokens: 4096,
            ..Default::default()
        })),
    );

    let pause_handles = configs
        .keys()
        .map(|k| (k.clone(), Arc::new(AtomicBool::new(false))))
        .collect();

    MultiAppState {
        statuses,
        chat_agents: HashMap::new(),
        configs,
        buffers: HashMap::new(),
        pause_handles,
        orchestrator_registry: None,
        base_hold_secs: Arc::new(AtomicU64::new(10)),
        response_sla_secs: Arc::new(AtomicU64::new(10)),
        buffer_floor_pct: Arc::new(AtomicU64::new(0)),
        before_release_middleware: None,
    }
}

/// Build a test state with HITL buffer enabled for ALPHA.
fn test_state_with_buffer() -> MultiAppState {
    let mut state = test_state();
    let buf = Arc::new(ResponseBuffer::new(std::time::Duration::from_secs(30)));
    state.buffers.insert("ALPHA".to_string(), buf);
    state.base_hold_secs = Arc::new(AtomicU64::new(30));
    state
}

/// Helper: perform a GET request and return (status_code, body_string).
async fn get_request(app: Router, uri: &str) -> (StatusCode, String) {
    let req = axum::http::Request::builder()
        .uri(uri)
        .body(Body::empty())
        .unwrap();
    let resp = app.oneshot(req).await.unwrap();
    let status = resp.status();
    let body = resp.into_body().collect().await.unwrap().to_bytes();
    (status, String::from_utf8(body.to_vec()).unwrap())
}

/// Helper: perform a POST request with JSON body.
async fn post_json(app: Router, uri: &str, json: &str) -> (StatusCode, String) {
    let req = axum::http::Request::builder()
        .method("POST")
        .uri(uri)
        .header("content-type", "application/json")
        .body(Body::from(json.to_string()))
        .unwrap();
    let resp = app.oneshot(req).await.unwrap();
    let status = resp.status();
    let body = resp.into_body().collect().await.unwrap().to_bytes();
    (status, String::from_utf8(body.to_vec()).unwrap())
}

/// Helper: perform a PUT request with JSON body.
async fn put_json(app: Router, uri: &str, json: &str) -> (StatusCode, String) {
    let req = axum::http::Request::builder()
        .method("PUT")
        .uri(uri)
        .header("content-type", "application/json")
        .body(Body::from(json.to_string()))
        .unwrap();
    let resp = app.oneshot(req).await.unwrap();
    let status = resp.status();
    let body = resp.into_body().collect().await.unwrap().to_bytes();
    (status, String::from_utf8(body.to_vec()).unwrap())
}

// -----------------------------------------------------------------------
// Existing tests (updated for new state shape)
// -----------------------------------------------------------------------

#[tokio::test]
async fn dashboard_returns_html() {
    let app = build_router(test_state());
    let (status, body) = get_request(app, "/").await;
    assert_eq!(status, StatusCode::OK);
    assert!(body.to_lowercase().contains("<!doctype html>"));
}

#[tokio::test]
async fn list_agents_returns_all_agents_sorted() {
    let app = build_router(test_state());
    let (status, body) = get_request(app, "/api/agents").await;
    assert_eq!(status, StatusCode::OK);

    let agents: Vec<serde_json::Value> = serde_json::from_str(&body).unwrap();
    assert_eq!(agents.len(), 2);
    // Sorted alphabetically: ALPHA before BETA
    assert_eq!(agents[0]["name"], "ALPHA");
    assert_eq!(agents[1]["name"], "BETA");
    assert_eq!(agents[0]["model_name"], "MiniMax-M2.5");
    assert_eq!(agents[1]["provider_id"], "ollama_local");
}

#[tokio::test]
async fn list_agents_shows_nats_disconnected_by_default() {
    let app = build_router(test_state());
    let (_, body) = get_request(app, "/api/agents").await;
    let agents: Vec<serde_json::Value> = serde_json::from_str(&body).unwrap();
    // New status snapshots default to nats_connected=false
    assert_eq!(agents[0]["nats_connected"], false);
    assert_eq!(agents[1]["nats_connected"], false);
}

#[tokio::test]
async fn list_agents_shows_has_chat_false_when_no_chat_agents() {
    let app = build_router(test_state());
    let (_, body) = get_request(app, "/api/agents").await;
    let agents: Vec<serde_json::Value> = serde_json::from_str(&body).unwrap();
    assert_eq!(agents[0]["has_chat"], false);
    assert_eq!(agents[1]["has_chat"], false);
}

#[tokio::test]
async fn list_agents_includes_hitl_fields() {
    let app = build_router(test_state());
    let (_, body) = get_request(app, "/api/agents").await;
    let agents: Vec<serde_json::Value> = serde_json::from_str(&body).unwrap();
    assert_eq!(agents[0]["is_paused"], false);
    assert_eq!(agents[0]["buffered_count"], 0);
    assert_eq!(agents[0]["error_rate"], 0.0);
    assert!(agents[0]["mean_score"].is_null());
}

#[tokio::test]
async fn agent_status_returns_snapshot() {
    let state = test_state();
    // Set a field on ALPHA's status to verify it's returned
    {
        let mut snap = state.statuses["ALPHA"].write().await;
        snap.nats_connected = true;
        snap.current_job = Some("job-123".to_string());
    }
    let app = build_router(state);
    let (status, body) = get_request(app, "/api/agents/ALPHA/status").await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["nats_connected"], true);
    assert_eq!(json["current_job"], "job-123");
}

#[tokio::test]
async fn agent_status_returns_404_for_unknown_agent() {
    let app = build_router(test_state());
    let (status, body) = get_request(app, "/api/agents/UNKNOWN/status").await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert!(body.contains("not found"));
}

#[tokio::test]
async fn agent_config_returns_config_view() {
    let app = build_router(test_state());
    let (status, body) = get_request(app, "/api/agents/ALPHA/config").await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["name"], "ALPHA");
    assert_eq!(json["model_name"], "MiniMax-M2.5");
    assert_eq!(json["provider_id"], "together_ai");
    // f32 → JSON serialization may introduce floating point drift
    let temp = json["temperature"].as_f64().unwrap();
    assert!((temp - 0.7).abs() < 0.001, "temperature was {}", temp);
}

#[tokio::test]
async fn agent_config_returns_404_for_unknown_agent() {
    let app = build_router(test_state());
    let (status, body) = get_request(app, "/api/agents/GHOST/config").await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert!(body.contains("not found"));
}

#[tokio::test]
async fn agent_chat_returns_404_when_no_chat_agent() {
    let app = build_router(test_state());
    let (status, body) = post_json(
        app,
        "/api/agents/ALPHA/chat",
        r#"{"messages":[{"role":"user","content":"hello"}]}"#,
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert!(body.contains("not found") || body.contains("does not support chat"));
}

#[tokio::test]
async fn agent_chat_returns_404_for_unknown_agent() {
    let app = build_router(test_state());
    let (status, _) = post_json(
        app,
        "/api/agents/NOBODY/chat",
        r#"{"messages":[{"role":"user","content":"hello"}]}"#,
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn list_agents_empty_state() {
    let state = MultiAppState {
        statuses: HashMap::new(),
        chat_agents: HashMap::new(),
        configs: HashMap::new(),
        buffers: HashMap::new(),
        pause_handles: HashMap::new(),
        orchestrator_registry: None,
        base_hold_secs: Arc::new(AtomicU64::new(10)),
        response_sla_secs: Arc::new(AtomicU64::new(10)),
        buffer_floor_pct: Arc::new(AtomicU64::new(0)),
        before_release_middleware: None,
    };
    let app = build_router(state);
    let (status, body) = get_request(app, "/api/agents").await;
    assert_eq!(status, StatusCode::OK);
    let agents: Vec<serde_json::Value> = serde_json::from_str(&body).unwrap();
    assert!(agents.is_empty());
}

#[tokio::test]
async fn agent_chat_rejects_unsupported_role() {
    let app = build_router(test_state());
    // "system" role is not accepted — ChatRole enum only allows "user" and "assistant".
    // Handler catches JsonRejection and maps it to 400 with ChatResponse body.
    let (status, body) = post_json(
        app,
        "/api/agents/ALPHA/chat",
        r#"{"messages":[{"role":"system","content":"You are a helper"}]}"#,
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body.contains("Invalid request"),
        "Expected rejection error, got: {}",
        body
    );
}

#[tokio::test]
async fn agent_chat_accepts_user_and_assistant_roles() {
    // This hits the 404 path (no chat agent configured), but importantly
    // it does NOT hit the 400 path — the roles are valid.
    let app = build_router(test_state());
    let (status, _) = post_json(
        app,
        "/api/agents/ALPHA/chat",
        r#"{"messages":[{"role":"user","content":"hi"},{"role":"assistant","content":"hello"},{"role":"user","content":"how are you"}]}"#,
    )
    .await;
    // ALPHA has no chat agent, so we get 404 (not found), not 400 (bad request)
    assert_eq!(status, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn agent_chat_rejects_malformed_json() {
    let app = build_router(test_state());
    // Completely invalid JSON body — handler catches JsonRejection → 400.
    let (status, body) = post_json(app, "/api/agents/ALPHA/chat", "not json at all").await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body.contains("Invalid request"),
        "Expected rejection error, got: {}",
        body
    );
}

#[tokio::test]
async fn agent_chat_rejects_empty_messages() {
    let app = build_router(test_state());
    let (status, body) = post_json(app, "/api/agents/ALPHA/chat", r#"{"messages":[]}"#).await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(
        body.contains("must not be empty"),
        "Expected empty-messages error, got: {}",
        body
    );
}

// -----------------------------------------------------------------------
// HITL Control Plane tests
// -----------------------------------------------------------------------

#[tokio::test]
async fn pause_agent_returns_ok() {
    let app = build_router(test_state_with_buffer());
    let (status, body) = put_json(app, "/api/agents/ALPHA/pause", r#"{"paused": true}"#).await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["paused"], true);
}

#[tokio::test]
async fn pause_agent_actually_pauses_buffer() {
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    assert!(!buf.is_paused());

    let app = build_router(state);
    let (status, _) = put_json(app, "/api/agents/ALPHA/pause", r#"{"paused": true}"#).await;
    assert_eq!(status, StatusCode::OK);
    assert!(buf.is_paused());
}

#[tokio::test]
async fn pause_unknown_agent_returns_404() {
    let app = build_router(test_state_with_buffer());
    let (status, _) = put_json(app, "/api/agents/GHOST/pause", r#"{"paused": true}"#).await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn pause_agent_without_buffer_succeeds() {
    let app = build_router(test_state()); // no buffers, but pause handles exist
    let (status, body) = put_json(app, "/api/agents/ALPHA/pause", r#"{"paused": true}"#).await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["paused"], true);
}

#[tokio::test]
async fn pause_agent_without_buffer_toggles_handle() {
    let state = test_state();
    let handle = state.pause_handles["ALPHA"].clone();
    assert!(!handle.load(Ordering::Relaxed));

    let app = build_router(state);
    let (status, _) = put_json(app, "/api/agents/ALPHA/pause", r#"{"paused": true}"#).await;
    assert_eq!(status, StatusCode::OK);
    assert!(handle.load(Ordering::Relaxed));
}

#[tokio::test]
async fn pause_all_pauses_all_agents() {
    let state = test_state();
    let alpha_handle = state.pause_handles["ALPHA"].clone();
    let beta_handle = state.pause_handles["BETA"].clone();
    assert!(!alpha_handle.load(Ordering::Relaxed));
    assert!(!beta_handle.load(Ordering::Relaxed));

    let app = build_router(state);
    let (status, body) = put_json(app, "/api/agents/pause-all", r#"{"paused": true}"#).await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["paused"], true);
    assert_eq!(json["count"], 2);
    assert!(alpha_handle.load(Ordering::Relaxed));
    assert!(beta_handle.load(Ordering::Relaxed));
}

#[tokio::test]
async fn pause_all_resumes_all_agents() {
    let state = test_state();
    let alpha_handle = state.pause_handles["ALPHA"].clone();
    let beta_handle = state.pause_handles["BETA"].clone();
    // Pre-pause both
    alpha_handle.store(true, Ordering::Relaxed);
    beta_handle.store(true, Ordering::Relaxed);

    let app = build_router(state);
    let (status, body) = put_json(app, "/api/agents/pause-all", r#"{"paused": false}"#).await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["paused"], false);
    assert!(!alpha_handle.load(Ordering::Relaxed));
    assert!(!beta_handle.load(Ordering::Relaxed));
}

#[tokio::test]
async fn update_config_applies_temperature() {
    let state = test_state();
    let alpha_config = state.configs["ALPHA"].clone();
    let app = build_router(state);
    let (status, _) = put_json(app, "/api/agents/ALPHA/config", r#"{"temperature": 1.2}"#).await;
    assert_eq!(status, StatusCode::OK);
    let config = alpha_config.read().await;
    assert!((config.temperature - 1.2).abs() < 0.001);
}

#[tokio::test]
async fn update_config_partial_patch() {
    let state = test_state();
    let alpha_config = state.configs["ALPHA"].clone();
    let app = build_router(state);
    let (status, _) = put_json(
        app,
        "/api/agents/ALPHA/config",
        r#"{"persona": "aggressive debater"}"#,
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    let config = alpha_config.read().await;
    assert_eq!(config.persona, Some("aggressive debater".into()));
    // Other fields unchanged
    assert!((config.temperature - 0.7).abs() < 0.001);
}

#[tokio::test]
async fn update_config_unknown_agent_404() {
    let app = build_router(test_state());
    let (status, _) = put_json(app, "/api/agents/GHOST/config", r#"{"temperature": 0.5}"#).await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn list_buffer_empty() {
    let app = build_router(test_state_with_buffer());
    let (status, body) = get_request(app, "/api/agents/ALPHA/buffer").await;
    assert_eq!(status, StatusCode::OK);
    let entries: Vec<serde_json::Value> = serde_json::from_str(&body).unwrap();
    assert!(entries.is_empty());
}

#[tokio::test]
async fn list_buffer_no_buffer_returns_empty() {
    // Agent without a buffer configured
    let app = build_router(test_state());
    let (status, body) = get_request(app, "/api/agents/ALPHA/buffer").await;
    assert_eq!(status, StatusCode::OK);
    let entries: Vec<serde_json::Value> = serde_json::from_str(&body).unwrap();
    assert!(entries.is_empty());
}

#[tokio::test]
async fn list_buffer_unknown_agent_404() {
    let app = build_router(test_state());
    let (status, _) = get_request(app, "/api/agents/GHOST/buffer").await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

/// Helper: push a test entry into a buffer.
async fn push_test_entry(buf: &ResponseBuffer, id: &str, action: &str, payload: &[u8]) {
    use crate::workers::buffer::BufferedResponse;
    use std::time::{Duration, Instant};

    let now = Instant::now();
    buf.push(BufferedResponse {
        id: id.to_string(),
        action: action.to_string(),
        job_id: "job-test".to_string(),
        round: 1,
        reply_subject: format!("nsed.job-test.result.1.agent.{}", action),
        payload: payload.to_vec(),
        created_at: now,
        release_at: now + Duration::from_secs(60),
        ack_handle: Box::new(NoopAck),
        msg_id: format!("msg-{}", id),
        annotations: Vec::new(),
        edited: false,
        stopped: false,
    })
    .await;
}

// -----------------------------------------------------------------------
// Buffer detail + edit endpoint tests
// -----------------------------------------------------------------------

#[tokio::test]
async fn buffer_detail_returns_content() {
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    let payload = serde_json::json!({"title": "Test Proposal", "content": "Hello"});
    push_test_entry(
        &buf,
        "entry-1",
        "propose",
        &serde_json::to_vec(&payload).unwrap(),
    )
    .await;

    let app = build_router(state);
    let (status, body) = get_request(app, "/api/agents/ALPHA/buffer/entry-1").await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["id"], "entry-1");
    assert_eq!(json["action"], "propose");
    assert_eq!(json["content"]["title"], "Test Proposal");
    assert!(json["release_in_ms"].as_i64().unwrap() > 0);
}

#[tokio::test]
async fn buffer_detail_unknown_entry_returns_404() {
    let app = build_router(test_state_with_buffer());
    let (status, body) = get_request(app, "/api/agents/ALPHA/buffer/nonexistent").await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert!(body.contains("not found"));
}

#[tokio::test]
async fn buffer_detail_unknown_agent_returns_404() {
    let app = build_router(test_state_with_buffer());
    let (status, _) = get_request(app, "/api/agents/GHOST/buffer/entry-1").await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn buffer_detail_agent_without_buffer_returns_404() {
    let app = build_router(test_state()); // no buffer for ALPHA
    let (status, body) = get_request(app, "/api/agents/ALPHA/buffer/entry-1").await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert!(body.contains("No buffer configured"));
}

#[tokio::test]
async fn buffer_edit_updates_content() {
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    let original = serde_json::json!({"title": "Original", "content": "v1"});
    push_test_entry(
        &buf,
        "edit-1",
        "propose",
        &serde_json::to_vec(&original).unwrap(),
    )
    .await;

    let app = build_router(state);
    let (status, body) = put_json(
        app,
        "/api/agents/ALPHA/buffer/edit-1",
        r#"{"content": {"title": "Modified", "content": "v2"}, "operator_comment": "Fixed wording"}"#,
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["status"], "edited");

    // Verify content was actually changed
    let detail = buf.get_detail("edit-1").await.unwrap();
    assert_eq!(detail.content["title"], "Modified");
    assert_eq!(detail.content["content"], "v2");
}

#[tokio::test]
async fn buffer_edit_unknown_entry_returns_404() {
    let app = build_router(test_state_with_buffer());
    let (status, body) = put_json(
        app,
        "/api/agents/ALPHA/buffer/nonexistent",
        r#"{"content": {"x": 1}}"#,
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert!(body.contains("not found"));
}

#[tokio::test]
async fn buffer_edit_unknown_agent_returns_404() {
    let app = build_router(test_state_with_buffer());
    let (status, _) = put_json(
        app,
        "/api/agents/GHOST/buffer/entry-1",
        r#"{"content": {"x": 1}}"#,
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn buffer_edit_agent_without_buffer_returns_404() {
    let app = build_router(test_state());
    let (status, body) = put_json(
        app,
        "/api/agents/ALPHA/buffer/entry-1",
        r#"{"content": {"x": 1}}"#,
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert!(body.contains("No buffer configured"));
}

#[tokio::test]
async fn buffer_comment_only_adds_annotation() {
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    let payload = serde_json::json!({"title": "Original"});
    push_test_entry(
        &buf,
        "comment-1",
        "propose",
        &serde_json::to_vec(&payload).unwrap(),
    )
    .await;

    let app = build_router(state);
    // No content field — only operator_comment
    let (status, body) = put_json(
        app,
        "/api/agents/ALPHA/buffer/comment-1",
        r#"{"operator_comment": "Looks good, proceed"}"#,
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["status"], "edited");

    // Content should be unchanged
    let detail = buf.get_detail("comment-1").await.unwrap();
    assert_eq!(detail.content["title"], "Original");
}

#[tokio::test]
async fn buffer_edit_no_content_no_comment_returns_400() {
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    let payload = serde_json::json!({"title": "Test"});
    push_test_entry(
        &buf,
        "empty-1",
        "propose",
        &serde_json::to_vec(&payload).unwrap(),
    )
    .await;

    let app = build_router(state);
    let (status, body) = put_json(app, "/api/agents/ALPHA/buffer/empty-1", r#"{}"#).await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(body.contains("Must provide either"));
}

#[tokio::test]
async fn release_unknown_entry_404() {
    let app = build_router(test_state_with_buffer());
    let (status, body) = post_json(app, "/api/agents/ALPHA/buffer/nonexistent/release", "").await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert!(body.contains("not found"));
}

#[tokio::test]
async fn reject_unknown_entry_404() {
    let app = build_router(test_state_with_buffer());
    let (status, body) = post_json(app, "/api/agents/ALPHA/buffer/nonexistent/reject", "").await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert!(body.contains("not found"));
}

// -- SLA / Config endpoint tests --

#[tokio::test]
async fn get_config_returns_response_sla() {
    let app = build_router(test_state());
    let (status, body) = get_request(app, "/api/config").await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    // test_state() sets response_sla_secs to 10 (hardcoded in test helper)
    assert_eq!(json["response_sla_secs"], 10);
}

#[tokio::test]
async fn put_config_updates_response_sla() {
    let state = test_state();
    let app = build_router(state.clone());
    let (status, body) = put_json(app, "/api/config", r#"{"response_sla_secs": 300}"#).await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["response_sla_secs"], 300);
    // Verify the atomic was actually updated
    assert_eq!(state.response_sla_secs.load(Ordering::Relaxed), 300);
}

#[tokio::test]
async fn put_config_sla_propagates_to_buffers() {
    let state = test_state_with_buffer();
    let buf = state.buffers.get("ALPHA").unwrap().clone();
    // SLA initializes to the hold_duration (30s) — no floor applied.
    assert_eq!(buf.response_sla().unwrap().as_secs(), 30);

    let app = build_router(state);
    // Set SLA to 600s — should propagate to buffer
    let (status, _) = put_json(app, "/api/config", r#"{"response_sla_secs": 600}"#).await;
    assert_eq!(status, StatusCode::OK);
    // Buffer should now have 600s SLA
    assert_eq!(buf.response_sla().unwrap().as_secs(), 600);
}

#[tokio::test]
async fn default_sla_is_zero_when_no_buffers() {
    // Production default: no buffers → pass-through (0)
    let state = MultiAppState {
        statuses: HashMap::new(),
        chat_agents: HashMap::new(),
        configs: HashMap::new(),
        buffers: HashMap::new(),
        pause_handles: HashMap::new(),
        orchestrator_registry: None,
        base_hold_secs: Arc::new(AtomicU64::new(0)),
        response_sla_secs: Arc::new(AtomicU64::new(0)),
        buffer_floor_pct: Arc::new(AtomicU64::new(0)),
        before_release_middleware: None,
    };
    let app = build_router(state);
    let (status, body) = get_request(app, "/api/config").await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["response_sla_secs"], 0);
}

#[tokio::test]
async fn sla_matches_configured_value_with_short_buffer_hold() {
    // When a buffer exists with a short base_hold (10s), the response_sla_secs
    // reflects the configured value — no floor applied.
    let mut state = test_state();
    let buf = Arc::new(ResponseBuffer::new(std::time::Duration::from_secs(10)));
    state.buffers.insert("ALPHA".to_string(), buf.clone());
    state.base_hold_secs = Arc::new(AtomicU64::new(10));
    state.response_sla_secs = Arc::new(AtomicU64::new(10));

    let app = build_router(state);
    let (status, body) = get_request(app, "/api/config").await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["response_sla_secs"], 10);
    assert_eq!(json["base_hold_secs"], 10);
    assert_eq!(buf.response_sla().unwrap().as_secs(), 10);
}

#[tokio::test]
async fn put_config_partial_update_preserves_other_fields() {
    let state = test_state();
    // Set known initial values
    state.base_hold_secs.store(30, Ordering::Relaxed);
    state.response_sla_secs.store(120, Ordering::Relaxed);

    let app = build_router(state.clone());
    // Only update response_sla_secs, not base_hold_secs
    let (status, body) = put_json(app, "/api/config", r#"{"response_sla_secs": 300}"#).await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["response_sla_secs"], 300);
    // base_hold_secs should be untouched
    assert_eq!(json["base_hold_secs"], 30);
    assert_eq!(state.base_hold_secs.load(Ordering::Relaxed), 30);
}

// -----------------------------------------------------------------------
// Stop / Unstop endpoint e2e tests
// -----------------------------------------------------------------------

#[tokio::test]
async fn stop_entry_returns_ok() {
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    push_test_entry(&buf, "stop-1", "propose", b"{}").await;

    let app = build_router(state);
    let (status, body) = post_json(app, "/api/agents/ALPHA/buffer/stop-1/stop", "").await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["status"], "stopped");
    assert_eq!(json["id"], "stop-1");
}

#[tokio::test]
async fn stop_unknown_entry_returns_404() {
    let app = build_router(test_state_with_buffer());
    let (status, body) = post_json(app, "/api/agents/ALPHA/buffer/nonexistent/stop", "").await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert!(body.contains("not found"));
}

#[tokio::test]
async fn stop_unknown_agent_returns_404() {
    let app = build_router(test_state_with_buffer());
    let (status, _) = post_json(app, "/api/agents/GHOST/buffer/entry-1/stop", "").await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn stop_agent_without_buffer_returns_404() {
    let app = build_router(test_state());
    let (status, body) = post_json(app, "/api/agents/ALPHA/buffer/entry-1/stop", "").await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert!(body.contains("No buffer"));
}

#[tokio::test]
async fn unstop_entry_returns_ok() {
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    push_test_entry(&buf, "unstop-1", "evaluate", b"{}").await;
    buf.stop("unstop-1").await;

    let app = build_router(state);
    let (status, body) = post_json(app, "/api/agents/ALPHA/buffer/unstop-1/unstop", "").await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["status"], "unstopped");
    assert_eq!(json["id"], "unstop-1");
}

#[tokio::test]
async fn unstop_unknown_entry_returns_404() {
    let app = build_router(test_state_with_buffer());
    let (status, body) = post_json(app, "/api/agents/ALPHA/buffer/nonexistent/unstop", "").await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert!(body.contains("not found"));
}

#[tokio::test]
async fn unstop_unknown_agent_returns_404() {
    let app = build_router(test_state_with_buffer());
    let (status, _) = post_json(app, "/api/agents/GHOST/buffer/entry-1/unstop", "").await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn unstop_agent_without_buffer_returns_404() {
    let app = build_router(test_state());
    let (status, body) = post_json(app, "/api/agents/ALPHA/buffer/entry-1/unstop", "").await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert!(body.contains("No buffer"));
}

// -----------------------------------------------------------------------
// Stop / Unstop integration with list + detail
// -----------------------------------------------------------------------

#[tokio::test]
async fn stopped_entry_visible_in_list_with_flag() {
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    push_test_entry(&buf, "vis-1", "propose", b"{}").await;
    buf.stop("vis-1").await;

    let app = build_router(state);
    let (status, body) = get_request(app, "/api/agents/ALPHA/buffer").await;
    assert_eq!(status, StatusCode::OK);
    let entries: Vec<serde_json::Value> = serde_json::from_str(&body).unwrap();
    assert_eq!(entries.len(), 1);
    assert_eq!(entries[0]["stopped"], true);
}

#[tokio::test]
async fn stopped_entry_visible_in_detail_with_flag() {
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    push_test_entry(&buf, "vis-d-1", "propose", b"{}").await;
    buf.stop("vis-d-1").await;

    let app = build_router(state);
    let (status, body) = get_request(app, "/api/agents/ALPHA/buffer/vis-d-1").await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["stopped"], true);
}

#[tokio::test]
async fn unstopped_entry_shows_stopped_false_in_list() {
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    push_test_entry(&buf, "unsf-1", "propose", b"{}").await;
    buf.stop("unsf-1").await;
    buf.unstop("unsf-1").await;

    let app = build_router(state);
    let (status, body) = get_request(app, "/api/agents/ALPHA/buffer").await;
    assert_eq!(status, StatusCode::OK);
    let entries: Vec<serde_json::Value> = serde_json::from_str(&body).unwrap();
    assert_eq!(entries.len(), 1);
    assert_eq!(entries[0]["stopped"], false);
}

// -----------------------------------------------------------------------
// Release endpoint e2e tests
// -----------------------------------------------------------------------

#[tokio::test]
async fn release_entry_returns_ok() {
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    push_test_entry(&buf, "rel-1", "propose", b"{}").await;

    let app = build_router(state);
    let (status, body) = post_json(app, "/api/agents/ALPHA/buffer/rel-1/release", "").await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["status"], "releasing");
    assert_eq!(json["id"], "rel-1");
}

#[tokio::test]
async fn release_marks_entry_for_immediate_drain() {
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    push_test_entry(&buf, "rel-drain-1", "propose", b"{}").await;

    // Entry has release_at 60s in the future — should NOT drain yet
    assert!(buf.drain_ready().await.is_empty());

    // Release via API
    let app = build_router(state);
    let (status, _) = post_json(app, "/api/agents/ALPHA/buffer/rel-drain-1/release", "").await;
    assert_eq!(status, StatusCode::OK);

    // After mark_for_release, drain_ready should pick it up
    let drained = buf.drain_ready().await;
    assert_eq!(drained.len(), 1);
    assert_eq!(drained[0].id, "rel-drain-1");
}

#[tokio::test]
async fn release_unknown_agent_returns_404() {
    let app = build_router(test_state_with_buffer());
    let (status, _) = post_json(app, "/api/agents/GHOST/buffer/entry-1/release", "").await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn release_agent_without_buffer_returns_404() {
    let app = build_router(test_state());
    let (status, body) = post_json(app, "/api/agents/ALPHA/buffer/entry-1/release", "").await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert!(body.contains("No buffer"));
}

// -----------------------------------------------------------------------
// Reject endpoint e2e tests
// -----------------------------------------------------------------------

#[tokio::test]
async fn reject_entry_returns_ok() {
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    push_test_entry(&buf, "rej-1", "propose", b"{}").await;

    let app = build_router(state);
    let (status, body) = post_json(app, "/api/agents/ALPHA/buffer/rej-1/reject", "").await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["status"], "rejected");
    assert_eq!(json["id"], "rej-1");
}

#[tokio::test]
async fn reject_removes_entry_from_buffer() {
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    push_test_entry(&buf, "rej-rem-1", "propose", b"{}").await;
    assert_eq!(buf.len().await, 1);

    let app = build_router(state);
    let (status, _) = post_json(app, "/api/agents/ALPHA/buffer/rej-rem-1/reject", "").await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(buf.len().await, 0, "rejected entry should be removed");
}

#[tokio::test]
async fn reject_unknown_agent_returns_404() {
    let app = build_router(test_state_with_buffer());
    let (status, _) = post_json(app, "/api/agents/GHOST/buffer/entry-1/reject", "").await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn reject_agent_without_buffer_returns_404() {
    let app = build_router(test_state());
    let (status, body) = post_json(app, "/api/agents/ALPHA/buffer/entry-1/reject", "").await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert!(body.contains("No buffer"));
}

// -----------------------------------------------------------------------
// Combined flows: stop → edit → unstop → release
// -----------------------------------------------------------------------

#[tokio::test]
async fn stop_then_edit_then_unstop_flow() {
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    let payload = serde_json::json!({"content": "original"});
    push_test_entry(
        &buf,
        "flow-1",
        "propose",
        &serde_json::to_vec(&payload).unwrap(),
    )
    .await;

    // Step 1: Stop
    let app = build_router(state.clone());
    let (status, _) = post_json(app, "/api/agents/ALPHA/buffer/flow-1/stop", "").await;
    assert_eq!(status, StatusCode::OK);

    // Verify stopped in detail
    let detail = buf.get_detail("flow-1").await.unwrap();
    assert!(detail.summary.stopped);

    // Step 2: Edit while stopped
    let app = build_router(state.clone());
    let (status, _) = put_json(
        app,
        "/api/agents/ALPHA/buffer/flow-1",
        r#"{"content": {"content": "edited while stopped"}, "operator_comment": "Regen"}"#,
    )
    .await;
    assert_eq!(status, StatusCode::OK);

    // Verify content changed but still stopped
    let detail = buf.get_detail("flow-1").await.unwrap();
    assert_eq!(detail.content["content"], "edited while stopped");
    assert!(detail.summary.stopped);

    // Step 3: Unstop
    let app = build_router(state.clone());
    let (status, _) = post_json(app, "/api/agents/ALPHA/buffer/flow-1/unstop", "").await;
    assert_eq!(status, StatusCode::OK);

    // Verify not stopped
    let detail = buf.get_detail("flow-1").await.unwrap();
    assert!(!detail.summary.stopped);
}

#[tokio::test]
async fn stop_prevents_raw_mark_for_release_drain() {
    // Low-level mark_for_release preserves the stopped flag — the SDK
    // primitive does not auto-unstop.
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    push_test_entry(&buf, "stop-rel-1", "propose", b"{}").await;

    buf.stop("stop-rel-1").await;

    // Raw mark_for_release (NOT via API) preserves stopped
    buf.mark_for_release("stop-rel-1").await;
    let drained = buf.drain_ready().await;
    assert!(
        drained.is_empty(),
        "stopped entry should not drain after raw mark_for_release"
    );

    // Explicit unstop → now it should drain
    buf.unstop("stop-rel-1").await;
    let drained = buf.drain_ready().await;
    assert_eq!(drained.len(), 1);
    assert_eq!(drained[0].id, "stop-rel-1");
}

#[tokio::test]
async fn api_release_force_releases_stopped_entry() {
    // The API release handler is a force-release — it unstops then marks
    // for release, so the operator can always get an entry out.
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    push_test_entry(&buf, "force-rel-1", "propose", b"{}").await;

    buf.stop("force-rel-1").await;

    // Force-release via API should unstop + mark
    let app = build_router(state.clone());
    let (status, _) = post_json(app, "/api/agents/ALPHA/buffer/force-rel-1/release", "").await;
    assert_eq!(status, StatusCode::OK);

    // Entry should drain immediately — API handler unstopped it
    let drained = buf.drain_ready().await;
    assert_eq!(drained.len(), 1, "force-released entry should drain");
    assert_eq!(drained[0].id, "force-rel-1");
}

#[tokio::test]
async fn edit_preserves_reply_subject_via_api() {
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    let payload = serde_json::json!({"content": "v1"});
    push_test_entry(
        &buf,
        "edit-rs-1",
        "propose",
        &serde_json::to_vec(&payload).unwrap(),
    )
    .await;

    // Capture original reply_subject from buffer (via known test helper format)
    let original_reply_subject = "nsed.job-test.result.1.agent.propose".to_string();
    let detail = buf.get_detail("edit-rs-1").await.unwrap();
    assert_eq!(detail.summary.action, "propose");

    // Edit via API
    let app = build_router(state.clone());
    let (status, _) = put_json(
        app,
        "/api/agents/ALPHA/buffer/edit-rs-1",
        r#"{"content": {"content": "v2"}, "operator_comment": "Better"}"#,
    )
    .await;
    assert_eq!(status, StatusCode::OK);

    // Verify reply_subject unchanged — release to get the full BufferedResponse
    let released = buf
        .release("edit-rs-1")
        .await
        .expect("entry should still exist");
    assert_eq!(released.id, "edit-rs-1");
    assert_eq!(released.action, "propose"); // action preserved
    assert_eq!(
        released.reply_subject, original_reply_subject,
        "reply_subject must survive API edits"
    );
}

#[tokio::test]
async fn list_buffer_with_multiple_entries() {
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    push_test_entry(&buf, "m-1", "propose", b"{}").await;
    push_test_entry(&buf, "m-2", "evaluate", b"{}").await;
    push_test_entry(&buf, "m-3", "propose", b"{}").await;

    // Stop one entry
    buf.stop("m-2").await;

    let app = build_router(state);
    let (status, body) = get_request(app, "/api/agents/ALPHA/buffer").await;
    assert_eq!(status, StatusCode::OK);
    let entries: Vec<serde_json::Value> = serde_json::from_str(&body).unwrap();
    assert_eq!(entries.len(), 3);

    // Find the stopped one
    let stopped: Vec<&serde_json::Value> = entries
        .iter()
        .filter(|e| e["stopped"].as_bool() == Some(true))
        .collect();
    assert_eq!(stopped.len(), 1);
    assert_eq!(stopped[0]["id"], "m-2");
}

// -----------------------------------------------------------------------
// Event logging verification
// -----------------------------------------------------------------------

#[tokio::test]
async fn stop_logs_event() {
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    push_test_entry(&buf, "evt-stop-1", "propose", b"{}").await;

    let app = build_router(state.clone());
    let (status, _) = post_json(app, "/api/agents/ALPHA/buffer/evt-stop-1/stop", "").await;
    assert_eq!(status, StatusCode::OK);

    // Check event was logged
    let snap = state.statuses["ALPHA"].read().await;
    let stop_events: Vec<_> = snap
        .event_log
        .iter()
        .filter(|e| e.event_type == "buffer_stopped")
        .collect();
    assert_eq!(stop_events.len(), 1);
    assert!(stop_events[0].detail.contains("stopped"));
}

#[tokio::test]
async fn unstop_logs_event() {
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    push_test_entry(&buf, "evt-unstop-1", "propose", b"{}").await;
    buf.stop("evt-unstop-1").await;

    let app = build_router(state.clone());
    let (status, _) = post_json(app, "/api/agents/ALPHA/buffer/evt-unstop-1/unstop", "").await;
    assert_eq!(status, StatusCode::OK);

    let snap = state.statuses["ALPHA"].read().await;
    let unstop_events: Vec<_> = snap
        .event_log
        .iter()
        .filter(|e| e.event_type == "buffer_unstopped")
        .collect();
    assert_eq!(unstop_events.len(), 1);
    assert!(unstop_events[0].detail.contains("eligible"));
}

#[tokio::test]
async fn release_logs_event() {
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    push_test_entry(&buf, "evt-rel-1", "propose", b"{}").await;

    let app = build_router(state.clone());
    let (status, _) = post_json(app, "/api/agents/ALPHA/buffer/evt-rel-1/release", "").await;
    assert_eq!(status, StatusCode::OK);

    let snap = state.statuses["ALPHA"].read().await;
    let release_events: Vec<_> = snap
        .event_log
        .iter()
        .filter(|e| e.event_type == "buffer_released")
        .collect();
    assert_eq!(release_events.len(), 1);
    assert!(release_events[0].detail.contains("release"));
}

#[tokio::test]
async fn reject_logs_event() {
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    push_test_entry(&buf, "evt-rej-1", "propose", b"{}").await;

    let app = build_router(state.clone());
    let (status, _) = post_json(app, "/api/agents/ALPHA/buffer/evt-rej-1/reject", "").await;
    assert_eq!(status, StatusCode::OK);

    let snap = state.statuses["ALPHA"].read().await;
    let reject_events: Vec<_> = snap
        .event_log
        .iter()
        .filter(|e| e.event_type == "buffer_rejected")
        .collect();
    assert_eq!(reject_events.len(), 1);
    assert!(reject_events[0].detail.contains("rejected"));
}

// -----------------------------------------------------------------------
// Regen / edit buffer preservation tests (API-level)
// -----------------------------------------------------------------------

/// Full regen flow via API: stop → edit → unstop → verify reply_subject preserved
#[tokio::test]
async fn regen_flow_preserves_reply_subject() {
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    let original_payload = serde_json::json!({"content": "original proposal"});
    push_test_entry(
        &buf,
        "regen-1",
        "propose",
        &serde_json::to_vec(&original_payload).unwrap(),
    )
    .await;

    // Capture original reply_subject from buffer
    let detail_before = buf.get_detail("regen-1").await.unwrap();
    assert_eq!(detail_before.content["content"], "original proposal");

    // Step 1: Stop the entry (simulates operator clicking "Re-generate")
    let app = build_router(state.clone());
    let (status, _) = post_json(app, "/api/agents/ALPHA/buffer/regen-1/stop", "").await;
    assert_eq!(status, StatusCode::OK);

    // Step 2: Edit with new content (simulates regen result being PUT)
    let app = build_router(state.clone());
    let (status, body) = put_json(
        app,
        "/api/agents/ALPHA/buffer/regen-1",
        r#"{"content": {"content": "regenerated proposal v2"}, "operator_comment": "Regenerated by operator"}"#,
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["status"], "edited");

    // Step 3: Unstop (makes it eligible for drain again)
    let app = build_router(state.clone());
    let (status, _) = post_json(app, "/api/agents/ALPHA/buffer/regen-1/unstop", "").await;
    assert_eq!(status, StatusCode::OK);

    // Verify: content changed, entry still in buffer, not stopped
    let detail_after = buf.get_detail("regen-1").await.unwrap();
    assert_eq!(detail_after.content["content"], "regenerated proposal v2");
    assert!(!detail_after.summary.stopped);
    assert_eq!(detail_after.summary.id, "regen-1");
    assert_eq!(detail_after.summary.action, "propose");
    assert_eq!(detail_after.summary.job_id, "job-test");
}

/// Verify multiple edits via API preserve entry identity
#[tokio::test]
async fn multiple_edits_preserve_entry_identity() {
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    let payload = serde_json::json!({"content": "v1"});
    push_test_entry(
        &buf,
        "multi-edit-1",
        "propose",
        &serde_json::to_vec(&payload).unwrap(),
    )
    .await;

    // Edit 1
    let app = build_router(state.clone());
    let (status, _) = put_json(
        app,
        "/api/agents/ALPHA/buffer/multi-edit-1",
        r#"{"content": {"content": "v2"}, "operator_comment": "First edit"}"#,
    )
    .await;
    assert_eq!(status, StatusCode::OK);

    // Edit 2
    let app = build_router(state.clone());
    let (status, _) = put_json(
        app,
        "/api/agents/ALPHA/buffer/multi-edit-1",
        r#"{"content": {"content": "v3"}, "operator_comment": "Second edit"}"#,
    )
    .await;
    assert_eq!(status, StatusCode::OK);

    // Comment only
    let app = build_router(state.clone());
    let (status, _) = put_json(
        app,
        "/api/agents/ALPHA/buffer/multi-edit-1",
        r#"{"operator_comment": "LGTM"}"#,
    )
    .await;
    assert_eq!(status, StatusCode::OK);

    // Verify final state
    let detail = buf.get_detail("multi-edit-1").await.unwrap();
    assert_eq!(detail.content["content"], "v3");
    assert_eq!(detail.summary.id, "multi-edit-1");
    assert_eq!(detail.summary.action, "propose");
    assert_eq!(detail.summary.job_id, "job-test");
}

/// Regen flow then release — verify the entry can be successfully released
#[tokio::test]
async fn regen_then_release_succeeds() {
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    push_test_entry(&buf, "regen-rel-1", "propose", b"{}").await;

    // Stop → edit → unstop (regen flow)
    buf.stop("regen-rel-1").await;
    let app = build_router(state.clone());
    let (status, _) = put_json(
        app,
        "/api/agents/ALPHA/buffer/regen-rel-1",
        r#"{"content": {"content": "regenerated"}, "operator_comment": "Regen"}"#,
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    buf.unstop("regen-rel-1").await;

    // Release
    let app = build_router(state.clone());
    let (status, body) = post_json(app, "/api/agents/ALPHA/buffer/regen-rel-1/release", "").await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["status"], "releasing");

    // Buffer should be drainable
    let drained = buf.drain_ready().await;
    assert_eq!(drained.len(), 1);
    assert_eq!(drained[0].id, "regen-rel-1");
    assert_eq!(
        drained[0].reply_subject, "nsed.job-test.result.1.agent.propose",
        "reply_subject must be preserved through regen flow"
    );
}

/// Edit after reject should fail (entry was removed)
#[tokio::test]
async fn edit_after_reject_returns_404() {
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    push_test_entry(&buf, "rej-edit-1", "propose", b"{}").await;

    // Reject the entry
    let app = build_router(state.clone());
    let (status, _) = post_json(app, "/api/agents/ALPHA/buffer/rej-edit-1/reject", "").await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(buf.len().await, 0);

    // Try to edit — should fail
    let app = build_router(state.clone());
    let (status, body) = put_json(
        app,
        "/api/agents/ALPHA/buffer/rej-edit-1",
        r#"{"content": {"content": "too late"}}"#,
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert!(body.contains("not found"));
}

/// Stop after release should fail (entry was marked for release)
#[tokio::test]
async fn stop_after_release_drain_returns_404() {
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    push_test_entry(&buf, "sr-1", "propose", b"{}").await;

    // Release then drain (entry removed from buffer)
    buf.mark_for_release("sr-1").await;
    buf.drain_ready().await;

    // Try to stop — should fail (entry gone)
    let app = build_router(state.clone());
    let (status, _) = post_json(app, "/api/agents/ALPHA/buffer/sr-1/stop", "").await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

/// Event log ordering after full regen flow via API
#[tokio::test]
async fn regen_flow_event_ordering() {
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    push_test_entry(&buf, "evt-regen-1", "propose", b"{}").await;

    // Stop
    let app = build_router(state.clone());
    post_json(app, "/api/agents/ALPHA/buffer/evt-regen-1/stop", "").await;

    // Unstop
    let app = build_router(state.clone());
    post_json(app, "/api/agents/ALPHA/buffer/evt-regen-1/unstop", "").await;

    // Release
    let app = build_router(state.clone());
    post_json(app, "/api/agents/ALPHA/buffer/evt-regen-1/release", "").await;

    // Verify event ordering
    let snap = state.statuses["ALPHA"].read().await;
    let types: Vec<&str> = snap
        .event_log
        .iter()
        .map(|e| e.event_type.as_str())
        .collect();
    assert_eq!(
        types,
        vec!["buffer_stopped", "buffer_unstopped", "buffer_released"],
        "events should be in chronological order"
    );
}

// -----------------------------------------------------------------------
// CodeRabbit fix: stop/unstop events use job_id, not entry_id
// -----------------------------------------------------------------------

#[tokio::test]
async fn stop_event_uses_job_id_not_entry_id() {
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    push_test_entry(&buf, "stop-jid-1", "propose", b"{}").await;

    let app = build_router(state.clone());
    let (status, _) = post_json(app, "/api/agents/ALPHA/buffer/stop-jid-1/stop", "").await;
    assert_eq!(status, StatusCode::OK);

    let snap = state.statuses["ALPHA"].read().await;
    let stop_event = snap
        .event_log
        .iter()
        .find(|e| e.event_type == "buffer_stopped")
        .expect("should have buffer_stopped event");
    // job_id should be "job-test" (from push_test_entry), NOT "stop-jid-1" (entry id)
    assert_eq!(
        stop_event.job_id.as_deref(),
        Some("job-test"),
        "stop event should use job_id not entry_id"
    );
}

#[tokio::test]
async fn unstop_event_uses_job_id_not_entry_id() {
    let state = test_state_with_buffer();
    let buf = state.buffers["ALPHA"].clone();
    push_test_entry(&buf, "unstop-jid-1", "propose", b"{}").await;
    buf.stop("unstop-jid-1").await;

    let app = build_router(state.clone());
    let (status, _) = post_json(app, "/api/agents/ALPHA/buffer/unstop-jid-1/unstop", "").await;
    assert_eq!(status, StatusCode::OK);

    let snap = state.statuses["ALPHA"].read().await;
    let unstop_event = snap
        .event_log
        .iter()
        .find(|e| e.event_type == "buffer_unstopped")
        .expect("should have buffer_unstopped event");
    assert_eq!(
        unstop_event.job_id.as_deref(),
        Some("job-test"),
        "unstop event should use job_id not entry_id"
    );
}

// -----------------------------------------------------------------------
// response_sla_secs accepts any value (no floor)
// -----------------------------------------------------------------------

#[tokio::test]
async fn put_config_sla_accepts_any_value() {
    let state = test_state_with_buffer();
    let buf = state.buffers.get("ALPHA").unwrap().clone();

    let app = build_router(state.clone());
    // Set SLA to 10s — accepted as-is (no floor)
    let (status, body) = put_json(app, "/api/config", r#"{"response_sla_secs": 10}"#).await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["response_sla_secs"], 10);
    assert_eq!(state.response_sla_secs.load(Ordering::Relaxed), 10);
    assert_eq!(buf.response_sla().unwrap().as_secs(), 10);
}

#[tokio::test]
async fn put_config_sla_zero_is_passthrough() {
    let state = test_state_with_buffer();
    let _buf = state.buffers.get("ALPHA").unwrap().clone();

    let app = build_router(state.clone());
    // Setting SLA to 0 means pass-through (no buffering)
    let (status, body) = put_json(app, "/api/config", r#"{"response_sla_secs": 0}"#).await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["response_sla_secs"], 0);
    assert_eq!(state.response_sla_secs.load(Ordering::Relaxed), 0);
}

#[tokio::test]
async fn put_config_sla_above_minimum_preserved() {
    let state = test_state_with_buffer();

    let app = build_router(state.clone());
    // 600s > 300s minimum — should be preserved exactly
    let (status, body) = put_json(app, "/api/config", r#"{"response_sla_secs": 600}"#).await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["response_sla_secs"], 600);
    assert_eq!(state.response_sla_secs.load(Ordering::Relaxed), 600);
}

// -----------------------------------------------------------------------
// CodeRabbit fix: config update rejects invalid values
// -----------------------------------------------------------------------

#[tokio::test]
async fn config_update_rejects_invalid_temperature() {
    let state = test_state_with_buffer();
    let app = build_router(state);
    let (status, body) = put_json(app, "/api/agents/ALPHA/config", r#"{"temperature": 5.0}"#).await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(body.contains("temperature"));
}

#[tokio::test]
async fn config_update_rejects_negative_retries() {
    let state = test_state_with_buffer();
    let app = build_router(state);
    let (status, body) = put_json(app, "/api/agents/ALPHA/config", r#"{"max_retries": -1}"#).await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(body.contains("max_retries"));
}

#[tokio::test]
async fn config_update_accepts_valid_values() {
    let state = test_state_with_buffer();
    let app = build_router(state);
    let (status, _) = put_json(
        app,
        "/api/agents/ALPHA/config",
        r#"{"temperature": 1.2, "max_retries": 3}"#,
    )
    .await;
    assert_eq!(status, StatusCode::OK);
}

// -------------------------------------------------------------------
// Auto-approve endpoint tests
// -------------------------------------------------------------------

#[tokio::test]
async fn auto_approve_enable_returns_200() {
    let state = test_state_with_buffer();
    let app = build_router(state);
    let (status, body) = put_json(
        app,
        "/api/agents/ALPHA/auto",
        r#"{"enabled": true, "threshold": 0.6}"#,
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["auto_approve"], true);
    assert!((json["threshold"].as_f64().unwrap() - 0.6).abs() < 0.01);
}

#[tokio::test]
async fn auto_approve_disable_returns_200() {
    let state = test_state_with_buffer();
    // First enable, then disable
    let buf = state.buffers.get("ALPHA").unwrap();
    buf.set_auto_approve(true);
    buf.set_auto_approve_threshold(0.7);

    let app = build_router(state);
    let (status, body) = put_json(app, "/api/agents/ALPHA/auto", r#"{"enabled": false}"#).await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["auto_approve"], false);
    // Threshold unchanged when not provided
    assert!((json["threshold"].as_f64().unwrap() - 0.7).abs() < 0.01);
}

#[tokio::test]
async fn auto_approve_unknown_agent_returns_404() {
    let app = build_router(test_state());
    let (status, body) = put_json(app, "/api/agents/UNKNOWN/auto", r#"{"enabled": true}"#).await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert!(body.contains("not found"));
}

#[tokio::test]
async fn auto_approve_invalid_threshold_returns_400() {
    let state = test_state_with_buffer();
    let app = build_router(state);
    let (status, body) = put_json(
        app,
        "/api/agents/ALPHA/auto",
        r#"{"enabled": true, "threshold": 1.5}"#,
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(body.contains("threshold"));
}

#[tokio::test]
async fn auto_approve_negative_threshold_returns_400() {
    let state = test_state_with_buffer();
    let app = build_router(state);
    let (status, body) = put_json(
        app,
        "/api/agents/ALPHA/auto",
        r#"{"enabled": true, "threshold": -0.1}"#,
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(body.contains("threshold"));
}

#[tokio::test]
async fn list_agents_includes_auto_approve_fields() {
    let state = test_state_with_buffer();
    let buf = state.buffers.get("ALPHA").unwrap();
    buf.set_auto_approve(true);
    buf.set_auto_approve_threshold(0.3);

    let app = build_router(state);
    let (status, body) = get_request(app, "/api/agents").await;
    assert_eq!(status, StatusCode::OK);
    let agents: Vec<serde_json::Value> = serde_json::from_str(&body).unwrap();
    let alpha = agents.iter().find(|a| a["name"] == "ALPHA").unwrap();
    assert_eq!(alpha["auto_approve"], true);
    assert!((alpha["auto_approve_threshold"].as_f64().unwrap() - 0.3).abs() < 0.01);

    // BETA has no buffer → pass-through defaults surfaced as
    // auto_approve=true, threshold=1.0 (an agent with no buffer IS a
    // pass-through, semantically identical to a buffered agent under
    // the new ResponseBuffer defaults).
    let beta = agents.iter().find(|a| a["name"] == "BETA").unwrap();
    assert_eq!(beta["auto_approve"], true);
    assert!((beta["auto_approve_threshold"].as_f64().unwrap() - 1.0).abs() < 0.01);
}

#[tokio::test]
async fn auto_approve_emits_status_event() {
    let state = test_state_with_buffer();
    let app = build_router(state.clone());
    let (_status, _body) = put_json(
        app,
        "/api/agents/ALPHA/auto",
        r#"{"enabled": true, "threshold": 0.4}"#,
    )
    .await;

    let snap = state.statuses["ALPHA"].read().await;
    let last_event = snap.event_log.back().unwrap();
    assert_eq!(last_event.event_type, "auto_approve_enabled");
    assert!(last_event.detail.contains("threshold: 40%"));
}

// -------------------------------------------------------------------
// Auto-approve ALL endpoint tests
// -------------------------------------------------------------------

/// Build a test state with HITL buffers for BOTH agents.
fn test_state_with_both_buffers() -> MultiAppState {
    let mut state = test_state();
    let alpha_buf = Arc::new(ResponseBuffer::new(std::time::Duration::from_secs(30)));
    let beta_buf = Arc::new(ResponseBuffer::new(std::time::Duration::from_secs(30)));
    state.buffers.insert("ALPHA".to_string(), alpha_buf);
    state.buffers.insert("BETA".to_string(), beta_buf);
    state
}

#[tokio::test]
async fn auto_all_enable_returns_200() {
    let state = test_state_with_both_buffers();
    let app = build_router(state);
    let (status, body) = put_json(
        app,
        "/api/agents/auto-all",
        r#"{"enabled": true, "threshold": 0.6}"#,
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["auto_approve"], true);
    assert!((json["threshold"].as_f64().unwrap() - 0.6).abs() < 0.01);
    assert_eq!(json["count"], 2);
}

#[tokio::test]
async fn auto_all_disable_returns_200() {
    let state = test_state_with_both_buffers();
    // Pre-enable both
    for buf in state.buffers.values() {
        buf.set_auto_approve(true);
    }

    let app = build_router(state);
    let (status, body) = put_json(app, "/api/agents/auto-all", r#"{"enabled": false}"#).await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["auto_approve"], false);
    assert_eq!(json["count"], 2);
}

#[tokio::test]
async fn auto_all_propagates_to_all_buffers() {
    let state = test_state_with_both_buffers();
    let alpha_buf = state.buffers["ALPHA"].clone();
    let beta_buf = state.buffers["BETA"].clone();

    // The ResponseBuffer default is now auto_approve=true, so we must
    // explicitly disable first to prove the /auto-all PUT flips the
    // flag back on (otherwise the post-condition assertions would be
    // satisfied vacuously by the default state).
    alpha_buf.set_auto_approve(false);
    beta_buf.set_auto_approve(false);
    assert!(!alpha_buf.is_auto_approve());
    assert!(!beta_buf.is_auto_approve());

    let app = build_router(state);
    let (status, _) = put_json(
        app,
        "/api/agents/auto-all",
        r#"{"enabled": true, "threshold": 0.35}"#,
    )
    .await;
    assert_eq!(status, StatusCode::OK);

    // Both should be on with the same threshold
    assert!(alpha_buf.is_auto_approve());
    assert!(beta_buf.is_auto_approve());
    assert!((alpha_buf.auto_approve_threshold() - 0.35).abs() < 0.01);
    assert!((beta_buf.auto_approve_threshold() - 0.35).abs() < 0.01);
}

#[tokio::test]
async fn auto_all_invalid_threshold_returns_400() {
    let state = test_state_with_both_buffers();
    let app = build_router(state);
    let (status, body) = put_json(
        app,
        "/api/agents/auto-all",
        r#"{"enabled": true, "threshold": 2.0}"#,
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(body.contains("threshold"));
}

#[tokio::test]
async fn auto_all_negative_threshold_returns_400() {
    let state = test_state_with_both_buffers();
    let app = build_router(state);
    let (status, body) = put_json(
        app,
        "/api/agents/auto-all",
        r#"{"enabled": true, "threshold": -0.5}"#,
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(body.contains("threshold"));
}

#[tokio::test]
async fn auto_all_emits_events_for_all_agents() {
    let state = test_state_with_both_buffers();
    let app = build_router(state.clone());
    let (status, _) = put_json(
        app,
        "/api/agents/auto-all",
        r#"{"enabled": true, "threshold": 0.5}"#,
    )
    .await;
    assert_eq!(status, StatusCode::OK);

    // Both agents should have auto_approve_enabled events
    for name in &["ALPHA", "BETA"] {
        let snap = state.statuses[*name].read().await;
        let events: Vec<_> = snap
            .event_log
            .iter()
            .filter(|e| e.event_type == "auto_approve_enabled")
            .collect();
        assert_eq!(
            events.len(),
            1,
            "Agent {} should have exactly one auto_approve_enabled event",
            name
        );
        assert!(events[0].detail.contains("master control"));
    }
}

#[tokio::test]
async fn auto_all_empty_state_returns_zero_count() {
    let state = MultiAppState {
        statuses: HashMap::new(),
        chat_agents: HashMap::new(),
        configs: HashMap::new(),
        buffers: HashMap::new(),
        pause_handles: HashMap::new(),
        orchestrator_registry: None,
        base_hold_secs: Arc::new(AtomicU64::new(10)),
        response_sla_secs: Arc::new(AtomicU64::new(10)),
        buffer_floor_pct: Arc::new(AtomicU64::new(0)),
        before_release_middleware: None,
    };
    let app = build_router(state);
    let (status, body) = put_json(app, "/api/agents/auto-all", r#"{"enabled": true}"#).await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["count"], 0);
}

#[tokio::test]
async fn auto_all_without_threshold_preserves_existing() {
    let state = test_state_with_both_buffers();
    let alpha_buf = state.buffers["ALPHA"].clone();
    // Set a custom threshold on ALPHA first
    alpha_buf.set_auto_approve_threshold(0.8);

    let app = build_router(state);
    // Enable without providing threshold
    let (status, _) = put_json(app, "/api/agents/auto-all", r#"{"enabled": true}"#).await;
    assert_eq!(status, StatusCode::OK);

    // ALPHA's custom threshold should be preserved (no threshold in request = no update)
    assert!(alpha_buf.is_auto_approve());
    assert!(
        (alpha_buf.auto_approve_threshold() - 0.8).abs() < 0.01,
        "threshold should be preserved when not specified in request"
    );
}

// =========================================================================
// E2E data contract tests — typed deserialization of API responses
// =========================================================================
//
// These tests validate that API responses match the exact data contracts
// the dashboard frontend depends on. Every field the JS code reads is
// verified via strongly-typed Rust deserialization.

/// Typed mirror of the AgentSummary struct for deserialization.
#[derive(serde::Deserialize, Debug)]
#[allow(dead_code)]
struct AgentSummaryContract {
    name: String,
    model_name: String,
    provider_id: String,
    nats_connected: bool,
    current_job: Option<String>,
    current_phase: Option<String>,
    has_chat: bool,
    is_paused: bool,
    buffered_count: u32,
    error_rate: f32,
    mean_score: Option<f32>,
    score_std_dev: Option<f32>,
    avg_response_ms: Option<u64>,
    is_flagged: bool,
    flag_reason: Option<String>,
    auto_approve: bool,
    auto_approve_threshold: f32,
}

/// Typed mirror of AgentStatusSnapshot for deserialization.
#[derive(serde::Deserialize, Debug)]
#[allow(dead_code)]
struct StatusContract {
    agent_id: String,
    model_name: String,
    provider_id: String,
    nats_connected: bool,
    current_job: Option<String>,
    current_round: Option<u32>,
    current_phase: Option<String>,
    uptime_secs: u64,
    tasks_completed: u64,
    tasks_failed: u64,
    recent_tasks: Vec<TaskLogContract>,
    scratchpad_keys: u64,
    event_log: Vec<EventLogContract>,
    is_paused: bool,
    buffered_count: u32,
    error_rate: f32,
    recent_scores: Vec<ScoreContract>,
    mean_score: Option<f32>,
    score_std_dev: Option<f32>,
    is_flagged: bool,
    flag_reason: Option<String>,
}

#[derive(serde::Deserialize, Debug)]
#[allow(dead_code)]
struct TaskLogContract {
    timestamp: String,
    action: String,
    job_id: String,
    round: u32,
    status: String,
    duration_ms: u64,
    content_preview: Option<String>,
}

#[derive(serde::Deserialize, Debug)]
#[allow(dead_code)]
struct EventLogContract {
    timestamp: String,
    event_type: String,
    job_id: Option<String>,
    detail: String,
}

#[derive(serde::Deserialize, Debug)]
#[allow(dead_code)]
struct ScoreContract {
    timestamp: String,
    job_id: String,
    round: u32,
    evaluator: String,
    score: f32,
}

/// Typed mirror of BufferEntrySummary.
#[derive(serde::Deserialize, Debug)]
#[allow(dead_code)]
struct BufferSummaryContract {
    id: String,
    action: String,
    job_id: String,
    round: u32,
    age_ms: u64,
    release_in_ms: i64,
    stopped: bool,
}

/// Typed mirror of BufferEntryDetail (flattened).
#[derive(serde::Deserialize, Debug)]
#[allow(dead_code)]
struct BufferDetailContract {
    id: String,
    action: String,
    job_id: String,
    round: u32,
    age_ms: u64,
    release_in_ms: i64,
    stopped: bool,
    content: serde_json::Value,
}

// ── OpenAPI spec generation test ──

#[test]
fn openapi_spec_generates_without_panic() {
    use utoipa::OpenApi;
    let spec = super::api_docs::ApiDoc::openapi();
    let json = spec.to_json().unwrap();
    assert!(json.contains("\"openapi\":\"3.1.0\""));
    assert!(json.contains("AgentStatusSnapshot"));
    assert!(json.contains("BufferEntrySummary"));
    assert!(json.contains("TaskLogEntry"));
    assert!(json.contains("/api/agents"));
    assert!(json.contains("/api/agents/{name}/status"));
    assert!(json.contains("/api/agents/{name}/buffer"));
}

// ── Swagger UI endpoint test ──

#[tokio::test]
async fn swagger_ui_endpoint_returns_html() {
    let app = build_router(test_state());
    let (status, body) = get_request(app, "/swagger-ui/").await;
    assert_eq!(status, StatusCode::OK);
    assert!(
        body.contains("swagger") || body.contains("Swagger"),
        "swagger-ui response should contain Swagger references"
    );
}

#[tokio::test]
async fn openapi_json_endpoint_returns_spec() {
    let app = build_router(test_state());
    let (status, body) = get_request(app, "/api-docs/openapi.json").await;
    assert_eq!(status, StatusCode::OK);
    let spec: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(spec["openapi"], "3.1.0");
    assert!(spec["paths"]["/api/agents"].is_object());
    assert!(spec["paths"]["/api/agents/{name}/status"].is_object());
}

// ── /api/agents typed contract ──

#[tokio::test]
async fn contract_list_agents_typed_deserialization() {
    let app = build_router(test_state());
    let (status, body) = get_request(app, "/api/agents").await;
    assert_eq!(status, StatusCode::OK);

    // Must deserialize into typed struct — validates all field names and types
    let agents: Vec<AgentSummaryContract> =
        serde_json::from_str(&body).expect("Failed to deserialize /api/agents into typed contract");
    assert_eq!(agents.len(), 2);
    assert_eq!(agents[0].name, "ALPHA");
    assert_eq!(agents[1].name, "BETA");
    assert!(!agents[0].is_paused);
    assert_eq!(agents[0].buffered_count, 0);
    assert!(agents[0].mean_score.is_none());
}

// ── /api/agents/{name}/status typed contract ──

#[tokio::test]
async fn contract_status_snapshot_typed_deserialization() {
    use crate::status::TaskLogEntry;

    let state = test_state();
    {
        let mut snap = state.statuses["ALPHA"].write().await;
        snap.nats_connected = true;
        snap.current_job = Some("job-xyz".into());
        snap.current_round = Some(3);
        snap.current_phase = Some("evaluate".into());
        snap.push_task(TaskLogEntry {
            timestamp: "2025-01-01T00:00:00Z".into(),
            action: "propose".into(),
            job_id: "job-xyz".into(),
            round: 2,
            status: "ok".into(),
            duration_ms: 1500,
            content_preview: Some(r#"{"t":"p","c":"Hello world"}"#.into()),
        });
        snap.push_event("agent_working", Some("job-xyz"), "Round 3 evaluate");
    }
    let app = build_router(state);
    let (status, body) = get_request(app, "/api/agents/ALPHA/status").await;
    assert_eq!(status, StatusCode::OK);

    let snap: StatusContract = serde_json::from_str(&body)
        .expect("Failed to deserialize /api/agents/ALPHA/status into typed contract");

    assert_eq!(snap.agent_id, "ALPHA");
    assert!(snap.nats_connected);
    assert_eq!(snap.current_job.as_deref(), Some("job-xyz"));
    assert_eq!(snap.current_round, Some(3));
    assert_eq!(snap.current_phase.as_deref(), Some("evaluate"));
    assert_eq!(snap.tasks_completed, 1);
    assert_eq!(snap.tasks_failed, 0);

    // recent_tasks: LIFO — most recent at index 0
    assert_eq!(snap.recent_tasks.len(), 1);
    let task = &snap.recent_tasks[0];
    assert_eq!(task.action, "propose");
    assert_eq!(task.job_id, "job-xyz");
    assert_eq!(task.round, 2);
    assert_eq!(task.status, "ok");
    assert_eq!(task.duration_ms, 1500);
    assert!(task.content_preview.is_some());

    // content_preview is a JSON string — the frontend parses it
    let preview: serde_json::Value =
        serde_json::from_str(task.content_preview.as_ref().unwrap()).unwrap();
    assert_eq!(preview["t"], "p");
    assert_eq!(preview["c"], "Hello world");

    // event_log
    assert!(!snap.event_log.is_empty());
    assert_eq!(snap.event_log.last().unwrap().event_type, "agent_working");
}

// ── /api/agents/{name}/status — recent_tasks LIFO ordering ──

#[tokio::test]
async fn contract_status_recent_tasks_lifo_ordering() {
    use crate::status::TaskLogEntry;

    let state = test_state();
    {
        let mut snap = state.statuses["ALPHA"].write().await;
        for i in 1..=5 {
            snap.push_task(TaskLogEntry {
                timestamp: format!("2025-01-01T00:00:{:02}Z", i),
                action: if i % 2 == 0 { "evaluate" } else { "propose" }.into(),
                job_id: "job-lifo".into(),
                round: i,
                status: "ok".into(),
                duration_ms: 100 * i as u64,
                content_preview: None,
            });
        }
    }
    let app = build_router(state);
    let (_, body) = get_request(app, "/api/agents/ALPHA/status").await;
    let snap: StatusContract = serde_json::from_str(&body).unwrap();

    assert_eq!(snap.recent_tasks.len(), 5);
    // Most recent (round 5) should be at index 0
    assert_eq!(snap.recent_tasks[0].round, 5);
    assert_eq!(snap.recent_tasks[4].round, 1);
    // Verify ordering is strictly newest-first
    for i in 0..4 {
        assert!(
            snap.recent_tasks[i].round > snap.recent_tasks[i + 1].round,
            "recent_tasks[{}].round={} should be > recent_tasks[{}].round={}",
            i,
            snap.recent_tasks[i].round,
            i + 1,
            snap.recent_tasks[i + 1].round
        );
    }
}

// ── /api/agents/{name}/status — scores and flagging ──

#[tokio::test]
async fn contract_status_scores_and_flagging() {
    use crate::status::ScoreEntry;

    let state = test_state();
    {
        let mut snap = state.statuses["ALPHA"].write().await;
        snap.push_score(ScoreEntry {
            timestamp: "t1".into(),
            job_id: "j1".into(),
            round: 1,
            evaluator: "BETA".into(),
            score: -0.5,
        });
        snap.push_score(ScoreEntry {
            timestamp: "t2".into(),
            job_id: "j1".into(),
            round: 1,
            evaluator: "GAMMA".into(),
            score: -0.6,
        });
        snap.push_score(ScoreEntry {
            timestamp: "t3".into(),
            job_id: "j1".into(),
            round: 2,
            evaluator: "BETA".into(),
            score: -0.4,
        });
    }
    let app = build_router(state);
    let (_, body) = get_request(app, "/api/agents/ALPHA/status").await;
    let snap: StatusContract = serde_json::from_str(&body).unwrap();

    assert_eq!(snap.recent_scores.len(), 3);
    assert!(snap.mean_score.is_some());
    assert!(snap.is_flagged, "low scores should trigger flagging");
    assert!(snap.flag_reason.is_some());
    assert!(
        snap.flag_reason.as_ref().unwrap().contains("Low scores"),
        "flag_reason: {:?}",
        snap.flag_reason
    );
}

// ── /api/agents/{name}/buffer — typed contract ──

#[tokio::test]
async fn contract_buffer_list_typed_deserialization() {
    use crate::workers::buffer::BufferedResponse;

    let state = test_state_with_buffer();
    let buf = state.buffers.get("ALPHA").unwrap();
    let now = std::time::Instant::now();
    let payload = serde_json::json!({"content": "test proposal", "thought_process": "thinking..."});
    buf.push(BufferedResponse {
        id: "buf-001".into(),
        action: "propose".into(),
        job_id: "job-abc".into(),
        round: 2,
        reply_subject: "nsed.job-abc.result.2.ALPHA.propose".into(),
        payload: serde_json::to_vec(&payload).unwrap(),
        created_at: now,
        release_at: now + std::time::Duration::from_secs(300),
        ack_handle: Box::new(NoopAck),
        msg_id: "msg-001".into(),
        annotations: vec![],
        edited: false,
        stopped: false,
    })
    .await;

    let app = build_router(state);
    let (status, body) = get_request(app, "/api/agents/ALPHA/buffer").await;
    assert_eq!(status, StatusCode::OK);

    let entries: Vec<BufferSummaryContract> = serde_json::from_str(&body)
        .expect("Failed to deserialize /api/agents/ALPHA/buffer into typed contract");
    assert_eq!(entries.len(), 1);
    let entry = &entries[0];
    assert_eq!(entry.id, "buf-001");
    assert_eq!(entry.action, "propose");
    assert_eq!(entry.job_id, "job-abc");
    assert_eq!(entry.round, 2);
    assert!(!entry.stopped);
    assert!(
        entry.release_in_ms > 0,
        "should have positive release_in_ms"
    );
}

// ── /api/agents/{name}/buffer/{id} — typed detail contract ──

#[tokio::test]
async fn contract_buffer_detail_typed_deserialization() {
    use crate::workers::buffer::BufferedResponse;

    let state = test_state_with_buffer();
    let buf = state.buffers.get("ALPHA").unwrap();
    let now = std::time::Instant::now();
    // Evaluation payload: [[target_agent, eval_obj], ...]
    let eval_payload = serde_json::json!([
        ["BETA", {"score": 7.5, "justification": "Good proposal"}],
        ["GAMMA", {"score": 4.0, "justification": "Needs work"}]
    ]);
    buf.push(BufferedResponse {
        id: "buf-eval-001".into(),
        action: "evaluate".into(),
        job_id: "job-eval".into(),
        round: 3,
        reply_subject: "nsed.job-eval.result.3.ALPHA.evaluate".into(),
        payload: serde_json::to_vec(&eval_payload).unwrap(),
        created_at: now,
        release_at: now + std::time::Duration::from_secs(300),
        ack_handle: Box::new(NoopAck),
        msg_id: "msg-eval-001".into(),
        annotations: vec![],
        edited: false,
        stopped: false,
    })
    .await;

    let app = build_router(state);
    let (status, body) = get_request(app, "/api/agents/ALPHA/buffer/buf-eval-001").await;
    assert_eq!(status, StatusCode::OK);

    let detail: BufferDetailContract = serde_json::from_str(&body)
        .expect("Failed to deserialize buffer detail into typed contract");
    assert_eq!(detail.id, "buf-eval-001");
    assert_eq!(detail.action, "evaluate");
    assert_eq!(detail.job_id, "job-eval");
    assert_eq!(detail.round, 3);
    assert!(!detail.stopped);

    // content is the raw evaluation payload — frontend extracts target agents from this
    let content = &detail.content;
    assert!(content.is_array(), "evaluation content should be array");
    let evals = content.as_array().unwrap();
    assert_eq!(evals.len(), 2);
    assert_eq!(evals[0][0], "BETA");
    assert_eq!(evals[1][0], "GAMMA");
    assert_eq!(evals[0][1]["score"], 7.5);
}

// ── /api/agents/{name}/status — content_preview formats ──

#[tokio::test]
async fn contract_status_content_preview_proposal_format() {
    use crate::status::TaskLogEntry;

    let state = test_state();
    {
        let mut snap = state.statuses["ALPHA"].write().await;
        snap.push_task(TaskLogEntry {
            timestamp: "2025-01-01T00:00:00Z".into(),
            action: "propose".into(),
            job_id: "job-cp".into(),
            round: 1,
            status: "ok".into(),
            duration_ms: 500,
            content_preview: Some(
                serde_json::json!({"t": "p", "c": "My proposal content", "tp": "My reasoning"})
                    .to_string(),
            ),
        });
    }
    let app = build_router(state);
    let (_, body) = get_request(app, "/api/agents/ALPHA/status").await;
    let snap: StatusContract = serde_json::from_str(&body).unwrap();

    let preview_str = snap.recent_tasks[0].content_preview.as_ref().unwrap();
    let preview: serde_json::Value = serde_json::from_str(preview_str).unwrap();
    assert_eq!(preview["t"], "p", "type marker should be 'p' for proposal");
    assert_eq!(preview["c"], "My proposal content");
    assert_eq!(preview["tp"], "My reasoning");
}

#[tokio::test]
async fn contract_status_content_preview_evaluation_format() {
    use crate::status::TaskLogEntry;

    let state = test_state();
    {
        let mut snap = state.statuses["ALPHA"].write().await;
        snap.push_task(TaskLogEntry {
            timestamp: "2025-01-01T00:00:00Z".into(),
            action: "evaluate".into(),
            job_id: "job-cp".into(),
            round: 1,
            status: "ok".into(),
            duration_ms: 800,
            content_preview: Some(
                serde_json::json!({
                    "t": "e",
                    "evals": [
                        {"target": "BETA", "s": 7.5, "j": "Good work"},
                        {"target": "GAMMA", "s": 3.0, "j": "Needs improvement"}
                    ]
                })
                .to_string(),
            ),
        });
    }
    let app = build_router(state);
    let (_, body) = get_request(app, "/api/agents/ALPHA/status").await;
    let snap: StatusContract = serde_json::from_str(&body).unwrap();

    let preview_str = snap.recent_tasks[0].content_preview.as_ref().unwrap();
    let preview: serde_json::Value = serde_json::from_str(preview_str).unwrap();
    assert_eq!(
        preview["t"], "e",
        "type marker should be 'e' for evaluation"
    );
    let evals = preview["evals"].as_array().unwrap();
    assert_eq!(evals.len(), 2);
    assert_eq!(evals[0]["target"], "BETA");
    assert_eq!(evals[0]["s"], 7.5);
    assert_eq!(evals[1]["target"], "GAMMA");
}

// ── /api/config typed contract ──

#[tokio::test]
async fn contract_global_config_typed_deserialization() {
    #[derive(serde::Deserialize, Debug)]
    #[allow(dead_code)]
    struct GlobalConfigContract {
        base_hold_secs: u64,
        response_sla_secs: u64,
        buffer_floor_pct: u64,
    }

    let app = build_router(test_state());
    let (status, body) = get_request(app, "/api/config").await;
    assert_eq!(status, StatusCode::OK);

    let config: GlobalConfigContract =
        serde_json::from_str(&body).expect("Failed to deserialize /api/config into typed contract");
    assert_eq!(config.base_hold_secs, 10);
    assert_eq!(config.response_sla_secs, 10);
    assert_eq!(config.buffer_floor_pct, 0);
}

// -----------------------------------------------------------------------
// Agent Config Management API (registration_handlers) integration tests
// -----------------------------------------------------------------------

/// Helper: perform a PATCH request with JSON body.
async fn patch_json(app: Router, uri: &str, json: &str) -> (StatusCode, String) {
    let req = axum::http::Request::builder()
        .method("PATCH")
        .uri(uri)
        .header("content-type", "application/json")
        .body(Body::from(json.to_string()))
        .unwrap();
    let resp = app.oneshot(req).await.unwrap();
    let status = resp.status();
    let body = resp.into_body().collect().await.unwrap().to_bytes();
    (status, String::from_utf8(body.to_vec()).unwrap())
}

/// Helper: perform a DELETE request.
async fn delete_request(app: Router, uri: &str) -> (StatusCode, String) {
    let req = axum::http::Request::builder()
        .method("DELETE")
        .uri(uri)
        .body(Body::empty())
        .unwrap();
    let resp = app.oneshot(req).await.unwrap();
    let status = resp.status();
    let body = resp.into_body().collect().await.unwrap().to_bytes();
    (status, String::from_utf8(body.to_vec()).unwrap())
}

#[tokio::test]
async fn register_agent_returns_501_pending_manager() {
    let app = build_router(test_state());
    let (status, body) = post_json(
        app,
        "/api/agents/register",
        r#"{"name":"NEW_AGENT","provider_id":"test","model_name":"gpt-4"}"#,
    )
    .await;
    assert_eq!(status, StatusCode::NOT_IMPLEMENTED);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["name"], "NEW_AGENT");
    assert!(json["validated"].as_bool().unwrap());
}

#[tokio::test]
async fn register_agent_rejects_empty_name() {
    let app = build_router(test_state());
    let (status, body) = post_json(
        app,
        "/api/agents/register",
        r#"{"name":"","provider_id":"test","model_name":"gpt-4"}"#,
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(body.contains("1-64 characters"));
}

#[tokio::test]
async fn register_agent_rejects_duplicate() {
    let app = build_router(test_state());
    let (status, _) = post_json(
        app,
        "/api/agents/register",
        r#"{"name":"ALPHA","provider_id":"test","model_name":"gpt-4"}"#,
    )
    .await;
    assert_eq!(status, StatusCode::CONFLICT);
}

#[tokio::test]
async fn replace_agent_updates_config() {
    let state = test_state();
    let app = build_router(state.clone());
    let (status, body) = put_json(
        app,
        "/api/agents/ALPHA/manage",
        r#"{"name":"ALPHA","provider_id":"new_provider","model_name":"new-model","persona":"new persona"}"#,
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["name"], "ALPHA");

    // Verify the config was actually updated
    let config = state.configs.get("ALPHA").unwrap().read().await;
    assert_eq!(config.provider_id, "new_provider");
    assert_eq!(config.model_name, "new-model");
}

#[tokio::test]
async fn replace_agent_404_for_unknown() {
    let app = build_router(test_state());
    let (status, _) = put_json(
        app,
        "/api/agents/NONEXISTENT/manage",
        r#"{"name":"NONEXISTENT","provider_id":"p","model_name":"m"}"#,
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn patch_agent_partial_update() {
    let state = test_state();
    let app = build_router(state.clone());
    let (status, _) = patch_json(
        app,
        "/api/agents/ALPHA/manage",
        r#"{"persona":"updated persona","capability_tags":["legal","audit"]}"#,
    )
    .await;
    assert_eq!(status, StatusCode::OK);

    // Verify only the patched fields changed
    let config = state.configs.get("ALPHA").unwrap().read().await;
    assert_eq!(config.persona.as_deref(), Some("updated persona"));
    assert_eq!(config.capability_tags, vec!["legal", "audit"]);
    // Original fields should be unchanged
    assert_eq!(config.provider_id, "together_ai");
    assert_eq!(config.model_name, "MiniMax-M2.5");
}

#[tokio::test]
async fn patch_agent_404_for_unknown() {
    let app = build_router(test_state());
    let (status, _) = patch_json(app, "/api/agents/GHOST/manage", r#"{"persona":"nope"}"#).await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn delete_agent_returns_501() {
    let state = test_state();
    assert!(state.configs.contains_key("BETA"));
    let app = build_router(state.clone());
    let (status, body) = delete_request(app, "/api/agents/BETA/manage").await;
    assert_eq!(status, StatusCode::NOT_IMPLEMENTED);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(json["id"], "BETA");
    assert!(json["validated"].as_bool().unwrap());
}

#[tokio::test]
async fn delete_agent_404_for_unknown() {
    let app = build_router(test_state());
    let (status, _) = delete_request(app, "/api/agents/GHOST/manage").await;
    assert_eq!(status, StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn bulk_register_validates_and_returns_501() {
    let app = build_router(test_state());
    let (status, body) = post_json(
        app,
        "/api/agents/bulk",
        r#"{"agents":[
            {"name":"BULK_A","provider_id":"p","model_name":"m"},
            {"name":"BULK_B","provider_id":"p","model_name":"m"}
        ]}"#,
    )
    .await;
    assert_eq!(status, StatusCode::NOT_IMPLEMENTED);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    let validated = json["validated"].as_array().unwrap();
    assert_eq!(validated.len(), 2);
}

#[tokio::test]
async fn bulk_register_reports_duplicates() {
    let app = build_router(test_state());
    let (status, body) = post_json(
        app,
        "/api/agents/bulk",
        r#"{"agents":[
            {"name":"ALPHA","provider_id":"p","model_name":"m"},
            {"name":"NEW_ONE","provider_id":"p","model_name":"m"}
        ]}"#,
    )
    .await;
    assert_eq!(status, StatusCode::NOT_IMPLEMENTED);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    let errors = json["validation_errors"].as_array().unwrap();
    assert_eq!(errors.len(), 1); // ALPHA is duplicate
    let validated = json["validated"].as_array().unwrap();
    assert_eq!(validated.len(), 1); // NEW_ONE validated
}

#[tokio::test]
async fn bulk_register_rejects_in_request_duplicates() {
    let app = build_router(test_state());
    let (status, body) = post_json(
        app,
        "/api/agents/bulk",
        r#"{"agents":[
            {"name":"DUP","provider_id":"p","model_name":"m"},
            {"name":"DUP","provider_id":"p","model_name":"m"}
        ]}"#,
    )
    .await;
    assert_eq!(status, StatusCode::NOT_IMPLEMENTED);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    let errors = json["validation_errors"].as_array().unwrap();
    assert!(
        errors
            .iter()
            .any(|e| e.as_str().unwrap().contains("duplicate"))
    );
}

#[tokio::test]
async fn register_rejects_nats_unsafe_name() {
    let app = build_router(test_state());
    let (status, _) = post_json(
        app,
        "/api/agents/register",
        r#"{"name":"bad.name","provider_id":"p","model_name":"m"}"#,
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
}

#[tokio::test]
async fn list_agents_includes_all() {
    let app = build_router(test_state());
    let (status, body) = get_request(app, "/api/agents").await;
    assert_eq!(status, StatusCode::OK);
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
    let agents = json.as_array().unwrap();
    // test_state has ALPHA and BETA
    assert!(agents.len() >= 2);
}

#[test]
fn resolve_dashboard_bind_falls_back_to_loopback_on_none() {
    assert_eq!(
        super::resolve_dashboard_bind(None),
        std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)
    );
}

#[test]
fn resolve_dashboard_bind_parses_lan_address() {
    assert_eq!(
        super::resolve_dashboard_bind(Some("0.0.0.0")),
        std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED)
    );
}

#[test]
fn resolve_dashboard_bind_parses_specific_iface() {
    assert_eq!(
        super::resolve_dashboard_bind(Some("192.168.1.42")),
        std::net::IpAddr::V4(std::net::Ipv4Addr::new(192, 168, 1, 42))
    );
}

/// Malformed env-var input must NOT panic — silent fallback to
/// loopback so a typo doesn't take the dashboard offline (operator
/// will see the loopback bind in the info-log + correct from there).
#[test]
fn resolve_dashboard_bind_falls_back_on_garbage() {
    assert_eq!(
        super::resolve_dashboard_bind(Some("not-an-ip")),
        std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)
    );
}