meerkat-mobkit 0.7.35

Companion orchestration platform for the Meerkat multi-agent runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
//! `mobkit/workgraph/*` RPC surface (docs/design/workgraph-wire-contract.md):
//! unified stdin dispatch for all 22 methods, the error taxonomy
//! (-32041 unavailable / -32042 conflict / -32602 params), server-side
//! authority-witness injection, identity-target lowering, capabilities
//! advertisement, console dispatch with read-only + ABAC gating, the
//! experience `workgraph` section, and console principal promotion into
//! `goal/confirm`.
#![allow(clippy::expect_used, clippy::unwrap_used, clippy::panic)]

use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::Duration;

use axum::body::{Body, to_bytes};
use axum::http::{Request, StatusCode, header};
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use hmac::{Hmac, Mac};
use meerkat::{AgentFactory, Config, build_ephemeral_service};
use meerkat_client::TestClient;
use meerkat_mob::ids::AgentIdentity;
use meerkat_mob::{MobDefinition, MobStorage, SpawnMemberSpec};
use meerkat_mobkit::{
    AccessControlConfig, AccessController, AccessRule, AuthPolicy, BigQueryNaming, ConsolePolicy,
    DiscoverySpec, MobBootstrapOptions, MobBootstrapSpec, MobKitConfig, RuntimeDecisionInputs,
    RuntimeOpsPolicy, TrustedOidcRuntimeConfig, UnifiedRuntime, build_runtime_decision_state,
    handle_unified_rpc_json, validate_access_config,
};
use serde_json::{Value, json};
use tower::ServiceExt;

type HmacSha256 = Hmac<sha2::Sha256>;

const WORKGRAPH_MOB_TOML: &str = r#"
[mob]
id = "workgraph-rpc-mob"

[profiles.worker]
model = "gpt-5.5"
runtime_mode = "autonomous_host"
external_addressable = true

[profiles.worker.tools]
comms = true
"#;

const ALL_WORKGRAPH_METHODS: &[&str] = &[
    "mobkit/workgraph/snapshot",
    "mobkit/workgraph/list",
    "mobkit/workgraph/get",
    "mobkit/workgraph/ready",
    "mobkit/workgraph/events",
    "mobkit/workgraph/attention/list",
    "mobkit/workgraph/goal/status",
    "mobkit/workgraph/create",
    "mobkit/workgraph/update",
    "mobkit/workgraph/claim",
    "mobkit/workgraph/release",
    "mobkit/workgraph/close",
    "mobkit/workgraph/block",
    "mobkit/workgraph/link",
    "mobkit/workgraph/evidence/add",
    "mobkit/workgraph/policy/escalate",
    "mobkit/workgraph/goal/create",
    "mobkit/workgraph/goal/confirm",
    "mobkit/workgraph/goal/request_close",
    "mobkit/workgraph/attention/pause",
    "mobkit/workgraph/attention/resume",
    "mobkit/workgraph/attention/reassign",
];

fn definition() -> MobDefinition {
    MobDefinition::from_toml(WORKGRAPH_MOB_TOML).expect("parse workgraph test definition")
}

/// Standard fixture: builder-constructed ephemeral runtime — the builder path
/// wires a memory-backed WorkGraph service automatically.
async fn build_runtime() -> UnifiedRuntime {
    Box::pin(
        UnifiedRuntime::builder()
            .definition(definition())
            .default_llm_client(Arc::new(TestClient::default()))
            .build(),
    )
    .await
    .expect("workgraph runtime builds")
}

/// Counter-fixture: a manually assembled spec (the `MobBootstrapSpec::new`
/// path both gateways use) with NO workgraph service.
async fn build_runtime_without_workgraph() -> (tempfile::TempDir, UnifiedRuntime) {
    let temp_dir = tempfile::tempdir().expect("temp dir");
    let factory = AgentFactory::new(temp_dir.path()).comms(true);
    let session_service = Arc::new(build_ephemeral_service(factory, Config::default(), 8));
    let mob_spec = MobBootstrapSpec::new(definition(), MobStorage::in_memory(), session_service)
        .with_options(MobBootstrapOptions {
            allow_ephemeral_sessions: true,
            notify_orchestrator_on_resume: true,
            default_llm_client: Some(Arc::new(TestClient::default())),
        });
    let module_config = MobKitConfig {
        modules: vec![],
        discovery: DiscoverySpec {
            namespace: "workgraph-rpc".to_string(),
            modules: vec![],
        },
        pre_spawn: vec![],
    };
    let runtime = UnifiedRuntime::bootstrap(mob_spec, module_config, Duration::from_secs(2))
        .await
        .expect("bootstrap runtime without workgraph");
    (temp_dir, runtime)
}

async fn rpc(runtime: &UnifiedRuntime, method: &str, params: Value) -> Value {
    let request = json!({
        "jsonrpc": "2.0",
        "id": "wg-test",
        "method": method,
        "params": params,
    })
    .to_string();
    let response =
        handle_unified_rpc_json(runtime, &request, Duration::from_secs(5), None, None).await;
    serde_json::from_str(&response).expect("rpc response json")
}

fn result(response: &Value) -> &Value {
    assert!(
        response["error"].is_null(),
        "expected success, got {response:#?}"
    );
    &response["result"]
}

fn error_code(response: &Value) -> i64 {
    response["error"]["code"]
        .as_i64()
        .unwrap_or_else(|| panic!("expected error, got {response:#?}"))
}

async fn create_item(runtime: &UnifiedRuntime, title: &str) -> Value {
    let response = rpc(
        runtime,
        "mobkit/workgraph/create",
        json!({ "title": title }),
    )
    .await;
    result(&response)["item"].clone()
}

// ---------------------------------------------------------------------------
// Capabilities + availability
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread")]
async fn capabilities_advertise_workgraph_when_configured() {
    let runtime = build_runtime().await;
    let response = rpc(&runtime, "mobkit/capabilities", json!({})).await;
    let result = result(&response);
    assert_eq!(result["workgraph"], json!(true));
    let methods: Vec<&str> = result["methods"]
        .as_array()
        .expect("methods array")
        .iter()
        .filter_map(Value::as_str)
        .collect();
    for method in ALL_WORKGRAPH_METHODS {
        assert!(
            methods.contains(method),
            "capabilities must advertise {method}: {methods:?}"
        );
    }
    runtime.mob_handle().stop().await.expect("stop");
}

#[tokio::test(flavor = "multi_thread")]
async fn workgraph_unavailable_without_service() {
    let (_dir, runtime) = build_runtime_without_workgraph().await;

    let caps = rpc(&runtime, "mobkit/capabilities", json!({})).await;
    assert_eq!(caps["result"]["workgraph"], json!(false));
    let methods = caps["result"]["methods"].to_string();
    assert!(
        !methods.contains("mobkit/workgraph/"),
        "unconfigured runtimes must not advertise workgraph methods"
    );

    let response = rpc(&runtime, "mobkit/workgraph/snapshot", json!({})).await;
    assert_eq!(error_code(&response), -32041, "{response:#?}");
    assert_eq!(
        response["error"]["data"]["kind"],
        json!("workgraph_unavailable")
    );
    runtime.mob_handle().stop().await.expect("stop");
}

#[tokio::test(flavor = "multi_thread")]
async fn unknown_workgraph_method_is_method_not_found() {
    let runtime = build_runtime().await;
    let response = rpc(&runtime, "mobkit/workgraph/bogus", json!({})).await;
    assert_eq!(error_code(&response), -32601, "{response:#?}");
    runtime.mob_handle().stop().await.expect("stop");
}

// ---------------------------------------------------------------------------
// Item lifecycle
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread")]
async fn item_lifecycle_end_to_end() {
    let runtime = build_runtime().await;

    // create
    let response = rpc(
        &runtime,
        "mobkit/workgraph/create",
        json!({
            "title": "ship the release",
            "description": "cut 0.7.30",
            "priority": "high",
            "labels": ["release"],
        }),
    )
    .await;
    let item = result(&response)["item"].clone();
    let item_id = item["id"].as_str().expect("item id").to_string();
    assert_eq!(item["title"], json!("ship the release"));
    assert_eq!(item["status"], json!("open"));
    assert_eq!(item["realm_id"], json!("workgraph-rpc-mob"));
    let revision = item["revision"].as_u64().expect("revision");

    // get
    let response = rpc(&runtime, "mobkit/workgraph/get", json!({ "id": item_id })).await;
    assert_eq!(result(&response)["item"]["id"], json!(item_id.clone()));

    // list + ready
    let response = rpc(&runtime, "mobkit/workgraph/list", json!({})).await;
    assert_eq!(result(&response)["items"].as_array().unwrap().len(), 1);
    let response = rpc(&runtime, "mobkit/workgraph/ready", json!({})).await;
    assert_eq!(
        result(&response)["items"][0]["id"],
        json!(item_id.clone()),
        "an open unclaimed item is ready"
    );

    // claim (upstream nested owner form)
    let response = rpc(
        &runtime,
        "mobkit/workgraph/claim",
        json!({
            "id": item_id,
            "expected_revision": revision,
            "owner": { "key": { "kind": "agent", "id": "helper" } },
        }),
    )
    .await;
    let item = result(&response)["item"].clone();
    assert_eq!(item["status"], json!("in_progress"));
    assert_eq!(item["claim"]["owner"]["key"]["id"], json!("helper"));
    let revision = item["revision"].as_u64().expect("revision");

    // release
    let response = rpc(
        &runtime,
        "mobkit/workgraph/release",
        json!({ "id": item_id, "expected_revision": revision }),
    )
    .await;
    let item = result(&response)["item"].clone();
    assert_eq!(item["status"], json!("open"));
    let revision = item["revision"].as_u64().expect("revision");

    // update
    let response = rpc(
        &runtime,
        "mobkit/workgraph/update",
        json!({
            "id": item_id,
            "expected_revision": revision,
            "description": "cut 0.7.30 with workgraph",
        }),
    )
    .await;
    let item = result(&response)["item"].clone();
    assert_eq!(item["description"], json!("cut 0.7.30 with workgraph"));
    let revision = item["revision"].as_u64().expect("revision");

    // evidence/add
    let response = rpc(
        &runtime,
        "mobkit/workgraph/evidence/add",
        json!({
            "id": item_id,
            "expected_revision": revision,
            "evidence": { "kind": "note", "id": "ci-run-1", "summary": "green" },
        }),
    )
    .await;
    let item = result(&response)["item"].clone();
    assert_eq!(item["evidence_refs"][0]["id"], json!("ci-run-1"));
    let revision = item["revision"].as_u64().expect("revision");

    // second item: block + link
    let second = create_item(&runtime, "follow-up docs").await;
    let second_id = second["id"].as_str().expect("second id").to_string();
    let second_revision = second["revision"].as_u64().expect("revision");
    let response = rpc(
        &runtime,
        "mobkit/workgraph/block",
        json!({ "id": second_id, "expected_revision": second_revision }),
    )
    .await;
    assert_eq!(result(&response)["item"]["status"], json!("blocked"));

    let response = rpc(
        &runtime,
        "mobkit/workgraph/link",
        json!({ "kind": "related", "from_id": item_id, "to_id": second_id }),
    )
    .await;
    let edge = result(&response)["edge"].clone();
    assert_eq!(edge["kind"], json!("related"));
    assert_eq!(edge["from_id"], json!(item_id.clone()));

    // snapshot carries items + edges + high-water mark
    let response = rpc(&runtime, "mobkit/workgraph/snapshot", json!({})).await;
    let snapshot = result(&response).clone();
    assert_eq!(snapshot["items"].as_array().unwrap().len(), 2);
    assert_eq!(snapshot["edges"].as_array().unwrap().len(), 1);
    assert!(snapshot["event_high_water_mark"].as_i64().is_some());

    // events tail
    let response = rpc(&runtime, "mobkit/workgraph/events", json!({ "limit": 100 })).await;
    let events = result(&response)["events"].as_array().unwrap().clone();
    assert!(!events.is_empty(), "event log must not be empty");

    // close
    let response = rpc(
        &runtime,
        "mobkit/workgraph/close",
        json!({ "id": item_id, "expected_revision": revision }),
    )
    .await;
    let item = result(&response)["item"].clone();
    assert_eq!(item["status"], json!("completed"), "default close status");
    runtime.mob_handle().stop().await.expect("stop");
}

#[tokio::test(flavor = "multi_thread")]
async fn claim_accepts_flat_owner_wire_form() {
    let runtime = build_runtime().await;
    let item = create_item(&runtime, "flat owner claim").await;
    let response = rpc(
        &runtime,
        "mobkit/workgraph/claim",
        json!({
            "id": item["id"],
            "expected_revision": item["revision"],
            "owner": { "kind": "session", "id": "sess-1", "display_name": "Helper" },
        }),
    )
    .await;
    let claimed = result(&response)["item"].clone();
    assert_eq!(claimed["claim"]["owner"]["key"]["kind"], json!("session"));
    assert_eq!(claimed["claim"]["owner"]["display_name"], json!("Helper"));
    runtime.mob_handle().stop().await.expect("stop");
}

// ---------------------------------------------------------------------------
// Error taxonomy
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread")]
async fn params_validation_errors_are_typed() {
    let runtime = build_runtime().await;

    // non-object params
    let response = rpc(&runtime, "mobkit/workgraph/create", json!([1, 2])).await;
    assert_eq!(error_code(&response), -32602);

    // missing required field
    let response = rpc(&runtime, "mobkit/workgraph/create", json!({})).await;
    assert_eq!(error_code(&response), -32602);

    // realm_id is never accepted over the wire
    let response = rpc(
        &runtime,
        "mobkit/workgraph/list",
        json!({ "realm_id": "other-realm" }),
    )
    .await;
    assert_eq!(error_code(&response), -32602);
    assert!(
        response["error"]["message"]
            .as_str()
            .unwrap()
            .contains("realm_id"),
        "{response:#?}"
    );

    // close with a non-terminal status
    let item = create_item(&runtime, "bad close").await;
    let response = rpc(
        &runtime,
        "mobkit/workgraph/close",
        json!({ "id": item["id"], "expected_revision": item["revision"], "status": "open" }),
    )
    .await;
    assert_eq!(error_code(&response), -32602);

    // update without expected_revision
    let response = rpc(
        &runtime,
        "mobkit/workgraph/update",
        json!({ "id": item["id"], "title": "x" }),
    )
    .await;
    assert_eq!(error_code(&response), -32602);
    runtime.mob_handle().stop().await.expect("stop");
}

#[tokio::test(flavor = "multi_thread")]
async fn stale_revision_maps_to_conflict_code() {
    let runtime = build_runtime().await;
    let item = create_item(&runtime, "cas target").await;
    let stale = item["revision"].as_u64().unwrap() + 41;
    let response = rpc(
        &runtime,
        "mobkit/workgraph/update",
        json!({ "id": item["id"], "expected_revision": stale, "title": "stale write" }),
    )
    .await;
    assert_eq!(error_code(&response), -32042, "{response:#?}");
    assert_eq!(
        response["error"]["data"]["kind"],
        json!("workgraph_conflict")
    );
    assert!(
        response["error"]["data"]["detail"]
            .as_str()
            .unwrap()
            .contains("stale"),
        "detail carries the upstream message: {response:#?}"
    );
    runtime.mob_handle().stop().await.expect("stop");
}

// ---------------------------------------------------------------------------
// Goals + attention
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread")]
async fn goal_lifecycle_with_identity_target() {
    let runtime = build_runtime().await;

    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/create",
        json!({
            "title": "keep the dashboards green",
            "target": { "kind": "identity", "identity": "helper" },
        }),
    )
    .await;
    let goal = result(&response).clone();
    let binding_id = goal["attention"]["binding_id"]
        .as_str()
        .unwrap()
        .to_string();
    // Identity targets lower to the mob-scoped owner key.
    assert_eq!(goal["attention"]["target"]["kind"], json!("lowered_owner"));
    assert_eq!(
        goal["attention"]["target"]["owner_key"],
        json!({ "kind": "agent", "id": "mob/workgraph-rpc-mob/agent/helper" })
    );
    assert_eq!(goal["attention"]["status"]["state"], json!("active"));
    let binding_revision = goal["attention"]["machine_state"]["revision"]
        .as_u64()
        .expect("binding revision");

    // goal/status round-trips item + attention
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/status",
        json!({ "binding_id": binding_id }),
    )
    .await;
    let status = result(&response).clone();
    assert_eq!(status["item"]["title"], json!("keep the dashboards green"));
    assert_eq!(status["attention"]["binding_id"], json!(binding_id.clone()));

    // attention/list sees the active binding
    let response = rpc(&runtime, "mobkit/workgraph/attention/list", json!({})).await;
    let attention = result(&response)["attention"].as_array().unwrap().clone();
    assert_eq!(attention.len(), 1);

    // pause → resume
    let response = rpc(
        &runtime,
        "mobkit/workgraph/attention/pause",
        json!({ "binding_id": binding_id, "expected_revision": binding_revision }),
    )
    .await;
    let paused = result(&response)["attention"].clone();
    assert_eq!(paused["status"]["state"], json!("paused"));
    let binding_revision = paused["machine_state"]["revision"].as_u64().unwrap();

    let response = rpc(
        &runtime,
        "mobkit/workgraph/attention/resume",
        json!({ "binding_id": binding_id, "expected_revision": binding_revision }),
    )
    .await;
    let resumed = result(&response)["attention"].clone();
    assert_eq!(resumed["status"]["state"], json!("active"));

    // confirm (SelfAttest, defaulted evidence) then policy-gated close
    let item_revision = status["item"]["revision"].as_u64().unwrap();
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/confirm",
        json!({ "binding_id": binding_id, "expected_revision": item_revision }),
    )
    .await;
    let confirmed = result(&response).clone();
    assert_eq!(
        confirmed["item"]["evidence_refs"][0]["kind"],
        json!("self_attest"),
        "absent wire evidence defaults to the policy's admissible kind"
    );
    let item_revision = confirmed["item"]["revision"].as_u64().unwrap();

    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/request_close",
        json!({ "binding_id": binding_id, "expected_revision": item_revision }),
    )
    .await;
    let closed = result(&response).clone();
    assert_eq!(closed["item"]["status"], json!("completed"));
    assert_eq!(
        closed["attention"]["status"]["state"],
        json!("stopped"),
        "closing the goal stops its attention binding"
    );
    runtime.mob_handle().stop().await.expect("stop");
}

/// Round-4 Q2 (write normalization): a session target that belongs to a
/// roster member is lowered to the member's OWNER form before the write, so
/// the stored row matches identity-form occupancy checks without a roster —
/// in a co-process sharing the SQLite store, and mid-respawn in this one.
/// Non-member sessions have no aliasing and keep their session form.
#[tokio::test(flavor = "multi_thread")]
async fn goal_create_lowers_member_session_targets_to_owner_form() {
    let runtime = build_runtime().await;
    runtime
        .spawn_many(vec![SpawnMemberSpec::from_wire(
            "worker".to_string(),
            "helper".to_string(),
            None,
            None,
            None,
        )])
        .await
        .expect("spawn member");
    let session_id = runtime
        .mob_handle()
        .resolve_bridge_session_id_observation(&AgentIdentity::from("helper"))
        .await
        .expect("member session id");

    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/create",
        json!({
            "title": "session-scoped goal",
            "target": { "kind": "session", "session_id": session_id.to_string() },
        }),
    )
    .await;
    let goal = result(&response).clone();
    assert_eq!(
        goal["attention"]["target"]["kind"],
        json!("lowered_owner"),
        "member session targets must be stored owner-form: {goal:#?}"
    );
    assert_eq!(
        goal["attention"]["target"]["owner_key"]["kind"],
        json!("agent")
    );
    assert_eq!(
        goal["attention"]["target"]["owner_key"]["id"],
        json!("mob/workgraph-rpc-mob/agent/helper")
    );

    // A session that is NOT a roster member keeps its session spelling.
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/create",
        json!({
            "title": "non-member session goal",
            "target": {
                "kind": "session",
                "session_id": "019e63c2-0000-7000-8000-00000000beef",
            },
        }),
    )
    .await;
    let goal = result(&response).clone();
    assert_eq!(goal["attention"]["target"]["kind"], json!("session"));

    // Unsupported target kinds are a params error.
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/create",
        json!({ "title": "bad target", "target": { "kind": "mob" } }),
    )
    .await;
    assert_eq!(error_code(&response), -32602);
    runtime.mob_handle().stop().await.expect("stop");
}

#[tokio::test(flavor = "multi_thread")]
async fn attention_reassign_injects_witness_server_side() {
    let runtime = build_runtime().await;
    // Coordinate mode grants can_link_derived_from, the reassign authority.
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/create",
        json!({
            "title": "coordinated goal",
            "target": { "kind": "identity", "identity": "helper" },
            "mode": "coordinate",
        }),
    )
    .await;
    let goal = result(&response).clone();
    let binding_id = goal["attention"]["binding_id"]
        .as_str()
        .unwrap()
        .to_string();
    let binding_revision = goal["attention"]["machine_state"]["revision"]
        .as_u64()
        .unwrap();

    // A wire-supplied witness is rejected — it is unforgeable by design.
    let response = rpc(
        &runtime,
        "mobkit/workgraph/attention/reassign",
        json!({
            "binding_id": binding_id,
            "expected_revision": binding_revision,
            "target": { "kind": "identity", "identity": "backup" },
            "authority_projection": { "forged": true },
        }),
    )
    .await;
    assert_eq!(error_code(&response), -32602);
    assert!(
        response["error"]["message"]
            .as_str()
            .unwrap()
            .contains("authority_projection"),
        "{response:#?}"
    );

    // Without one, the server fetches the live projection and reassigns.
    let response = rpc(
        &runtime,
        "mobkit/workgraph/attention/reassign",
        json!({
            "binding_id": binding_id,
            "expected_revision": binding_revision,
            "target": { "kind": "identity", "identity": "backup" },
        }),
    )
    .await;
    let reassigned = result(&response).clone();
    assert_eq!(
        reassigned["previous"]["status"]["state"],
        json!("superseded")
    );
    assert_eq!(reassigned["attention"]["status"]["state"], json!("active"));
    assert_eq!(
        reassigned["attention"]["target"]["owner_key"]["id"],
        json!("mob/workgraph-rpc-mob/agent/backup")
    );
    runtime.mob_handle().stop().await.expect("stop");
}

/// Round-5 S2: every RESULT serializes the stored binding target, whose
/// owner form is spelled `lowered_owner` — the exact string
/// `resolve_goal_target` used to reject. A read-back `attention.target`
/// must round-trip VERBATIM into `attention/reassign` params.
#[tokio::test(flavor = "multi_thread")]
async fn result_attention_target_round_trips_verbatim_into_reassign() {
    let runtime = build_runtime().await;
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/create",
        json!({
            "title": "round-trip goal",
            "target": { "kind": "identity", "identity": "helper" },
            "mode": "coordinate",
        }),
    )
    .await;
    let goal = result(&response).clone();
    let read_back_target = goal["attention"]["target"].clone();
    assert_eq!(
        read_back_target["kind"],
        json!("lowered_owner"),
        "precondition: results serialize the lowered_owner spelling: {goal:#?}"
    );

    // Reassigning the binding onto its own read-back target supersedes it
    // with a fresh Active binding on the same member — the admission
    // excludes the binding being moved, and upstream has no same-target
    // rejection. Before the fix this was -32602 (unsupported target.kind).
    let response = rpc(
        &runtime,
        "mobkit/workgraph/attention/reassign",
        json!({
            "binding_id": goal["attention"]["binding_id"],
            "expected_revision": goal["attention"]["machine_state"]["revision"],
            "target": read_back_target,
        }),
    )
    .await;
    let reassigned = result(&response).clone();
    assert_eq!(
        reassigned["previous"]["status"]["state"],
        json!("superseded")
    );
    assert_eq!(reassigned["attention"]["status"]["state"], json!("active"));
    assert_eq!(
        reassigned["attention"]["target"], read_back_target,
        "the stored target must survive the round-trip unchanged"
    );
    runtime.mob_handle().stop().await.expect("stop");
}

/// Adversarial finding F10: a second ACTIVE binding for a target that
/// already has one bricks the member — every subsequent scoped turn is a
/// hard upstream `MultipleActiveBindings` error. `goal/create` must reject
/// it up front as the typed conflict, naming the existing binding.
#[tokio::test(flavor = "multi_thread")]
async fn duplicate_active_binding_for_same_target_is_conflict() {
    let runtime = build_runtime().await;
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/create",
        json!({
            "title": "first goal",
            "target": { "kind": "identity", "identity": "helper" },
        }),
    )
    .await;
    let first = result(&response).clone();
    let first_binding = first["attention"]["binding_id"]
        .as_str()
        .unwrap()
        .to_string();

    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/create",
        json!({
            "title": "second goal, same target",
            "target": { "kind": "identity", "identity": "helper" },
        }),
    )
    .await;
    assert_eq!(error_code(&response), -32042, "{response:#?}");
    assert_eq!(
        response["error"]["data"]["kind"],
        json!("workgraph_conflict")
    );
    let detail = response["error"]["data"]["detail"].as_str().unwrap();
    assert!(
        detail.contains(&first_binding),
        "conflict must name the existing binding: {detail}"
    );
    assert!(
        detail.contains("reassign") && detail.contains("close its goal"),
        "detail must hint the way out: {detail}"
    );

    // A different target is unaffected.
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/create",
        json!({
            "title": "different member",
            "target": { "kind": "identity", "identity": "backup" },
        }),
    )
    .await;
    assert!(response["error"].is_null(), "{response:#?}");

    // Round-2 hole 4: pausing the existing binding does NOT free the target
    // — the pause auto-reactivates at expiry, so a goal created "into" the
    // pause becomes the second Active binding the moment it expires. The
    // conflict must name the paused binding and hint resume-or-close.
    let binding_revision = first["attention"]["machine_state"]["revision"]
        .as_u64()
        .unwrap();
    let response = rpc(
        &runtime,
        "mobkit/workgraph/attention/pause",
        json!({ "binding_id": first_binding, "expected_revision": binding_revision }),
    )
    .await;
    assert!(response["error"].is_null(), "{response:#?}");
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/create",
        json!({
            "title": "into the pause",
            "target": { "kind": "identity", "identity": "helper" },
        }),
    )
    .await;
    assert_eq!(error_code(&response), -32042, "{response:#?}");
    let detail = response["error"]["data"]["detail"].as_str().unwrap();
    assert!(
        detail.contains("paused") && detail.contains(&first_binding) && detail.contains("resume"),
        "paused conflict must name the binding and hint resume-or-close: {detail}"
    );

    // Closing the goal (confirm + request_close stops its binding) genuinely
    // frees the target.
    let item_revision = first["item"]["revision"].as_u64().unwrap();
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/confirm",
        json!({ "binding_id": first_binding, "expected_revision": item_revision }),
    )
    .await;
    let item_revision = result(&response)["item"]["revision"].as_u64().unwrap();
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/request_close",
        json!({ "binding_id": first_binding, "expected_revision": item_revision }),
    )
    .await;
    assert!(response["error"].is_null(), "{response:#?}");
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/create",
        json!({
            "title": "after close",
            "target": { "kind": "identity", "identity": "helper" },
        }),
    )
    .await;
    assert!(response["error"].is_null(), "{response:#?}");
    runtime.mob_handle().stop().await.expect("stop");
}

/// Round-2 hole 1: `attention/reassign` creates an Active binding on the
/// NEW target, so reassigning onto a member that already has one re-creates
/// the `MultipleActiveBindings` bricked state `goal/create` guards against.
/// The reassign target must pass the same occupancy guard (excluding the
/// binding being superseded, which never conflicts with its own move).
#[tokio::test(flavor = "multi_thread")]
async fn reassign_onto_occupied_target_is_conflict() {
    let runtime = build_runtime().await;
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/create",
        json!({
            "title": "already watching",
            "target": { "kind": "identity", "identity": "occupied" },
            "mode": "coordinate",
        }),
    )
    .await;
    let occupied_binding = result(&response)["attention"]["binding_id"]
        .as_str()
        .unwrap()
        .to_string();

    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/create",
        json!({
            "title": "about to move",
            "target": { "kind": "identity", "identity": "mover" },
            "mode": "coordinate",
        }),
    )
    .await;
    let mover = result(&response).clone();
    let mover_binding = mover["attention"]["binding_id"].as_str().unwrap();
    let mover_revision = mover["attention"]["machine_state"]["revision"]
        .as_u64()
        .unwrap();

    let response = rpc(
        &runtime,
        "mobkit/workgraph/attention/reassign",
        json!({
            "binding_id": mover_binding,
            "expected_revision": mover_revision,
            "target": { "kind": "identity", "identity": "occupied" },
        }),
    )
    .await;
    assert_eq!(error_code(&response), -32042, "{response:#?}");
    assert_eq!(
        response["error"]["data"]["kind"],
        json!("workgraph_conflict")
    );
    let detail = response["error"]["data"]["detail"].as_str().unwrap();
    assert!(
        detail.contains(&occupied_binding),
        "conflict must name the occupying binding: {detail}"
    );

    // A free target reassigns normally — the guard does not over-block.
    let response = rpc(
        &runtime,
        "mobkit/workgraph/attention/reassign",
        json!({
            "binding_id": mover_binding,
            "expected_revision": mover_revision,
            "target": { "kind": "identity", "identity": "free" },
        }),
    )
    .await;
    assert!(response["error"].is_null(), "{response:#?}");
    runtime.mob_handle().stop().await.expect("stop");
}

/// Round-2 hole 2: pause A, get a second binding onto the same member, then
/// resume A = two Active bindings. The second binding here is created
/// directly on the service (the member tool surface and pre-guard data can
/// both do that), so only the resume guard stands between the operator and
/// the bricked member.
///
/// Round-3 R2: a PAUSED sibling occupies too — a timed pause auto-reactivates
/// at expiry, so resuming "into" it just schedules the second Active. The
/// resume guard counts siblings exactly like create/reassign (Active OR
/// Paused); only closing the sibling's goal frees the target.
#[tokio::test(flavor = "multi_thread")]
async fn resume_with_another_active_binding_on_the_target_is_conflict() {
    let runtime = build_runtime().await;
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/create",
        json!({
            "title": "first watch",
            "target": { "kind": "identity", "identity": "helper" },
        }),
    )
    .await;
    let first = result(&response).clone();
    let first_binding = first["attention"]["binding_id"].as_str().unwrap();
    let first_revision = first["attention"]["machine_state"]["revision"]
        .as_u64()
        .unwrap();
    let response = rpc(
        &runtime,
        "mobkit/workgraph/attention/pause",
        json!({ "binding_id": first_binding, "expected_revision": first_revision }),
    )
    .await;
    let paused_revision = result(&response)["attention"]["machine_state"]["revision"]
        .as_u64()
        .unwrap();

    // Second binding for the SAME lowered owner, created past the RPC guard.
    let service = runtime.workgraph_service().expect("workgraph service");
    let second = service
        .create_goal(meerkat::GoalCreateRequest {
            realm_id: None,
            namespace: None,
            title: "second watch".to_string(),
            description: None,
            target: meerkat::GoalAttentionTarget::Owner {
                owner_key: meerkat_mob::lower_agent_identity_owner_key(
                    &definition().id,
                    &AgentIdentity::from("helper"),
                )
                .expect("lower owner key"),
            },
            mode: Default::default(),
            completion_policy: Default::default(),
            delegated_authority: Default::default(),
            projection_policy: Default::default(),
        })
        .await
        .expect("service-side goal create");
    let second_binding = second.attention.binding_id.to_string();

    let response = rpc(
        &runtime,
        "mobkit/workgraph/attention/resume",
        json!({ "binding_id": first_binding, "expected_revision": paused_revision }),
    )
    .await;
    assert_eq!(error_code(&response), -32042, "{response:#?}");
    let detail = response["error"]["data"]["detail"].as_str().unwrap();
    assert!(
        detail.contains(&second_binding),
        "conflict must name the active binding: {detail}"
    );

    // Round-3 R2: a TIMED pause on the sibling does NOT clear the way — it
    // auto-reactivates at expiry, so the resumed binding would become the
    // second Active the moment it fires. The conflict must name the paused
    // sibling and say why.
    let second_revision = second.attention.machine_state.revision;
    let response = rpc(
        &runtime,
        "mobkit/workgraph/attention/pause",
        json!({
            "binding_id": second_binding,
            "expected_revision": second_revision,
            "until": "2099-01-01T00:00:00Z",
        }),
    )
    .await;
    assert!(response["error"].is_null(), "{response:#?}");
    let response = rpc(
        &runtime,
        "mobkit/workgraph/attention/resume",
        json!({ "binding_id": first_binding, "expected_revision": paused_revision }),
    )
    .await;
    assert_eq!(error_code(&response), -32042, "{response:#?}");
    let detail = response["error"]["data"]["detail"].as_str().unwrap();
    assert!(
        detail.contains(&second_binding)
            && detail.contains("paused")
            && detail.contains("reactivate"),
        "timed-paused sibling must block resume and name itself: {detail}"
    );

    // Closing the sibling's goal (confirm + request_close stops its binding)
    // genuinely frees the target for the resume.
    let second_item_revision = second.item.revision;
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/confirm",
        json!({ "binding_id": second_binding, "expected_revision": second_item_revision }),
    )
    .await;
    let second_item_revision = result(&response)["item"]["revision"].as_u64().unwrap();
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/request_close",
        json!({ "binding_id": second_binding, "expected_revision": second_item_revision }),
    )
    .await;
    assert!(response["error"].is_null(), "{response:#?}");
    let response = rpc(
        &runtime,
        "mobkit/workgraph/attention/resume",
        json!({ "binding_id": first_binding, "expected_revision": paused_revision }),
    )
    .await;
    assert!(response["error"].is_null(), "{response:#?}");
    runtime.mob_handle().stop().await.expect("stop");
}

/// Round-2 hole 3 (aliasing): upstream `attention_target_matches_session`
/// matches BOTH a `Session{session_id}` target and the lowered
/// `mob/<mob>/agent/<identity>` owner target to the same member's turns, so
/// one member with a session-form binding and an identity-form binding is
/// still bricked. The guard must resolve session↔identity through the
/// roster, in both directions.
#[tokio::test(flavor = "multi_thread")]
async fn session_and_identity_goal_targets_conflict_as_the_same_member() {
    let runtime = build_runtime().await;
    runtime
        .spawn_many(vec![SpawnMemberSpec::from_wire(
            "worker".to_string(),
            "helper".to_string(),
            None,
            None,
            None,
        )])
        .await
        .expect("spawn member");
    let session_id = runtime
        .mob_handle()
        .resolve_bridge_session_id_observation(&AgentIdentity::from("helper"))
        .await
        .expect("member session id")
        .to_string();

    // identity first, session second: the session spelling must conflict.
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/create",
        json!({
            "title": "identity-form goal",
            "target": { "kind": "identity", "identity": "helper" },
        }),
    )
    .await;
    let identity_goal = result(&response).clone();
    let identity_binding = identity_goal["attention"]["binding_id"]
        .as_str()
        .unwrap()
        .to_string();
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/create",
        json!({
            "title": "session-form goal for the same member",
            "target": { "kind": "session", "session_id": session_id },
        }),
    )
    .await;
    assert_eq!(error_code(&response), -32042, "{response:#?}");
    assert!(
        response["error"]["data"]["detail"]
            .as_str()
            .unwrap()
            .contains(&identity_binding),
        "{response:#?}"
    );

    // Free the member (confirm + request_close stops the binding), then the
    // reverse direction: session first, identity second.
    let item_revision = identity_goal["item"]["revision"].as_u64().unwrap();
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/confirm",
        json!({ "binding_id": identity_binding, "expected_revision": item_revision }),
    )
    .await;
    let item_revision = result(&response)["item"]["revision"].as_u64().unwrap();
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/request_close",
        json!({ "binding_id": identity_binding, "expected_revision": item_revision }),
    )
    .await;
    assert!(response["error"].is_null(), "{response:#?}");

    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/create",
        json!({
            "title": "session-form goal",
            "target": { "kind": "session", "session_id": session_id },
        }),
    )
    .await;
    let session_binding = result(&response)["attention"]["binding_id"]
        .as_str()
        .unwrap()
        .to_string();
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/create",
        json!({
            "title": "identity-form goal for the same member",
            "target": { "kind": "identity", "identity": "helper" },
        }),
    )
    .await;
    assert_eq!(error_code(&response), -32042, "{response:#?}");
    assert!(
        response["error"]["data"]["detail"]
            .as_str()
            .unwrap()
            .contains(&session_binding),
        "{response:#?}"
    );
    runtime.mob_handle().stop().await.expect("stop");
}

/// Round-2 hole 5 (TOCTOU): two concurrent `goal/create` calls for the same
/// target must admit exactly one — the admission gate serializes the
/// check-then-act window shared by the stdin and console surfaces.
#[tokio::test(flavor = "multi_thread")]
async fn concurrent_goal_creates_for_same_target_admit_exactly_one() {
    let runtime = Arc::new(build_runtime().await);
    let call = |title: &str| {
        let runtime = Arc::clone(&runtime);
        let title = title.to_string();
        tokio::spawn(async move {
            rpc(
                &runtime,
                "mobkit/workgraph/goal/create",
                json!({
                    "title": title,
                    "target": { "kind": "identity", "identity": "racer" },
                }),
            )
            .await
        })
    };
    let (left, right) = tokio::join!(call("left lane"), call("right lane"));
    let (left, right) = (left.expect("join"), right.expect("join"));

    let successes = [&left, &right]
        .iter()
        .filter(|response| response["error"].is_null())
        .count();
    let conflicts = [&left, &right]
        .iter()
        .filter(|response| response["error"]["code"] == json!(-32042))
        .count();
    assert_eq!(
        (successes, conflicts),
        (1, 1),
        "exactly one create wins the race: left={left:#?} right={right:#?}"
    );
    runtime.mob_handle().stop().await.expect("stop");
}

/// Round-2 finding B: SDKs send the attention-list `status` filter as a
/// bare string, which upstream's internally-tagged enum rejects — the
/// filter never worked over the wire. Both spellings must filter, and
/// unknown strings are a typed params error.
#[tokio::test(flavor = "multi_thread")]
async fn attention_list_status_filter_accepts_sdk_strings() {
    let runtime = build_runtime().await;
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/create",
        json!({
            "title": "filter me",
            "target": { "kind": "identity", "identity": "helper" },
        }),
    )
    .await;
    let goal = result(&response).clone();
    let binding_id = goal["attention"]["binding_id"].as_str().unwrap();
    let binding_revision = goal["attention"]["machine_state"]["revision"]
        .as_u64()
        .unwrap();

    // Bare-string form (what both SDKs send).
    let response = rpc(
        &runtime,
        "mobkit/workgraph/attention/list",
        json!({ "status": "active" }),
    )
    .await;
    assert_eq!(
        result(&response)["attention"].as_array().unwrap().len(),
        1,
        "{response:#?}"
    );
    let response = rpc(
        &runtime,
        "mobkit/workgraph/attention/list",
        json!({ "status": "stopped" }),
    )
    .await;
    assert!(
        result(&response)["attention"]
            .as_array()
            .unwrap()
            .is_empty(),
        "{response:#?}"
    );

    // Tagged-object form passes through verbatim.
    let response = rpc(
        &runtime,
        "mobkit/workgraph/attention/pause",
        json!({ "binding_id": binding_id, "expected_revision": binding_revision }),
    )
    .await;
    assert!(response["error"].is_null(), "{response:#?}");
    let response = rpc(
        &runtime,
        "mobkit/workgraph/attention/list",
        json!({ "status": "paused" }),
    )
    .await;
    assert_eq!(
        result(&response)["attention"].as_array().unwrap().len(),
        1,
        "{response:#?}"
    );
    let response = rpc(
        &runtime,
        "mobkit/workgraph/attention/list",
        json!({ "status": { "state": "paused" } }),
    )
    .await;
    assert_eq!(
        result(&response)["attention"].as_array().unwrap().len(),
        1,
        "{response:#?}"
    );

    // Unknown strings are a params error naming the vocabulary.
    let response = rpc(
        &runtime,
        "mobkit/workgraph/attention/list",
        json!({ "status": "everything" }),
    )
    .await;
    assert_eq!(error_code(&response), -32602, "{response:#?}");
    assert!(
        response["error"]["message"]
            .as_str()
            .unwrap()
            .contains("active"),
        "{response:#?}"
    );
    runtime.mob_handle().stop().await.expect("stop");
}

/// Round-2 finding K: upstream turn-overlay resolution lists attention only
/// in the default namespace, so goals/bindings filed anywhere else are
/// silently inert. Goal/attention methods must reject a non-default
/// namespace; item-level methods keep passthrough.
#[tokio::test(flavor = "multi_thread")]
async fn non_default_namespace_is_rejected_on_goal_and_attention_methods() {
    let runtime = build_runtime().await;
    let cases: &[(&str, Value)] = &[
        (
            "mobkit/workgraph/goal/create",
            json!({
                "title": "stranded goal",
                "target": { "kind": "identity", "identity": "helper" },
                "namespace": "sidecar",
            }),
        ),
        (
            "mobkit/workgraph/attention/list",
            json!({ "namespace": "sidecar" }),
        ),
        (
            "mobkit/workgraph/attention/pause",
            json!({ "binding_id": "b-1", "expected_revision": 0, "namespace": "sidecar" }),
        ),
        (
            "mobkit/workgraph/attention/resume",
            json!({ "binding_id": "b-1", "expected_revision": 0, "namespace": "sidecar" }),
        ),
        (
            "mobkit/workgraph/attention/reassign",
            json!({
                "binding_id": "b-1",
                "expected_revision": 0,
                "target": { "kind": "identity", "identity": "helper" },
                "namespace": "sidecar",
            }),
        ),
        (
            "mobkit/workgraph/policy/escalate",
            json!({
                "binding_id": "b-1",
                "id": "work_1",
                "expected_revision": 0,
                "completion_policy": { "kind": "host_confirmed" },
                "namespace": "sidecar",
            }),
        ),
    ];
    for (method, params) in cases {
        let response = rpc(&runtime, method, params.clone()).await;
        assert_eq!(error_code(&response), -32602, "{method}: {response:#?}");
        assert!(
            response["error"]["message"]
                .as_str()
                .unwrap()
                .contains("default namespace"),
            "{method} must explain the overlay restriction: {response:#?}"
        );
    }

    // Spelling the default namespace explicitly stays accepted.
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/create",
        json!({
            "title": "explicit default",
            "target": { "kind": "identity", "identity": "helper" },
            "namespace": "default",
        }),
    )
    .await;
    assert!(response["error"].is_null(), "{response:#?}");

    // Item-level methods keep namespace passthrough.
    let response = rpc(
        &runtime,
        "mobkit/workgraph/create",
        json!({ "title": "namespaced item", "namespace": "sidecar" }),
    )
    .await;
    assert!(response["error"].is_null(), "{response:#?}");
    assert_eq!(result(&response)["item"]["namespace"], json!("sidecar"));
    runtime.mob_handle().stop().await.expect("stop");
}

/// Adversarial finding F11: reassign of a non-coordinate binding can never
/// succeed on meerkat 0.7.23 (only coordinate mode derives the required
/// `derived_from` link authority), and the raw upstream denial is a generic
/// invalid-input. The RPC must name the binding's mode and the restriction.
/// The coordinate-mode success path is covered by
/// `attention_reassign_injects_witness_server_side`.
#[tokio::test(flavor = "multi_thread")]
async fn reassign_of_non_coordinate_binding_names_the_mode_restriction() {
    let runtime = build_runtime().await;
    // Default mode is pursue.
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/create",
        json!({
            "title": "pursue goal",
            "target": { "kind": "identity", "identity": "helper" },
        }),
    )
    .await;
    let goal = result(&response).clone();
    let binding_id = goal["attention"]["binding_id"]
        .as_str()
        .unwrap()
        .to_string();
    let binding_revision = goal["attention"]["machine_state"]["revision"]
        .as_u64()
        .unwrap();

    let response = rpc(
        &runtime,
        "mobkit/workgraph/attention/reassign",
        json!({
            "binding_id": binding_id,
            "expected_revision": binding_revision,
            "target": { "kind": "identity", "identity": "backup" },
        }),
    )
    .await;
    assert_eq!(error_code(&response), -32000, "{response:#?}");
    assert_eq!(response["error"]["data"]["kind"], json!("workgraph_error"));
    let detail = response["error"]["data"]["detail"].as_str().unwrap();
    assert!(
        detail.contains(&binding_id),
        "must name the binding: {detail}"
    );
    assert!(
        detail.contains("'pursue' mode"),
        "must name the binding's mode: {detail}"
    );
    assert!(
        detail.contains("coordinate"),
        "must name the mode restriction: {detail}"
    );
    runtime.mob_handle().stop().await.expect("stop");
}

#[tokio::test(flavor = "multi_thread")]
async fn policy_escalate_injects_witness_server_side() {
    let runtime = build_runtime().await;
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/create",
        json!({
            "title": "tighten me",
            "target": { "kind": "identity", "identity": "helper" },
        }),
    )
    .await;
    let goal = result(&response).clone();
    let binding_id = goal["attention"]["binding_id"]
        .as_str()
        .unwrap()
        .to_string();
    let item_id = goal["item"]["id"].as_str().unwrap().to_string();
    let item_revision = goal["item"]["revision"].as_u64().unwrap();

    // Forged witness rejected.
    let response = rpc(
        &runtime,
        "mobkit/workgraph/policy/escalate",
        json!({
            "binding_id": binding_id,
            "id": item_id,
            "expected_revision": item_revision,
            "completion_policy": { "kind": "host_confirmed" },
            "authority_projection": { "forged": true },
        }),
    )
    .await;
    assert_eq!(error_code(&response), -32602);

    // Server-side witness: SelfAttest → HostConfirmed is a monotonic tighten.
    let response = rpc(
        &runtime,
        "mobkit/workgraph/policy/escalate",
        json!({
            "binding_id": binding_id,
            "id": item_id,
            "expected_revision": item_revision,
            "completion_policy": { "kind": "host_confirmed" },
        }),
    )
    .await;
    let item = result(&response)["item"].clone();
    assert_eq!(item["completion_policy"]["kind"], json!("host_confirmed"));
    runtime.mob_handle().stop().await.expect("stop");
}

#[tokio::test(flavor = "multi_thread")]
async fn goal_confirm_requires_principal_for_principal_confirmed_policy() {
    let runtime = build_runtime().await;
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/create",
        json!({
            "title": "operator sign-off",
            "target": { "kind": "identity", "identity": "helper" },
            "completion_policy": { "kind": "principal_confirmed" },
        }),
    )
    .await;
    let goal = result(&response).clone();
    let binding_id = goal["attention"]["binding_id"].as_str().unwrap();
    let item_revision = goal["item"]["revision"].as_u64().unwrap();

    // The unified stdin surface has no wire principal to promote, so a
    // principal-confirmed policy cannot be confirmed here.
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/confirm",
        json!({ "binding_id": binding_id, "expected_revision": item_revision }),
    )
    .await;
    assert_eq!(error_code(&response), -32602, "{response:#?}");
    assert!(
        response["error"]["message"]
            .as_str()
            .unwrap()
            .contains("principal"),
        "{response:#?}"
    );

    // Reserved confirmation classifications cannot be smuggled in evidence.
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/confirm",
        json!({
            "binding_id": binding_id,
            "expected_revision": item_revision,
            "evidence": {
                "kind": "confirmation",
                "id": "smuggle",
                "confirmation_kind": "host_confirmation",
            },
        }),
    )
    .await;
    assert_eq!(error_code(&response), -32602, "{response:#?}");
    runtime.mob_handle().stop().await.expect("stop");
}

// ---------------------------------------------------------------------------
// Console surface
// ---------------------------------------------------------------------------

fn trusted_oidc() -> TrustedOidcRuntimeConfig {
    // HS256 tokens are only honored for development (`.localhost`) issuers.
    TrustedOidcRuntimeConfig {
        discovery_json:
            r#"{"issuer":"https://trusted.mobkit.localhost","jwks_uri":"https://trusted.mobkit.localhost/.well-known/jwks.json"}"#
                .to_string(),
        jwks_json: r#"{"keys":[{"kid":"kid-current","kty":"oct","alg":"HS256","k":"cGhhc2U3LXRydXN0ZWQtY3VycmVudC1zZWNyZXQ"}]}"#
            .to_string(),
        audience: "meerkat-console".to_string(),
    }
}

fn decision_state(require_app_auth: bool, read_only: bool) -> meerkat_mobkit::RuntimeDecisionState {
    build_runtime_decision_state(RuntimeDecisionInputs {
        bigquery: BigQueryNaming {
            dataset: "workgraph_dataset".to_string(),
            table: "workgraph_table".to_string(),
        },
        trusted_mobkit_toml: r#"
[[modules]]
id = "router"
command = "router-bin"
args = []
restart_policy = "always"
"#
        .to_string(),
        auth: AuthPolicy {
            default_provider: meerkat_mobkit::AuthProvider::GoogleOAuth,
            email_allowlist: vec!["alice@example.test".to_string()],
        },
        trusted_oidc: trusted_oidc(),
        console: ConsolePolicy {
            require_app_auth,
            read_only,
            ..ConsolePolicy::default()
        },
        ops: RuntimeOpsPolicy::default(),
        release_metadata_json: include_str!("../assets/release-targets.json").to_string(),
    })
    .expect("decision state builds")
}

fn sign_hs256(payload: Value, secret: &str, kid: &str) -> String {
    let header = json!({"alg":"HS256","typ":"JWT","kid":kid});
    let header_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header).expect("encode header"));
    let payload_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&payload).expect("encode claims"));
    let signing_input = format!("{header_b64}.{payload_b64}");
    let mut mac = HmacSha256::new_from_slice(secret.as_bytes()).expect("hmac init");
    mac.update(signing_input.as_bytes());
    let signature_b64 = URL_SAFE_NO_PAD.encode(mac.finalize().into_bytes());
    format!("{signing_input}.{signature_b64}")
}

fn alice_bearer() -> String {
    sign_hs256(
        json!({
            "sub": "alice@example.test",
            "email": "alice@example.test",
            "provider": "google_oauth",
            "iss": "https://trusted.mobkit.localhost",
            "aud": "meerkat-console",
            "exp": 4_000_000_000_u64,
        }),
        "phase7-trusted-current-secret",
        "kid-current",
    )
}

async fn console_rpc_with_bearer(
    app: &axum::Router,
    method: &str,
    params: Value,
    bearer: Option<&str>,
) -> Value {
    let payload = json!({
        "jsonrpc": "2.0",
        "id": "console-wg",
        "method": method,
        "params": params,
    });
    let mut request = Request::builder()
        .method("POST")
        .uri("/console/rpc")
        .header(header::CONTENT_TYPE, "application/json");
    if let Some(bearer) = bearer {
        request = request.header(header::AUTHORIZATION, format!("Bearer {bearer}"));
    }
    let response = app
        .clone()
        .oneshot(
            request
                .body(Body::from(payload.to_string()))
                .expect("request"),
        )
        .await
        .expect("console rpc response");
    // 200 for dispatched calls, 401 for the auth-door rejection — both carry
    // a JSON-RPC body the callers assert on.
    assert!(
        response.status() == StatusCode::OK || response.status() == StatusCode::UNAUTHORIZED,
        "unexpected console rpc status: {}",
        response.status()
    );
    let body = to_bytes(response.into_body(), 1024 * 1024)
        .await
        .expect("body");
    serde_json::from_slice(&body).expect("console rpc json")
}

async fn console_rpc(app: &axum::Router, method: &str, params: Value) -> Value {
    console_rpc_with_bearer(app, method, params, None).await
}

async fn console_experience(app: &axum::Router) -> Value {
    let response = app
        .clone()
        .oneshot(
            Request::builder()
                .method("GET")
                .uri("/console/experience")
                .body(Body::empty())
                .expect("experience request"),
        )
        .await
        .expect("experience response");
    assert_eq!(response.status(), StatusCode::OK);
    let body = to_bytes(response.into_body(), 1024 * 1024)
        .await
        .expect("experience body");
    serde_json::from_slice(&body).expect("experience json")
}

fn workgraph_view_only_config() -> AccessControlConfig {
    AccessControlConfig {
        enabled: true,
        admins: vec!["root@example.test".to_string()],
        groups: BTreeMap::new(),
        rules: vec![
            AccessRule {
                id: "everyone-views-agents".to_string(),
                actions: vec!["agent.view".to_string()],
                ..AccessRule::default()
            },
            AccessRule {
                id: "everyone-views-workgraph".to_string(),
                actions: vec!["workgraph.view".to_string()],
                ..AccessRule::default()
            },
        ],
    }
}

fn workgraph_manage_config() -> AccessControlConfig {
    let mut config = workgraph_view_only_config();
    config.rules.push(AccessRule {
        id: "everyone-manages-workgraph".to_string(),
        actions: vec!["workgraph.manage".to_string()],
        ..AccessRule::default()
    });
    config
}

#[tokio::test(flavor = "multi_thread")]
async fn console_dispatch_and_capabilities() {
    let runtime = build_runtime().await;
    let app = runtime.build_reference_app_router(decision_state(false, false));

    let caps = console_rpc(&app, "mobkit/capabilities", json!({})).await;
    assert_eq!(caps["result"]["workgraph"], json!(true));
    let methods = caps["result"]["methods"].to_string();
    assert!(methods.contains("mobkit/workgraph/snapshot"));
    assert!(methods.contains("mobkit/workgraph/goal/create"));

    let created = console_rpc(
        &app,
        "mobkit/workgraph/create",
        json!({ "title": "console item" }),
    )
    .await;
    assert!(created["error"].is_null(), "{created:#?}");
    assert_eq!(created["result"]["item"]["title"], json!("console item"));

    let snapshot = console_rpc(&app, "mobkit/workgraph/snapshot", json!({})).await;
    assert_eq!(
        snapshot["result"]["items"].as_array().unwrap().len(),
        1,
        "{snapshot:#?}"
    );

    // Experience: no access control → affordances mirror availability.
    let experience = console_experience(&app).await;
    assert_eq!(
        experience["workgraph"],
        json!({ "available": true, "can_view": true, "can_manage": true })
    );
    runtime.mob_handle().stop().await.expect("stop");
}

#[tokio::test(flavor = "multi_thread")]
async fn console_read_only_blocks_workgraph_mutations() {
    let runtime = build_runtime().await;
    let app = runtime.build_reference_app_router(decision_state(false, true));

    let denied = console_rpc(&app, "mobkit/workgraph/create", json!({ "title": "nope" })).await;
    assert_eq!(denied["error"]["code"], json!(-32010), "{denied:#?}");
    assert_eq!(denied["error"]["data"]["kind"], json!("read_only"));

    // Reads still work.
    let snapshot = console_rpc(&app, "mobkit/workgraph/snapshot", json!({})).await;
    assert!(snapshot["error"].is_null(), "{snapshot:#?}");

    // Capabilities advertise only the read set.
    let caps = console_rpc(&app, "mobkit/capabilities", json!({})).await;
    let methods = caps["result"]["methods"].to_string();
    assert!(methods.contains("mobkit/workgraph/snapshot"));
    assert!(!methods.contains("mobkit/workgraph/goal/create"));
    runtime.mob_handle().stop().await.expect("stop");
}

#[tokio::test(flavor = "multi_thread")]
async fn console_abac_gates_view_and_manage() {
    let runtime = build_runtime().await;

    // View-only grants: reads pass, mutations are access-denied, and the
    // capability list strips the mutate set.
    let controller = AccessController::new(workgraph_view_only_config()).expect("controller");
    {
        // set_access_controller needs &mut; rebuild per grant set instead.
        let mut runtime_ref = runtime;
        runtime_ref.set_access_controller(controller.clone());
        let app = runtime_ref.build_reference_app_router(decision_state(false, false));

        let snapshot = console_rpc(&app, "mobkit/workgraph/snapshot", json!({})).await;
        assert!(snapshot["error"].is_null(), "{snapshot:#?}");

        let denied = console_rpc(
            &app,
            "mobkit/workgraph/create",
            json!({ "title": "denied" }),
        )
        .await;
        assert_eq!(denied["error"]["code"], json!(-32030), "{denied:#?}");
        assert_eq!(denied["error"]["data"]["kind"], json!("access_denied"));
        assert_eq!(denied["error"]["data"]["action"], json!("workgraph.manage"));

        let caps = console_rpc(&app, "mobkit/capabilities", json!({})).await;
        let methods = caps["result"]["methods"].to_string();
        assert!(methods.contains("mobkit/workgraph/snapshot"));
        assert!(
            !methods.contains("mobkit/workgraph/create"),
            "grant intersection must strip unusable mutate methods: {methods}"
        );

        let experience = console_experience(&app).await;
        assert_eq!(
            experience["workgraph"],
            json!({ "available": true, "can_view": true, "can_manage": false })
        );

        // Manage grants unlock mutations end to end.
        controller
            .replace_config(workgraph_manage_config())
            .expect("upgrade grants");
        let allowed = console_rpc(
            &app,
            "mobkit/workgraph/create",
            json!({ "title": "allowed" }),
        )
        .await;
        assert!(allowed["error"].is_null(), "{allowed:#?}");

        let experience = console_experience(&app).await;
        assert_eq!(experience["workgraph"]["can_manage"], json!(true));

        runtime_ref.mob_handle().stop().await.expect("stop");
    }
}

#[test]
fn workgraph_actions_are_valid_vocabulary_and_admins_bypass() {
    let config = AccessControlConfig {
        enabled: true,
        admins: vec!["root@example.test".to_string()],
        groups: BTreeMap::new(),
        rules: vec![AccessRule {
            id: "wg".to_string(),
            actions: vec![
                "workgraph.view".to_string(),
                "workgraph.manage".to_string(),
                "workgraph.*".to_string(),
            ],
            subjects: vec!["alice@example.test".to_string()],
            ..AccessRule::default()
        }],
    };
    validate_access_config(&config).expect("workgraph actions validate");

    let controller = AccessController::new(config).expect("controller");
    let admin = controller.view_for_subject(Some("root@example.test"));
    assert!(admin.allows("workgraph.view"));
    assert!(admin.allows("workgraph.manage"));
    let alice = controller.view_for_subject(Some("alice@example.test"));
    assert!(alice.allows("workgraph.manage"));
    let outsider = controller.view_for_subject(Some("carol@example.test"));
    assert!(!outsider.allows("workgraph.view"), "deny by default");
}

#[tokio::test(flavor = "multi_thread")]
async fn experience_reports_workgraph_unavailable_without_service() {
    let (_dir, runtime) = build_runtime_without_workgraph().await;
    let app = runtime.build_reference_app_router(decision_state(false, false));
    let experience = console_experience(&app).await;
    assert_eq!(
        experience["workgraph"],
        json!({ "available": false, "can_view": false, "can_manage": false })
    );

    let caps = console_rpc(&app, "mobkit/capabilities", json!({})).await;
    assert_eq!(caps["result"]["workgraph"], json!(false));
    assert!(!caps["result"]["methods"].to_string().contains("workgraph"));

    let response = console_rpc(&app, "mobkit/workgraph/snapshot", json!({})).await;
    assert_eq!(response["error"]["code"], json!(-32041), "{response:#?}");
    runtime.mob_handle().stop().await.expect("stop");
}

#[tokio::test(flavor = "multi_thread")]
async fn console_goal_confirm_promotes_authenticated_principal() {
    let runtime = build_runtime().await;

    // Host-trusted create of a principal-confirmed goal via the stdin surface.
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/create",
        json!({
            "title": "needs alice",
            "target": { "kind": "identity", "identity": "helper" },
            "completion_policy": { "kind": "principal_confirmed" },
        }),
    )
    .await;
    let goal = result(&response).clone();
    let binding_id = goal["attention"]["binding_id"]
        .as_str()
        .unwrap()
        .to_string();
    let item_revision = goal["item"]["revision"].as_u64().unwrap();

    let app = runtime.build_reference_app_router(decision_state(true, false));
    let bearer = alice_bearer();

    // Unauthenticated confirm is rejected at the console door.
    let unauthenticated = console_rpc(
        &app,
        "mobkit/workgraph/goal/confirm",
        json!({ "binding_id": binding_id, "expected_revision": item_revision }),
    )
    .await;
    assert!(
        unauthenticated["error"]["message"]
            .as_str()
            .unwrap_or_default()
            .contains("unauthorized"),
        "{unauthenticated:#?}"
    );

    // Alice's authenticated confirm is promoted to the trusted principal.
    let confirmed = console_rpc_with_bearer(
        &app,
        "mobkit/workgraph/goal/confirm",
        json!({ "binding_id": binding_id, "expected_revision": item_revision }),
        Some(&bearer),
    )
    .await;
    assert!(confirmed["error"].is_null(), "{confirmed:#?}");
    let evidence = confirmed["result"]["item"]["evidence_refs"][0].clone();
    assert_eq!(
        evidence["confirmation_kind"],
        json!("principal_confirmation")
    );
    assert_eq!(
        evidence["confirming_owner_key"],
        json!({ "kind": "principal", "id": "alice@example.test" })
    );
    runtime.mob_handle().stop().await.expect("stop");
}

// ---------------------------------------------------------------------------
// meerkat 0.7.25: attention prune (ask 24) + break-glass reassign (ask 23)
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread")]
async fn attention_prune_removes_terminal_bindings() {
    let runtime = build_runtime().await;
    // Coordinate goal, then reassign: the previous binding goes superseded —
    // exactly the monotonically-growing row class prune exists for.
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/create",
        json!({
            "title": "prunable",
            "target": { "kind": "identity", "identity": "helper" },
            "mode": "coordinate",
        }),
    )
    .await;
    let goal = result(&response).clone();
    let binding_id = goal["attention"]["binding_id"].as_str().unwrap();
    let binding_revision = goal["attention"]["machine_state"]["revision"]
        .as_u64()
        .unwrap();
    let response = rpc(
        &runtime,
        "mobkit/workgraph/attention/reassign",
        json!({
            "binding_id": binding_id,
            "expected_revision": binding_revision,
            "target": { "kind": "identity", "identity": "backup" },
        }),
    )
    .await;
    assert_eq!(
        result(&response)["previous"]["status"]["state"],
        json!("superseded")
    );

    let response = rpc(&runtime, "mobkit/workgraph/attention/prune", json!({})).await;
    assert_eq!(result(&response)["pruned"], json!(1), "{response:#?}");

    // The superseded row is gone; the live binding survives. The event
    // stream (audit history) is untouched by prune.
    let response = rpc(&runtime, "mobkit/workgraph/attention/list", json!({})).await;
    let bindings = result(&response)["attention"].as_array().unwrap().clone();
    assert_eq!(bindings.len(), 1, "{bindings:#?}");
    assert_eq!(bindings[0]["status"]["state"], json!("active"));

    // Idempotent: nothing terminal left.
    let response = rpc(&runtime, "mobkit/workgraph/attention/prune", json!({})).await;
    assert_eq!(result(&response)["pruned"], json!(0));
    runtime.mob_handle().stop().await.expect("stop");
}

#[tokio::test(flavor = "multi_thread")]
async fn break_glass_reassign_does_not_exist_on_the_stdin_surface() {
    let runtime = build_runtime().await;
    let response = rpc(
        &runtime,
        "mobkit/workgraph/attention/break_glass_reassign",
        json!({
            "binding_id": "wab-000000000000000000000000000000",
            "expected_revision": 0,
            "target": { "kind": "identity", "identity": "backup" },
            "reason": "should never be dispatched",
        }),
    )
    .await;
    assert_eq!(error_code(&response), -32601, "{response:#?}");
    // The stdin capabilities catalog does not advertise it either.
    let caps = rpc(&runtime, "mobkit/capabilities", json!({})).await;
    let methods = result(&caps)["methods"].as_array().unwrap().clone();
    assert!(
        !methods
            .iter()
            .any(|m| m == "mobkit/workgraph/attention/break_glass_reassign"),
        "console-only method leaked into the stdin catalog"
    );
    runtime.mob_handle().stop().await.expect("stop");
}

/// Ask 23 end-to-end: a PURSUE-mode binding (which the agent-plane reassign
/// refuses — only coordinate mode derives the authority) is recovered by an
/// authenticated console operator through the break-glass seam, with the
/// principal recorded server-side and the reason mandatory.
#[tokio::test(flavor = "multi_thread")]
async fn console_break_glass_reassign_recovers_pursue_binding_with_audit() {
    let runtime = build_runtime().await;
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/create",
        json!({
            "title": "stuck on a wedged pursuer",
            "target": { "kind": "identity", "identity": "helper" },
        }),
    )
    .await;
    let goal = result(&response).clone();
    let binding_id = goal["attention"]["binding_id"]
        .as_str()
        .unwrap()
        .to_string();
    let binding_revision = goal["attention"]["machine_state"]["revision"]
        .as_u64()
        .unwrap();

    let app = runtime.build_reference_app_router(decision_state(true, false));
    let bearer = alice_bearer();

    // Reason is mandatory.
    let response = console_rpc_with_bearer(
        &app,
        "mobkit/workgraph/attention/break_glass_reassign",
        json!({
            "binding_id": binding_id,
            "expected_revision": binding_revision,
            "target": { "kind": "identity", "identity": "backup" },
        }),
        Some(&bearer),
    )
    .await;
    assert_eq!(response["error"]["code"], json!(-32602), "{response:#?}");
    assert!(
        response["error"]["message"]
            .as_str()
            .unwrap()
            .contains("reason"),
        "{response:#?}"
    );

    // The principal is never a wire parameter.
    let response = console_rpc_with_bearer(
        &app,
        "mobkit/workgraph/attention/break_glass_reassign",
        json!({
            "binding_id": binding_id,
            "expected_revision": binding_revision,
            "target": { "kind": "identity", "identity": "backup" },
            "reason": "operator recovery",
            "principal": "mallory@example.test",
        }),
        Some(&bearer),
    )
    .await;
    assert_eq!(response["error"]["code"], json!(-32602), "{response:#?}");

    // The authenticated operator's break-glass move succeeds on a binding
    // the agent-plane reassign would refuse for mode.
    let response = console_rpc_with_bearer(
        &app,
        "mobkit/workgraph/attention/break_glass_reassign",
        json!({
            "binding_id": binding_id,
            "expected_revision": binding_revision,
            "target": { "kind": "identity", "identity": "backup" },
            "reason": "pursuer wedged; no coordinator holds authority",
        }),
        Some(&bearer),
    )
    .await;
    assert!(response["error"].is_null(), "{response:#?}");
    assert_eq!(
        response["result"]["previous"]["status"]["state"],
        json!("superseded")
    );
    assert_eq!(
        response["result"]["attention"]["target"]["owner_key"]["id"],
        json!("mob/workgraph-rpc-mob/agent/backup")
    );

    // The audit trail carries the authenticated principal and the reason.
    let events = rpc(&runtime, "mobkit/workgraph/events", json!({ "limit": 200 })).await;
    let events_json = serde_json::to_string(result(&events)).expect("events json");
    assert!(events_json.contains("alice@example.test"), "{events_json}");
    assert!(
        events_json.contains("pursuer wedged"),
        "reason missing from the audit stream: {events_json}"
    );
    runtime.mob_handle().stop().await.expect("stop");
}

/// Without an authenticated console principal there is no one to attribute
/// the break-glass move to: the method refuses (access_denied) instead of
/// minting an anonymous audit row.
#[tokio::test(flavor = "multi_thread")]
async fn console_break_glass_reassign_requires_authenticated_principal() {
    let runtime = build_runtime().await;
    let response = rpc(
        &runtime,
        "mobkit/workgraph/goal/create",
        json!({
            "title": "anonymous operators need not apply",
            "target": { "kind": "identity", "identity": "helper" },
        }),
    )
    .await;
    let goal = result(&response).clone();

    // Console with app auth DISABLED: requests dispatch, but there is no
    // authenticated principal.
    let app = runtime.build_reference_app_router(decision_state(false, false));
    let response = console_rpc(
        &app,
        "mobkit/workgraph/attention/break_glass_reassign",
        json!({
            "binding_id": goal["attention"]["binding_id"],
            "expected_revision": goal["attention"]["machine_state"]["revision"],
            "target": { "kind": "identity", "identity": "backup" },
            "reason": "no principal available",
        }),
    )
    .await;
    assert_eq!(response["error"]["code"], json!(-32030), "{response:#?}");
    assert_eq!(response["error"]["data"]["kind"], json!("access_denied"));
    runtime.mob_handle().stop().await.expect("stop");
}