greentic-aw-runtime 1.2.2

Enterprise Agentic Worker runtime — Plan-Act-Observe loop, Redis state, tool dispatch via greentic-ext-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
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
//! Tool resolution + dispatch helpers.
//!
//! `ExtensionRuntime::invoke_tool` is a synchronous `fn` performing
//! Wasmtime WASM dispatch (CPU-bound, may block seconds). Every call
//! site MUST wrap it in `tokio::task::spawn_blocking` (spec §5.3). This
//! module calls it for agent tool dispatch; `llm_extension::RuntimeInvoker`
//! also calls it (likewise wrapped) when the LLM runs through an extension.
//!
//! Each tool call is recorded in Redis by `tool_call_id` BEFORE the
//! result is committed so a state-save failure cannot cause a
//! double-dispatch on the next `step()` (idempotency ledger).

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use greentic_ext_runtime::ExtensionRuntime;
use greentic_ext_runtime::host_ports::HostCallContext;
use redis::AsyncCommands;
use redis::aio::ConnectionManager;
use serde::{Deserialize, Serialize};

use crate::a2a_source::{A2aContinuations, A2aToolCatalog};
use crate::component_source::ComponentToolCatalog;
use crate::config::ToolRef;
use crate::error::{AgentError, StateError};
use crate::flow_source::FlowToolCatalog;
use crate::kv::AwKv;
use crate::llm::LlmToolSchema;
use crate::mcp_source::McpToolCatalog;
use crate::playbook_source::PlaybookToolCatalog;
use crate::sorla_source::SorlaToolCatalog;
use crate::state::ToolCallRecord;
use crate::tenant::TenantContext;

/// Append an author `usage_note` to a resolved tool description. A `None` or
/// whitespace-only note is a no-op (no trailing whitespace, no empty block).
fn with_usage_note(description: String, note: &Option<String>) -> String {
    match note {
        Some(n) if !n.trim().is_empty() => format!("{description}\n\n{}", n.trim()),
        _ => description,
    }
}

/// Whether the agent may call this tool — exact (extension_id, tool_name) match.
pub fn is_tool_allowed(call: &ToolCallRecord, allowed: &[ToolRef]) -> bool {
    allowed
        .iter()
        .any(|t| t.extension_id == call.extension_id && t.tool_name == call.tool_name)
}

/// Map allow-listed tools to LLM-facing schemas via
/// `ExtensionRuntime::list_tools`. Tools whose extension is not loaded,
/// or that the extension doesn't expose, are logged and skipped (the
/// LLM simply won't see them). `input_schema_json` is parsed into a
/// JSON Value for the LLM tool parameters; on parse failure an empty
/// object schema is used.
///
/// Tools whose `extension_id` starts with `"mcp:"` are resolved from the
/// per-tenant [`McpToolCatalog`] (`mcp`) instead of the extension runtime: the
/// suffix after `"mcp:"` is the MCP `server_id`, and the catalog supplies the
/// LLM-facing `description`/`parameters`. When the catalog has no entry, the
/// ref's own `description`/`input_schema` are used — the schema the pack's
/// `AgentConfig` snapshotted at authoring time — so a deployed runner with no
/// admin credentials still advertises the tool. The catalog WINS whenever it has
/// an entry: it was probed from the live server this run. An mcp ref with
/// neither is logged and dropped, mirroring the extension-runtime "tool not
/// found" path.
///
/// Tools whose `extension_id` starts with `"component:"` are resolved the same
/// way from the per-tenant [`ComponentToolCatalog`] (`components`): the suffix
/// is the `component_ref` and `tool_name` the operation, and the catalog
/// supplies the operation's `description`/`parameters`. A `component:` ref with
/// no matching catalog entry (or no catalog) is likewise logged and dropped.
///
/// Tools whose `extension_id` starts with `"sorla:"` are resolved the same way
/// from the per-tenant [`SorlaToolCatalog`] (`sorla`): the suffix is the SoR
/// `pack` and `tool_name` the action, and the catalog supplies the action's
/// `description`/`parameters`. A `sorla:` ref with no matching catalog entry
/// (or no catalog) is likewise logged and dropped.
///
/// Tools whose `extension_id` starts with `"flow:"` are resolved from the
/// per-tenant [`FlowToolCatalog`] (`flows`): the suffix after `"flow:"` is the
/// `flow_ref`, which is the sole key (no operation). The catalog supplies the
/// LLM-facing `description`/`parameters`. A `flow:` ref with no matching catalog
/// entry (or no catalog) is likewise logged and dropped.
///
/// Tools whose `extension_id` starts with `"a2a:"` are resolved from the
/// per-tenant [`A2aToolCatalog`] (`a2a`): the suffix after `"a2a:"` is the
/// `agent_id`. Unlike every other prefix here, description and schema resolve
/// in DIFFERENT directions: the catalog's description wins when present — it
/// was fetched from the agent's own live card this run, the same reasoning as
/// the `mcp:` branch above — but the schema can ONLY come from the `ToolRef`'s
/// own author contract, because an A2A `AgentSkill` carries no input schema at
/// all. A ref with no `input_schema` is dropped regardless of the catalog.
#[allow(clippy::too_many_arguments)]
pub fn list_tools_for_llm(
    ext_runtime: &ExtensionRuntime,
    mcp: Option<&McpToolCatalog>,
    components: Option<&ComponentToolCatalog>,
    flows: Option<&FlowToolCatalog>,
    playbooks: Option<&PlaybookToolCatalog>,
    sorla: Option<&SorlaToolCatalog>,
    a2a: Option<&A2aToolCatalog>,
    allowed: &[ToolRef],
) -> Vec<LlmToolSchema> {
    let mut out = Vec::with_capacity(allowed.len());
    for t in allowed {
        if let Some(server_id) = t.extension_id.strip_prefix("mcp:") {
            let entry = mcp.and_then(|c| c.tool_entry(server_id, &t.tool_name));
            // Catalog FIRST, the author contract second — deliberately the
            // OPPOSITE order from the `flow:` branch below. A catalog entry was
            // probed from the live server this run, whereas `ToolRef` carries a
            // schema snapshotted into the pack at authoring time; preferring the
            // pack would downgrade every deployment that does have a working
            // admin source to a staler schema. The fallback exists so a deployed
            // runner with NO admin credentials still advertises the tool at all
            // instead of dropping it (spec §4.2).
            let description = entry
                .map(|e| e.description.clone())
                .or_else(|| t.description.clone());
            let parameters = entry
                .map(|e| e.parameters.clone())
                .or_else(|| t.input_schema.clone());
            match (description, parameters) {
                (Some(description), Some(parameters)) => out.push(LlmToolSchema {
                    extension_id: t.extension_id.clone(),
                    tool_name: t.tool_name.clone(),
                    description: with_usage_note(description, &t.usage_note),
                    parameters,
                }),
                _ => tracing::warn!(
                    extension = %t.extension_id, tool = %t.tool_name,
                    "mcp tool has neither a catalog entry nor an author contract; \
                     dropping from LLM tool list"
                ),
            }
            continue;
        }
        if let Some(component_ref) = t.extension_id.strip_prefix("component:") {
            match components.and_then(|c| c.tool_entry(component_ref, &t.tool_name)) {
                Some(entry) => out.push(LlmToolSchema {
                    extension_id: t.extension_id.clone(),
                    tool_name: t.tool_name.clone(),
                    description: with_usage_note(entry.description.clone(), &t.usage_note),
                    parameters: entry.parameters.clone(),
                }),
                None => tracing::warn!(
                    extension = %t.extension_id, tool = %t.tool_name,
                    "component tool not found in catalog; dropping from LLM tool list"
                ),
            }
            continue;
        }
        if let Some(pack) = t.extension_id.strip_prefix("sorla:") {
            match sorla.and_then(|c| c.tool_entry(pack, &t.tool_name)) {
                Some(entry) => out.push(LlmToolSchema {
                    extension_id: t.extension_id.clone(),
                    tool_name: t.tool_name.clone(),
                    description: with_usage_note(entry.description.clone(), &t.usage_note),
                    parameters: entry.parameters.clone(),
                }),
                None => tracing::warn!(
                    extension = %t.extension_id, tool = %t.tool_name,
                    "sorla tool not found in catalog; dropping from LLM tool list"
                ),
            }
            continue;
        }
        if let Some(flow_ref) = t.extension_id.strip_prefix("flow:") {
            let entry = flows.and_then(|c| c.tool_entry(flow_ref));
            let description = t
                .description
                .clone()
                .or_else(|| entry.map(|e| e.description.clone()));
            let parameters = t
                .input_schema
                .clone()
                .or_else(|| entry.map(|e| e.parameters.clone()));
            match (description, parameters) {
                (Some(description), Some(parameters)) => out.push(LlmToolSchema {
                    extension_id: t.extension_id.clone(),
                    tool_name: t.tool_name.clone(),
                    description: with_usage_note(description, &t.usage_note),
                    parameters,
                }),
                _ => tracing::warn!(
                    extension = %t.extension_id, tool = %t.tool_name,
                    "flow tool has neither an author contract nor a catalog entry; dropping from LLM tool list"
                ),
            }
            continue;
        }
        if let Some(playbook_id) = t.extension_id.strip_prefix("playbook:") {
            // The CATALOG wins on both fields, which is the `mcp:` precedence
            // rather than the `flow:` one beside it. A playbook's summary and
            // its declared inputs are authored in the same document as its
            // behaviour and are read from the pack this run, while the author
            // contract on the ref is a snapshot taken when the tool was bound —
            // so the document is the fresher statement of what this skill does.
            let entry = playbooks.and_then(|c| c.tool_entry(playbook_id));
            let description = entry
                .map(|e| e.description.clone())
                .or_else(|| t.description.clone());
            let parameters = entry
                .map(|e| e.parameters.clone())
                .or_else(|| t.input_schema.clone());
            match (description, parameters) {
                (Some(description), Some(parameters)) => out.push(LlmToolSchema {
                    extension_id: t.extension_id.clone(),
                    tool_name: t.tool_name.clone(),
                    description: with_usage_note(description, &t.usage_note),
                    parameters,
                }),
                _ => tracing::warn!(
                    extension = %t.extension_id, tool = %t.tool_name,
                    "playbook tool has neither an author contract nor a catalog entry; dropping from LLM tool list"
                ),
            }
            continue;
        }
        if let Some(agent_id) = t.extension_id.strip_prefix("a2a:") {
            // Only a configured agent is a tool at all: dispatch refuses any
            // other, so advertising one would offer the model a call that can
            // only fail. Then the card wins on description — it is the agent's
            // own live statement about itself, as the mcp catalogue is — and
            // the schema can only come from the author contract, since an
            // `AgentSkill` carries none.
            let Some(catalog) = a2a.filter(|c| c.is_configured(agent_id)) else {
                tracing::warn!(
                    extension = %t.extension_id, tool = %t.tool_name,
                    "a2a agent is not configured for this worker; dropping from LLM tool list"
                );
                continue;
            };
            let description = catalog
                .tool_entry(agent_id)
                .map(|e| e.description.clone())
                .or_else(|| t.description.clone());
            match (description, t.input_schema.clone()) {
                (Some(description), Some(parameters)) => out.push(LlmToolSchema {
                    extension_id: t.extension_id.clone(),
                    tool_name: t.tool_name.clone(),
                    description: with_usage_note(description, &t.usage_note),
                    parameters,
                }),
                _ => tracing::warn!(
                    extension = %t.extension_id, tool = %t.tool_name,
                    "a2a tool has no input schema on its author contract; \
                     dropping from LLM tool list"
                ),
            }
            continue;
        }
        match ext_runtime.list_tools(&t.extension_id) {
            Ok(defs) => {
                if let Some(def) = defs.into_iter().find(|d| d.name == t.tool_name) {
                    let parameters: serde_json::Value = serde_json::from_str(
                        &def.input_schema_json,
                    )
                    .unwrap_or_else(|_| serde_json::json!({"type": "object", "properties": {}}));
                    out.push(LlmToolSchema {
                        extension_id: t.extension_id.clone(),
                        tool_name: t.tool_name.clone(),
                        description: with_usage_note(def.description, &t.usage_note),
                        parameters,
                    });
                } else {
                    tracing::warn!(
                        extension = %t.extension_id, tool = %t.tool_name,
                        "tool not found in extension; dropping from LLM tool list"
                    );
                }
            }
            Err(e) => {
                tracing::warn!(
                    extension = %t.extension_id, error = %e,
                    "extension list_tools failed; skipping"
                );
            }
        }
    }
    out
}

/// A tool an agent declared that will NOT be visible to the LLM, with a
/// human-readable reason. Produced by [`missing_tools`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MissingTool {
    pub extension_id: String,
    pub tool_name: String,
    pub reason: String,
}

/// Preflight check: of the `allowed` tools an agent declares, return those that
/// cannot be resolved to a live LLM schema, each with a reason.
///
/// This mirrors the resolution logic in [`list_tools_for_llm`] exactly, but
/// reports failures instead of dropping them silently. Callers use it to warn
/// the operator at startup — otherwise an agent whose tools all failed to load
/// runs with an empty tool set and hallucinates tool results.
#[allow(clippy::too_many_arguments)]
pub fn missing_tools(
    ext_runtime: &ExtensionRuntime,
    mcp: Option<&McpToolCatalog>,
    components: Option<&ComponentToolCatalog>,
    flows: Option<&FlowToolCatalog>,
    playbooks: Option<&PlaybookToolCatalog>,
    sorla: Option<&SorlaToolCatalog>,
    a2a: Option<&A2aToolCatalog>,
    allowed: &[ToolRef],
) -> Vec<MissingTool> {
    let mut missing = Vec::new();
    for t in allowed {
        if let Some(server_id) = t.extension_id.strip_prefix("mcp:") {
            // Mirrors `list_tools_for_llm`'s mcp branch exactly: a catalog entry
            // resolves the tool, and so does a complete author contract
            // (description AND input schema) on the `ToolRef` itself. Without
            // this second arm `preflight_warn_tools` would warn loudly about a
            // pack-schema'd tool that now works.
            let resolvable = mcp
                .and_then(|c| c.tool_entry(server_id, &t.tool_name))
                .is_some()
                || (t.description.is_some() && t.input_schema.is_some());
            if !resolvable {
                missing.push(MissingTool {
                    extension_id: t.extension_id.clone(),
                    tool_name: t.tool_name.clone(),
                    reason: "MCP tool not found in the tenant catalog, and the agent config \
                             carries no description + input schema for it"
                        .to_string(),
                });
            }
            continue;
        }
        if let Some(component_ref) = t.extension_id.strip_prefix("component:") {
            if components
                .and_then(|c| c.tool_entry(component_ref, &t.tool_name))
                .is_none()
            {
                missing.push(MissingTool {
                    extension_id: t.extension_id.clone(),
                    tool_name: t.tool_name.clone(),
                    reason: "component tool not found in the catalog".to_string(),
                });
            }
            continue;
        }
        if let Some(pack) = t.extension_id.strip_prefix("sorla:") {
            if sorla
                .and_then(|c| c.tool_entry(pack, &t.tool_name))
                .is_none()
            {
                missing.push(MissingTool {
                    extension_id: t.extension_id.clone(),
                    tool_name: t.tool_name.clone(),
                    reason: "sorla tool not found in the catalog".to_string(),
                });
            }
            continue;
        }
        if let Some(flow_ref) = t.extension_id.strip_prefix("flow:") {
            if flows.and_then(|c| c.tool_entry(flow_ref)).is_none() {
                missing.push(MissingTool {
                    extension_id: t.extension_id.clone(),
                    tool_name: t.tool_name.clone(),
                    reason: "flow tool not found in the catalog".to_string(),
                });
            }
            continue;
        }
        if let Some(playbook_id) = t.extension_id.strip_prefix("playbook:") {
            if playbooks.and_then(|c| c.tool_entry(playbook_id)).is_none() {
                missing.push(MissingTool {
                    extension_id: t.extension_id.clone(),
                    tool_name: t.tool_name.clone(),
                    reason: "playbook tool not found in the catalog".to_string(),
                });
            }
            continue;
        }
        if let Some(agent_id) = t.extension_id.strip_prefix("a2a:") {
            // Mirrors `list_tools_for_llm`'s a2a branch exactly: the agent must
            // be configured; then the description may come from the card OR
            // the author contract, but the schema has only one source.
            let reason = match a2a.filter(|c| c.is_configured(agent_id)) {
                None => Some("a2a agent is not configured for this worker"),
                Some(catalog) => {
                    let described =
                        catalog.tool_entry(agent_id).is_some() || t.description.is_some();
                    (!(described && t.input_schema.is_some())).then_some(
                        "a2a agent card unavailable, or the agent config carries \
                         no input schema for it",
                    )
                }
            };
            if let Some(reason) = reason {
                missing.push(MissingTool {
                    extension_id: t.extension_id.clone(),
                    tool_name: t.tool_name.clone(),
                    reason: reason.to_string(),
                });
            }
            continue;
        }
        match ext_runtime.list_tools(&t.extension_id) {
            Ok(defs) => {
                if !defs.iter().any(|d| d.name == t.tool_name) {
                    missing.push(MissingTool {
                        extension_id: t.extension_id.clone(),
                        tool_name: t.tool_name.clone(),
                        reason: "extension loaded but does not expose this tool".to_string(),
                    });
                }
            }
            Err(e) => {
                missing.push(MissingTool {
                    extension_id: t.extension_id.clone(),
                    tool_name: t.tool_name.clone(),
                    reason: format!("extension failed to load: {e}"),
                });
            }
        }
    }
    missing
}

/// Build a [`HostCallContext`] from the per-step [`TenantContext`].
///
/// The extension host (e.g. the designer's `DesignerLlmBridge`) uses
/// `ctx.tenant` to resolve the LLM provider per-tenant and `ctx.user_email`
/// for optional per-user override (present only in interactive test-chat steps;
/// `None` for autonomous workers).
pub(crate) fn host_ctx_from_tenant(t: &TenantContext) -> HostCallContext {
    HostCallContext {
        tenant: if t.tenant_id.is_empty() {
            None
        } else {
            Some(t.tenant_id.clone())
        },
        user_email: t.user_email.clone(),
    }
}

/// Reserved argument key carrying the session-established caller.
///
/// Host-owned: [`stamp_caller`] OVERWRITES it on every dispatch, so an LLM that
/// writes one into its tool arguments cannot be believed. Same contract as the
/// designer's `_tenant_overlay`, which has shipped on exactly this basis.
pub const CALLER_ARG_KEY: &str = "_caller";

/// Replace `args`' caller block with the one the SESSION established.
///
/// Three properties, and each one is load-bearing:
///
/// 1. **Unconditional.** The key is written on every dispatch, including for an
///    anonymous turn, where it is written as `user_verified: false`. Writing it
///    only when a caller is known would make "anonymous" and "this runtime is
///    too old to say" the same observation — and a tool that cannot tell those
///    apart is a tool that trusts whatever an older runtime left behind.
/// 2. **Overwrite, never merge.** Whatever the model composed under this key is
///    discarded. A merge would let the model contribute fields the host did not
///    set, which is the whole attack: a worker once sent
///    `sub: "user@example.com", principals: ["employee"]` for a caller who had
///    sent neither.
/// 3. **Non-object arguments are left alone.** A tool whose arguments are an
///    array or a scalar has nowhere to put the key, and wrapping them would
///    change the shape the tool declared. It gets no stamp, which reads as
///    "too old to say" — correct, because it is equally unable to receive one.
///
/// ## The version-skew hole this does NOT close
///
/// Trust here rests on the host overwriting the key. A runtime PREDATING this
/// function stamps nothing, so a model-written `_caller` survives to a tool
/// that has learned to trust the key. The contract is therefore: **an absent
/// `_caller` means unverified**, and a tool must not treat a present one as
/// authoritative unless the runtime it runs on is known to stamp. Closing it
/// properly means the tool PULLING identity from a host import rather than
/// receiving it in arguments, which is a WIT change and a rebuild of every
/// extension; this ships the contract without one. Do not describe this as
/// unforgeable — it is unforgeable on a runtime that stamps.
fn stamp_caller(args: &mut serde_json::Value, caller: &crate::tenant::VerifiedCaller) {
    let Some(map) = args.as_object_mut() else {
        return;
    };
    map.insert(
        CALLER_ARG_KEY.to_string(),
        serde_json::to_value(caller).unwrap_or(serde_json::Value::Null),
    );
}

/// Dispatch a single tool call. Wraps the blocking `invoke_tool_ctx` in
/// `tokio::task::spawn_blocking` so the async executor thread is never
/// stalled. Returns the tool result as a JSON Value.
///
/// Calls whose `extension_id` starts with `"mcp:"` route through the
/// per-tenant [`McpToolCatalog`] (`mcp`) instead: the suffix is the MCP
/// `server_id`, and dispatch goes over HTTP via
/// [`crate::mcp_source::dispatch_route`]. An MCP call NEVER yields `Err` — a
/// missing route or remote failure is surfaced as an `{"error": ...}` value so
/// the LLM observes it as a normal tool result.
///
/// Calls whose `extension_id` starts with `"component:"` route through the
/// per-tenant [`ComponentToolCatalog`] (`components`): the suffix is the
/// `component_ref` and dispatch goes to the host component invoker via
/// [`ComponentToolCatalog::dispatch`]. Like the mcp path it NEVER yields `Err`
/// — an unknown operation or a missing catalog becomes an `{"error": ...}`
/// value.
///
/// Calls whose `extension_id` starts with `"sorla:"` route through the
/// per-tenant [`SorlaToolCatalog`] (`sorla`): the suffix is the SoR `pack`
/// and dispatch goes to the host SoRX interact client via
/// [`SorlaToolCatalog::dispatch`]. Like the mcp/component paths it NEVER
/// yields `Err` — an unknown action or a missing catalog becomes an
/// `{"error": ...}` value. Other ids keep the existing blocking WASM path.
///
/// Calls whose `extension_id` starts with `"a2a:"` route through the
/// per-tenant [`A2aToolCatalog`] (`a2a`): the suffix is the `agent_id` and
/// dispatch goes over HTTP via [`A2aToolCatalog::dispatch`], which is
/// attempted even for an agent absent from the catalog (the listing side can
/// still advertise it from the author contract). Like the mcp/component/sorla
/// paths it NEVER yields `Err` — an unknown or unreachable agent becomes an
/// `{"error": ...}` value.
#[allow(clippy::too_many_arguments)]
pub async fn dispatch_tool_call(
    ext_runtime: Arc<ExtensionRuntime>,
    mcp: Option<Arc<McpToolCatalog>>,
    components: Option<Arc<ComponentToolCatalog>>,
    flows: Option<Arc<FlowToolCatalog>>,
    sorla: Option<Arc<SorlaToolCatalog>>,
    a2a: Option<Arc<A2aToolCatalog>>,
    call: ToolCallRecord,
    tenant: &TenantContext,
) -> Result<serde_json::Value, AgentError> {
    dispatch_tool_call_in_conversation(
        ext_runtime,
        mcp,
        components,
        flows,
        // A one-shot dispatch holds no worker, so it narrows no playbook and
        // must offer none: see `playbook_source`'s narrowing rule.
        None,
        sorla,
        a2a,
        call,
        tenant,
        None,
    )
    .await
}

/// What the agent loop's interactive `flow:` dispatch produced.
#[derive(Debug)]
pub(crate) enum FlowToolDispatch {
    /// A tool result, exactly what [`dispatch_tool_call`] would have returned.
    Value(serde_json::Value),
    /// The flow parked on the user; the loop suspends the turn.
    Suspend {
        snapshot: serde_json::Value,
        presentation: serde_json::Value,
    },
}

/// Interactive dispatch for the `flow:` arm ONLY — the one prefix whose tool
/// may park on the user. Every other prefix, and every other caller (graph
/// tool nodes, deep workers, [`dispatch_tool_call`]), keeps the
/// non-interactive path, where a parking flow is an error value.
///
/// `flow_ref` is the call's `extension_id` with the `flow:` prefix stripped.
pub(crate) async fn dispatch_flow_tool_interactive(
    flows: Option<&FlowToolCatalog>,
    flow_ref: &str,
    call: &ToolCallRecord,
) -> FlowToolDispatch {
    let Some(cat) = flows else {
        tracing::warn!(flow = %flow_ref, "flow call has no catalog wired; returning error value");
        return FlowToolDispatch::Value(
            serde_json::json!({ "error": format!("unknown flow tool '{flow_ref}'") }),
        );
    };
    // A nested flow is `.await`ed here, so it inherits the run context; it
    // runs under what the caller's policy grants this binding (shared
    // context, Phase A2). Nothing changes when no context is open.
    let args = call.args.to_string();
    let outcome = crate::run_trace::under_binding(
        &call.extension_id,
        cat.dispatch_interactive(flow_ref, &args),
    )
    .await;
    match outcome {
        crate::flow_source::FlowInvokeOutcome::Completed(value) => FlowToolDispatch::Value(value),
        crate::flow_source::FlowInvokeOutcome::Waiting {
            snapshot,
            presentation,
        } => FlowToolDispatch::Suspend {
            snapshot,
            presentation,
        },
    }
}

/// [`dispatch_tool_call`], plus the conversation's A2A continuations.
///
/// `a2a_continuations` is the ONLY difference. Passing `Some` lets an `a2a:`
/// call resume the remote task this conversation already has open with that
/// agent; passing `None` means "this caller holds no conversation state", so
/// every `a2a:` call opens a fresh remote context — correct for a one-shot
/// dispatch, and exactly what a remote agent asking `input-required` cannot
/// be answered through.
///
/// Split out rather than folded into [`dispatch_tool_call`] so that function
/// keeps its signature: it is `pub`, and greentic-start and
/// greentic-designer pin this crate.
#[allow(clippy::too_many_arguments)]
pub async fn dispatch_tool_call_in_conversation(
    ext_runtime: Arc<ExtensionRuntime>,
    mcp: Option<Arc<McpToolCatalog>>,
    components: Option<Arc<ComponentToolCatalog>>,
    flows: Option<Arc<FlowToolCatalog>>,
    playbooks: Option<Arc<PlaybookToolCatalog>>,
    sorla: Option<Arc<SorlaToolCatalog>>,
    a2a: Option<Arc<A2aToolCatalog>>,
    call: ToolCallRecord,
    tenant: &TenantContext,
    a2a_continuations: Option<&mut A2aContinuations>,
) -> Result<serde_json::Value, AgentError> {
    // Established once, applied to the extension and component arms below —
    // the same arms #760 stamps on develop. Not to the `mcp:` arm: that
    // dispatches over HTTP to a server outside this deployment, and forwarding
    // a caller's identity to a third party is a disclosure decision for whoever
    // configures that server, not a plumbing detail of this one. The `flow:`
    // and `sorla:` arms (research-only) are left unstamped too: a flow's input
    // is flow data, which is exactly the position a caller must not travel
    // through, and SoRX is its own service boundary. The `a2a:` arm is
    // likewise unstamped, for the same reason as `mcp:`: an A2A agent is a
    // third-party server outside this deployment.
    let caller = tenant.caller_or_anonymous();
    if let Some(server_id) = call.extension_id.strip_prefix("mcp:") {
        // `resolve_route` takes the catalog's exact `(server, tool)` entry when
        // it has one and otherwise stamps the tool onto a pack-carried
        // server-level route. An admin-built catalog registers no server-level
        // routes, so its behaviour here is unchanged.
        let value = match mcp
            .as_deref()
            .and_then(|c| c.resolve_route(server_id, &call.tool_name))
        {
            Some(route) => {
                let args = call.args.to_string();
                let scope = match mcp.as_deref().and_then(|c| c.secrets()) {
                    Some(manager) => {
                        crate::mcp_scope::McpCallScope::with_secrets(tenant.clone(), manager)
                    }
                    None => crate::mcp_scope::McpCallScope::new(tenant.clone()),
                };
                crate::mcp_source::dispatch_route(&route, &args, &scope).await
            }
            None => {
                tracing::warn!(
                    server = %server_id,
                    tool = %call.tool_name,
                    "mcp call has no route in the tenant catalog; returning error value"
                );
                // A per-server diagnostic (only the pack path records one) names
                // the real cause; without it a missing credential and an
                // unregistered server are indistinguishable to the operator.
                serde_json::json!({
                    "error": match mcp.as_deref().and_then(|c| c.server_error(server_id)) {
                        Some(detail) => format!(
                            "mcp tool '{}/{}' is unavailable: mcp server '{}' has {detail}",
                            server_id, call.tool_name, server_id
                        ),
                        None => format!("unknown mcp tool '{}/{}'", server_id, call.tool_name),
                    }
                })
            }
        };
        return Ok(value);
    }

    if let Some(component_ref) = call.extension_id.strip_prefix("component:") {
        let value = match components.as_deref() {
            Some(cat) => {
                let mut args_value = call.args.clone();
                stamp_caller(&mut args_value, &caller);
                let args = args_value.to_string();
                cat.dispatch(component_ref, &call.tool_name, &args).await
            }
            None => {
                tracing::warn!(
                    component = %component_ref,
                    tool = %call.tool_name,
                    "component call has no catalog wired; returning error value"
                );
                serde_json::json!({
                    "error": format!(
                        "unknown component tool '{}/{}'",
                        component_ref, call.tool_name
                    )
                })
            }
        };
        return Ok(value);
    }

    if let Some(pack) = call.extension_id.strip_prefix("sorla:") {
        let value = match sorla.as_deref() {
            Some(cat) => {
                let args = call.args.to_string();
                cat.dispatch(pack, &call.tool_name, &args).await
            }
            None => {
                tracing::warn!(
                    pack = %pack, tool = %call.tool_name,
                    "sorla call has no catalog wired; returning error value"
                );
                serde_json::json!({ "error": format!("unknown sorla tool '{}/{}'", pack, call.tool_name) })
            }
        };
        return Ok(value);
    }

    if let Some(flow_ref) = call.extension_id.strip_prefix("flow:") {
        let value = match flows.as_deref() {
            Some(cat) => {
                let args = call.args.to_string();
                crate::run_trace::under_binding(&call.extension_id, cat.dispatch(flow_ref, &args))
                    .await
            }
            None => {
                tracing::warn!(flow = %flow_ref, "flow call has no catalog wired; returning error value");
                serde_json::json!({ "error": format!("unknown flow tool '{flow_ref}'") })
            }
        };
        return Ok(value);
    }
    if let Some(playbook_id) = call.extension_id.strip_prefix("playbook:") {
        // Like the flow arm this NEVER yields `Err`: the catalog turns an
        // unknown playbook, unreadable arguments and a failed turn all into an
        // `{"error": ...}` value, so one skill cannot end the caller's step.
        let value = match playbooks.as_deref() {
            Some(cat) => {
                // A playbook turn is `.await`ed here and would inherit the
                // whole run context; spec section 4.4 makes it `none` unless
                // the caller's policy names this binding.
                let args = call.args.to_string();
                crate::run_trace::under_binding(
                    &call.extension_id,
                    cat.dispatch(playbook_id, &args),
                )
                .await
            }
            None => {
                tracing::warn!(
                    playbook = %playbook_id,
                    "playbook call has no catalog wired; returning error value"
                );
                serde_json::json!({ "error": format!("unknown playbook tool '{playbook_id}'") })
            }
        };
        return Ok(value);
    }

    // `a2a:` never receives the run context (spec section 4.1): the call leaves
    // this process over HTTP and nothing on this path reads
    // `RunContext::current()`. Do not wrap it in `under_binding`;
    // `ShareMode::for_binding` forces `None` for this prefix in case someone
    // does. Pinned by `an_a2a_call_carries_nothing_from_the_run_context`
    // (tests/a2a_loop.rs).
    if let Some(agent_id) = call.extension_id.strip_prefix("a2a:") {
        let value = match a2a.as_deref() {
            Some(catalog) => match a2a_continuations {
                Some(continuations) => {
                    catalog
                        .dispatch_in_conversation(
                            agent_id,
                            &call.args,
                            tenant,
                            continuations,
                            chrono::Utc::now(),
                        )
                        .await
                }
                None => catalog.dispatch(agent_id, &call.args).await,
            },
            None => {
                tracing::warn!(agent = %agent_id, "a2a call has no catalog wired; returning error value");
                serde_json::json!({
                    "status": "error",
                    "agent": agent_id,
                    "error": format!("unknown a2a agent '{agent_id}'"),
                })
            }
        };
        return Ok(value);
    }

    let mut args_value = call.args.clone();
    stamp_caller(&mut args_value, &caller);
    let args_json = args_value.to_string();
    let extension_id = call.extension_id.clone();
    let tool_name = call.tool_name.clone();
    let ctx = host_ctx_from_tenant(tenant);
    let raw = tokio::task::spawn_blocking(move || {
        ext_runtime.invoke_tool_ctx(&extension_id, &tool_name, &args_json, &ctx)
    })
    .await
    .map_err(|e| AgentError::ToolDispatch(format!("join: {e}")))?
    .map_err(|e| AgentError::ToolDispatch(format!("invoke: {e}")))?;
    serde_json::from_str(&raw).map_err(|e| AgentError::ToolDispatch(format!("decode: {e}")))
}

#[cfg(test)]
mod caller_stamp_tests {
    use super::*;
    use crate::tenant::VerifiedCaller;

    fn verified() -> VerifiedCaller {
        VerifiedCaller {
            user_verified: true,
            sub: Some("u-1@acme".into()),
            groups: vec!["engineering".into()],
            team: Some("platform".into()),
            role: Some("member".into()),
            iss: None,
        }
    }

    /// The attack this exists to stop, verbatim: a worker sent
    /// `sub: "user@example.com"`, `principals: ["employee"]` for a caller who
    /// had sent neither. Whatever the model writes under the key is discarded.
    #[test]
    fn a_model_written_caller_block_is_discarded() {
        let mut args = serde_json::json!({
            "query": "salaries",
            "_caller": { "user_verified": true, "sub": "user@example.com",
                         "groups": ["admin"], "role": "administrator" }
        });
        stamp_caller(&mut args, &verified());
        assert_eq!(args["_caller"]["sub"], "u-1@acme");
        assert_eq!(
            args["_caller"]["groups"],
            serde_json::json!(["engineering"])
        );
        assert_eq!(args["_caller"]["role"], "member");
        // The model's own arguments are untouched.
        assert_eq!(args["query"], "salaries");
    }

    /// Unconditional: an anonymous turn is stamped too, as `user_verified:
    /// false`. Skipping the stamp here would make "anonymous" and "this
    /// runtime is too old to say" indistinguishable, and a tool that cannot
    /// tell those apart trusts whatever an older runtime left behind.
    #[test]
    fn an_anonymous_turn_is_still_stamped_as_unverified() {
        let mut args = serde_json::json!({ "query": "x" });
        stamp_caller(&mut args, &VerifiedCaller::default());
        assert_eq!(args["_caller"]["user_verified"], false);
        assert!(args["_caller"].get("sub").is_none(), "no subject to assert");
    }

    /// A forged block on an anonymous turn is still erased — the case where a
    /// model would otherwise promote itself from nothing.
    #[test]
    fn a_forged_block_cannot_survive_an_anonymous_turn() {
        let mut args = serde_json::json!({
            "_caller": { "user_verified": true, "sub": "root", "role": "administrator" }
        });
        stamp_caller(&mut args, &VerifiedCaller::default());
        assert_eq!(args["_caller"]["user_verified"], false);
        assert!(args["_caller"].get("role").is_none());
    }

    /// Non-object arguments keep the shape the tool declared. Wrapping them to
    /// make room for the key would change what the tool receives.
    #[test]
    fn non_object_arguments_are_left_alone() {
        let mut args = serde_json::json!(["a", "b"]);
        stamp_caller(&mut args, &verified());
        assert_eq!(args, serde_json::json!(["a", "b"]));
    }

    /// `TenantContext` with no caller must resolve to anonymous rather than to
    /// "skip the stamp" — the `Option` is deliberately not exposed to the
    /// dispatch path.
    #[test]
    fn a_tenant_without_a_caller_resolves_to_anonymous() {
        let t = TenantContext::new("acme", "prod");
        assert_eq!(t.caller_or_anonymous(), VerifiedCaller::default());
        assert!(!t.caller_or_anonymous().user_verified);
    }
}

/// Idempotency ledger entry stored under
/// `aw:{tenant}:{env}:{session_len}.{session}:tool_calls:{call_len}.{call_id}`
/// (TTL 7 days). The session and call ids are length-prefixed because either
/// may contain `:`, which made plain concatenation ambiguous (two different
/// `(session, call)` pairs could build the same key).
#[derive(Serialize, Deserialize, Clone)]
pub struct ToolLedgerEntry {
    pub result: serde_json::Value,
}

pub fn ledger_key(tenant: &TenantContext, session_id: &str, call_id: &str) -> String {
    format!(
        "{}:{}.{session_id}:tool_calls:{}.{call_id}",
        tenant.key_prefix(),
        session_id.len(),
        call_id.len()
    )
}

/// Give every call in a batch a non-empty id that is unique within the batch.
///
/// Some providers (and the streaming accumulator) can emit an empty or
/// repeated `tool_call_id`. Left alone, two calls would share one ledger entry
/// and one of them would be answered with the other's cached result, and the
/// `Tool` messages could not be paired with their calls.
pub(crate) fn ensure_unique_call_ids(calls: &mut [ToolCallRecord]) {
    let mut seen = std::collections::HashSet::new();
    for call in calls.iter_mut() {
        if call.call_id.trim().is_empty() || !seen.insert(call.call_id.clone()) {
            call.call_id = format!("call_{}", uuid::Uuid::new_v4().simple());
            seen.insert(call.call_id.clone());
        }
    }
}

/// The idempotency-ledger id for a call: the provider's call id plus a digest
/// of what was asked (extension, tool, arguments). A reused or colliding call
/// id with different arguments then misses the cache instead of replaying an
/// unrelated result.
pub(crate) fn ledger_call_id(call: &ToolCallRecord) -> String {
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    hasher.update(call.extension_id.as_bytes());
    hasher.update([0x1f]);
    hasher.update(call.tool_name.as_bytes());
    hasher.update([0x1f]);
    hasher.update(call.args.to_string().as_bytes());
    let digest = hasher.finalize();
    let mut suffix = String::with_capacity(16);
    for byte in digest.iter().take(8) {
        suffix.push_str(&format!("{byte:02x}"));
    }
    format!("{}:{suffix}", call.call_id)
}

/// Whether a tool's `Ok` value is really a failure report (`{"error": ...}`).
/// Such a result must not be cached: a retry should run the tool again.
pub(crate) fn is_error_result(result: &serde_json::Value) -> bool {
    result.as_object().is_some_and(|o| o.contains_key("error"))
}

#[cfg(test)]
mod ledger_id_tests {
    use super::*;

    fn call(id: &str, args: serde_json::Value) -> ToolCallRecord {
        ToolCallRecord {
            call_id: id.into(),
            extension_id: "e".into(),
            tool_name: "t".into(),
            args,
        }
    }

    #[test]
    fn empty_and_repeated_call_ids_are_replaced_with_unique_ones() {
        let mut calls = vec![
            call("", serde_json::json!({})),
            call("", serde_json::json!({})),
            call("a", serde_json::json!({})),
            call("a", serde_json::json!({})),
        ];
        ensure_unique_call_ids(&mut calls);
        let ids: std::collections::HashSet<_> = calls.iter().map(|c| c.call_id.clone()).collect();
        assert_eq!(ids.len(), 4);
        assert!(calls.iter().all(|c| !c.call_id.is_empty()));
        assert_eq!(calls[2].call_id, "a", "first holder of an id keeps it");
    }

    #[test]
    fn ledger_id_changes_with_the_arguments_but_not_between_replays() {
        let a = call("c1", serde_json::json!({"x": 1}));
        let b = call("c1", serde_json::json!({"x": 2}));
        assert_ne!(ledger_call_id(&a), ledger_call_id(&b));
        assert_eq!(ledger_call_id(&a), ledger_call_id(&a.clone()));
    }

    #[test]
    fn error_shaped_results_are_not_cacheable() {
        assert!(is_error_result(&serde_json::json!({"error": "boom"})));
        assert!(!is_error_result(&serde_json::json!({"ok": true})));
        assert!(!is_error_result(&serde_json::json!("error")));
    }
}

/// Idempotency ledger for tool calls. Records tool results keyed by
/// `tool_call_id` so a state-save failure does not cause a duplicate
/// dispatch (re-sending the same email, etc.) on the next `step()`.
///
/// Dyn-safe (`Arc<dyn ToolLedger>`); production uses [`RedisToolLedger`],
/// tests use `NoopToolLedger` (from the `test-mock` module).
pub trait ToolLedger: Send + Sync {
    /// Return a previously-recorded result for this call_id, or `None`.
    fn get<'a>(
        &'a self,
        tenant: &'a TenantContext,
        session_id: &'a str,
        call_id: &'a str,
    ) -> Pin<Box<dyn Future<Output = Result<Option<serde_json::Value>, StateError>> + Send + 'a>>;

    /// Record a tool result (TTL 7 days).
    fn record<'a>(
        &'a self,
        tenant: &'a TenantContext,
        session_id: &'a str,
        call_id: &'a str,
        result: serde_json::Value,
    ) -> Pin<Box<dyn Future<Output = Result<(), StateError>> + Send + 'a>>;
}

const LEDGER_TTL_SECS: u64 = 7 * 24 * 60 * 60;

/// Production tool ledger backed by a multiplexed `ConnectionManager`.
///
/// Shares the Redis instance with `RedisAgentStateStore` via
/// `RedisAgentStateStore::manager()`. The manager is `Clone` (cheap,
/// reference-counted) so per-call clones open no new connections.
pub struct RedisToolLedger {
    manager: ConnectionManager,
}

impl RedisToolLedger {
    pub fn new(manager: ConnectionManager) -> Self {
        Self { manager }
    }
}

impl ToolLedger for RedisToolLedger {
    fn get<'a>(
        &'a self,
        tenant: &'a TenantContext,
        session_id: &'a str,
        call_id: &'a str,
    ) -> Pin<Box<dyn Future<Output = Result<Option<serde_json::Value>, StateError>> + Send + 'a>>
    {
        Box::pin(async move {
            let key = ledger_key(tenant, session_id, call_id);
            let mut conn = self.manager.clone();
            let raw: Option<String> = conn
                .get(&key)
                .await
                .map_err(|e| StateError::Redis(format!("ledger get: {e}")))?;
            match raw {
                Some(json) => {
                    let entry: ToolLedgerEntry = serde_json::from_str(&json)
                        .map_err(|e| StateError::Decode(format!("ledger decode: {e}")))?;
                    Ok(Some(entry.result))
                }
                None => Ok(None),
            }
        })
    }

    fn record<'a>(
        &'a self,
        tenant: &'a TenantContext,
        session_id: &'a str,
        call_id: &'a str,
        result: serde_json::Value,
    ) -> Pin<Box<dyn Future<Output = Result<(), StateError>> + Send + 'a>> {
        Box::pin(async move {
            let key = ledger_key(tenant, session_id, call_id);
            let entry = ToolLedgerEntry { result };
            let json = serde_json::to_string(&entry)
                .map_err(|e| StateError::Decode(format!("ledger encode: {e}")))?;
            let mut conn = self.manager.clone();
            let _: () = conn
                .set_ex(&key, json, LEDGER_TTL_SECS)
                .await
                .map_err(|e| StateError::Redis(format!("ledger set_ex: {e}")))?;
            Ok(())
        })
    }
}

const KV_LEDGER_TTL: std::time::Duration = std::time::Duration::from_secs(7 * 24 * 60 * 60);

/// Tool-call idempotency ledger over [`AwKv`] (Redis-free). Same key format
/// and 7-day TTL as [`RedisToolLedger`].
pub struct KvToolLedger {
    kv: Arc<dyn AwKv>,
}

impl KvToolLedger {
    pub fn new(kv: Arc<dyn AwKv>) -> Self {
        Self { kv }
    }
}

impl ToolLedger for KvToolLedger {
    fn get<'a>(
        &'a self,
        tenant: &'a TenantContext,
        session_id: &'a str,
        call_id: &'a str,
    ) -> Pin<Box<dyn Future<Output = Result<Option<serde_json::Value>, StateError>> + Send + 'a>>
    {
        Box::pin(async move {
            let key = ledger_key(tenant, session_id, call_id);
            match self.kv.get(&key).await? {
                Some(bytes) => {
                    let entry: ToolLedgerEntry = serde_json::from_slice(&bytes)
                        .map_err(|e| StateError::Decode(format!("ledger decode: {e}")))?;
                    Ok(Some(entry.result))
                }
                None => Ok(None),
            }
        })
    }

    fn record<'a>(
        &'a self,
        tenant: &'a TenantContext,
        session_id: &'a str,
        call_id: &'a str,
        result: serde_json::Value,
    ) -> Pin<Box<dyn Future<Output = Result<(), StateError>> + Send + 'a>> {
        Box::pin(async move {
            let key = ledger_key(tenant, session_id, call_id);
            let bytes = serde_json::to_vec(&ToolLedgerEntry { result })
                .map_err(|e| StateError::Decode(format!("ledger encode: {e}")))?;
            self.kv.set_ex(&key, bytes, KV_LEDGER_TTL).await
        })
    }
}

#[cfg(test)]
mod ctx_tests {
    use super::*;
    use crate::tenant::TenantContext;

    #[test]
    fn host_ctx_carries_tenant_and_optional_user() {
        let c1 = host_ctx_from_tenant(&TenantContext::new("acme", "prod"));
        assert_eq!(c1.tenant.as_deref(), Some("acme"));
        assert_eq!(c1.user_email, None);
        let c2 = host_ctx_from_tenant(
            &TenantContext::new("acme", "prod").with_user_email(Some("u@x.com".into())),
        );
        assert_eq!(c2.user_email.as_deref(), Some("u@x.com"));
        let c3 = host_ctx_from_tenant(&TenantContext::new("", ""));
        assert_eq!(
            c3.tenant, None,
            "empty tenant_id must map to None, not Some(\"\")"
        );
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    #[test]
    fn with_usage_note_appends_when_present() {
        let d = with_usage_note(
            "Base description.".into(),
            &Some("Use for VIP customers.".into()),
        );
        assert_eq!(d, "Base description.\n\nUse for VIP customers.");
    }

    #[test]
    fn with_usage_note_noop_when_none_or_blank() {
        assert_eq!(with_usage_note("Base.".into(), &None), "Base.");
        assert_eq!(
            with_usage_note("Base.".into(), &Some("   ".into())),
            "Base."
        );
    }

    #[test]
    fn is_tool_allowed_returns_true_for_exact_match() {
        let allowed = vec![ToolRef {
            extension_id: "http".into(),
            tool_name: "fetch".into(),
            description: None,
            input_schema: None,
            usage_note: None,
        }];
        let call = ToolCallRecord {
            call_id: "c1".into(),
            extension_id: "http".into(),
            tool_name: "fetch".into(),
            args: serde_json::json!({}),
        };
        assert!(is_tool_allowed(&call, &allowed));
    }

    #[test]
    fn is_tool_allowed_returns_false_for_unauthorized_tool() {
        let allowed = vec![ToolRef {
            extension_id: "http".into(),
            tool_name: "fetch".into(),
            description: None,
            input_schema: None,
            usage_note: None,
        }];
        let call = ToolCallRecord {
            call_id: "c1".into(),
            extension_id: "http".into(),
            tool_name: "post".into(),
            args: serde_json::json!({}),
        };
        assert!(!is_tool_allowed(&call, &allowed));
    }

    #[test]
    fn ledger_key_includes_tenant_env_session_callid() {
        let tc = TenantContext::new("acme", "prod");
        let key = ledger_key(&tc, "sess-1", "call-abc");
        assert_eq!(key, "aw:acme:prod:6.sess-1:tool_calls:8.call-abc");
    }

    #[test]
    fn ledger_key_is_unambiguous_with_colons_in_ids() {
        let tc = TenantContext::new("acme", "prod");
        // Plain concatenation made these two collide.
        let a = ledger_key(&tc, "s:tool_calls:x", "y");
        let b = ledger_key(&tc, "s", "x:y");
        assert_ne!(a, b);
        assert_ne!(ledger_key(&tc, "a:b", "c"), ledger_key(&tc, "a", "b:c"));
    }

    #[test]
    fn list_tools_for_llm_with_no_extensions_returns_empty() {
        // for_test runtime has no extensions loaded → list_tools errors
        // (NotFound) for every ext → all skipped → empty result.
        let rt = ExtensionRuntime::for_test().unwrap();
        let allowed = vec![ToolRef {
            extension_id: "http".into(),
            tool_name: "fetch".into(),
            description: None,
            input_schema: None,
            usage_note: None,
        }];
        let schemas = list_tools_for_llm(&rt, None, None, None, None, None, None, &allowed);
        assert!(schemas.is_empty());
    }

    #[test]
    fn missing_tools_reports_unloaded_extension() {
        // No extensions loaded → the declared tool cannot resolve and is
        // reported as missing with a load-failure reason (instead of being
        // dropped silently, which is what causes hallucinated tool results).
        let rt = ExtensionRuntime::for_test().unwrap();
        let allowed = vec![ToolRef {
            extension_id: "greentic.hubspot".into(),
            tool_name: "hubspot_contacts".into(),
            description: None,
            input_schema: None,
            usage_note: None,
        }];
        let missing = missing_tools(&rt, None, None, None, None, None, None, &allowed);
        assert_eq!(missing.len(), 1);
        assert_eq!(missing[0].extension_id, "greentic.hubspot");
        assert_eq!(missing[0].tool_name, "hubspot_contacts");
        assert!(
            missing[0].reason.contains("failed to load"),
            "got: {}",
            missing[0].reason
        );
    }

    #[test]
    fn missing_tools_reports_mcp_tool_absent_from_catalog() {
        let rt = ExtensionRuntime::for_test().unwrap();
        let allowed = vec![ToolRef {
            extension_id: "mcp:github".into(),
            tool_name: "create_issue".into(),
            description: None,
            input_schema: None,
            usage_note: None,
        }];
        // No catalog provided → the mcp tool is unresolvable.
        let missing = missing_tools(&rt, None, None, None, None, None, None, &allowed);
        assert_eq!(missing.len(), 1);
        assert!(
            missing[0].reason.contains("MCP tool not found"),
            "got: {}",
            missing[0].reason
        );
    }

    use std::collections::HashMap;

    use crate::mcp_source::{McpRoute, McpToolCatalog, McpToolEntry, route_for_tests};

    /// Build a one-tool catalog whose route (when present) aims at
    /// `transport_url`. Pass `with_route = false` to register only the schema
    /// (list-side) without a dispatch route.
    fn catalog_with(
        server: &str,
        tool: &str,
        description: &str,
        parameters: serde_json::Value,
        transport_url: Option<&str>,
    ) -> McpToolCatalog {
        let mut tools: HashMap<(String, String), McpToolEntry> = HashMap::new();
        tools.insert(
            (server.to_string(), tool.to_string()),
            McpToolEntry {
                description: description.to_string(),
                parameters,
            },
        );
        let mut routes: HashMap<(String, String), McpRoute> = HashMap::new();
        if let Some(url) = transport_url {
            routes.insert(
                (server.to_string(), tool.to_string()),
                route_for_tests(server, tool, url),
            );
        }
        McpToolCatalog::from_parts(tools, routes, None)
    }

    /// Mount the minimal MCP JSON-RPC contract (initialize, initialized,
    /// tools/call) on a fresh wiremock server returning `call_result`.
    /// Replicated from `mcp_source` tests — only the few mount lines needed
    /// to exercise dispatch.
    async fn fake_mcp_call_server(call_result: serde_json::Value) -> wiremock::MockServer {
        use wiremock::matchers::{body_partial_json, method};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(body_partial_json(
                serde_json::json!({ "method": "initialize" }),
            ))
            .respond_with(
                ResponseTemplate::new(200)
                    .insert_header("Mcp-Session-Id", "sess-1")
                    .set_body_json(serde_json::json!({
                        "jsonrpc": "2.0", "id": 1,
                        "result": {
                            "protocolVersion": "2025-06-18",
                            "serverInfo": { "name": "fake", "version": "1.0.0" }
                        }
                    })),
            )
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(body_partial_json(
                serde_json::json!({ "method": "notifications/initialized" }),
            ))
            .respond_with(ResponseTemplate::new(202))
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(body_partial_json(
                serde_json::json!({ "method": "tools/call" }),
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "jsonrpc": "2.0", "id": 3,
                "result": call_result
            })))
            .mount(&server)
            .await;
        server
    }

    #[test]
    fn mcp_ref_listed_from_catalog() {
        // A catalog-backed mcp: ref is emitted as an LlmToolSchema with the
        // catalog's description/parameters; the ext_runtime is never consulted
        // for it (the for_test runtime has no extensions loaded).
        let rt = ExtensionRuntime::for_test().unwrap();
        let params = serde_json::json!({
            "type": "object",
            "properties": { "id": { "type": "string" } }
        });
        let catalog = catalog_with("s1", "get_issue", "Get an issue", params.clone(), None);

        let allowed = vec![
            ToolRef {
                extension_id: "mcp:s1".into(),
                tool_name: "get_issue".into(),
                description: None,
                input_schema: None,
                usage_note: None,
            },
            // Absent from the catalog → dropped (warn), not panicked.
            ToolRef {
                extension_id: "mcp:s1".into(),
                tool_name: "missing".into(),
                description: None,
                input_schema: None,
                usage_note: None,
            },
        ];

        let schemas =
            list_tools_for_llm(&rt, Some(&catalog), None, None, None, None, None, &allowed);
        assert_eq!(schemas.len(), 1, "only the catalog-backed ref is emitted");
        let s = &schemas[0];
        assert_eq!(s.extension_id, "mcp:s1");
        assert_eq!(s.tool_name, "get_issue");
        assert_eq!(s.description, "Get an issue");
        assert_eq!(s.parameters, params);
    }

    /// The author contract a pack's `AgentConfig` carries for an `mcp:` binding.
    fn mcp_ref_with_contract(server: &str, tool: &str) -> ToolRef {
        ToolRef {
            extension_id: format!("mcp:{server}"),
            tool_name: tool.into(),
            description: Some("Pack-carried description".into()),
            input_schema: Some(serde_json::json!({
                "type": "object",
                "properties": { "pack_arg": { "type": "string" } }
            })),
            usage_note: None,
        }
    }

    #[test]
    fn mcp_ref_listed_from_tool_ref_when_catalog_has_no_entry() {
        // The deployed-runner case: no admin credentials, so no catalog at all.
        // The schema the designer snapshotted into the pack's `AgentConfig` is
        // what reaches the LLM. Before this, the tool was silently dropped.
        let rt = ExtensionRuntime::for_test().unwrap();
        let allowed = vec![mcp_ref_with_contract("s1", "get_issue")];

        let schemas = list_tools_for_llm(&rt, None, None, None, None, None, None, &allowed);
        assert_eq!(schemas.len(), 1, "the author contract resolves the tool");
        assert_eq!(schemas[0].extension_id, "mcp:s1");
        assert_eq!(schemas[0].tool_name, "get_issue");
        assert_eq!(schemas[0].description, "Pack-carried description");
        assert_eq!(
            schemas[0].parameters["properties"]["pack_arg"]["type"],
            "string"
        );
    }

    #[test]
    fn mcp_catalog_entry_wins_over_tool_ref_contract() {
        // REGRESSION GUARD for every existing admin-backed deployment: when the
        // catalog has an entry it was probed from the live server this run, and
        // it must be emitted byte-for-byte even though the ref also carries a
        // (possibly stale) snapshot. Flipping the precedence would silently
        // downgrade every deployment that has a working admin source.
        let rt = ExtensionRuntime::for_test().unwrap();
        let live_params = serde_json::json!({
            "type": "object",
            "properties": { "live_arg": { "type": "number" } }
        });
        let catalog = catalog_with("s1", "get_issue", "Live description", live_params, None);
        let allowed = vec![mcp_ref_with_contract("s1", "get_issue")];

        let schemas =
            list_tools_for_llm(&rt, Some(&catalog), None, None, None, None, None, &allowed);
        assert_eq!(schemas.len(), 1);
        assert_eq!(schemas[0].description, "Live description");
        assert_eq!(
            schemas[0].parameters["properties"]["live_arg"]["type"], "number",
            "the catalog's parameters must survive intact"
        );
        assert!(
            schemas[0].parameters["properties"]
                .get("pack_arg")
                .is_none(),
            "the pack snapshot must not leak into a catalog-resolved schema"
        );
    }

    #[test]
    fn mcp_ref_with_partial_contract_and_no_catalog_is_dropped() {
        // Both halves are required, mirroring the `flow:` branch: a description
        // with no schema cannot be offered to the LLM as a callable tool.
        let rt = ExtensionRuntime::for_test().unwrap();
        let mut description_only = mcp_ref_with_contract("s1", "get_issue");
        description_only.input_schema = None;
        let mut schema_only = mcp_ref_with_contract("s1", "list_issues");
        schema_only.description = None;
        let bare = ToolRef {
            extension_id: "mcp:s1".into(),
            tool_name: "nothing".into(),
            description: None,
            input_schema: None,
            usage_note: None,
        };

        let schemas = list_tools_for_llm(
            &rt,
            None,
            None,
            None,
            None,
            None,
            None,
            &[description_only, schema_only, bare],
        );
        assert!(schemas.is_empty(), "got: {schemas:?}");
    }

    #[test]
    fn mcp_ref_contract_still_takes_the_usage_note() {
        // The usage note is an author addendum to whichever description won; it
        // must not be lost on the new fallback arm.
        let rt = ExtensionRuntime::for_test().unwrap();
        let mut t = mcp_ref_with_contract("s1", "get_issue");
        t.usage_note = Some("Only for open issues.".into());

        let schemas = list_tools_for_llm(&rt, None, None, None, None, None, None, &[t]);
        assert_eq!(schemas.len(), 1);
        assert_eq!(
            schemas[0].description,
            "Pack-carried description\n\nOnly for open issues."
        );
    }

    #[test]
    fn missing_tools_accepts_mcp_tool_resolved_by_its_author_contract() {
        // `preflight_warn_tools` would otherwise warn loudly at startup about a
        // tool that `list_tools_for_llm` now resolves and offers.
        let rt = ExtensionRuntime::for_test().unwrap();
        let allowed = vec![mcp_ref_with_contract("s1", "get_issue")];
        assert!(missing_tools(&rt, None, None, None, None, None, None, &allowed).is_empty());
    }

    #[test]
    fn missing_tools_still_reports_mcp_tool_with_no_contract_and_no_catalog() {
        let rt = ExtensionRuntime::for_test().unwrap();
        let mut half = mcp_ref_with_contract("s1", "get_issue");
        half.input_schema = None;
        let missing = missing_tools(&rt, None, None, None, None, None, None, &[half]);
        assert_eq!(missing.len(), 1);
        assert!(
            missing[0].reason.contains("MCP tool not found"),
            "got: {}",
            missing[0].reason
        );
    }

    #[test]
    fn non_mcp_ref_unchanged() {
        // A normal ref still routes through ext_runtime. The for_test runtime
        // loads no extensions, so list_tools errors → the ref is skipped,
        // exactly as in `list_tools_for_llm_with_no_extensions_returns_empty`.
        // The presence of a catalog must not change that path.
        //
        // The catalog deliberately contains an entry keyed by the FULL
        // non-mcp extension id — if the mcp branch ever matched non-`mcp:`
        // ids and consulted the catalog, this entry would be emitted and the
        // empty assertion below would catch the regression.
        let rt = ExtensionRuntime::for_test().unwrap();
        let catalog = catalog_with(
            "greentic.tavily",
            "search",
            "decoy: must never be emitted for a non-mcp ref",
            serde_json::json!({}),
            None,
        );
        let allowed = vec![ToolRef {
            extension_id: "greentic.tavily".into(),
            tool_name: "search".into(),
            description: None,
            input_schema: None,
            usage_note: None,
        }];
        let schemas =
            list_tools_for_llm(&rt, Some(&catalog), None, None, None, None, None, &allowed);
        assert!(
            schemas.is_empty(),
            "non-mcp ref still goes through ext_runtime (unloaded → dropped)"
        );
    }

    #[test]
    fn is_tool_allowed_matches_mcp_ref() {
        // Exact (mcp:s1, get_issue) match works with no change to the fn.
        let allowed = vec![ToolRef {
            extension_id: "mcp:s1".into(),
            tool_name: "get_issue".into(),
            description: None,
            input_schema: None,
            usage_note: None,
        }];
        let call = ToolCallRecord {
            call_id: "c1".into(),
            extension_id: "mcp:s1".into(),
            tool_name: "get_issue".into(),
            args: serde_json::json!({}),
        };
        assert!(is_tool_allowed(&call, &allowed));

        let other = ToolCallRecord {
            call_id: "c1".into(),
            extension_id: "mcp:s1".into(),
            tool_name: "search_code".into(),
            args: serde_json::json!({}),
        };
        assert!(!is_tool_allowed(&other, &allowed));
    }

    #[tokio::test]
    async fn dispatch_routes_mcp_ref() {
        // Route present → calls the fake MCP server and returns its output.
        let mcp = fake_mcp_call_server(serde_json::json!({
            "structuredContent": { "ok": 1 }
        }))
        .await;
        let uri = mcp.uri();
        let catalog = Arc::new(catalog_with(
            "s1",
            "get_issue",
            "Get an issue",
            serde_json::json!({}),
            Some(&uri),
        ));
        let rt = Arc::new(ExtensionRuntime::for_test().unwrap());

        let call = ToolCallRecord {
            call_id: "c1".into(),
            extension_id: "mcp:s1".into(),
            tool_name: "get_issue".into(),
            args: serde_json::json!({}),
        };
        let tc = TenantContext::new("t", "e");
        let out = dispatch_tool_call(
            rt.clone(),
            Some(catalog.clone()),
            None,
            None,
            None,
            None,
            call,
            &tc,
        )
        .await
        .expect("mcp dispatch never returns Err");
        assert_eq!(out, serde_json::json!({ "ok": 1 }), "got: {out}");

        // Route missing → shaped error value, still Ok.
        let missing = ToolCallRecord {
            call_id: "c2".into(),
            extension_id: "mcp:s1".into(),
            tool_name: "no_such".into(),
            args: serde_json::json!({}),
        };
        let out = dispatch_tool_call(
            rt.clone(),
            Some(catalog),
            None,
            None,
            None,
            None,
            missing,
            &tc,
        )
        .await
        .expect("missing mcp route still returns Ok");
        assert_eq!(
            out,
            serde_json::json!({ "error": "unknown mcp tool 's1/no_such'" }),
            "got: {out}"
        );

        // A non-mcp call still hits the ext_runtime path (unloaded → Err).
        let non_mcp = ToolCallRecord {
            call_id: "c3".into(),
            extension_id: "greentic.absent".into(),
            tool_name: "nope".into(),
            args: serde_json::json!({}),
        };
        let res = dispatch_tool_call(rt, None, None, None, None, None, non_mcp, &tc).await;
        assert!(
            res.is_err(),
            "non-mcp dispatch against an unloaded extension must error"
        );
    }

    use crate::component_source::ComponentToolCatalog;
    use crate::component_source::test_support::{FakeInvoker, one_tool};
    use crate::flow_source::{FlowInvoker, FlowOperation, FlowToolCatalog};
    use crate::sorla_source::test_support::FakeInvoker as SorlaFakeInvoker;
    use crate::sorla_source::{SorlaToolCatalog, SorlaToolEntry};

    struct FakeFlowInvoker;
    impl FlowInvoker for FakeFlowInvoker {
        fn list_flows(&self) -> Vec<FlowOperation> {
            vec![FlowOperation {
                flow_ref: "lookup".into(),
                description: "Look things up".into(),
                parameters: serde_json::json!({ "type": "object", "properties": { "q": { "type": "integer" } } }),
            }]
        }
        fn invoke<'a>(
            &'a self,
            flow_ref: &'a str,
            args_json: &'a str,
        ) -> std::pin::Pin<
            Box<dyn std::future::Future<Output = Result<serde_json::Value, String>> + Send + 'a>,
        > {
            Box::pin(async move {
                if flow_ref == "lookup" {
                    Ok(serde_json::json!({ "echoed": args_json }))
                } else {
                    Err(format!("flow '{flow_ref}' not found"))
                }
            })
        }
    }

    fn ext_runtime_stub() -> ExtensionRuntime {
        ExtensionRuntime::for_test().unwrap()
    }

    fn test_flow_invoker() -> FakeFlowInvoker {
        FakeFlowInvoker
    }

    #[test]
    fn flow_tool_prefers_author_contract_over_catalog() {
        // Catalog has flow "lookup" with its own description + parameters.
        // ToolRef carries author overrides — these must win.
        let flows = Arc::new(FlowToolCatalog::from_invoker(Arc::new(test_flow_invoker())));
        let allowed = vec![ToolRef {
            extension_id: "flow:lookup".into(),
            tool_name: "look_up".into(),
            description: Some("Author description".into()),
            input_schema: Some(
                serde_json::json!({"type":"object","properties":{"q":{"type":"string"}}}),
            ),
            usage_note: None,
        }];
        let schemas = list_tools_for_llm(
            &ext_runtime_stub(),
            None,
            None,
            Some(&flows),
            None,
            None,
            None,
            &allowed,
        );
        let s = schemas
            .iter()
            .find(|s| s.extension_id == "flow:lookup")
            .expect("flow tool listed");
        assert_eq!(
            s.description, "Author description",
            "override description must win over catalog"
        );
        assert_eq!(
            s.parameters["properties"]["q"]["type"], "string",
            "override schema must win over catalog"
        );
    }

    #[test]
    fn flow_tool_falls_back_to_catalog_when_no_override() {
        // ToolRef has no override — the catalog entry must be used.
        let flows = Arc::new(FlowToolCatalog::from_invoker(Arc::new(test_flow_invoker())));
        let allowed = vec![ToolRef {
            extension_id: "flow:lookup".into(),
            tool_name: "look_up".into(),
            description: None,
            input_schema: None,
            usage_note: None,
        }];
        let schemas = list_tools_for_llm(
            &ext_runtime_stub(),
            None,
            None,
            Some(&flows),
            None,
            None,
            None,
            &allowed,
        );
        assert!(
            schemas.iter().any(|s| s.extension_id == "flow:lookup"),
            "with no override the catalog entry must still be used to list the tool"
        );
    }

    #[test]
    fn list_tools_appends_usage_note_for_flow_tool() {
        // Flow branch: ToolRef.description supplies the base description
        // directly (no live runtime needed), so this proves the usage_note
        // reaches the LLM-facing schema without an ExtensionRuntime fixture.
        let flows = Arc::new(FlowToolCatalog::from_invoker(Arc::new(test_flow_invoker())));
        let allowed = vec![ToolRef {
            extension_id: "flow:lookup".into(),
            tool_name: "look_up".into(),
            description: Some("Base.".into()),
            input_schema: Some(serde_json::json!({"type":"object","properties":{}})),
            usage_note: Some("note-Z".into()),
        }];
        let schemas = list_tools_for_llm(
            &ext_runtime_stub(),
            None,
            None,
            Some(&flows),
            None,
            None,
            None,
            &allowed,
        );
        let s = schemas
            .iter()
            .find(|s| s.extension_id == "flow:lookup")
            .expect("flow tool listed");
        assert!(s.description.contains("Base."), "got: {}", s.description);
        assert!(s.description.contains("note-Z"), "got: {}", s.description);
    }

    #[tokio::test]
    async fn flow_prefixed_tool_is_listed_and_dispatched() {
        let flows = Arc::new(FlowToolCatalog::from_invoker(Arc::new(FakeFlowInvoker)));
        let rt = ExtensionRuntime::for_test().unwrap();
        let allowed = vec![ToolRef {
            extension_id: "flow:lookup".into(),
            tool_name: "look_up".into(),
            description: None,
            input_schema: None,
            usage_note: None,
        }];
        let schemas = list_tools_for_llm(&rt, None, None, Some(&flows), None, None, None, &allowed);
        assert!(
            schemas
                .iter()
                .any(|s| s.extension_id == "flow:lookup" && s.tool_name == "look_up"),
            "flow: tool must appear in listed schemas"
        );

        let call = ToolCallRecord {
            call_id: "c1".into(),
            extension_id: "flow:lookup".into(),
            tool_name: "look_up".into(),
            args: serde_json::json!({ "q": 1 }),
        };
        let rt_arc = Arc::new(ExtensionRuntime::for_test().unwrap());
        let tc = TenantContext::new("t", "e");
        let out = dispatch_tool_call(rt_arc, None, None, Some(flows), None, None, call, &tc)
            .await
            .expect("flow dispatch must not return Err");
        assert!(
            out.get("error").is_none(),
            "known flow must dispatch, got {out}"
        );
    }

    /// A catalog holding one playbook, with no tools and a turn that echoes.
    fn playbook_catalog() -> Arc<crate::playbook_source::PlaybookToolCatalog> {
        use crate::playbook_source::{
            PlaybookLlmRequirement, PlaybookOperation, PlaybookSource, PlaybookToolCatalog,
            PlaybookTurnFn, PlaybookTurnResult,
        };
        struct One;
        impl PlaybookSource for One {
            fn list_playbooks(&self) -> Vec<PlaybookOperation> {
                vec![PlaybookOperation {
                    playbook_id: "refund".into(),
                    description: "From the document".into(),
                    parameters: serde_json::json!({ "type": "object" }),
                    instructions: "Follow the policy.".into(),
                    llm: PlaybookLlmRequirement::default(),
                    allow_list: vec![],
                    guardrails: vec![],
                }]
            }
        }
        let turn: PlaybookTurnFn = Arc::new(|_req| {
            Box::pin(async move {
                Ok(PlaybookTurnResult {
                    reply: "handled".into(),
                })
            })
        });
        Arc::new(PlaybookToolCatalog::from_source(
            &One,
            turn,
            &[],
            crate::config::LlmProviderRef {
                provider: "openai".into(),
                model: "gpt-4o-mini".into(),
                credential_ref: None,
            },
            crate::tenant::TenantContext::new("t", "e"),
        ))
    }

    fn playbook_ref(description: Option<&str>) -> ToolRef {
        ToolRef {
            extension_id: "playbook:refund".into(),
            tool_name: "run".into(),
            description: description.map(str::to_string),
            input_schema: None,
            usage_note: None,
        }
    }

    #[tokio::test]
    async fn playbook_prefixed_tool_is_listed_and_dispatched() {
        let playbooks = playbook_catalog();
        let rt = ExtensionRuntime::for_test().unwrap();
        let allowed = vec![playbook_ref(None)];
        let schemas = list_tools_for_llm(
            &rt,
            None,
            None,
            None,
            Some(&playbooks),
            None,
            None,
            &allowed,
        );
        assert!(
            schemas
                .iter()
                .any(|s| s.extension_id == "playbook:refund" && s.tool_name == "run"),
            "playbook: tool must appear in listed schemas"
        );

        let call = ToolCallRecord {
            call_id: "c1".into(),
            extension_id: "playbook:refund".into(),
            tool_name: "run".into(),
            args: serde_json::json!({ "order": 1 }),
        };
        let rt_arc = Arc::new(ExtensionRuntime::for_test().unwrap());
        let tc = TenantContext::new("t", "e");
        let out = dispatch_tool_call_in_conversation(
            rt_arc,
            None,
            None,
            None,
            Some(playbooks),
            None,
            None,
            call,
            &tc,
            None,
        )
        .await
        .expect("playbook dispatch must not return Err");
        assert_eq!(
            out["reply"], "handled",
            "known playbook must run, got {out}"
        );
    }

    /// The `playbook:` arm takes the `mcp:` precedence, NOT the `flow:` one
    /// beside it: the document is read from the pack this run, while the ref's
    /// description is a snapshot taken when the tool was bound.
    #[tokio::test]
    async fn the_documents_summary_wins_over_the_author_contract() {
        let playbooks = playbook_catalog();
        let rt = ExtensionRuntime::for_test().unwrap();
        let allowed = vec![playbook_ref(Some("Stale snapshot"))];
        let schemas = list_tools_for_llm(
            &rt,
            None,
            None,
            None,
            Some(&playbooks),
            None,
            None,
            &allowed,
        );
        let s = schemas
            .iter()
            .find(|s| s.extension_id == "playbook:refund")
            .expect("playbook listed");
        assert!(
            s.description.contains("From the document"),
            "the document must win, got: {}",
            s.description
        );
    }

    #[tokio::test]
    async fn missing_tools_reports_a_playbook_absent_from_the_catalog() {
        let playbooks = playbook_catalog();
        let rt = ExtensionRuntime::for_test().unwrap();
        let absent = ToolRef {
            extension_id: "playbook:not_carried".into(),
            tool_name: "run".into(),
            description: None,
            input_schema: None,
            usage_note: None,
        };
        let missing = missing_tools(
            &rt,
            None,
            None,
            None,
            Some(&playbooks),
            None,
            None,
            &[absent, playbook_ref(None)],
        );
        assert_eq!(missing.len(), 1, "only the uncarried one is missing");
        assert_eq!(missing[0].extension_id, "playbook:not_carried");
    }

    /// `dispatch_tool_call` passes `None` for the playbook catalog on purpose:
    /// it holds no calling worker, so it can narrow no allow-list. Offering a
    /// playbook there would run one with a tool set nobody intersected.
    #[tokio::test]
    async fn a_one_shot_dispatch_offers_no_playbook() {
        let call = ToolCallRecord {
            call_id: "c1".into(),
            extension_id: "playbook:refund".into(),
            tool_name: "run".into(),
            args: serde_json::json!({}),
        };
        let rt_arc = Arc::new(ExtensionRuntime::for_test().unwrap());
        let tc = TenantContext::new("t", "e");
        let out = dispatch_tool_call(rt_arc, None, None, None, None, None, call, &tc)
            .await
            .expect("must be an error value, never Err");
        assert!(
            out.get("error").is_some(),
            "a one-shot dispatch must refuse a playbook, got {out}"
        );
    }

    #[test]
    fn component_ref_listed_from_catalog() {
        // A catalog-backed component: ref is emitted as an LlmToolSchema with
        // the catalog's description/parameters; ext_runtime is never consulted.
        let rt = ExtensionRuntime::for_test().unwrap();
        let params = serde_json::json!({
            "type": "object",
            "properties": { "order_id": { "type": "string" } }
        });
        let invoker = Arc::new(FakeInvoker::new(vec![], Ok(serde_json::json!({}))));
        let catalog = ComponentToolCatalog::for_tests(
            one_tool(
                "greentic.refund",
                "issue_refund",
                "Issue a refund",
                params.clone(),
            ),
            invoker,
        );

        let allowed = vec![
            ToolRef {
                extension_id: "component:greentic.refund".into(),
                tool_name: "issue_refund".into(),
                description: None,
                input_schema: None,
                usage_note: None,
            },
            // Absent from the catalog → dropped (warn), not panicked.
            ToolRef {
                extension_id: "component:greentic.refund".into(),
                tool_name: "missing".into(),
                description: None,
                input_schema: None,
                usage_note: None,
            },
        ];

        let schemas =
            list_tools_for_llm(&rt, None, Some(&catalog), None, None, None, None, &allowed);
        assert_eq!(schemas.len(), 1, "only the catalog-backed ref is emitted");
        let s = &schemas[0];
        assert_eq!(s.extension_id, "component:greentic.refund");
        assert_eq!(s.tool_name, "issue_refund");
        assert_eq!(s.description, "Issue a refund");
        assert_eq!(s.parameters, params);
    }

    #[test]
    fn non_component_ref_unaffected_by_catalog() {
        // A plain ext ref still routes through ext_runtime even when a
        // component catalog is present. The decoy entry is keyed by the FULL
        // non-prefixed id — if the component branch ever matched it, this entry
        // would leak into the list and the empty assertion would catch it.
        let rt = ExtensionRuntime::for_test().unwrap();
        let invoker = Arc::new(FakeInvoker::new(vec![], Ok(serde_json::json!({}))));
        let catalog = ComponentToolCatalog::for_tests(
            one_tool(
                "greentic.tavily",
                "search",
                "decoy: must never be emitted for a non-component ref",
                serde_json::json!({}),
            ),
            invoker,
        );
        let allowed = vec![ToolRef {
            extension_id: "greentic.tavily".into(),
            tool_name: "search".into(),
            description: None,
            input_schema: None,
            usage_note: None,
        }];
        let schemas =
            list_tools_for_llm(&rt, None, Some(&catalog), None, None, None, None, &allowed);
        assert!(
            schemas.is_empty(),
            "non-component ref still goes through ext_runtime (unloaded → dropped)"
        );
    }

    #[tokio::test]
    async fn dispatch_routes_component_ref() {
        // Catalog entry present → routes to the invoker and returns its value.
        let invoker = Arc::new(FakeInvoker::new(
            vec![],
            Ok(serde_json::json!({ "refund_id": "r-1" })),
        ));
        let catalog = Arc::new(ComponentToolCatalog::for_tests(
            one_tool(
                "greentic.refund",
                "issue_refund",
                "Issue a refund",
                serde_json::json!({}),
            ),
            invoker,
        ));
        let rt = Arc::new(ExtensionRuntime::for_test().unwrap());

        let tc = TenantContext::new("t", "e");
        let call = ToolCallRecord {
            call_id: "c1".into(),
            extension_id: "component:greentic.refund".into(),
            tool_name: "issue_refund".into(),
            args: serde_json::json!({}),
        };
        let out = dispatch_tool_call(
            rt.clone(),
            None,
            Some(catalog.clone()),
            None,
            None,
            None,
            call,
            &tc,
        )
        .await
        .expect("component dispatch never returns Err");
        assert_eq!(out, serde_json::json!({ "refund_id": "r-1" }), "got: {out}");

        // Unknown op → shaped error value, still Ok.
        let missing = ToolCallRecord {
            call_id: "c2".into(),
            extension_id: "component:greentic.refund".into(),
            tool_name: "no_such".into(),
            args: serde_json::json!({}),
        };
        let out = dispatch_tool_call(
            rt.clone(),
            None,
            Some(catalog),
            None,
            None,
            None,
            missing,
            &tc,
        )
        .await
        .expect("missing component op still returns Ok");
        assert!(out.to_string().contains("error"), "got: {out}");

        // No component catalog wired → shaped error value, still Ok (mirrors
        // the mcp branch's "no route" behaviour).
        let no_cat = ToolCallRecord {
            call_id: "c3".into(),
            extension_id: "component:greentic.refund".into(),
            tool_name: "issue_refund".into(),
            args: serde_json::json!({}),
        };
        let out = dispatch_tool_call(rt, None, None, None, None, None, no_cat, &tc)
            .await
            .expect("component dispatch with no catalog still returns Ok");
        assert!(out.to_string().contains("error"), "got: {out}");
    }

    #[test]
    fn list_includes_sorla_ref() {
        // A catalog-backed sorla: ref is emitted as an LlmToolSchema with the
        // catalog's description/parameters; ext_runtime is never consulted.
        let rt = ExtensionRuntime::for_test().unwrap();
        let params = serde_json::json!({
            "type": "object",
            "properties": { "amount": { "type": "number" } }
        });
        let invoker = Arc::new(SorlaFakeInvoker::new(vec![], Ok(serde_json::json!({}))));
        let mut tools = HashMap::new();
        tools.insert(
            ("landlord".to_string(), "record_rent_payment".to_string()),
            SorlaToolEntry {
                description: "Record a rent payment".to_string(),
                parameters: params.clone(),
            },
        );
        let catalog = SorlaToolCatalog::for_tests(tools, invoker);

        let allowed = vec![
            ToolRef {
                extension_id: "sorla:landlord".into(),
                tool_name: "record_rent_payment".into(),
                description: None,
                input_schema: None,
                usage_note: None,
            },
            // Absent from the catalog → dropped (warn), not panicked.
            ToolRef {
                extension_id: "sorla:landlord".into(),
                tool_name: "missing".into(),
                description: None,
                input_schema: None,
                usage_note: None,
            },
        ];

        let schemas =
            list_tools_for_llm(&rt, None, None, None, None, Some(&catalog), None, &allowed);
        assert_eq!(schemas.len(), 1, "only the catalog-backed ref is emitted");
        let s = &schemas[0];
        assert_eq!(s.extension_id, "sorla:landlord");
        assert_eq!(s.tool_name, "record_rent_payment");
        assert_eq!(s.description, "Record a rent payment");
        assert_eq!(s.parameters, params);
    }

    #[tokio::test]
    async fn dispatch_routes_sorla_ref() {
        // Catalog entry present → routes to the invoker and returns its value.
        let invoker = Arc::new(SorlaFakeInvoker::new(
            vec![],
            Ok(serde_json::json!({"ok":true})),
        ));
        let mut tools = HashMap::new();
        tools.insert(
            ("landlord".to_string(), "record_rent_payment".to_string()),
            SorlaToolEntry {
                description: "Record a rent payment".to_string(),
                parameters: serde_json::json!({ "type": "object" }),
            },
        );
        let catalog = Arc::new(SorlaToolCatalog::for_tests(tools, invoker));
        let rt = Arc::new(ExtensionRuntime::for_test().unwrap());

        let tc = TenantContext::new("t", "e");
        let call = ToolCallRecord {
            call_id: "c1".into(),
            extension_id: "sorla:landlord".into(),
            tool_name: "record_rent_payment".into(),
            args: serde_json::json!({}),
        };
        let out = dispatch_tool_call(rt, None, None, None, Some(catalog), None, call, &tc)
            .await
            .expect("sorla dispatch never returns Err");
        assert_eq!(out, serde_json::json!({"ok":true}), "got: {out}");
    }

    fn a2a_ref(description: Option<&str>, input_schema: Option<serde_json::Value>) -> ToolRef {
        ToolRef {
            extension_id: "a2a:my-agent".into(),
            tool_name: "call".into(),
            description: description.map(str::to_string),
            input_schema,
            usage_note: None,
        }
    }

    #[test]
    fn an_a2a_ref_is_advertised_with_the_cards_description_and_the_authors_schema() {
        // The card wins on description: it is the agent's live statement
        // about itself. The schema can ONLY be the author contract's — an
        // AgentSkill has none — so the ref's own input_schema must survive
        // even though its description is overridden by the card.
        let rt = ExtensionRuntime::for_test().unwrap();
        let params = serde_json::json!({
            "type": "object",
            "properties": { "q": { "type": "string" } }
        });
        let allowed = vec![a2a_ref(Some("local"), Some(params.clone()))];
        let catalog = A2aToolCatalog::for_tests(&[("my-agent", "from the card")], &[]);

        let schemas =
            list_tools_for_llm(&rt, None, None, None, None, None, Some(&catalog), &allowed);
        assert_eq!(schemas.len(), 1, "got: {schemas:?}");
        let s = &schemas[0];
        assert_eq!(s.extension_id, "a2a:my-agent");
        assert_eq!(s.description, "from the card");
        assert_eq!(s.parameters, params);
    }

    #[test]
    fn an_a2a_ref_without_an_author_schema_is_not_advertised() {
        // No input_schema anywhere, so the tool cannot be called correctly —
        // an AgentSkill carries no schema, so there is no fallback source.
        let rt = ExtensionRuntime::for_test().unwrap();
        let allowed = vec![a2a_ref(Some("local"), None)];
        let catalog = A2aToolCatalog::for_tests(&[("my-agent", "from the card")], &[]);

        let schemas =
            list_tools_for_llm(&rt, None, None, None, None, None, Some(&catalog), &allowed);
        assert!(schemas.is_empty(), "got: {schemas:?}");
    }

    #[test]
    fn an_a2a_ref_falls_back_to_its_own_description_when_the_agent_is_unreachable() {
        // The agent is configured, but its card could not be fetched this run.
        // The ref's own description and schema still advertise the tool.
        let rt = ExtensionRuntime::for_test().unwrap();
        let params = serde_json::json!({"type": "object", "properties": {}});
        let allowed = vec![a2a_ref(Some("own description"), Some(params.clone()))];
        let catalog = A2aToolCatalog::for_tests(&[], &["my-agent"]);

        let schemas =
            list_tools_for_llm(&rt, None, None, None, None, None, Some(&catalog), &allowed);
        assert_eq!(schemas.len(), 1, "got: {schemas:?}");
        let s = &schemas[0];
        assert_eq!(s.description, "own description");
        assert_eq!(s.parameters, params);
    }

    #[test]
    fn a_resolvable_a2a_ref_is_not_reported_as_missing() {
        // Without the a2a arm this falls through to the extension runtime and
        // reports "extension failed to load" for a tool that works — a loud,
        // wrong warning on every turn.
        let rt = ExtensionRuntime::for_test().unwrap();
        let params = serde_json::json!({"type": "object", "properties": {}});
        let allowed = vec![a2a_ref(None, Some(params))];
        let catalog = A2aToolCatalog::for_tests(&[("my-agent", "from the card")], &[]);

        let missing = missing_tools(&rt, None, None, None, None, None, Some(&catalog), &allowed);
        assert!(missing.is_empty(), "got: {missing:?}");
    }

    #[test]
    fn an_a2a_ref_with_no_schema_and_no_catalog_entry_is_reported_as_missing() {
        // Genuinely unusable: no card, no author schema. Must be reported,
        // and the reason must name a2a rather than extensions.
        let rt = ExtensionRuntime::for_test().unwrap();
        let allowed = vec![a2a_ref(None, None)];

        let missing = missing_tools(&rt, None, None, None, None, None, None, &allowed);
        assert_eq!(missing.len(), 1, "got: {missing:?}");
        assert_eq!(missing[0].extension_id, "a2a:my-agent");
        assert!(
            missing[0].reason.contains("a2a"),
            "got: {}",
            missing[0].reason
        );
    }

    #[test]
    fn an_a2a_ref_for_an_unconfigured_agent_is_neither_advertised_nor_silent() {
        // A full author contract is not enough: dispatch refuses an agent the
        // worker was not configured with, so listing it would offer the model
        // a call that can only fail. The listing and the preflight check must
        // agree — dropped from one, reported by the other.
        let rt = ExtensionRuntime::for_test().unwrap();
        let params = serde_json::json!({"type": "object", "properties": {}});
        let allowed = vec![a2a_ref(Some("own description"), Some(params))];
        let other_agent = A2aToolCatalog::for_tests(&[("someone-else", "x")], &[]);

        for catalog in [None, Some(&other_agent)] {
            let schemas = list_tools_for_llm(&rt, None, None, None, None, None, catalog, &allowed);
            assert!(
                schemas.is_empty(),
                "must not be advertised, got: {schemas:?}"
            );

            let missing = missing_tools(&rt, None, None, None, None, None, catalog, &allowed);
            assert_eq!(missing.len(), 1, "must be reported, got: {missing:?}");
            assert!(
                missing[0].reason.contains("not configured"),
                "got: {}",
                missing[0].reason
            );
        }
    }

    #[tokio::test]
    async fn dispatching_an_a2a_call_with_no_catalog_yields_an_error_value_naming_the_agent() {
        // With no catalogue wired at all, dispatch must still return `Ok` with
        // an `{"error": ...}` value the LLM can observe — never `Err`, never a
        // panic.
        let rt = Arc::new(ExtensionRuntime::for_test().unwrap());
        let tc = TenantContext::new("t", "e");
        let call = ToolCallRecord {
            call_id: "c1".into(),
            extension_id: "a2a:my-agent".into(),
            tool_name: "call".into(),
            args: serde_json::json!({ "message": "hi" }),
        };
        let out = dispatch_tool_call(rt, None, None, None, None, None, call, &tc)
            .await
            .expect("a2a dispatch with no catalog must not return Err");
        let error = out
            .get("error")
            .and_then(|v| v.as_str())
            .expect("expected an error value");
        assert!(error.contains("my-agent"), "got: {error}");
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod kv_ledger_tests {
    use super::*;
    use crate::kv::MemoryKv;
    use std::sync::Arc;

    #[tokio::test]
    async fn record_then_get_replays_result() {
        let ledger = KvToolLedger::new(Arc::new(MemoryKv::new()));
        let t = TenantContext::new("acme", "prod");
        assert!(ledger.get(&t, "sess", "call1").await.unwrap().is_none());
        ledger
            .record(&t, "sess", "call1", serde_json::json!({"ok": true}))
            .await
            .unwrap();
        let got = ledger.get(&t, "sess", "call1").await.unwrap();
        assert_eq!(got, Some(serde_json::json!({"ok": true})));
    }
}