meerkat-mobkit 0.8.34

Companion orchestration platform for the Meerkat multi-agent runtime
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
//! Operator verbs for oversized/wedged member transcripts.
//!
//! Two verbs, one incident class (HomeCore parent-1: a member transcript
//! grows past what a turn can carry and the only prior remedy was row
//! surgery):
//!
//! - `mobkit/compact_member` — the routine verb. Arms a temporary
//!   auto-compaction floor for the identity (bridge-applied via the typed
//!   `override_profile.auto_compact_threshold` carrier), rebuilds the member
//!   onto its SAME durable session (retire to roster absence, then
//!   re-materialize — identity respawn only re-fences authority and never
//!   rebuilds the agent) so a fresh build picks the floor up, drives one
//!   queued maintenance turn so the forced compaction fires at that turn's
//!   pre-LLM boundary, then disarms the floor and rebuilds again so the live
//!   build returns to the original profile value. Leaving the floor armed
//!   would compact every turn — the meerkat override is deliberately
//!   non-durable across recovery, so the profile is what re-supplies it on
//!   every build.
//!
//! - `mobkit/bound_member_transcript` — the surgical escape hatch. Commits
//!   one audited keep-last-N rewrite through meerkat's
//!   `SessionServiceTranscriptEditExt` on the CONCRETE persistent session
//!   service (the erased `dyn MobSessionService` cannot reach the extension
//!   trait — no trait upcasting), with a pair-safe cut point that never
//!   separates an assistant tool-use message from its adjacent tool_results.
//!   The service refuses live/running sessions with `SessionError::Busy`
//!   (`TranscriptEditRunningBehavior` has only `Reject`); that surfaces as
//!   this verb's typed refusal — quiesce the member first (retire/park), then
//!   retry.
//!
//! Both verbs resolve their target through the same identity-control gate the
//! neighboring destructive verbs (`mobkit/respawn`, `mobkit/reset`,
//! `mobkit/retire`) use, so identities the gateway does not own are refused
//! at resolution.

use super::*;
use crate::identity_first::AgentIdentity;
use meerkat_core::SessionError;
use meerkat_core::types::{Message, SystemNoticeKind, SystemNoticeMessage};
use std::num::NonZeroU64;

/// Typed refusal: the target session is live/running and transcript surgery
/// only supports `Reject` while work is active. Distinct from the SDKs'
/// reserved `-32004` capability code and the identity-plane `-32001..-32005`
/// band.
pub const OPERATOR_SESSION_BUSY_CODE: i64 = -32015;

/// The verb exists on this gateway build but its wiring is absent (no
/// compaction-floor registry / no concrete transcript-edit service threaded
/// into the RPC context).
pub const OPERATOR_VERB_UNAVAILABLE_CODE: i64 = -32016;

/// Default temporary floor: small enough that any oversized transcript is
/// past it, large enough to be a legal non-zero threshold.
const DEFAULT_COMPACT_FLOOR_TOKENS: u64 = 1024;

/// Default budget for the forced-compaction maintenance turn.
const DEFAULT_COMPACT_TIMEOUT_MS: u64 = 60_000;

/// Secondary observation budget after the caller's deadline. Expiry reports
/// pending ownership; it does not cancel the exact-input observer or its cleanup.
const COMPACT_TIMEOUT_EVIDENCE_BUDGET: Duration = Duration::from_secs(5);

/// Default keep-last-N for `bound_member_transcript`.
const DEFAULT_BOUND_KEEP_LAST: usize = 50;

fn rpc_error(response_id: Value, code: i64, message: String) -> JsonRpcResponse {
    JsonRpcResponse {
        jsonrpc: JSONRPC_VERSION.to_string(),
        id: response_id,
        result: None,
        error: Some(JsonRpcError {
            code,
            message,
            data: None,
        }),
    }
}

fn rpc_result(response_id: Value, result: Value) -> JsonRpcResponse {
    JsonRpcResponse {
        jsonrpc: JSONRPC_VERSION.to_string(),
        id: response_id,
        result: Some(result),
        error: None,
    }
}

fn optional_u64_param(params: &Value, field: &str) -> Result<Option<u64>, String> {
    match params.get(field) {
        None | Some(Value::Null) => Ok(None),
        Some(value) => match value.as_u64() {
            Some(parsed) if parsed > 0 => Ok(Some(parsed)),
            _ => Err(format!("{field} must be a positive integer")),
        },
    }
}

/// The largest prefix length that can be cut while keeping at least
/// `keep_last` trailing messages without orphaning a tool pair.
///
/// The transcript shape rule (meerkat-core `validate_transcript_tool_result_shape`)
/// makes tool pairs ADJACENT: every `ToolResults` is immediately preceded by
/// the assistant tool-use message carrying exactly its tool_use_id set, and
/// vice versa. A cut point is therefore pair-safe iff the first KEPT message
/// is not a `ToolResults`; walking the cut back one message re-includes the
/// paired assistant message. In a shape-valid transcript one step suffices
/// (two adjacent `ToolResults` are impossible); the loop is defensive.
pub(crate) fn pair_safe_cut_index(messages: &[Message], keep_last: usize) -> usize {
    let mut cut = messages.len().saturating_sub(keep_last);
    while cut > 0 && matches!(messages.get(cut), Some(Message::ToolResults { .. })) {
        cut -= 1;
    }
    cut
}

struct ResolvedOperatorTarget {
    identity: AgentIdentity,
    /// Alias-pinned lifecycle precondition, mirroring `mobkit/respawn`:
    /// present only when the caller addressed the member by its reserved
    /// generated runtime alias.
    expected_alias: Option<String>,
}

/// Shared target resolution + authorization for both operator verbs: the
/// exact identity-control gate the destructive identity verbs use, including
/// the stale-live-alias refusal.
async fn resolve_operator_target(
    runtime: &UnifiedRuntime,
    identity_rt: &crate::identity_first::IdentityRuntime,
    params: &Value,
    response_id: &Value,
) -> Result<ResolvedOperatorTarget, Box<JsonRpcResponse>> {
    let identity_str = params
        .get("identity")
        .and_then(|v| v.as_str())
        .unwrap_or("");
    let target = match resolve_rpc_identity_control_target(runtime, identity_rt, identity_str).await
    {
        Ok(target) => target,
        Err(e) => {
            return Err(Box::new(rpc_error(
                response_id.clone(),
                -32602,
                format!("invalid identity: {e}"),
            )));
        }
    };
    if let Some(response) =
        rpc_stale_live_alias_error_response(identity_rt, &target, response_id.clone()).await
    {
        return Err(Box::new(response));
    }
    let expected_alias = crate::member_comms_id::is_reserved_generated_alias(identity_str)
        .then(|| identity_str.to_string());
    Ok(ResolvedOperatorTarget {
        identity: target.identity,
        expected_alias,
    })
}

/// Transcript facts read through the concrete session service: message count
/// plus the head revision and the most recent rewrite commit reason.
async fn read_transcript_facts(
    service: &Arc<dyn crate::memory::hygienist::TranscriptEditSessionService>,
    session_id: &meerkat_core::types::SessionId,
) -> Result<(usize, Option<String>, Option<String>), SessionError> {
    let page = service
        .read_history(
            session_id,
            meerkat_core::service::SessionHistoryQuery {
                offset: 0,
                limit: None,
            },
        )
        .await?;
    let (head_revision, last_reason) = match service
        .list_transcript_revisions(
            session_id,
            meerkat_core::service::SessionTranscriptRevisionListQuery {
                limit: None,
                offset: None,
            },
        )
        .await
    {
        Ok(list) => (
            Some(list.head_revision),
            list.entries.last().map(|entry| entry.reason.clone()),
        ),
        Err(SessionError::Unsupported(_)) => (None, None),
        Err(err) => return Err(err),
    };
    Ok((page.messages.len(), head_revision, last_reason))
}

/// `mobkit/compact_member`: force one compaction on a member's next turn via
/// a temporary profile-level threshold floor, then restore the original
/// threshold.
pub(super) async fn handle_compact_member(
    runtime: &UnifiedRuntime,
    ctx: &IdentityFirstContext,
    params: &Value,
    response_id: Value,
) -> JsonRpcResponse {
    let identity_rt = &ctx.runtime;
    let Some(floors) = ctx.compaction_floors.as_ref() else {
        return rpc_error(
            response_id,
            OPERATOR_VERB_UNAVAILABLE_CODE,
            "compact_member is not wired on this gateway: the identity bridge's compaction-floor \
             registry was not threaded into the RPC context"
                .to_string(),
        );
    };
    let floor_tokens = match optional_u64_param(params, "floor_tokens") {
        Ok(value) => value.unwrap_or(DEFAULT_COMPACT_FLOOR_TOKENS),
        Err(message) => return rpc_error(response_id, -32602, message),
    };
    let Some(floor) = NonZeroU64::new(floor_tokens) else {
        return rpc_error(
            response_id,
            -32602,
            "floor_tokens must be greater than 0".to_string(),
        );
    };
    let timeout_ms = match optional_u64_param(params, "timeout_ms") {
        Ok(value) => value.unwrap_or(DEFAULT_COMPACT_TIMEOUT_MS),
        Err(message) => return rpc_error(response_id, -32602, message),
    };
    let target = match resolve_operator_target(runtime, identity_rt, params, &response_id).await {
        Ok(target) => target,
        Err(response) => return *response,
    };
    let Some(observer) = runtime
        .mob_runtime()
        .committed_boundary_recoverer()
        .and_then(|owner| owner.runtime_completion_observer())
    else {
        return rpc_error(
            response_id,
            OPERATOR_VERB_UNAVAILABLE_CODE,
            "compact_member requires the persistent session owner's exact completion observer"
                .to_string(),
        );
    };
    let operation = CompactOperation {
        ctx: ctx.clone(),
        identity: target.identity,
        expected_alias: target.expected_alias,
        observer,
        admission: Arc::new(IdentityCompactionAdmission),
        floors: Arc::clone(floors),
        floor,
        timeout_ms,
        response_id: response_id.clone(),
        operation_id: meerkat_core::SessionId::new().to_string(),
    };
    let (early_tx, mut early_rx) = tokio::sync::oneshot::channel();
    let owned =
        identity_rt.run_tracked_foreground(async move { Ok(operation.run(early_tx).await) });
    tokio::pin!(owned);
    tokio::select! {
        biased;
        Ok(response) = &mut early_rx => response,
        result = &mut owned => match result {
            Ok(response) => response,
            Err(error) => identity_error_response(response_id, &error),
        }
    }
}

#[async_trait::async_trait]
trait CompactCompletionObserver: Send + Sync {
    async fn observe(
        &self,
        session_id: &meerkat_core::SessionId,
        key: &str,
        input_id: &mut Option<meerkat_core::lifecycle::InputId>,
    ) -> Result<Option<meerkat_runtime::CompletionOutcome>, meerkat_runtime::RuntimeDriverError>;
}

#[async_trait::async_trait]
trait CompactAdmission: Send + Sync {
    async fn dispatch(
        &self,
        runtime: &crate::identity_first::IdentityRuntime,
        identity: &AgentIdentity,
        incarnation: &crate::identity_first::runtime::CapturedIncarnation,
        input: &crate::identity_first::DispatchInput,
    ) -> Result<
        crate::identity_first::runtime::DispatchOutcome,
        crate::identity_first::IdentityRuntimeError,
    >;
}

struct IdentityCompactionAdmission;

#[async_trait::async_trait]
impl CompactAdmission for IdentityCompactionAdmission {
    async fn dispatch(
        &self,
        runtime: &crate::identity_first::IdentityRuntime,
        identity: &AgentIdentity,
        incarnation: &crate::identity_first::runtime::CapturedIncarnation,
        input: &crate::identity_first::DispatchInput,
    ) -> Result<
        crate::identity_first::runtime::DispatchOutcome,
        crate::identity_first::IdentityRuntimeError,
    > {
        runtime
            .dispatch_with_expected_incarnation(identity, None, Some(incarnation), input)
            .await
    }
}

fn compaction_admission_is_uncertain(error: &crate::identity_first::IdentityRuntimeError) -> bool {
    use crate::identity_first::{ActorCallObservation, IdentityRuntimeError};
    !matches!(
        error,
        IdentityRuntimeError::AdmissionBacklogFull { .. }
            | IdentityRuntimeError::ReloadRequired { .. }
            | IdentityRuntimeError::NoActiveLease(_)
            | IdentityRuntimeError::InvalidState { .. }
            | IdentityRuntimeError::StaleRuntimeAlias { .. }
            | IdentityRuntimeError::PostAdmissionSuperseded { .. }
            | IdentityRuntimeError::ActorLoopStalled {
                observation: ActorCallObservation::BeforeCall,
                ..
            }
            | IdentityRuntimeError::ActorTerminated {
                observation: ActorCallObservation::BeforeCall,
                ..
            }
    )
}

#[async_trait::async_trait]
impl CompactCompletionObserver for meerkat_runtime::MeerkatMachine {
    async fn observe(
        &self,
        session_id: &meerkat_core::SessionId,
        key: &str,
        input_id: &mut Option<meerkat_core::lifecycle::InputId>,
    ) -> Result<Option<meerkat_runtime::CompletionOutcome>, meerkat_runtime::RuntimeDriverError>
    {
        use meerkat_runtime::SessionServiceRuntimeExt;
        if input_id.is_none() {
            *input_id = self
                .input_state_by_idempotency_key(session_id, key)
                .await?
                .map(|state| state.state.input_id);
        }
        match input_id.as_ref() {
            Some(id) => self.input_terminal_completion(session_id, id).await,
            None => Ok(None),
        }
    }
}

struct CompactOperation {
    ctx: IdentityFirstContext,
    identity: AgentIdentity,
    expected_alias: Option<String>,
    observer: Arc<dyn CompactCompletionObserver>,
    admission: Arc<dyn CompactAdmission>,
    floors: Arc<crate::identity_first::CompactionFloorRegistry>,
    floor: NonZeroU64,
    timeout_ms: u64,
    response_id: Value,
    operation_id: String,
}

impl CompactOperation {
    fn error(&self, kind: &str, stage: &str, detail: impl std::fmt::Display) -> JsonRpcResponse {
        self.error_with_data(kind, stage, detail, serde_json::Map::new())
    }

    fn error_with_data(
        &self,
        kind: &str,
        stage: &str,
        detail: impl std::fmt::Display,
        mut data: serde_json::Map<String, Value>,
    ) -> JsonRpcResponse {
        tracing::warn!(identity = %self.identity, operation_id = %self.operation_id,
            kind, stage, %detail, "compaction operation did not report completed restoration");
        data.insert("kind".to_string(), serde_json::json!(kind));
        data.insert("stage".to_string(), serde_json::json!(stage));
        data.insert(
            "operation_id".to_string(),
            serde_json::json!(self.operation_id),
        );
        data.insert(
            "identity".to_string(),
            serde_json::json!(self.identity.as_str()),
        );
        JsonRpcResponse {
            jsonrpc: JSONRPC_VERSION.to_string(),
            id: self.response_id.clone(),
            result: None,
            error: Some(JsonRpcError {
                code: -32000,
                message: detail.to_string(),
                data: Some(Value::Object(data)),
            }),
        }
    }

    async fn run(self, early_tx: tokio::sync::oneshot::Sender<JsonRpcResponse>) -> JsonRpcResponse {
        let Ok(_operation_guard) = self.floors.operation_lock(&self.identity).try_lock_owned()
        else {
            return self.error(
                "compact_member_busy",
                "admission",
                "compaction already owns this member",
            );
        };
        if self.floors.get(&self.identity).is_some() {
            return self.error(
                "compact_member_busy",
                "admission",
                "a prior compaction floor remains unsettled",
            );
        }
        let runtime = &self.ctx.runtime;
        let initial = match runtime.capture_incarnation(&self.identity).await {
            Ok(initial) => initial,
            Err(error) => return identity_error_response(self.response_id.clone(), &error),
        };
        let before_session = match runtime.status(&self.identity).await {
            Ok(status) => match status.session_id {
                Some(session) => session,
                None => {
                    return self.error(
                        "compact_member_refused",
                        "before",
                        "member has no durable session",
                    );
                }
            },
            Err(error) => return identity_error_response(self.response_id.clone(), &error),
        };
        let before = match self.ctx.transcript_edit_service.as_ref() {
            Some(service) => match tokio::time::timeout(
                COMPACT_TIMEOUT_EVIDENCE_BUDGET,
                read_transcript_facts(service, &before_session),
            )
            .await
            {
                Ok(Ok(facts)) => Some(facts),
                Ok(Err(error)) => {
                    return self.error("compact_member_observation_failed", "before", error);
                }
                Err(_) => {
                    return self.error(
                        "compact_member_observation_failed",
                        "before",
                        "preparation transcript read timed out; no floor installed",
                    );
                }
            },
            None => None,
        };
        let (record, incarnation) = match runtime
            .rebuild_compaction_owner(
                &self.identity,
                &initial,
                self.expected_alias.as_deref(),
                crate::identity_first::bridge::CompactionFloorChange {
                    registry: &self.floors,
                    operation_id: &self.operation_id,
                    floor: Some(self.floor),
                },
            )
            .await
        {
            Ok(owner) => owner,
            Err(error) => {
                return self.error("compact_member_rebuild_failed", "floor_install", error);
            }
        };
        let session_id = record.session_id;
        let key = format!("mobkit-compact:{}", self.operation_id);
        let input = crate::identity_first::DispatchInput::system(
            "[mobkit-gateway operator verb compact_member] Maintenance turn: transcript compaction \
             was forced for this turn. Reply with a brief acknowledgement only.",
        )
        .with_idempotency(&key)
        .with_correlation(&self.operation_id);
        let mut early_tx = Some(early_tx);
        let mut had_observation_failure = false;
        let observed_incarnation = match self
            .admission
            .dispatch(runtime, &self.identity, &incarnation, &input)
            .await
        {
            Ok(admission) if admission.session_id.as_ref() == Some(&session_id) => {
                admission.incarnation
            }
            Ok(_) => {
                runtime
                    .invalidate_superseded_compaction_floor(
                        &self.identity,
                        &incarnation,
                        &self.floors,
                        &self.operation_id,
                    )
                    .await;
                return self.error(
                    "compact_member_superseded",
                    "dispatch",
                    "maintenance session changed",
                );
            }
            Err(error) if compaction_admission_is_uncertain(&error) => {
                had_observation_failure = true;
                let mut data = serde_json::Map::new();
                if let Some(observation) = error.structured_data() {
                    data.insert("admission_observation".to_string(), observation);
                }
                if let Some(sender) = early_tx.take() {
                    let response = self.error_with_data(
                        "compact_member_admission_pending", "admission_pending",
                        format!("maintenance admission outcome is unknown: {error}; original key and cleanup ownership retained without resubmission"),
                        data,
                    );
                    let _ = sender.send(response);
                }
                incarnation
            }
            Err(error) => {
                self.floors.clear_owned(&self.identity, &self.operation_id);
                return self.error("compact_member_admission_failed", "dispatch", error);
            }
        };
        let deadline = tokio::time::Instant::now() + Duration::from_millis(self.timeout_ms);
        let secondary_deadline = deadline + COMPACT_TIMEOUT_EVIDENCE_BUDGET;
        let mut timed_out = false;
        let mut input_id = None;
        let outcome = loop {
            if !matches!(
                runtime.capture_incarnation(&self.identity).await,
                Ok(current) if current == observed_incarnation
            ) {
                runtime
                    .invalidate_superseded_compaction_floor(
                        &self.identity,
                        &observed_incarnation,
                        &self.floors,
                        &self.operation_id,
                    )
                    .await;
                return self.error(
                    "compact_member_superseded",
                    "terminal",
                    "maintenance incarnation changed; no rebuild attempted",
                );
            }
            let now = tokio::time::Instant::now();
            timed_out |= now >= deadline;
            if now >= secondary_deadline
                && let Some(sender) = early_tx.take()
            {
                let response = self.error(
                    "compact_member_timeout", "terminal_pending",
                    format!("compact_member maintenance turn did not complete within {}ms; exact terminal is pending/unknown; runtime retains completion and profile-cleanup ownership, no retire or rebuild attempted", self.timeout_ms),
                );
                let _ = sender.send(response);
            }
            let observation = self.observer.observe(&session_id, &key, &mut input_id);
            match tokio::time::timeout(COMPACT_TIMEOUT_EVIDENCE_BUDGET, observation).await {
                Ok(Ok(Some(outcome))) => {
                    timed_out |= tokio::time::Instant::now() >= deadline;
                    break outcome;
                }
                Ok(Ok(None)) => {}
                Ok(Err(error)) => {
                    had_observation_failure = true;
                    tracing::warn!(identity = %self.identity, operation_id = %self.operation_id,
                        %error, "exact compaction terminal read failed; ownership retained");
                    if let Some(sender) = early_tx.take() {
                        let response = self.error(
                            "compact_member_observation_failed", "terminal_pending",
                            format!("exact compaction terminal is unknown after read failure: {error}; runtime retains completion and profile-cleanup ownership, no retire or rebuild attempted"),
                        );
                        let _ = sender.send(response);
                    }
                    tokio::time::sleep(Duration::from_secs(1)).await;
                }
                Err(_) => {
                    tracing::warn!(identity = %self.identity, operation_id = %self.operation_id,
                        "exact compaction terminal read timed out; ownership retained");
                }
            }
            tokio::time::sleep(Duration::from_millis(20)).await;
        };
        let failure_metadata = match &outcome {
            meerkat_runtime::CompletionOutcome::Abandoned { error, .. }
            | meerkat_runtime::CompletionOutcome::AbandonedWithError { error, .. }
            | meerkat_runtime::CompletionOutcome::CompletedWithFinalizationFailure { error }
            | meerkat_runtime::CompletionOutcome::RuntimeTerminated { error, .. } => {
                Some(serde_json::json!(error))
            }
            _ => None,
        };
        let terminal_error = match outcome {
            meerkat_runtime::CompletionOutcome::Completed(result)
                if result.session_id == session_id =>
            {
                None
            }
            meerkat_runtime::CompletionOutcome::Completed(_) => Some("wrong_session"),
            meerkat_runtime::CompletionOutcome::CompletedWithoutResult => {
                Some("completed_without_result")
            }
            meerkat_runtime::CompletionOutcome::CallbackPending { .. } => Some("callback_pending"),
            meerkat_runtime::CompletionOutcome::CallbackBatchPending { .. } => {
                Some("callback_batch_pending")
            }
            meerkat_runtime::CompletionOutcome::Cancelled => Some("cancelled"),
            meerkat_runtime::CompletionOutcome::Abandoned { .. } => Some("abandoned"),
            meerkat_runtime::CompletionOutcome::AbandonedWithError { .. } => {
                Some("abandoned_with_error")
            }
            meerkat_runtime::CompletionOutcome::CompletedWithFinalizationFailure { .. } => {
                Some("completed_with_finalization_failure")
            }
            meerkat_runtime::CompletionOutcome::RuntimeTerminated { .. } => {
                Some("runtime_terminated")
            }
        };
        if let Some(class) = terminal_error {
            let deadline_detail = if timed_out {
                format!(
                    "maintenance turn did not complete within {}ms; ",
                    self.timeout_ms
                )
            } else {
                String::new()
            };
            let mut data = serde_json::Map::new();
            data.insert("completion_type".to_string(), serde_json::json!(class));
            data.insert(
                "observation_timed_out".to_string(),
                serde_json::json!(timed_out),
            );
            if let Some(error) = failure_metadata {
                data.insert("error".to_string(), error);
            }
            return self.error_with_data("compact_member_completion_failed", "terminal", format!(
                "compact_member {deadline_detail}exact input ended as {class}; profile restoration was not authorized"
            ), data);
        }
        if let Err(error) = runtime
            .rebuild_compaction_owner(
                &self.identity,
                &observed_incarnation,
                None,
                crate::identity_first::bridge::CompactionFloorChange {
                    registry: &self.floors,
                    operation_id: &self.operation_id,
                    floor: None,
                },
            )
            .await
        {
            runtime
                .invalidate_superseded_compaction_floor(
                    &self.identity,
                    &observed_incarnation,
                    &self.floors,
                    &self.operation_id,
                )
                .await;
            return self.error("compact_member_rebuild_failed", "profile_restore", error);
        }
        if timed_out {
            return self.error(
                "compact_member_timeout", "profile_restored",
                format!("compact_member maintenance turn did not complete within {}ms; the exact maintenance input completed after the observation deadline; member rebuilt at its original threshold", self.timeout_ms),
            );
        }
        if had_observation_failure {
            return self.error(
                "compact_member_observation_failed", "profile_restored",
                "maintenance observation failed before exact completion; the original input later completed and its profile was restored",
            );
        }
        let after = match self.ctx.transcript_edit_service.as_ref() {
            Some(service) => match read_transcript_facts(service, &session_id).await {
                Ok(facts) => Some(facts),
                Err(error) => {
                    return self.error("compact_member_observation_failed", "after", error);
                }
            },
            None => None,
        };
        let messages_before = before.as_ref().map(|(count, _, _)| *count);
        let messages_after = after.as_ref().map(|(count, _, _)| *count);
        rpc_result(
            self.response_id,
            serde_json::json!({
                "identity": self.identity.as_str(),
                "session_id": session_id.to_string(),
                "floor_tokens": self.floor.get(),
                "messages_before": messages_before,
                "messages_after": messages_after,
                "compaction_applied": messages_before.zip(messages_after).map(|(before, after)| after < before),
                "head_revision": after.as_ref().and_then(|(_, head, _)| head.clone()),
                "last_rewrite_reason": after.as_ref().and_then(|(_, _, reason)| reason.clone()),
            }),
        )
    }
}

/// Tear the identity's live member down and re-materialize it onto the SAME
/// durable session, forcing a fresh agent build.
///
/// This is the quiesce-and-rebuild cycle `compact_member` rides: identity
/// respawn (`respawn_identity_in_place_tracked`) only re-fences authority and
/// leaves the live agent's build untouched, so a build-time input like the
/// armed compaction floor never reaches it. Retire tears the member down to
/// roster absence with the durable session preserved; `restore_flow` then
/// re-registers the identity from its current spec and resumes the SAME
/// session through the bridge's spawn-spec build (where the floor applies).
///
/// A Dormant/never-materialized identity skips the retire and goes straight
/// to materialization. Deliberately NOT `restore_flow`: that is fleet-scoped
/// (it overwrites the runtime's desired peer edges from the roster it is
/// handed), while this verb must touch exactly one identity. Fails typed when
/// the durable continuity binding needed for a same-session resume is
/// incomplete - materializing a fresh session would abandon the transcript
/// this verb exists to compact.
#[cfg(test)]
async fn rebuild_member_for_fresh_build(
    ctx: &IdentityFirstContext,
    identity: &AgentIdentity,
    expected_alias: Option<&str>,
    spec: crate::identity_first::DurableAgentSpec,
) -> Result<meerkat_core::types::SessionId, String> {
    use crate::identity_first::IdentityLifecycleState;
    let identity_rt = &ctx.runtime;
    let state = identity_rt
        .status(identity)
        .await
        .map_err(|err| format!("status before rebuild: {err}"))?
        .state;
    if state == IdentityLifecycleState::Active {
        match expected_alias {
            Some(alias) => identity_rt
                .retire_member_alias_tracked(identity, alias)
                .await
                .map(|_| ()),
            None => identity_rt.retire_tracked(identity).await.map(|_| ()),
        }
        .map_err(|err| format!("quiesce retire: {err}"))?;
    }
    // Reproject the entry as Dormant with the DURABLE continuity binding so
    // `materialize` (which refuses Retiring) resumes the SAME durable
    // session. The store record is read after the retire because retire runs
    // a final checkpoint - the stored row carries the freshest checkpoint
    // version.
    let resolved = identity_rt
        .continuity_store()
        .resolve_many(std::slice::from_ref(identity))
        .await
        .map_err(|err| format!("continuity resolve after quiesce: {err}"))?;
    let record = match resolved.get(identity) {
        Some(crate::identity_first::ContinuityResolveState::Ready { record }) => record.clone(),
        Some(crate::identity_first::ContinuityResolveState::Broken { failure }) => {
            return Err(format!(
                "identity {} has broken continuity ({}); cannot rebuild onto the same durable \
                 session",
                identity.as_str(),
                failure.detail
            ));
        }
        Some(crate::identity_first::ContinuityResolveState::Uninitialized) | None => {
            return Err(format!(
                "identity {} has no durable continuity record; cannot rebuild onto the same \
                 durable session",
                identity.as_str()
            ));
        }
    };
    identity_rt
        .register(spec, IdentityLifecycleState::Dormant, Some(record), None)
        .await;
    identity_rt
        .materialize_tracked(identity)
        .await
        .map(|record| record.session_id)
        .map_err(|err| format!("re-materialization: {err}"))
}

/// `mobkit/bound_member_transcript`: one audited keep-last-N transcript
/// rewrite on a quiesced member session.
pub(super) async fn handle_bound_member_transcript(
    runtime: &UnifiedRuntime,
    ctx: &IdentityFirstContext,
    params: &Value,
    response_id: Value,
) -> JsonRpcResponse {
    let identity_rt = &ctx.runtime;
    let Some(service) = ctx.transcript_edit_service.as_ref() else {
        return rpc_error(
            response_id,
            OPERATOR_VERB_UNAVAILABLE_CODE,
            "bound_member_transcript is not wired on this gateway: the concrete persistent \
             session service was not threaded into the RPC context (the erased MobSessionService \
             cannot reach SessionServiceTranscriptEditExt)"
                .to_string(),
        );
    };
    let keep_last = match optional_u64_param(params, "keep_last") {
        Ok(value) => value.map_or(DEFAULT_BOUND_KEEP_LAST, |parsed| parsed as usize),
        Err(message) => return rpc_error(response_id, -32602, message),
    };
    let note = match params.get("note") {
        None | Some(Value::Null) => None,
        Some(Value::String(note)) => Some(note.clone()),
        Some(_) => {
            return rpc_error(
                response_id,
                -32602,
                "note must be a string when provided".to_string(),
            );
        }
    };
    let target = match resolve_operator_target(runtime, identity_rt, params, &response_id).await {
        Ok(target) => target,
        Err(response) => return *response,
    };
    let identity = target.identity;

    let status = match identity_rt.status(&identity).await {
        Ok(status) => status,
        Err(err) => return identity_error_response(response_id, &err),
    };
    let Some(session_id) = status.session_id else {
        return rpc_error(
            response_id,
            -32000,
            format!(
                "identity {} has no current session to bound",
                identity.as_str()
            ),
        );
    };

    let messages = match service
        .read_history(
            &session_id,
            meerkat_core::service::SessionHistoryQuery {
                offset: 0,
                limit: None,
            },
        )
        .await
    {
        Ok(page) => page.messages,
        Err(err) => {
            return rpc_error(
                response_id,
                -32000,
                format!("bound_member_transcript failed to read the transcript: {err}"),
            );
        }
    };
    // Fresh head for the compare-and-swap: the rewrite is rejected if the
    // head advances between this read and the commit.
    let expected_parent_revision = match service
        .list_transcript_revisions(
            &session_id,
            meerkat_core::service::SessionTranscriptRevisionListQuery {
                limit: Some(0),
                offset: None,
            },
        )
        .await
    {
        Ok(list) => Some(list.head_revision),
        Err(SessionError::Unsupported(_)) => None,
        Err(err) => {
            return rpc_error(
                response_id,
                -32000,
                format!("bound_member_transcript failed to read the head revision: {err}"),
            );
        }
    };

    let cut = pair_safe_cut_index(&messages, keep_last);
    if cut == 0 {
        return rpc_result(
            response_id,
            serde_json::json!({
                "identity": identity.as_str(),
                "session_id": session_id.to_string(),
                "bounded": false,
                "removed": 0,
                "message_count": messages.len(),
            }),
        );
    }

    let marker = Message::SystemNotice(SystemNoticeMessage::new(
        SystemNoticeKind::Generic,
        format!(
            "[operator] transcript bounded: {cut} earlier message(s) were removed by \
             bound_member_transcript; the conversation continues from the {} most recent \
             message(s).",
            messages.len() - cut
        ),
    ));
    let mut reason = meerkat_core::TranscriptRewriteReason::new("operator_bound_transcript");
    reason.note = Some(note.unwrap_or_else(|| {
        format!("mobkit-gateway operator verb bound_member_transcript keep_last={keep_last}")
    }));
    let request = meerkat_core::service::SessionTranscriptRewriteRequest {
        selection: meerkat_core::TranscriptRewriteSelection::MessageRange { start: 0, end: cut },
        replacement: vec![marker],
        reason,
        actor: Some("mobkit-gateway operator verb".to_string()),
        expected_parent_revision,
        running_behavior: meerkat_core::TranscriptEditRunningBehavior::default(),
    };
    match service
        .rewrite_session_transcript(&session_id, request)
        .await
    {
        Ok(result) => rpc_result(
            response_id,
            serde_json::json!({
                "identity": identity.as_str(),
                "session_id": result.session_id.to_string(),
                "bounded": true,
                "removed": cut,
                "kept": messages.len() - cut,
                "message_count": result.message_count,
                "parent_revision": result.parent_revision,
                "revision": result.revision,
            }),
        ),
        Err(SessionError::Busy { id }) => rpc_error(
            response_id,
            OPERATOR_SESSION_BUSY_CODE,
            format!(
                "session {id} is live/running; transcript surgery only supports Reject while \
                 work is active - quiesce the member first (retire or park it), then retry"
            ),
        ),
        Err(err) => rpc_error(
            response_id,
            -32000,
            format!("bound_member_transcript rewrite failed: {err}"),
        ),
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use super::*;
    use meerkat_core::types::{AssistantBlock, BlockAssistantMessage, ToolResult, UserMessage};

    fn user(text: &str) -> Message {
        Message::User(UserMessage::text(text))
    }

    fn tool_use_pair(id: &str) -> (Message, Message) {
        let assistant = Message::BlockAssistant(BlockAssistantMessage::new(
            vec![AssistantBlock::ToolUse {
                id: id.to_string(),
                name: "probe".to_string(),
                args: serde_json::value::RawValue::from_string("{}".to_string()).expect("raw args"),
                meta: None,
            }],
            meerkat_core::types::StopReason::ToolUse,
        ));
        let results = Message::tool_results(vec![ToolResult {
            tool_use_id: id.to_string(),
            content: vec![],
            is_error: false,
        }]);
        (assistant, results)
    }

    #[test]
    fn cut_keeps_whole_transcript_when_keep_last_covers_it() {
        let messages = vec![user("a"), user("b")];
        assert_eq!(pair_safe_cut_index(&messages, 2), 0);
        assert_eq!(pair_safe_cut_index(&messages, 10), 0);
    }

    #[test]
    fn cut_lands_on_plain_message_boundary() {
        let messages = vec![user("a"), user("b"), user("c"), user("d")];
        assert_eq!(pair_safe_cut_index(&messages, 2), 2);
    }

    /// The naive cut would land ON the tool_results (index 2), orphaning it
    /// from its assistant tool-use message at index 1. The pair-safe cut must
    /// walk back to include the whole pair.
    #[test]
    fn cut_never_orphans_tool_results_from_their_assistant_message() {
        let (assistant, results) = tool_use_pair("call-1");
        let messages = vec![user("a"), assistant, results, user("tail")];
        assert_eq!(pair_safe_cut_index(&messages, 2), 1);
    }

    #[test]
    fn cut_after_tool_pair_is_untouched() {
        let (assistant, results) = tool_use_pair("call-1");
        let messages = vec![user("a"), assistant, results, user("tail")];
        // keep_last = 1 cuts [0, 3): the pair is entirely inside the cut.
        assert_eq!(pair_safe_cut_index(&messages, 1), 3);
    }

    #[test]
    fn cut_walks_back_to_zero_when_transcript_leads_with_pairs() {
        let (assistant, results) = tool_use_pair("call-1");
        let messages = vec![assistant, results, user("tail")];
        // Naive cut = 1 lands on the results; walking back reaches 0.
        assert_eq!(pair_safe_cut_index(&messages, 2), 0);
    }

    use crate::identity_first::{
        AgentAddressability, ContinuityGeneration, ContinuityRecord, ContinuityStore,
        DurabilityPolicy, DurableAgentSpec, IdentityLifecycleState, IdentityRuntime,
        IdentityRuntimeConfig, LeaseAcquireResult, LeaseProvider, LocalContinuityStore,
        LocalLeaseProvider, MobSessionBridge, RosterContext, RosterError, RosterProvider,
    };
    use async_trait::async_trait;
    use std::sync::atomic::{AtomicBool, Ordering};

    fn worker_spec(identity: &AgentIdentity) -> DurableAgentSpec {
        DurableAgentSpec {
            identity: identity.clone(),
            profile: meerkat_mob::ProfileName::from("worker"),
            addressability: AgentAddressability::Addressable,
            display_name: None,
            labels: std::collections::BTreeMap::new(),
            context: None,
            additional_instructions: Vec::new(),
            initial_message: None,
            runtime_mode_override: None,
            backend: None,
            binding: None,
            placement: None,
        }
    }

    struct EmptyRoster;

    #[async_trait]
    impl RosterProvider for EmptyRoster {
        async fn roster(
            &self,
            _context: &RosterContext,
        ) -> Result<Vec<DurableAgentSpec>, RosterError> {
            Ok(Vec::new())
        }
    }

    /// Scripted LLM double reporting REAL input-token usage (zero usage
    /// silently disarms the compaction input trigger) with an optional gate
    /// that holds a turn in flight so the Busy refusal is deterministic.
    struct GatedUsageLlmClient {
        input_tokens: u64,
        gate_armed: Arc<AtomicBool>,
        in_call: Arc<AtomicBool>,
        release: Arc<tokio::sync::Notify>,
        maintenance_only: Arc<AtomicBool>,
        fail_maintenance: Arc<AtomicBool>,
    }

    impl meerkat_client::LlmClient for GatedUsageLlmClient {
        fn project_replay_messages(
            &self,
            messages: &[meerkat_core::Message],
        ) -> Result<Vec<meerkat_core::Message>, meerkat_client::LlmError> {
            Ok(messages.to_vec())
        }
        fn stream<'a>(
            &'a self,
            request: &'a meerkat_client::LlmRequest,
        ) -> std::pin::Pin<
            Box<
                dyn futures::Stream<
                        Item = Result<meerkat_client::LlmEvent, meerkat_client::LlmError>,
                    > + Send
                    + 'a,
            >,
        > {
            use futures::StreamExt;
            let maintenance = serde_json::to_string(&request.messages)
                .expect("test request")
                .contains("[mobkit-gateway operator verb compact_member]");
            let gate_armed = self.gate_armed.load(Ordering::SeqCst)
                && (!self.maintenance_only.load(Ordering::SeqCst) || maintenance);
            let fail = maintenance && self.fail_maintenance.load(Ordering::SeqCst);
            let in_call = Arc::clone(&self.in_call);
            let release = Arc::clone(&self.release);
            let input_tokens = self.input_tokens;
            Box::pin(
                futures::stream::once(async move {
                    if gate_armed {
                        in_call.store(true, Ordering::SeqCst);
                        release.notified().await;
                    }
                    in_call.store(false, Ordering::SeqCst);
                    if fail {
                        return futures::stream::iter(vec![Err(
                            meerkat_client::LlmError::InvalidRequest {
                                message: "injected terminal maintenance failure".to_string(),
                            },
                        )]);
                    }
                    let [usage, done] =
                        crate::mob_handle_runtime::test_llm_usage::usage_then_done_with(
                            request,
                            meerkat_core::Provider::OpenAI,
                            meerkat_core::types::Usage {
                                input_tokens,
                                ..Default::default()
                            },
                            meerkat_core::types::StopReason::EndTurn,
                        );
                    futures::stream::iter(vec![
                        Ok(meerkat_client::LlmEvent::TextDelta {
                            delta: "ack".to_string(),
                            meta: None,
                        }),
                        Ok(usage),
                        Ok(done),
                    ])
                })
                .flatten(),
            )
        }
        fn provider(&self) -> meerkat_core::Provider {
            meerkat_core::Provider::OpenAI
        }
        fn health_check<'life0, 'async_trait>(
            &'life0 self,
        ) -> std::pin::Pin<
            Box<
                dyn std::future::Future<Output = Result<(), meerkat_client::LlmError>>
                    + Send
                    + 'async_trait,
            >,
        >
        where
            'life0: 'async_trait,
            Self: 'async_trait,
        {
            Box::pin(async { Ok(()) })
        }
    }

    struct OperatorVerbHarness {
        _temp_dir: tempfile::TempDir,
        runtime: crate::UnifiedRuntime,
        concrete: Arc<meerkat_session::PersistentSessionService<meerkat::FactoryAgentBuilder>>,
        adapter: Arc<meerkat_runtime::MeerkatMachine>,
        identity_runtime: Arc<IdentityRuntime>,
        floors: Arc<crate::identity_first::CompactionFloorRegistry>,
        identity: AgentIdentity,
        member_alias: String,
        gate_armed: Arc<AtomicBool>,
        in_call: Arc<AtomicBool>,
        release: Arc<tokio::sync::Notify>,
        maintenance_only: Arc<AtomicBool>,
        fail_maintenance: Arc<AtomicBool>,
    }

    impl OperatorVerbHarness {
        fn identity_ctx(&self) -> IdentityFirstContext {
            IdentityFirstContext {
                runtime: Arc::clone(&self.identity_runtime),
                roster_provider: Arc::new(EmptyRoster),
                topology_provider: None,
                customizer: None,
                agent_memory_provider: None,
                mob_definition: Some(self.runtime.mob_handle().definition().clone()),
                transcript_edit_service: Some(Arc::clone(&self.concrete) as _),
                compaction_floors: Some(Arc::clone(&self.floors)),
            }
        }

        /// Drive one member turn to completion through the identity runtime.
        async fn run_turn(&self, text: String) {
            let admission = self
                .identity_runtime
                .send_admission_tracked(
                    &self.identity,
                    None,
                    &meerkat_core::ContentInput::Text(text),
                    meerkat_core::types::HandlingMode::Queue,
                    None,
                )
                .await
                .expect("seed turn admitted");
            self.identity_runtime
                .wait_for_completion(
                    &self.identity,
                    admission.completion_baseline,
                    Duration::from_secs(30),
                )
                .await
                .expect("seed turn completed");
        }

        /// Observe the exact probe's finalized receipt before tearing down the
        /// runtime; a session-wide completion cursor can precede finalization.
        async fn run_exact_probe(&self, text: &str) {
            use meerkat_runtime::SessionServiceRuntimeExt;
            let owner = meerkat_mob::MobSessionService::runtime_adapter(self.concrete.as_ref())
                .expect("persistent completion owner");
            let session = self
                .identity_runtime
                .status(&self.identity)
                .await
                .expect("probe identity")
                .session_id
                .expect("probe session");
            let correlation = meerkat_core::SessionId::new().to_string();
            let key = format!("operator-probe:{correlation}");
            self.identity_runtime
                .dispatch_admission_tracked(
                    &self.identity,
                    None,
                    &crate::identity_first::DispatchInput::system(text)
                        .with_correlation(correlation)
                        .with_idempotency(&key),
                )
                .await
                .expect("exact probe admitted");
            tokio::time::timeout(Duration::from_secs(30), async {
                let mut input_id = None;
                loop {
                    if input_id.is_none() {
                        input_id = owner
                            .input_state_by_idempotency_key(&session, &key)
                            .await
                            .expect("probe input read")
                            .map(|state| state.state.input_id);
                    }
                    if let Some(id) = &input_id
                        && let Some(outcome) = owner
                            .input_terminal_completion(&session, id)
                            .await
                            .expect("probe terminal read")
                    {
                        match outcome {
                            meerkat_runtime::CompletionOutcome::Completed(result) => {
                                assert_eq!(result.session_id, session);
                                break;
                            }
                            other => panic!("probe did not complete successfully: {other:?}"),
                        }
                    }
                    tokio::time::sleep(Duration::from_millis(10)).await;
                }
            })
            .await
            .expect("exact probe finalizes within backstop");
        }

        async fn transcript_facts(&self) -> (usize, Option<String>) {
            let service: Arc<dyn crate::memory::hygienist::TranscriptEditSessionService> =
                Arc::clone(&self.concrete) as _;
            let session_id = self
                .identity_runtime
                .status(&self.identity)
                .await
                .expect("identity status")
                .session_id
                .expect("identity session");
            let (count, _head, last_reason) = read_transcript_facts(&service, &session_id)
                .await
                .expect("transcript facts");
            (count, last_reason)
        }

        /// `transcript_facts` count, read off a transcript that has stopped
        /// moving. Use this for any count a later assertion is COMPARED
        /// AGAINST: a baseline snapshotted mid-write drifts upward on its own,
        /// and then a "did it grow" check passes without the growth it names.
        async fn settled_transcript_count(&self) -> usize {
            let service: Arc<dyn crate::memory::hygienist::TranscriptEditSessionService> =
                Arc::clone(&self.concrete) as _;
            let session_id = self
                .identity_runtime
                .status(&self.identity)
                .await
                .expect("identity status")
                .session_id
                .expect("identity session");
            settled_transcript_len(&service, &session_id).await
        }
    }

    /// Message count on the DURABLE session surface - the one the operator
    /// verbs read, which is not the same clock as the identity's completion
    /// cursor.
    async fn transcript_len(
        service: &Arc<dyn crate::memory::hygienist::TranscriptEditSessionService>,
        session_id: &meerkat_core::types::SessionId,
    ) -> usize {
        service
            .read_history(
                session_id,
                meerkat_core::service::SessionHistoryQuery {
                    offset: 0,
                    limit: None,
                },
            )
            .await
            .expect("read durable transcript")
            .messages
            .len()
    }

    /// [`transcript_len`], but only once the durable transcript has stopped
    /// moving.
    ///
    /// A turn's completion cursor advances before the turn's rows are all
    /// durable, so a length read immediately after `run_turn` is a RACING
    /// READ. Any index computed from it is stale the moment a trailing row
    /// lands, which does not happen on an idle box and does happen under
    /// full-suite contention. Requiring the length to repeat across
    /// consecutive observations is what makes it usable as an index.
    ///
    /// The ceiling is a backstop, not a measurement: the transcript settles in
    /// milliseconds when anything is working.
    async fn settled_transcript_len(
        service: &Arc<dyn crate::memory::hygienist::TranscriptEditSessionService>,
        session_id: &meerkat_core::types::SessionId,
    ) -> usize {
        const REQUIRED_STABLE_OBSERVATIONS: usize = 3;
        let deadline = std::time::Instant::now() + Duration::from_mins(1);
        let mut settled = transcript_len(service, session_id).await;
        let mut stable = 1;
        while stable < REQUIRED_STABLE_OBSERVATIONS {
            tokio::time::sleep(Duration::from_millis(100)).await;
            let observed = transcript_len(service, session_id).await;
            if observed == settled {
                stable += 1;
            } else {
                settled = observed;
                stable = 1;
            }
            assert!(
                std::time::Instant::now() < deadline,
                "durable transcript never settled: still growing (last observed {observed} \
                 messages), so no index derived from it can be trusted"
            );
        }
        settled
    }

    /// Full production wiring in one process: a concrete
    /// `PersistentSessionService` backing the mob, an identity-first member
    /// bridged by the production `MobSessionBridge`, and the bridge's own
    /// compaction-floor registry shared into the RPC context - exactly the
    /// rpc_gateway composition, minus the stdio callback bridge.
    async fn operator_verb_harness(member: &str, mob_id: &str) -> OperatorVerbHarness {
        let temp_dir = tempfile::tempdir().expect("temp dir");
        let state = temp_dir.path().join("state");
        std::fs::create_dir_all(&state).expect("state dir");
        let session_store: Arc<dyn meerkat::SessionStore> = Arc::new(
            meerkat_store::SqliteSessionStore::open(state.join("sessions.db"))
                .expect("session store"),
        );
        let runtime_store: Arc<dyn meerkat_runtime::RuntimeStore> = Arc::new(
            meerkat_runtime::store::SqliteRuntimeStore::new(state.join("runtime.sqlite"))
                .expect("runtime store"),
        );
        let blob_store: Arc<dyn meerkat_core::BlobStore> =
            Arc::new(meerkat_store::MemoryBlobStore::new());
        let factory = meerkat::AgentFactory::new(&state).comms(true);
        let mut inner_builder =
            meerkat::FactoryAgentBuilder::new(factory, meerkat::Config::default());
        inner_builder.default_session_store = Some(Arc::new(meerkat_store::StoreAdapter::new(
            session_store.clone(),
        )));
        inner_builder.default_blob_store = Some(blob_store.clone());
        let adapter = Arc::new(meerkat_runtime::MeerkatMachine::persistent(
            Arc::clone(&runtime_store),
            Arc::clone(&blob_store),
        ));
        let concrete = Arc::new(meerkat_session::PersistentSessionService::new(
            inner_builder,
            16,
            session_store.clone(),
            runtime_store,
            blob_store,
        ));

        let gate_armed = Arc::new(AtomicBool::new(false));
        let in_call = Arc::new(AtomicBool::new(false));
        let release = Arc::new(tokio::sync::Notify::new());
        let maintenance_only = Arc::new(AtomicBool::new(false));
        let fail_maintenance = Arc::new(AtomicBool::new(false));
        let definition = meerkat_mob::MobDefinition::from_toml(&format!(
            r#"
[mob]
id = "{mob_id}"

[profiles.worker]
model = "gpt-5.5"

[profiles.worker.tools]
comms = true
"#
        ))
        .expect("mob definition");
        let mut mob_spec = crate::mob_handle_runtime::MobBootstrapSpec::new(
            definition,
            meerkat_mob::MobStorage::in_memory(),
            concrete.clone(),
        )
        .with_session_runtime_adapter(Arc::clone(&adapter))
        .with_options(crate::mob_handle_runtime::MobBootstrapOptions {
            allow_ephemeral_sessions: true,
            notify_orchestrator_on_resume: true,
            default_llm_client: Some(Arc::new(GatedUsageLlmClient {
                input_tokens: 5_000,
                gate_armed: Arc::clone(&gate_armed),
                in_call: Arc::clone(&in_call),
                release: Arc::clone(&release),
                maintenance_only: Arc::clone(&maintenance_only),
                fail_maintenance: Arc::clone(&fail_maintenance),
            })),
        });
        mob_spec.committed_boundary_recoverer = Some(concrete.clone());
        let mut runtime = crate::UnifiedRuntime::bootstrap(
            mob_spec,
            crate::MobKitConfig {
                modules: vec![],
                discovery: crate::DiscoverySpec {
                    namespace: mob_id.to_string(),
                    modules: vec![],
                },
                pre_spawn: vec![],
            },
            Duration::from_secs(5),
        )
        .await
        .expect("bootstrap unified runtime");
        let handle = runtime.mob_handle();

        // Identity-first member: the roster id is the mk--encoded generated
        // runtime alias, the shape HomeCore fleets address. The
        // `agent_identity` label is what the identity health monitor uses to
        // map this member's RunCompleted events onto the durable identity's
        // completion cursor.
        // `member` is the DURABLE identity now, not a generated `rt:{id}:{gen}`
        // alias: the roster identity is the durable identity's comms-safe
        // encoding, and AgentRuntimeId is incarnation detail. This used to
        // receive an alias and derive the durable identity back out of it.
        let roster_id = crate::member_comms_id::mob_member_id_str(member).into_owned();
        let roster_identity = meerkat_mob::ids::AgentIdentity::from(roster_id.clone());
        let durable_identity = crate::identity_first::AgentIdentity::parse(member)
            .expect("member argument must be a durable identity");
        let mut member_labels = std::collections::BTreeMap::new();
        member_labels.insert(
            "agent_identity".to_string(),
            durable_identity.as_str().to_string(),
        );
        handle
            .ensure_member(
                meerkat_mob::SpawnMemberSpec::new(
                    meerkat_mob::ProfileName::from("worker"),
                    roster_identity.clone(),
                )
                .with_labels(member_labels),
            )
            .await
            .expect("spawn identity-first member");
        handle
            .wait_for_members_kickoff_complete(
                std::slice::from_ref(&roster_identity),
                Some(Duration::from_secs(5)),
            )
            .await
            .expect("member kickoff settled");
        let member_session = handle
            .resolve_bridge_session_id_observation(&roster_identity)
            .await
            .expect("member session id");

        // Durable identity authority over that member, bridged by the
        // production MobSessionBridge (the gateway wiring).
        let public_member_alias =
            crate::member_comms_id::runtime_alias_str(&roster_id).into_owned();
        let identity = durable_identity;
        // The roster identity and the runtime BINDING are different things now.
        // The roster row is the durable identity's encoding; the binding is a
        // generated `rt:{identity}:{generation}` incarnation. This harness needs
        // both, and used to conflate them because they were the same string.
        let runtime_alias = format!("rt:{}:0", identity.as_str());
        let continuity_store =
            Arc::new(LocalContinuityStore::in_memory().expect("continuity store"));
        let lease_provider = Arc::new(LocalLeaseProvider::new());
        let lease_results = LeaseProvider::acquire_leases(
            lease_provider.as_ref(),
            std::slice::from_ref(&identity),
            "operator-verb-test",
        )
        .await
        .expect("acquire identity lease");
        let lease = match lease_results.get(&identity) {
            Some(LeaseAcquireResult::Acquired(lease)) => lease.clone(),
            other => panic!("expected acquired identity lease, got {other:?}"),
        };
        let record = ContinuityRecord {
            identity: identity.clone(),
            agent_runtime_id: crate::identity_first::AgentRuntimeId::parse(&runtime_alias)
                .expect("runtime alias"),
            session_id: member_session,
            generation: ContinuityGeneration::new(0),
            checkpoint_version: crate::identity_first::CheckpointVersion::new(0),
        };
        ContinuityStore::upsert_continuity_record(
            continuity_store.as_ref(),
            &record,
            lease.fencing_token,
        )
        .await
        .expect("persist identity continuity");
        let bridge = MobSessionBridge::with_session_service(handle.clone(), concrete.clone());
        let floors = bridge.compaction_floors();
        let identity_runtime = Arc::new(IdentityRuntime::new(IdentityRuntimeConfig {
            continuity_store,
            lease_provider,
            runtime_instance_id: "operator-verb-test".to_string(),
            has_runtime_store: true,
            durability_policy: DurabilityPolicy::SyncWriteThrough,
            bridge: Some(Arc::new(bridge)),
            default_timeout: None,
        }));
        identity_runtime
            .register(
                worker_spec(&identity),
                IdentityLifecycleState::Active,
                Some(record),
                Some(lease),
            )
            .await;

        // Install the identity authority on the unified runtime so its
        // identity health monitor drives the completion cursor from member
        // RunCompleted events (`wait_for_completion` moves on nothing else).
        runtime.attach_identity_first_context(Arc::new(
            crate::identity_first::IdentityFirstRuntimeContext::new(
                Arc::clone(&identity_runtime),
                Arc::new(EmptyRoster),
                None,
                None,
                Some(handle.definition().clone()),
            ),
        ));

        OperatorVerbHarness {
            _temp_dir: temp_dir,
            runtime,
            concrete,
            adapter,
            identity_runtime,
            floors,
            identity,
            member_alias: public_member_alias,
            gate_armed,
            in_call,
            release,
            maintenance_only,
            fail_maintenance,
        }
    }

    async fn rpc(harness: &OperatorVerbHarness, method: &str, params: Value) -> Value {
        let ctx = harness.identity_ctx();
        let raw = handle_unified_rpc_json(
            &harness.runtime,
            &serde_json::json!({
                "jsonrpc": "2.0",
                "id": 1,
                "method": method,
                "params": params,
            })
            .to_string(),
            Duration::from_mins(1),
            None,
            Some(&ctx),
        )
        .await;
        serde_json::from_str(&raw).expect("json-rpc response")
    }

    /// End-to-end `mobkit/compact_member`: seed a member transcript past the
    /// floor, invoke the verb, and require (a) a compaction-semantic rewrite
    /// landed (messages_after < messages_before), (b) the floor registry is
    /// disarmed afterwards, and (c) the restored build does NOT keep
    /// compacting (the compact-every-turn hazard the restore step exists to
    /// prevent).
    ///
    /// What this proves with the scripted keyless LLM double: the full arm ->
    /// respawn -> forced pre-LLM compaction -> disarm -> restore-respawn loop
    /// over the production bridge/service wiring, with the double reporting
    /// real input-token usage (5k > the 256-token floor) so the provider
    /// input trigger fires exactly as it would in production. It does NOT
    /// prove real-model summary quality.
    #[tokio::test(flavor = "multi_thread")]
    async fn compact_member_forces_one_compaction_and_restores_the_profile() {
        let harness = operator_verb_harness("worker:main", "operator-compact-verb").await;

        // Seed past both the floor and the recent-turn budget (4 turns) so
        // compaction has an older region to summarize away.
        let fat = "seeded transcript ballast ".repeat(160);
        for turn in 0..8 {
            harness.run_turn(format!("turn {turn}: {fat}")).await;
        }
        // Settled: this is a LOWER BOUND on a durable surface that lags the
        // completion cursor, so an unsettled read fails at `>= 16` for a
        // transcript that is merely still landing rather than one that is short.
        let messages_before = harness.settled_transcript_count().await;
        assert!(
            messages_before >= 16,
            "seed must materialize a fat transcript, got {messages_before}"
        );

        let response = rpc(
            &harness,
            "mobkit/compact_member",
            serde_json::json!({
                "identity": harness.member_alias,
                "floor_tokens": 256,
                "timeout_ms": 30_000,
            }),
        )
        .await;
        assert!(
            response["error"].is_null(),
            "compact_member must succeed: {response:#?}"
        );
        let result = &response["result"];
        assert_eq!(
            result["compaction_applied"],
            Value::Bool(true),
            "{result:#?}"
        );
        let reported_before = result["messages_before"].as_u64().expect("messages_before");
        let reported_after = result["messages_after"].as_u64().expect("messages_after");
        assert!(
            reported_after < reported_before,
            "compaction must shrink the transcript: {result:#?}"
        );
        assert!(
            result["last_rewrite_reason"]
                .as_str()
                .is_some_and(|reason| reason.to_lowercase().contains("compact")),
            "the landed rewrite must be compaction-semantic: {result:#?}"
        );
        assert!(
            harness.floors.get(&harness.identity).is_none(),
            "the floor registry must be disarmed after the verb"
        );

        // Restore evidence: the post-verb build must be back on the original
        // profile threshold. The recent turns alone (~5k reported input
        // tokens) are far past the 256-token floor, so a still-armed floor
        // would compact again on this very turn.
        // Both reads are on the DURABLE session surface, and `run_turn` returns
        // on the identity's COMPLETION CURSOR, which leads it (same clock split
        // documented on `transcript_len` and already fixed once in the sibling
        // timeout test). Sampling the surface once, at cursor timing, made this
        // read the append before it landed and report `3 -> 3` - a lagging
        // write and a wrongly re-compacting build are indistinguishable in a
        // single sample. Baseline is settled so it cannot drift upward on its
        // own and satisfy the comparison without an append; the growth itself
        // is then polled under the structural backstop, so a build that really
        // does re-compact never satisfies it and fails naming what never
        // happened.
        let count_after_verb = harness.settled_transcript_count().await;
        harness.run_turn("post-verb probe turn".to_string()).await;
        crate::test_wait::poll_until(
            &format!(
                "the restored build appended to the durable transcript instead of re-compacting \
                 (still {count_after_verb} messages)"
            ),
            crate::test_wait::STRUCTURAL_BACKSTOP,
            async || harness.transcript_facts().await.0 > count_after_verb,
        )
        .await;

        // Authorization shape: an identity the gateway does not own is a
        // typed refusal, not a fall-through.
        let response = rpc(
            &harness,
            "mobkit/compact_member",
            serde_json::json!({ "identity": "nobody:here" }),
        )
        .await;
        assert_eq!(
            response["error"]["code"],
            serde_json::json!(-32001),
            "an unowned identity must surface the typed unknown-identity refusal: {response:#?}"
        );

        let _ = harness.runtime.mob_handle().stop().await;
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn autonomous_compaction_exact_input_completion_survives_observation_timeout() {
        use meerkat_runtime::SessionServiceRuntimeExt;

        let harness = operator_verb_harness("worker:main", "operator-exact-input").await;
        let completion_runtime =
            meerkat_mob::MobSessionService::runtime_adapter(harness.concrete.as_ref())
                .expect("persistent service runtime adapter");
        assert!(!Arc::ptr_eq(&completion_runtime, &harness.adapter));
        let configured_observer = harness
            .runtime
            .mob_runtime()
            .committed_boundary_recoverer()
            .expect("concrete owner")
            .runtime_completion_observer()
            .expect("owner observer");
        assert!(
            Arc::ptr_eq(&configured_observer, &completion_runtime),
            "operator observer must use the concrete service, not the live-empty bootstrap override"
        );
        let fat = "seeded transcript ballast ".repeat(160);
        for turn in 0..4 {
            harness.run_turn(format!("turn {turn}: {fat}")).await;
        }
        let ctx = harness.identity_ctx();
        let spec = harness
            .identity_runtime
            .roster_inspect()
            .await
            .remove(&harness.identity)
            .expect("registered spec")
            .0;
        harness.floors.set(
            &harness.identity,
            NonZeroU64::new(256).expect("positive floor"),
        );
        let session_id =
            rebuild_member_for_fresh_build(&ctx, &harness.identity, None, spec.clone())
                .await
                .expect("install floor");
        let member_id = meerkat_mob::AgentIdentity::from(
            crate::member_comms_id::mob_member_id_str(harness.identity.as_str()).into_owned(),
        );
        let handle = harness.runtime.mob_handle();
        let member = handle
            .get_member(&member_id)
            .await
            .expect("read member")
            .expect("member present");
        assert_eq!(
            member.runtime_mode,
            meerkat_mob::MobRuntimeMode::AutonomousHost
        );
        let runtime_id = member.agent_runtime_id.clone();
        let fence = member.fence_token;
        let correlation = meerkat_core::SessionId::new().to_string();
        let key = format!("mobkit-compact-proof:{correlation}");
        let delivery = meerkat_mob::store::MobDeliveryIdentity::new(&key, &correlation)
            .expect("caller-owned delivery identity");
        harness.gate_armed.store(true, Ordering::SeqCst);
        handle
            .submit_work_with_mode_and_delivery_identity(
                runtime_id.clone(),
                fence,
                meerkat_mob::WorkSpec::new(
                    "exact input compaction maintenance",
                    meerkat_mob::WorkOrigin::Internal,
                ),
                meerkat_core::types::HandlingMode::Queue,
                delivery,
            )
            .await
            .expect("one autonomous ingress admission");
        let input = tokio::time::timeout(Duration::from_secs(30), async {
            loop {
                if let Some(input) = completion_runtime
                    .input_state_by_idempotency_key(&session_id, &key)
                    .await
                    .expect("owner admission read")
                {
                    break input.state.input_id;
                }
                tokio::time::sleep(Duration::from_millis(1)).await;
            }
        })
        .await
        .expect("exact key resolves within backstop");
        assert!(
            completion_runtime
                .input_state_by_idempotency_key(&session_id, "unrelated-operation")
                .await
                .expect("unrelated key read")
                .is_none()
        );
        let completion = async {
            loop {
                if let Some(completion) = completion_runtime
                    .input_terminal_completion(&session_id, &input)
                    .await
                    .expect("exact rich terminal read")
                {
                    break completion;
                }
                tokio::time::sleep(Duration::from_millis(1)).await;
            }
        };
        tokio::pin!(completion);
        assert!(
            tokio::time::timeout(Duration::from_millis(1), &mut completion)
                .await
                .is_err(),
            "admission alone cannot complete a held input"
        );
        harness.gate_armed.store(false, Ordering::SeqCst);
        harness.release.notify_one();
        let outcome = tokio::time::timeout(Duration::from_secs(30), &mut completion).await;
        if outcome.is_err() {
            let state = completion_runtime
                .input_state(&session_id, &input)
                .await
                .expect("exact input diagnostic");
            eprintln!(
                "exact input timeout: key={key} input={input:?} state={state:?} in_call={}",
                harness.in_call.load(Ordering::SeqCst),
            );
        }
        let outcome = outcome.expect("original input completion within backstop");
        match outcome {
            meerkat_runtime::CompletionOutcome::Completed(result) => {
                assert_eq!(result.session_id, session_id);
            }
            other => panic!("expected exact successful terminal, got {other:?}"),
        }
        harness.floors.clear(&harness.identity);
        let restored = rebuild_member_for_fresh_build(&ctx, &harness.identity, None, spec)
            .await
            .expect("restore only after rich exact input completion");
        assert_eq!(restored, session_id);
        let before = harness.settled_transcript_count().await;
        harness.run_turn("post-exact-input probe".to_string()).await;
        crate::test_wait::poll_until(
            "member accepts durable work after exact input settlement",
            crate::test_wait::STRUCTURAL_BACKSTOP,
            async || harness.transcript_facts().await.0 > before,
        )
        .await;
        harness.runtime.mob_handle().stop().await.expect("stop mob");
    }

    async fn held_compaction_harness(name: &str) -> Arc<OperatorVerbHarness> {
        let harness = Arc::new(operator_verb_harness("worker:main", name).await);
        let fat = "seeded transcript ballast ".repeat(160);
        for turn in 0..4 {
            harness.run_turn(format!("turn {turn}: {fat}")).await;
        }
        harness.maintenance_only.store(true, Ordering::SeqCst);
        harness.gate_armed.store(true, Ordering::SeqCst);
        harness
    }

    fn start_held_compaction(harness: &Arc<OperatorVerbHarness>) -> tokio::task::JoinHandle<Value> {
        let harness = Arc::clone(harness);
        tokio::spawn(async move {
            rpc(
                &harness,
                "mobkit/compact_member",
                serde_json::json!({
                    "identity": harness.member_alias,
                    "floor_tokens": 256,
                    "timeout_ms": 1,
                }),
            )
            .await
        })
    }

    async fn wait_for_held_compaction(harness: &OperatorVerbHarness) {
        crate::test_wait::poll_until(
            "maintenance LLM holds the admitted compaction",
            crate::test_wait::STRUCTURAL_BACKSTOP,
            async || harness.in_call.load(Ordering::SeqCst),
        )
        .await;
    }

    async fn release_compaction_and_join(harness: &OperatorVerbHarness) {
        harness.gate_armed.store(false, Ordering::SeqCst);
        harness.release.notify_one();
        tokio::time::timeout(
            Duration::from_secs(30),
            harness.identity_runtime.join_foreground_operations(),
        )
        .await
        .expect("owned compaction cleanup finishes");
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn compact_member_secondary_timeout_retains_owner_without_retire_or_second_send() {
        let harness = held_compaction_harness("operator-secondary-timeout").await;
        let caller = start_held_compaction(&harness);
        wait_for_held_compaction(&harness).await;
        let before = harness
            .identity_runtime
            .status(&harness.identity)
            .await
            .expect("status");
        let response = tokio::time::timeout(Duration::from_secs(15), caller)
            .await
            .expect("secondary observation is bounded")
            .expect("caller task");
        assert_eq!(response["error"]["data"]["kind"], "compact_member_timeout");
        assert_eq!(response["error"]["data"]["stage"], "terminal_pending");
        assert!(response["result"].is_null());
        assert!(harness.floors.get(&harness.identity).is_some());
        assert!(harness.in_call.load(Ordering::SeqCst));
        let after = harness
            .identity_runtime
            .status(&harness.identity)
            .await
            .expect("status");
        assert_eq!(
            after.state,
            crate::identity_first::IdentityLifecycleState::Active
        );
        assert_eq!(after.session_id, before.session_id);
        assert_eq!(after.agent_runtime_id, before.agent_runtime_id);
        let concurrent = rpc(
            &harness,
            "mobkit/compact_member",
            serde_json::json!({
                "identity": harness.member_alias, "timeout_ms": 1,
            }),
        )
        .await;
        assert_eq!(concurrent["error"]["data"]["kind"], "compact_member_busy");
        release_compaction_and_join(&harness).await;
        assert!(harness.floors.get(&harness.identity).is_none());
        let settled = harness
            .identity_runtime
            .status(&harness.identity)
            .await
            .expect("settled");
        assert_eq!(
            settled.state,
            crate::identity_first::IdentityLifecycleState::Active
        );
        assert_eq!(settled.session_id, before.session_id);
        harness
            .run_exact_probe("after pending-owner settlement")
            .await;
        harness.runtime.mob_handle().stop().await.expect("stop");
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn compact_member_caller_drop_keeps_exact_completion_and_profile_cleanup_owned() {
        let harness = held_compaction_harness("operator-caller-drop").await;
        let caller = start_held_compaction(&harness);
        wait_for_held_compaction(&harness).await;
        let original = harness
            .identity_runtime
            .status(&harness.identity)
            .await
            .expect("status");
        caller.abort();
        assert!(caller.await.expect_err("caller cancelled").is_cancelled());
        assert!(harness.floors.get(&harness.identity).is_some());
        release_compaction_and_join(&harness).await;
        assert!(harness.floors.get(&harness.identity).is_none());
        let restored = harness
            .identity_runtime
            .status(&harness.identity)
            .await
            .expect("restored");
        assert_eq!(restored.session_id, original.session_id);
        assert_eq!(
            restored.state,
            crate::identity_first::IdentityLifecycleState::Active
        );
        harness.run_exact_probe("after caller dropped").await;
        harness.runtime.mob_handle().stop().await.expect("stop");
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn compact_member_failed_exact_terminal_does_not_authorize_rebuild() {
        let harness = held_compaction_harness("operator-terminal-failure").await;
        harness.fail_maintenance.store(true, Ordering::SeqCst);
        let caller = start_held_compaction(&harness);
        wait_for_held_compaction(&harness).await;
        let before = harness
            .identity_runtime
            .status(&harness.identity)
            .await
            .expect("status");
        release_compaction_and_join(&harness).await;
        let response = caller.await.expect("caller result");
        assert_eq!(
            response["error"]["data"]["kind"],
            "compact_member_completion_failed"
        );
        assert!(
            response["error"]["data"]["completion_type"]
                .as_str()
                .is_some()
        );
        assert!(response["result"].is_null());
        assert!(harness.floors.get(&harness.identity).is_some());
        let after = harness
            .identity_runtime
            .status(&harness.identity)
            .await
            .expect("status");
        assert_eq!(after.session_id, before.session_id);
        assert_eq!(after.agent_runtime_id, before.agent_runtime_id);
        harness.runtime.mob_handle().stop().await.expect("stop");
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn compact_member_superseded_incarnation_cannot_restore_or_revive_retired_member() {
        let harness = held_compaction_harness("operator-superseded").await;
        let caller = start_held_compaction(&harness);
        wait_for_held_compaction(&harness).await;
        harness
            .identity_runtime
            .retire_tracked(&harness.identity)
            .await
            .expect("explicit retire");
        let retired = harness
            .identity_runtime
            .status(&harness.identity)
            .await
            .expect("retired");
        release_compaction_and_join(&harness).await;
        let response = caller.await.expect("caller");
        assert_eq!(
            response["error"]["data"]["kind"],
            "compact_member_superseded"
        );
        let after = harness
            .identity_runtime
            .status(&harness.identity)
            .await
            .expect("status");
        assert_eq!(
            after.state,
            crate::identity_first::IdentityLifecycleState::Retiring
        );
        assert!(harness.floors.get(&harness.identity).is_none());
        assert_eq!(after.session_id, retired.session_id);
        assert_eq!(after.agent_runtime_id, retired.agent_runtime_id);
        harness.runtime.mob_handle().stop().await.expect("stop");
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn compact_member_stale_pre_admission_owner_cannot_revive_retired_target() {
        let harness = operator_verb_harness("worker:main", "operator-stale-before-admit").await;
        let expected = harness
            .identity_runtime
            .capture_incarnation(&harness.identity)
            .await
            .expect("capture owner");
        harness
            .identity_runtime
            .retire_tracked(&harness.identity)
            .await
            .expect("retire");
        let input = crate::identity_first::DispatchInput::system("must never be admitted")
            .with_idempotency("stale-maintenance")
            .with_correlation(meerkat_core::SessionId::new().to_string());
        let result = harness
            .identity_runtime
            .dispatch_with_expected_incarnation(&harness.identity, None, Some(&expected), &input)
            .await;
        assert!(matches!(
            result,
            Err(crate::identity_first::IdentityRuntimeError::PostAdmissionSuperseded { .. })
        ));
        let after = harness
            .identity_runtime
            .status(&harness.identity)
            .await
            .expect("status");
        assert_eq!(
            after.state,
            crate::identity_first::IdentityLifecycleState::Retiring
        );
        assert!(harness.floors.get(&harness.identity).is_none());
        harness.runtime.mob_handle().stop().await.expect("stop");
    }

    struct FailingCompletionObserver {
        inner: Arc<meerkat_runtime::MeerkatMachine>,
        failing: AtomicBool,
    }

    struct AdmissionReplyLost {
        calls: std::sync::atomic::AtomicUsize,
    }

    #[async_trait::async_trait]
    impl CompactAdmission for AdmissionReplyLost {
        async fn dispatch(
            &self,
            runtime: &crate::identity_first::IdentityRuntime,
            identity: &AgentIdentity,
            incarnation: &crate::identity_first::runtime::CapturedIncarnation,
            input: &crate::identity_first::DispatchInput,
        ) -> Result<
            crate::identity_first::runtime::DispatchOutcome,
            crate::identity_first::IdentityRuntimeError,
        > {
            self.calls.fetch_add(1, Ordering::SeqCst);
            IdentityCompactionAdmission
                .dispatch(runtime, identity, incarnation, input)
                .await?;
            Err(
                crate::identity_first::IdentityRuntimeError::ActorAdmissionTimeout {
                    identity: identity.clone(),
                    operation: "test.admission_reply",
                    waited: Duration::from_millis(1),
                    command: None,
                },
            )
        }
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn compact_member_uncertain_admission_keeps_original_key_and_cleanup_without_resend() {
        use meerkat_runtime::SessionServiceRuntimeExt;
        let harness = held_compaction_harness("operator-admission-uncertain").await;
        let admission = Arc::new(AdmissionReplyLost {
            calls: std::sync::atomic::AtomicUsize::new(0),
        });
        let observer = meerkat_mob::MobSessionService::runtime_adapter(harness.concrete.as_ref())
            .expect("persistent owner");
        let operation_id = meerkat_core::SessionId::new().to_string();
        let key = format!("mobkit-compact:{operation_id}");
        let operation = CompactOperation {
            ctx: harness.identity_ctx(),
            identity: harness.identity.clone(),
            expected_alias: None,
            observer: observer.clone(),
            admission: admission.clone(),
            floors: harness.floors.clone(),
            floor: NonZeroU64::new(256).expect("floor"),
            timeout_ms: 1,
            response_id: serde_json::json!(1),
            operation_id,
        };
        let (sender, receiver) = tokio::sync::oneshot::channel();
        let runtime = harness.identity_runtime.clone();
        let owner = tokio::spawn(async move {
            runtime
                .run_tracked_foreground(async move { Ok(operation.run(sender).await) })
                .await
        });
        wait_for_held_compaction(&harness).await;
        let response = tokio::time::timeout(Duration::from_secs(15), receiver)
            .await
            .expect("bounded admission response")
            .expect("response");
        assert_eq!(
            response.error.expect("error").data.expect("data")["kind"],
            "compact_member_admission_pending"
        );
        assert!(!owner.is_finished());
        assert!(harness.floors.get(&harness.identity).is_some());
        let session = harness
            .identity_runtime
            .status(&harness.identity)
            .await
            .expect("status")
            .session_id
            .expect("session");
        let original = observer
            .input_state_by_idempotency_key(&session, &key)
            .await
            .expect("input read")
            .expect("admitted original input")
            .state
            .input_id;
        release_compaction_and_join(&harness).await;
        let response = owner.await.expect("owner").expect("result");
        assert_eq!(
            response.error.expect("timeout error").data.expect("data")["stage"],
            "profile_restored"
        );
        assert_eq!(admission.calls.load(Ordering::SeqCst), 1);
        assert_eq!(
            observer
                .input_state_by_idempotency_key(&session, &key)
                .await
                .expect("same-key read")
                .expect("original input retained")
                .state
                .input_id,
            original,
        );
        assert!(harness.floors.get(&harness.identity).is_none());
        harness.run_exact_probe("after lost admission reply").await;
        harness.runtime.mob_handle().stop().await.expect("stop");
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn compact_member_preparation_read_failure_does_not_install_or_strand_floor() {
        let harness = operator_verb_harness("worker:main", "operator-preflight-read").await;
        let other = operator_verb_harness("worker:other", "operator-other-store").await;
        let before = harness
            .identity_runtime
            .capture_incarnation(&harness.identity)
            .await
            .expect("capture");
        let mut ctx = harness.identity_ctx();
        ctx.transcript_edit_service = Some(other.concrete.clone());
        let operation = CompactOperation {
            ctx,
            identity: harness.identity.clone(),
            expected_alias: None,
            observer: meerkat_mob::MobSessionService::runtime_adapter(harness.concrete.as_ref())
                .expect("observer"),
            admission: Arc::new(IdentityCompactionAdmission),
            floors: harness.floors.clone(),
            floor: NonZeroU64::new(256).expect("floor"),
            timeout_ms: 1,
            response_id: serde_json::json!(1),
            operation_id: meerkat_core::SessionId::new().to_string(),
        };
        let (sender, _receiver) = tokio::sync::oneshot::channel();
        let response = operation.run(sender).await;
        assert_eq!(
            response.error.expect("read error").data.expect("data")["stage"],
            "before"
        );
        assert!(harness.floors.get(&harness.identity).is_none());
        assert_eq!(
            harness
                .identity_runtime
                .capture_incarnation(&harness.identity)
                .await
                .expect("owner"),
            before,
        );
        harness.runtime.mob_handle().stop().await.expect("stop");
        other.runtime.mob_handle().stop().await.expect("stop other");
    }

    #[async_trait::async_trait]
    impl CompactCompletionObserver for FailingCompletionObserver {
        async fn observe(
            &self,
            session_id: &meerkat_core::SessionId,
            key: &str,
            input_id: &mut Option<meerkat_core::lifecycle::InputId>,
        ) -> Result<Option<meerkat_runtime::CompletionOutcome>, meerkat_runtime::RuntimeDriverError>
        {
            if self.failing.load(Ordering::SeqCst) {
                return Err(meerkat_runtime::RuntimeDriverError::Internal(
                    "injected observation outage".to_string(),
                ));
            }
            CompactCompletionObserver::observe(self.inner.as_ref(), session_id, key, input_id).await
        }
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn compact_member_observation_error_retains_original_input_and_cleanup_owner() {
        let harness = held_compaction_harness("operator-read-error").await;
        let observer = Arc::new(FailingCompletionObserver {
            inner: meerkat_mob::MobSessionService::runtime_adapter(harness.concrete.as_ref())
                .expect("persistent owner"),
            failing: AtomicBool::new(true),
        });
        let operation = CompactOperation {
            ctx: harness.identity_ctx(),
            identity: harness.identity.clone(),
            expected_alias: None,
            observer: observer.clone(),
            admission: Arc::new(IdentityCompactionAdmission),
            floors: harness.floors.clone(),
            floor: NonZeroU64::new(256).expect("floor"),
            timeout_ms: 1,
            response_id: serde_json::json!(1),
            operation_id: meerkat_core::SessionId::new().to_string(),
        };
        let (sender, receiver) = tokio::sync::oneshot::channel();
        let runtime = harness.identity_runtime.clone();
        let owner = tokio::spawn(async move {
            runtime
                .run_tracked_foreground(async move { Ok(operation.run(sender).await) })
                .await
        });
        wait_for_held_compaction(&harness).await;
        let response = tokio::time::timeout(Duration::from_secs(15), receiver)
            .await
            .expect("bounded read error response")
            .expect("response");
        assert_eq!(
            response.error.expect("error").data.expect("data")["stage"],
            "terminal_pending"
        );
        assert!(harness.floors.get(&harness.identity).is_some());
        assert!(
            !owner.is_finished(),
            "read failure cannot end admitted operation custody"
        );
        observer.failing.store(false, Ordering::SeqCst);
        release_compaction_and_join(&harness).await;
        let response = owner.await.expect("owner task").expect("owned result");
        assert_eq!(
            response.error.expect("deadline error").data.expect("data")["stage"],
            "profile_restored"
        );
        assert!(harness.floors.get(&harness.identity).is_none());
        harness.run_exact_probe("after observer outage").await;
        harness.runtime.mob_handle().stop().await.expect("stop");
    }

    /// Honest timeout semantics: when the maintenance-turn wait gives up, the
    /// error must state what actually happened to the turn - the rollback
    /// rebuild's retire quiesces it, or, when the rollback did not land, it
    /// may still be running on the floored build - instead of implying the
    /// timeout stopped anything. The member must also come back usable: the
    /// rollback rebuild restores the original profile threshold.
    ///
    /// Only the invariants that hold on BOTH branches are asserted. Which
    /// branch runs depends on wall-clock progress the test does not control,
    /// and the optional compaction-evidence clause is dropped whenever its
    /// own bounded read cannot answer.
    #[tokio::test(flavor = "multi_thread")]
    async fn compact_member_timeout_names_the_turn_fate_and_restores_the_member() {
        let harness = operator_verb_harness("worker:main", "operator-compact-timeout").await;
        let fat = "seeded transcript ballast ".repeat(160);
        for turn in 0..4 {
            harness.run_turn(format!("turn {turn}: {fat}")).await;
        }

        // A 1ms wait cannot outlast a real bridge respawn + turn: the wait
        // times out while the verb's machinery is still working.
        let response = rpc(
            &harness,
            "mobkit/compact_member",
            serde_json::json!({
                "identity": harness.member_alias,
                "floor_tokens": 256,
                "timeout_ms": 1,
            }),
        )
        .await;
        let message = response["error"]["message"]
            .as_str()
            .unwrap_or_else(|| panic!("timeout must surface a typed error: {response:#?}"));
        assert!(
            message.contains("did not complete within 1ms"),
            "the error must name the exhausted deadline: {message}"
        );
        assert!(
            message.contains("quiesced by the rollback rebuild")
                || message.contains("may still be running on the floored build")
                || message
                    .contains("exact maintenance input completed after the observation deadline"),
            "the error must state the in-flight turn's actual fate: {message}"
        );
        assert!(
            !message.contains("did not complete: "),
            "the pre-fix message shape (bare wait error, no turn fate) must be gone: {message}"
        );
        assert!(
            harness.floors.get(&harness.identity).is_none(),
            "the floor registry must be disarmed after a timed-out verb"
        );

        // The member must be usable after the rollback: a probe turn appends.
        //
        // Read off the clock the assertion actually reads. `run_turn` returns on
        // the identity's COMPLETION CURSOR; this reads the DURABLE session
        // surface, which lags it. Sampling once at cursor timing cannot tell a
        // write that has not landed from a member that never accepted the turn -
        // both render as no growth, which is how this failed CI at `3 -> 3`.
        // Third instance of this split in this file: the seeded-length read and
        // the sibling forced-compaction probe were both fixed the same way.
        let restored = harness
            .identity_runtime
            .status(&harness.identity)
            .await
            .expect("post-timeout identity status");
        assert_eq!(
            restored.state,
            crate::identity_first::IdentityLifecycleState::Active,
            "rollback must leave the member usable: {response:#?}; status={restored:#?}"
        );
        let count_before_probe = harness.settled_transcript_count().await;
        harness
            .run_turn("post-timeout probe turn".to_string())
            .await;
        crate::test_wait::poll_until(
            &format!(
                "the rolled-back member accepted a turn and appended to the durable transcript \
                 (still {count_before_probe} messages)"
            ),
            crate::test_wait::STRUCTURAL_BACKSTOP,
            async || harness.transcript_facts().await.0 > count_before_probe,
        )
        .await;

        let _ = harness.runtime.mob_handle().stop().await;
    }

    /// `mobkit/bound_member_transcript` on an idle member session whose tool
    /// pair straddles the naive cut point: the commit must succeed with the
    /// pair kept whole, and the resulting transcript must start with the
    /// operator marker followed by the intact pair.
    #[tokio::test(flavor = "multi_thread")]
    async fn bound_member_transcript_commits_a_pair_safe_cut() {
        let harness = operator_verb_harness("worker:main", "operator-bound-verb").await;
        let service: Arc<dyn crate::memory::hygienist::TranscriptEditSessionService> =
            Arc::clone(&harness.concrete) as _;

        // Commit one ordinary turn so the session is materialized/idle, then
        // seed the tool-pair fixture through the SAME audited edit surface
        // the verb uses (append at the end; the whole-transcript shape
        // validation admits the adjacent pair). The turn just finished, so a
        // still-draining runtime admission can answer Busy briefly; that is
        // the documented posture, retried here rather than raced.
        harness
            .run_turn("seed one committed turn".to_string())
            .await;
        let session_id = harness
            .identity_runtime
            .status(&harness.identity)
            .await
            .expect("identity status")
            .session_id
            .expect("identity session");
        // Every index below is derived from this length, so it must be read
        // off a SETTLED transcript. `run_turn` waits on the identity's
        // completion cursor, which advances when the turn completes - not when
        // the turn's rows are durable in the session store, which is the
        // surface both this rewrite and the verb read. Snapshotting on the
        // cursor's timing is a racing read: under full-suite contention two
        // further rows landed between the snapshot and the rewrite and every
        // derived index was wrong (`removed` 7 against an expected 4, 1-of-5
        // full-suite runs). Quiesce on the durable surface instead.
        let seeded_len = settled_transcript_len(&service, &session_id).await;
        let (assistant, results) = tool_use_pair("call-straddle");
        let fixture = vec![user("older"), assistant, results, user("tail")];
        let fixture_len = fixture.len();
        // The turn just finished, so a still-draining runtime admission can
        // answer Busy briefly; that is the documented posture, retried here
        // rather than raced. Kept tight deliberately: the refusal is TRUE when
        // it happens, so a longer wait would only delay a correct answer and
        // hide the mechanism behind it.
        let deadline = std::time::Instant::now() + Duration::from_secs(10);
        loop {
            let request = meerkat_core::service::SessionTranscriptRewriteRequest {
                selection: meerkat_core::TranscriptRewriteSelection::MessageRange {
                    start: seeded_len,
                    end: seeded_len,
                },
                replacement: fixture.clone(),
                reason: meerkat_core::TranscriptRewriteReason::new("test_seed"),
                actor: Some("operator-verb-test".to_string()),
                expected_parent_revision: None,
                running_behavior: meerkat_core::TranscriptEditRunningBehavior::default(),
            };
            match service
                .rewrite_session_transcript(&session_id, request)
                .await
            {
                Ok(_) => break,
                Err(SessionError::Busy { .. }) if std::time::Instant::now() < deadline => {
                    tokio::time::sleep(Duration::from_millis(50)).await;
                }
                Err(err) => panic!("fixture seed rewrite failed: {err}"),
            }
        }

        // Transcript is now [..seeded_len ordinary rows, older, assistant,
        // results, tail] with the results row at index seeded_len + 2.
        // keep_last = 2 naively cuts at len - 2 = seeded_len + 2, which IS
        // the tool_results row; the pair-safe cut walks back one to keep the
        // pair whole (removed = seeded_len + 1, kept = 3).
        //
        // Pin that premise before spending it on `removed` below. If anything
        // else reached the transcript, this fails naming the race rather than
        // surfacing later as unexplained index arithmetic.
        let staged_len = transcript_len(&service, &session_id).await;
        assert_eq!(
            staged_len,
            seeded_len + fixture_len,
            "the seeded fixture must be the whole of the transcript growth: expected the \
             {seeded_len} settled rows plus the {fixture_len} fixture rows, saw {staged_len}. A \
             different count means rows landed alongside the fixture and every index below is \
             derived from a stale premise."
        );
        let response = rpc(
            &harness,
            "mobkit/bound_member_transcript",
            serde_json::json!({
                "identity": harness.member_alias,
                "keep_last": 2,
            }),
        )
        .await;
        assert!(
            response["error"].is_null(),
            "bound_member_transcript must succeed on an idle session: {response:#?}"
        );
        let result = &response["result"];
        assert_eq!(result["bounded"], Value::Bool(true), "{result:#?}");
        assert_eq!(
            result["removed"],
            serde_json::json!(seeded_len + 1),
            "the cut must walk back off the tool_results row: {result:#?}"
        );
        assert!(result["revision"].as_str().is_some(), "{result:#?}");

        let page = service
            .read_history(
                &session_id,
                meerkat_core::service::SessionHistoryQuery {
                    offset: 0,
                    limit: None,
                },
            )
            .await
            .expect("read bounded transcript");
        assert_eq!(page.messages.len(), 4, "marker + intact pair + tail");
        assert!(
            matches!(page.messages[0], Message::SystemNotice(_)),
            "bounded transcript must lead with the operator marker"
        );
        assert!(
            matches!(page.messages[1], Message::BlockAssistant(_))
                && matches!(page.messages[2], Message::ToolResults { .. }),
            "the straddled tool pair must survive whole"
        );

        let _ = harness.runtime.mob_handle().stop().await;
    }

    /// `mobkit/bound_member_transcript` while the member is mid-turn: the
    /// service's `SessionError::Busy` surfaces as the verb's typed refusal.
    #[tokio::test(flavor = "multi_thread")]
    async fn bound_member_transcript_refuses_running_sessions_typed() {
        let harness = operator_verb_harness("worker:main", "operator-bound-busy").await;

        // Commit one ordinary turn first so the transcript has messages past
        // keep_last = 1 (a zero-length transcript would no-op before ever
        // reaching the rewrite's Busy check).
        harness
            .run_turn("seed one committed turn".to_string())
            .await;

        // Arm the gate, then hold one member turn in flight inside the LLM
        // call so the session's active runtime admission is observably held.
        harness.gate_armed.store(true, Ordering::SeqCst);
        let admission = harness
            .identity_runtime
            .send_admission_tracked(
                &harness.identity,
                None,
                &meerkat_core::ContentInput::Text("held turn".to_string()),
                meerkat_core::types::HandlingMode::Queue,
                None,
            )
            .await
            .expect("held turn admitted");
        // Backstop only: the admitted turn either reaches the gated LLM call or
        // it never will. Generous so full-suite CPU starvation cannot reach it.
        let deadline = std::time::Instant::now() + Duration::from_mins(1);
        while !harness.in_call.load(Ordering::SeqCst) {
            assert!(
                std::time::Instant::now() < deadline,
                "the held turn never reached the LLM call: the gate was armed and the turn was \
                 admitted, but `in_call` was never set"
            );
            tokio::time::sleep(Duration::from_millis(10)).await;
        }

        let response = rpc(
            &harness,
            "mobkit/bound_member_transcript",
            serde_json::json!({
                "identity": harness.member_alias,
                "keep_last": 1,
            }),
        )
        .await;
        assert_eq!(
            response["error"]["code"],
            serde_json::json!(OPERATOR_SESSION_BUSY_CODE),
            "a running session must surface the typed Busy refusal: {response:#?}"
        );
        assert!(
            response["error"]["message"]
                .as_str()
                .is_some_and(|message| message.contains("quiesce")),
            "the refusal must document quiesce-first: {response:#?}"
        );

        // Release the held turn so shutdown is clean.
        harness.gate_armed.store(false, Ordering::SeqCst);
        harness.release.notify_waiters();
        harness
            .identity_runtime
            .wait_for_completion(
                &harness.identity,
                admission.completion_baseline,
                Duration::from_secs(30),
            )
            .await
            .expect("held turn completed after release");

        let _ = harness.runtime.mob_handle().stop().await;
    }

    #[test]
    fn optional_u64_param_rejects_zero_and_non_integers() {
        let params = serde_json::json!({ "floor_tokens": 0 });
        assert!(optional_u64_param(&params, "floor_tokens").is_err());
        let params = serde_json::json!({ "floor_tokens": "many" });
        assert!(optional_u64_param(&params, "floor_tokens").is_err());
        let params = serde_json::json!({});
        assert_eq!(optional_u64_param(&params, "floor_tokens").unwrap(), None);
        let params = serde_json::json!({ "floor_tokens": 2048 });
        assert_eq!(
            optional_u64_param(&params, "floor_tokens").unwrap(),
            Some(2048)
        );
    }
}