klieo 3.2.1

Open-source Rust agent framework — typed agents, durable inter-agent comms, local-first.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
//! `App` — fluent assembler that collapses the 13-field `AgentContext`
//! into a one-call wiring surface.
//!
//! Use [`App::local`] for ephemeral dev (Ollama + sqlite + memory bus),
//! [`App::local_at`] for persistent dev,
//! [`App::builder`] for custom impls. All three produce an [`App`] that
//! mints fresh [`AgentContext`] per run via [`App::context`] and
//! shares a parent [`tokio_util::sync::CancellationToken`] across runs.
//!
//! ```ignore
//! use klieo::{App, SimpleAgent};
//! let app = App::local().model("qwen2.5:14b").build().await?;
//! let agent = SimpleAgent::new("hello", "Be brief.", app.tools_catalogue().to_vec());
//! let answer = app.run(&agent, "hi".into()).await?;
//! ```
//!
//! Power users who need a port shape `App` does not surface can still
//! hand-build `AgentContext` directly — `App` is shortcut, not
//! replacement.

use klieo_core::{
    Agent, AgentContext, AuditRedactor, BusHandles, EpisodicMemory, Error, LlmClient,
    LongTermMemory, MemoryHandles, RunId, ShortTermMemory, ToolDef, ToolInvoker,
};
use std::sync::Arc;
use tokio_util::sync::CancellationToken;

#[cfg(feature = "tools")]
use klieo_core::Tool;

#[cfg(feature = "graph-rag")]
use crate::recall_recorder::{RecallRecorder, MAX_RECALL_QUERY_CHARS};
#[cfg(feature = "graph-rag")]
use klieo_core::Scope;
#[cfg(feature = "graph-rag")]
use klieo_memory_graph::KnowledgeGraph;
#[cfg(feature = "graph-rag")]
use klieo_memory_graph_rag::GraphAwareLongTerm;

#[cfg(feature = "runlog-sqlite")]
use klieo_runlog::RunLogStore;
#[cfg(any(feature = "runlog-sqlite", feature = "provenance-sqlite"))]
use std::path::PathBuf;

#[cfg(any(
    feature = "llm-openai",
    feature = "llm-anthropic",
    feature = "llm-gemini"
))]
use secrecy::SecretString;

/// Resolved klieo runtime. Holds every `Arc<dyn …>` port plus a parent
/// cancel token. Cheap to clone; expensive to construct (impl crates
/// open DB handles / pools during their `From` impls).
#[derive(Clone)]
pub struct App {
    llm: Arc<dyn LlmClient>,
    memory: MemoryHandles,
    bus: BusHandles,
    tools: Arc<dyn ToolInvoker>,
    catalogue: Vec<ToolDef>,
    parent_cancel: CancellationToken,
    audit_redactor: Option<Arc<dyn AuditRedactor>>,
    /// Default live-capture sink, `None` unless [`AppBuilder::runlog_capture`]
    /// opted in. Held as the concrete [`klieo_runlog::RunLogCaptureSink`] so
    /// callers can both attach it (as a `dyn CaptureSink`) onto a run's
    /// `RunOptions` and `drain` its recording afterwards. `App::run` does not
    /// auto-attach it — an agent owns its own `RunOptions`.
    #[cfg(feature = "runlog")]
    capture_sink: Option<Arc<klieo_runlog::RunLogCaptureSink>>,
    /// Opt-in [`RunLogStore`] for episodes-only auto-persist on `App::run`
    /// completion, `None` unless [`AppBuilder::sqlite_runlog`] opted in. This
    /// is a SEPARATE concern from `capture_sink`: it projects the run-keyed
    /// episode timeline (never the shared live-capture buffer) so per-call
    /// token cost stays the existing manual capture path.
    #[cfg(feature = "runlog-sqlite")]
    runlog_store: Option<Arc<dyn RunLogStore>>,
    #[cfg(feature = "graph-rag")]
    graph_rag_metrics: Option<Arc<klieo_memory_graph::RecallMetrics>>,
    // Shared across clones so `shutdown` can take the JoinHandle out and
    // await it once; an `Arc<JoinHandle>` could not be awaited by value.
    #[cfg(feature = "graph-rag")]
    graph_projector: Option<Arc<std::sync::Mutex<Option<tokio::task::JoinHandle<()>>>>>,
    #[cfg(feature = "graph-rag")]
    graph_projector_cancel: Option<CancellationToken>,
    /// Read handles over the projected knowledge graph, for the ops-viz
    /// explorer. All three are `Some` together (set at build time from the
    /// same [`crate::graph_rag::WiredGraphRag`]) or `None` together.
    #[cfg(feature = "graph-rag")]
    graph_explorer_graph: Option<Arc<dyn KnowledgeGraph>>,
    #[cfg(feature = "graph-rag")]
    graph_explorer_recall: Option<Arc<GraphAwareLongTerm>>,
    #[cfg(feature = "graph-rag")]
    graph_explorer_scope: Option<Scope>,
}

impl std::fmt::Debug for App {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("App")
            .field("llm", &self.llm.name())
            .field("tools", &self.catalogue.len())
            .field("cancelled", &self.parent_cancel.is_cancelled())
            .finish_non_exhaustive()
    }
}

/// Cap on episodes auto-persisted per run on [`App::run`] completion. Beyond
/// this the projection + store write is skipped (with a `warn`) so the
/// completion hook's work stays bounded regardless of run length; the run's
/// outcome is unaffected.
#[cfg(feature = "runlog-sqlite")]
const MAX_AUTO_PERSIST_EPISODES: usize = 10_000;

impl App {
    /// Start a local-defaults builder: Ollama at
    /// `http://localhost:11434` + sqlite (`:memory:`) with the dummy
    /// embedder + in-process [`klieo_bus_memory::MemoryBus`]. Override
    /// any default by calling its setter on the returned builder.
    ///
    /// State is **ephemeral** — the in-memory SQLite database resets
    /// every run. Use this for tests, CI, and one-shot scripts. For
    /// iterative dev where memory should survive restarts use
    /// [`App::local_at`].
    ///
    /// Available only when the `llm-ollama`, `memory-sqlite`, and
    /// `bus-memory` features are all active. Without them, use
    /// [`App::builder`] and wire ports by hand.
    #[cfg(all(
        feature = "llm-ollama",
        feature = "memory-sqlite",
        feature = "bus-memory",
        feature = "tools",
    ))]
    pub fn local() -> AppBuilder {
        AppBuilder::new()
            .ollama("http://localhost:11434", "qwen2.5:14b")
            .sqlite(":memory:")
            .memory_bus()
    }

    /// Start a local-defaults builder that persists memory to `db_path`.
    ///
    /// Same as [`App::local`] except the SQLite database is written to
    /// the given path instead of `:memory:`. Memory (threads, episodic
    /// events) survives process restarts — the file is created on first
    /// run and reused on every subsequent run.
    ///
    /// Recommended for interactive dev:
    ///
    /// ```ignore
    /// let app = App::local_at("klieo.db").model("qwen2.5:14b").build().await?;
    /// ```
    ///
    /// Use [`App::local`] (`:memory:`) for tests and CI.
    #[cfg(all(
        feature = "llm-ollama",
        feature = "memory-sqlite",
        feature = "bus-memory",
        feature = "tools",
    ))]
    pub fn local_at(db_path: impl Into<std::path::PathBuf>) -> AppBuilder {
        AppBuilder::new()
            .ollama("http://localhost:11434", "qwen2.5:14b")
            .sqlite(db_path)
            .memory_bus()
    }

    /// Start a local-defaults builder with persistent memory in the
    /// user's standard data directory.
    ///
    /// Path is resolved as `dirs::data_dir().join("klieo/klieo.db")`:
    ///
    /// | OS      | Resolved path                                 |
    /// |---------|-----------------------------------------------|
    /// | Linux   | `$XDG_DATA_HOME/klieo/klieo.db` (default `~/.local/share/klieo/klieo.db`) |
    /// | macOS   | `~/Library/Application Support/klieo/klieo.db` |
    /// | Windows | `%APPDATA%\klieo\klieo.db`                    |
    ///
    /// The parent directory is created on first call (`create_dir_all`
    /// is idempotent on repeat runs). The SQLite file itself is opened
    /// lazily on first connection.
    ///
    /// Returns an error if the platform does not expose a data
    /// directory (rare; on those platforms fall back to
    /// [`App::local_at`] with an explicit path) or if the directory
    /// cannot be created (filesystem error). Override the location by
    /// pointing `XDG_DATA_HOME` at a writable path before calling.
    ///
    /// Available with the `data-dir` feature.
    #[cfg(feature = "data-dir")]
    pub fn local_at_data_dir() -> Result<AppBuilder, Error> {
        let dir = dirs::data_dir().ok_or_else(|| {
            Error::Config(klieo_core::error::ConfigError::MissingKey(
                "platform data directory unavailable; call App::local_at with an explicit path"
                    .into(),
            ))
        })?;
        let path = dir.join("klieo").join("klieo.db");
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| Error::wrap("create klieo data dir", e))?;
        }
        Ok(AppBuilder::new()
            .ollama("http://localhost:11434", "qwen2.5:14b")
            .sqlite(path)
            .memory_bus())
    }

    /// Start an empty builder. Every port must be set explicitly.
    pub fn builder() -> AppBuilder {
        AppBuilder::new()
    }

    /// Mint a fresh [`AgentContext`] for one agent run. Each call
    /// produces a distinct [`RunId`] and a child cancel derived from
    /// `App`'s parent token — cancelling the parent cancels every
    /// in-flight run; per-run cancel does not affect siblings.
    ///
    /// When graph-rag is configured, the context's long-term port is
    /// wrapped in a fresh `RecallRecorder` bound to this run's id, so
    /// every recall the run performs is recorded as a redacted, bounded
    /// [`klieo_core::Episode::MemoryRecall`] — one recorder per run, never
    /// shared across runs the way the underlying long-term store is.
    pub fn context(&self, agent_name: impl Into<String>) -> AgentContext {
        let run_id = RunId::new();
        let ctx = AgentContext::new(
            self.llm.clone(),
            self.memory.short_term.clone(),
            self.long_term_for_run(run_id),
            self.memory.episodic.clone(),
            self.bus.pubsub.clone(),
            self.bus.kv.clone(),
            self.bus.request_reply.clone(),
            self.bus.jobs.clone(),
            self.tools.clone(),
            run_id,
            self.parent_cancel.child_token(),
            agent_name,
        );
        match &self.audit_redactor {
            Some(redactor) => ctx.with_audit_redactor(redactor.clone()),
            None => ctx,
        }
    }

    /// The long-term port for a freshly-minted run: the shared
    /// [`MemoryHandles::long_term`] store, wrapped in a per-run
    /// `RecallRecorder` when graph-rag is configured so every recall this
    /// run performs is traced under `run_id`. Without graph-rag (or when
    /// its recall handle was never installed) this is just the shared
    /// store, unwrapped.
    #[cfg(feature = "graph-rag")]
    fn long_term_for_run(&self, run_id: RunId) -> Arc<dyn LongTermMemory> {
        if self.graph_explorer_recall.is_none() {
            return self.memory.long_term.clone();
        }
        Arc::new(RecallRecorder::new(
            self.memory.long_term.clone(),
            self.memory.episodic.clone(),
            run_id,
            self.recall_redactor(),
            MAX_RECALL_QUERY_CHARS,
        ))
    }

    /// The redactor a per-run `RecallRecorder` records recall queries
    /// through: the App's resolved [`AuditRedactor`] (explicit override, or
    /// the `ops`-feature default — see `resolve_audit_redactor`) when one
    /// is configured, otherwise a passthrough that leaves the query as-is.
    ///
    /// The passthrough is only reached when NO real redactor is available
    /// anywhere in the App — it never overrides a configured one. That
    /// mirrors how a non-PII-flagged `ToolCall`'s args reach episodic
    /// storage unredacted (see `klieo_core::runtime::dispatch`): the query
    /// is still protected by `RecallRecorder`'s length bound
    /// (`MAX_RECALL_QUERY_CHARS`), just not content-redacted.
    #[cfg(feature = "graph-rag")]
    fn recall_redactor(&self) -> Arc<dyn AuditRedactor> {
        self.audit_redactor
            .clone()
            .unwrap_or_else(|| Arc::new(PassthroughRedactor))
    }

    #[cfg(not(feature = "graph-rag"))]
    fn long_term_for_run(&self, _run_id: RunId) -> Arc<dyn LongTermMemory> {
        self.memory.long_term.clone()
    }

    /// Use this to call [`LlmClient::complete`] directly from custom
    /// HTTP / CLI wrappers that do not want to mint an
    /// [`AgentContext`] per call.
    pub fn llm(&self) -> Arc<dyn LlmClient> {
        self.llm.clone()
    }

    /// Every handle in the returned bundle shares the underlying memory
    /// backend — cloning one and mutating through another are visible to
    /// each other under that backend's consistency model.
    pub fn memory(&self) -> &MemoryHandles {
        &self.memory
    }

    /// Every handle in the returned bundle shares the underlying bus
    /// transport — pubsub messages published on one handle are visible
    /// to subscribers on any clone.
    pub fn bus(&self) -> &BusHandles {
        &self.bus
    }

    /// Pair with [`App::tools_catalogue`] when you need both the
    /// dispatcher and the `Vec<ToolDef>` advertised to the LLM.
    pub fn tools_invoker(&self) -> Arc<dyn ToolInvoker> {
        self.tools.clone()
    }

    /// Tool catalogue advertised to the LLM.
    pub fn tools_catalogue(&self) -> &[ToolDef] {
        &self.catalogue
    }

    /// An [`McpServer`](klieo_mcp_server::McpServer) that publishes this
    /// App's tools to MCP clients: the App's tool catalogue becomes the
    /// MCP `tools/list` response and `tools/call` dispatches through the
    /// App's invoker. The transport is chosen by the caller — pass the
    /// returned server to a transport driver, or use the
    /// [`App::serve_mcp_stdio`] shortcut for the process stdio loop.
    ///
    /// Available with the `mcp-server` feature.
    #[cfg(feature = "mcp-server")]
    pub fn mcp_server(&self) -> Arc<klieo_mcp_server::McpServer> {
        Arc::new(klieo_mcp_server::McpServer::expose_tools(
            self.tools_invoker(),
        ))
    }

    /// Publish this App's tools to MCP clients over the process stdin /
    /// stdout. Blocks until the stdio transport closes (peer disconnect)
    /// or a fatal I/O error, returning [`Error`] on failure.
    ///
    /// Available with the `mcp-server` feature.
    #[cfg(feature = "mcp-server")]
    pub async fn serve_mcp_stdio(&self) -> Result<(), Error> {
        self.mcp_server()
            .serve_stdio()
            .await
            .map_err(|e| Error::wrap("serve mcp stdio", e))
    }

    /// Parent cancel token. Clone to share across runs (e.g.
    /// SIGINT-driven shutdown).
    pub fn cancel_token(&self) -> CancellationToken {
        self.parent_cancel.clone()
    }

    /// The default live LLM-I/O capture sink as a `dyn CaptureSink`, if
    /// [`AppBuilder::runlog_capture`] opted in. `App::run` does not
    /// auto-attach it (an agent owns its own [`RunOptions`]); attach it
    /// explicitly via
    /// [`RunOptions::with_capture_sink`](klieo_core::runtime::RunOptions::with_capture_sink)
    /// — e.g. `SimpleAgent::with_run_options(RunOptions::default().with_capture_sink(app.capture_sink().unwrap()))`
    /// — then drive the agent and `drain` the recording from the same App via
    /// [`App::runlog_capture_sink`]. Returns `None` when capture was not configured.
    #[cfg(feature = "runlog")]
    pub fn capture_sink(&self) -> Option<Arc<dyn klieo_core::runtime::CaptureSink>> {
        self.capture_sink
            .clone()
            .map(|sink| sink as Arc<dyn klieo_core::runtime::CaptureSink>)
    }

    /// The opt-in capture sink as its concrete [`klieo_runlog::RunLogCaptureSink`],
    /// so callers can `drain` the recording after a run. Shares the same buffer
    /// as the `dyn CaptureSink` handed out by [`App::capture_sink`] — attach that
    /// to the run, then `drain` here. `None` when capture was not configured.
    #[cfg(feature = "runlog")]
    pub fn runlog_capture_sink(&self) -> Option<Arc<klieo_runlog::RunLogCaptureSink>> {
        self.capture_sink.clone()
    }

    /// Snapshot of GraphRAG recall metrics (graph-hit rate, candidate
    /// counts, projector lag), or `None` if this App was not built with
    /// `graph_rag`.
    #[cfg(feature = "graph-rag")]
    pub fn graph_rag_metrics(&self) -> Option<klieo_memory_graph::RecallSnapshot> {
        self.graph_rag_metrics.as_ref().map(|m| m.snapshot())
    }

    /// Read handles over the projected knowledge graph, for the ops-viz
    /// explorer. `None` unless graph-rag is configured.
    #[cfg(feature = "graph-rag")]
    pub fn graph_explorer(
        &self,
    ) -> Option<(Arc<dyn KnowledgeGraph>, Arc<GraphAwareLongTerm>, Scope)> {
        Some((
            self.graph_explorer_graph.clone()?,
            self.graph_explorer_recall.clone()?,
            self.graph_explorer_scope.clone()?,
        ))
    }

    /// Attach this App's graph-explorer handles to an ops-viz router builder,
    /// enabling the `/viz/graph` browse + `/viz/graph/query` lens tab. A no-op
    /// when graph-rag is not configured, so embedders opt in with one call
    /// instead of destructuring [`Self::graph_explorer`] themselves.
    ///
    /// ```ignore
    /// let router = app
    ///     .wire_graph_explorer(VizRouterBuilder::from_stores(/* … */).with_live(live))
    ///     .build();
    /// ```
    #[cfg(all(feature = "graph-rag", feature = "observability-viz"))]
    pub fn wire_graph_explorer(
        &self,
        builder: klieo_ops_viz::VizRouterBuilder,
    ) -> klieo_ops_viz::VizRouterBuilder {
        match self.graph_explorer() {
            Some((graph, recall, scope)) => builder.with_graph_explorer(graph, recall, scope),
            None => builder,
        }
    }

    /// Convenience: mint a context with `agent.name()` as
    /// `agent_name`, then delegate to [`Agent::run`].
    ///
    /// Useful when the caller does not need to inspect or mutate the
    /// context between minting and run start. For composite agents
    /// that thread the same context through multiple `Agent::run`
    /// calls, mint via [`App::context`] and call [`Agent::run`]
    /// directly.
    ///
    /// ## Episodes-only run-log auto-persist
    ///
    /// When the App was built with [`AppBuilder::sqlite_runlog`], `App::run`
    /// projects the run's **episode timeline** into the wired
    /// [`RunLogStore`](klieo_runlog::RunLogStore) on completion — on both `Ok`
    /// and `Err` — keyed by the run's own [`RunId`]. The projection is
    /// **episodes-only**: it replays `ctx.episodic` for this run and prices
    /// against an *empty* `LlmIo` sidecar. It deliberately does **not** drain
    /// the shared live-capture buffer
    /// ([`AppBuilder::runlog_capture`]) — that buffer is a single,
    /// non-run-keyed sink shared across every `App::run` call, so draining it
    /// here would mis-attribute LLM cost across runs. Per-call token cost
    /// therefore stays the existing manual capture path; the auto-persisted log
    /// always carries a correct, run-keyed episode timeline. A run that records
    /// no episodes writes no log. Persist failures are logged and never
    /// surfaced — the agent's original result is returned unchanged.
    #[cfg(feature = "runlog-sqlite")]
    pub async fn run<A: Agent>(&self, agent: &A, input: A::Input) -> Result<A::Output, A::Error> {
        let ctx = self.context(agent.name());
        // Capture before `agent.run` consumes `ctx`; `RunId` is `Copy`.
        let run_id = ctx.run_id;
        let agent_name = agent.name().to_string();
        let result = agent.run(ctx, input).await;
        if self.runlog_store.is_some() {
            self.persist_run_log(run_id, &agent_name).await;
        }
        result
    }

    /// Convenience: mint a context with `agent.name()` as
    /// `agent_name`, then delegate to [`Agent::run`].
    ///
    /// Useful when the caller does not need to inspect or mutate the
    /// context between minting and run start. For composite agents
    /// that thread the same context through multiple `Agent::run`
    /// calls, mint via [`App::context`] and call [`Agent::run`]
    /// directly.
    #[cfg(not(feature = "runlog-sqlite"))]
    pub async fn run<A: Agent>(&self, agent: &A, input: A::Input) -> Result<A::Output, A::Error> {
        let ctx = self.context(agent.name());
        agent.run(ctx, input).await
    }

    /// Project this run's episode timeline into the wired
    /// [`RunLogStore`](klieo_runlog::RunLogStore) and persist it. Episodes-only
    /// by contract — passes an empty `LlmIo` slice so the shared live-capture
    /// buffer is never consulted (see [`App::run`]). Skips the write when the
    /// run recorded no episodes. Every failure is logged with structured
    /// context and swallowed: observability side-writes must never fail or
    /// alter a run's outcome.
    #[cfg(feature = "runlog-sqlite")]
    async fn persist_run_log(&self, run_id: RunId, agent_name: &str) {
        let Some(store) = &self.runlog_store else {
            return;
        };
        let episodes = match self.memory.episodic.replay(run_id).await {
            Ok(episodes) => episodes,
            Err(err) => {
                tracing::warn!(%err, %run_id, "runlog auto-persist: replay failed");
                return;
            }
        };
        if episodes.is_empty() {
            return;
        }
        if episodes.len() > MAX_AUTO_PERSIST_EPISODES {
            tracing::warn!(
                %run_id,
                episode_count = episodes.len(),
                cap = MAX_AUTO_PERSIST_EPISODES,
                "runlog auto-persist: skipped, run's episode count exceeds the cap"
            );
            return;
        }
        let log = klieo_runlog::project_with_price_table(
            run_id,
            agent_name,
            &episodes,
            &[],
            &klieo_runlog::PriceTable::default(),
        );
        if let Err(err) = store.put(&log).await {
            tracing::warn!(%err, %run_id, "runlog auto-persist: store put failed");
        }
    }
}

/// Cancels the auto-spawned GraphRAG projector when the last (or any)
/// clone is dropped, so a short-lived `App` never leaks the projector task
/// past runtime shutdown. The cancel is fire-and-forget — `Drop` is sync,
/// so the task is signalled but not awaited; call [`App::shutdown`] first
/// when the drain must complete before the process exits.
///
/// All clones share one projector token, so dropping any clone cancels it;
/// cancellation is idempotent, so a later drop of a sibling is harmless.
#[cfg(feature = "graph-rag")]
impl Drop for App {
    fn drop(&mut self) {
        if let Some(cancel) = &self.graph_projector_cancel {
            cancel.cancel();
        }
    }
}

#[cfg(feature = "graph-rag")]
impl App {
    /// Cancel the GraphRAG projector and await its task drain. Idempotent
    /// across clones and repeat calls: a no-op when `graph_rag` was not
    /// configured or the projector already drained. Cancels only the
    /// projector's child token, never the App's parent token, so sibling
    /// runs sharing that parent are unaffected.
    pub async fn shutdown(&self) {
        if let Some(cancel) = &self.graph_projector_cancel {
            cancel.cancel();
        }
        let handle = self
            .graph_projector
            .as_ref()
            .and_then(|projector| match projector.lock() {
                Ok(mut guard) => guard.take(),
                Err(_) => {
                    tracing::error!("graph-rag projector mutex poisoned; skipping drain");
                    None
                }
            });
        if let Some(handle) = handle {
            if let Err(error) = handle.await {
                tracing::error!(%error, "graph-rag projector task panicked during shutdown");
            }
        }
    }
}

/// Deferred-construction record for a provider chosen via shortcut.
///
/// Lets the builder hold provider-shaped config without instantiating
/// the client until [`AppBuilder::build`] runs (some providers do
/// async/fallible work in their ctors; recording the choice keeps the
/// chain sync until the final await point).
enum LlmShortcut {
    #[cfg(feature = "llm-ollama")]
    Ollama { base_url: String, model: String },
    #[cfg(feature = "llm-openai")]
    OpenAi {
        api_key: SecretString,
        model: String,
    },
    #[cfg(feature = "llm-anthropic")]
    Anthropic {
        api_key: SecretString,
        model: String,
    },
    #[cfg(feature = "llm-gemini")]
    Gemini {
        api_key: SecretString,
        model: String,
    },
}

/// Deferred-construction record for a bus chosen via shortcut.
enum BusShortcut {
    #[cfg(feature = "bus-memory")]
    Memory,
    #[cfg(feature = "bus-nats")]
    Nats(Box<klieo_bus_nats::NatsBusConfig>),
}

/// Deferred-construction record for a memory backend chosen via a
/// shortcut ([`AppBuilder::qdrant`], [`AppBuilder::neo4j`], …).
///
/// Each backend covers a different subset of the memory triple: Qdrant
/// provides `LongTermMemory` only; Neo4j provides `ShortTermMemory` +
/// `EpisodicMemory` only. [`AppBuilder::build`] resolves the recorded
/// choice into a connected backend and composes its covered ports onto
/// the assembled [`MemoryHandles`] via [`apply_ports`].
#[cfg(any(feature = "memory-qdrant", feature = "memory-neo4j"))]
enum MemoryShortcut {
    /// Qdrant long-term vector store. `embedder` is `None` for the
    /// fastembed-default [`AppBuilder::qdrant`] convenience, resolved at
    /// `build()`; `Some` for the explicit [`AppBuilder::qdrant_with`].
    #[cfg(feature = "memory-qdrant")]
    Qdrant {
        config: klieo_memory_qdrant::QdrantConfig,
        embedder: Option<Arc<dyn klieo_embed_common::Embedder>>,
    },
    /// Neo4j short-term + episodic store.
    #[cfg(feature = "memory-neo4j")]
    Neo4j(Box<klieo_memory_neo4j::Neo4jConfig>),
}

/// The connected ports a resolved [`MemoryShortcut`] contributes, kept
/// as a distinct shape so [`apply_ports`] is a pure, offline-testable
/// seam independent of any live backend connection.
#[cfg(any(feature = "memory-qdrant", feature = "memory-neo4j"))]
enum ResolvedPorts {
    /// Sets `long_term`, leaves `short_term` + `episodic` unchanged.
    #[cfg(feature = "memory-qdrant")]
    LongTermOnly(Arc<dyn LongTermMemory>),
    /// Sets `short_term` + `episodic`, leaves `long_term` unchanged.
    #[cfg(feature = "memory-neo4j")]
    ShortTermAndEpisodic {
        short_term: Arc<dyn ShortTermMemory>,
        episodic: Arc<dyn EpisodicMemory>,
    },
}

/// Compose a resolved backend's covered ports onto `memory`, leaving
/// every port the backend does not implement at its prior value. Pure
/// and synchronous: the connection work happens in
/// [`AppBuilder::resolve_memory_shortcut`]; this seam only assigns
/// fields, so it is unit-testable without a live Qdrant/Neo4j.
#[cfg(any(feature = "memory-qdrant", feature = "memory-neo4j"))]
fn apply_ports(resolved: ResolvedPorts, memory: &mut MemoryHandles) {
    match resolved {
        #[cfg(feature = "memory-qdrant")]
        ResolvedPorts::LongTermOnly(long_term) => {
            memory.long_term = long_term;
        }
        #[cfg(feature = "memory-neo4j")]
        ResolvedPorts::ShortTermAndEpisodic {
            short_term,
            episodic,
        } => {
            memory.short_term = short_term;
            memory.episodic = episodic;
        }
    }
}

/// Connect the backend a [`MemoryShortcut`] describes and return the
/// ports it contributes. Qdrant uses the supplied embedder, defaulting
/// to [`klieo_embed_common::FastEmbedEmbedder`] when none was given (the
/// [`AppBuilder::qdrant`] convenience path). The fastembed default is
/// reachable only under the `embed-fastembed` feature, which is the same
/// feature that exposes [`AppBuilder::qdrant`].
#[cfg(any(feature = "memory-qdrant", feature = "memory-neo4j"))]
async fn resolve_memory_backend(shortcut: MemoryShortcut) -> Result<ResolvedPorts, Error> {
    match shortcut {
        #[cfg(feature = "memory-qdrant")]
        MemoryShortcut::Qdrant { config, embedder } => {
            let embedder = resolve_qdrant_embedder(embedder)?;
            let mem = klieo_memory_qdrant::MemoryQdrant::new(config, embedder).await?;
            Ok(ResolvedPorts::LongTermOnly(mem.long_term))
        }
        #[cfg(feature = "memory-neo4j")]
        MemoryShortcut::Neo4j(config) => {
            let mem = klieo_memory_neo4j::MemoryNeo4j::new(*config).await?;
            Ok(ResolvedPorts::ShortTermAndEpisodic {
                short_term: mem.short_term,
                episodic: mem.episodic,
            })
        }
    }
}

/// An explicit embedder (from [`AppBuilder::qdrant_with`]) always wins.
/// Otherwise default to fastembed — reachable only under
/// `embed-fastembed`, the feature that also gates [`AppBuilder::qdrant`],
/// so a `None` embedder cannot occur without it.
#[cfg(feature = "memory-qdrant")]
fn resolve_qdrant_embedder(
    explicit: Option<Arc<dyn klieo_embed_common::Embedder>>,
) -> Result<Arc<dyn klieo_embed_common::Embedder>, Error> {
    if let Some(embedder) = explicit {
        return Ok(embedder);
    }
    #[cfg(feature = "embed-fastembed")]
    {
        let embedder = klieo_embed_common::FastEmbedEmbedder::new()?;
        Ok(Arc::new(embedder))
    }
    #[cfg(not(feature = "embed-fastembed"))]
    {
        Err(Error::AppBuildError {
            missing: "memory.long_term embedder (qdrant_with requires an explicit \
                      embedder when the embed-fastembed feature is off)",
        })
    }
}

/// Deferred-construction record for one stdio MCP server.
#[cfg(feature = "mcp")]
struct McpStdioSpec {
    id: String,
    cmd: String,
    args: Vec<String>,
}

/// Deferred-construction record for one streamable-HTTP MCP server.
#[cfg(feature = "http")]
struct McpHttpSpec {
    id: String,
    url: String,
    opts: klieo_tools_mcp::HttpConnectOptions,
}

/// One pending MCP server source, resolved at [`AppBuilder::build`] time
/// into wrapped tools. The HTTP variant exists only under the `http`
/// feature.
#[cfg(feature = "mcp")]
enum McpSpec {
    Stdio(McpStdioSpec),
    #[cfg(feature = "http")]
    Http(McpHttpSpec),
}

/// Fluent assembler for [`App`]. All setters consume `self` so the
/// chain reads top-to-bottom in user code.
#[derive(Default)]
pub struct AppBuilder {
    llm: Option<Arc<dyn LlmClient>>,
    memory: Option<MemoryHandles>,
    bus: Option<BusHandles>,
    tools_invoker: Option<Arc<dyn ToolInvoker>>,
    #[cfg(feature = "tools")]
    pending_tools: Vec<Arc<dyn Tool>>,
    parent_cancel: Option<CancellationToken>,
    audit_redactor: Option<Arc<dyn AuditRedactor>>,

    /// Provider label recorded for opt-in live capture. `Some` ⇒ `build()`
    /// mints a [`klieo_runlog::RunLogCaptureSink`] tagged with it so live
    /// captures price correctly. See [`AppBuilder::runlog_capture`].
    #[cfg(feature = "runlog")]
    runlog_capture_provider: Option<String>,

    /// Path for the opt-in episodes-only [`SqliteRunLogStore`](klieo_runlog::SqliteRunLogStore),
    /// opened at [`AppBuilder::build`]. `Some` ⇒ `App::run` auto-persists each
    /// run's episode timeline. See [`AppBuilder::sqlite_runlog`].
    #[cfg(feature = "runlog-sqlite")]
    runlog_sqlite_path: Option<PathBuf>,

    /// Path for the opt-in sqlite-backed provenance chain, opened at
    /// [`AppBuilder::build`]. `Some` ⇒ `build()` wraps `memory.episodic`
    /// in a [`klieo_provenance::ProvenanceEpisodic`] so every episode write
    /// also appends to the chain. See [`AppBuilder::sqlite_provenance`].
    #[cfg(feature = "provenance-sqlite")]
    provenance_sqlite_path: Option<PathBuf>,

    llm_shortcut: Option<LlmShortcut>,
    bus_shortcut: Option<BusShortcut>,

    #[cfg(any(feature = "memory-qdrant", feature = "memory-neo4j"))]
    memory_shortcut: Option<MemoryShortcut>,

    model_registry_path: Option<std::path::PathBuf>,

    short_term: Option<Arc<dyn ShortTermMemory>>,
    long_term: Option<Arc<dyn LongTermMemory>>,
    episodic: Option<Arc<dyn EpisodicMemory>>,

    #[cfg(feature = "memory-sqlite")]
    sqlite_path: Option<std::path::PathBuf>,

    #[cfg(feature = "graph-rag")]
    graph_rag: Option<crate::graph_rag::GraphRagConfig>,

    #[cfg(feature = "mcp")]
    pending_mcp: Vec<McpSpec>,
}

impl AppBuilder {
    /// Construct an empty builder. Prefer [`App::builder`] or
    /// [`App::local`] at the call site.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the LLM port directly with an already-`Arc`-wrapped client.
    pub fn llm(mut self, llm: Arc<dyn LlmClient>) -> Self {
        self.llm = Some(llm);
        self
    }

    /// Set the three memory ports from any value convertible into
    /// [`MemoryHandles`] (e.g. `MemorySqlite::new(...).await?`).
    pub fn memory(mut self, memory: impl Into<MemoryHandles>) -> Self {
        self.memory = Some(memory.into());
        self
    }

    /// Set the four bus ports from any value convertible into
    /// [`BusHandles`] (e.g. `MemoryBus::new()` or
    /// `NatsBus::connect(cfg).await?`).
    pub fn bus(mut self, bus: impl Into<BusHandles>) -> Self {
        self.bus = Some(bus.into());
        self
    }

    /// Set the tool dispatcher directly. Mutually exclusive with
    /// [`AppBuilder::tool`] — calling both errors at `build()`.
    pub fn tools_invoker(mut self, tools: Arc<dyn ToolInvoker>) -> Self {
        self.tools_invoker = Some(tools);
        self
    }

    /// Install the audit redactor applied to PII-flagged tools' recorded
    /// args/results during a run. Overrides the default that the `ops`
    /// feature wires (`klieo_ops::redactor::DefaultRedactor`). When no
    /// redactor is set and the `ops` feature is off, dispatch falls back
    /// to the fail-closed opaque digest for flagged tools.
    pub fn audit_redactor(mut self, redactor: Arc<dyn AuditRedactor>) -> Self {
        self.audit_redactor = Some(redactor);
        self
    }

    /// Opt in to live LLM-I/O capture: at `build()` the App mints a
    /// [`klieo_runlog::RunLogCaptureSink`] tagged with `provider` (so live
    /// captures carry the cost sidecar the projector prices against) and
    /// exposes it via [`App::capture_sink`].
    ///
    /// `App::run` does not auto-attach it — an agent owns its own
    /// [`RunOptions`]. Thread it onto the run yourself, e.g.
    /// `SimpleAgent::with_run_options(RunOptions::default().with_capture_sink(app.capture_sink().unwrap()))`,
    /// then `RunLogCaptureSink::drain` the recording after the run.
    ///
    /// Available with the `runlog` feature.
    #[cfg(feature = "runlog")]
    pub fn runlog_capture(mut self, provider: impl Into<String>) -> Self {
        self.runlog_capture_provider = Some(provider.into());
        self
    }

    /// Opt in to **episodes-only** run-log auto-persist: at `build()` the App
    /// opens a [`SqliteRunLogStore`](klieo_runlog::SqliteRunLogStore) at `path`
    /// (`":memory:"` or a file), and every [`App::run`] projects the run's
    /// episode timeline into it on completion.
    ///
    /// This is **episodes-only** and distinct from [`AppBuilder::runlog_capture`]:
    /// the auto-persist replays the run-keyed `ctx.episodic` timeline and prices
    /// against an empty `LlmIo` sidecar. It never drains the shared live-capture
    /// buffer — that buffer is non-run-keyed and shared across every `App::run`
    /// call, so draining it here would mis-attribute LLM cost across runs.
    /// Per-call token cost stays the existing manual `runlog_capture` path. A run
    /// that records no episodes writes no log, and persist failures are logged,
    /// never surfaced.
    ///
    /// Available with the `runlog-sqlite` feature.
    #[cfg(feature = "runlog-sqlite")]
    pub fn sqlite_runlog(mut self, path: impl Into<PathBuf>) -> Self {
        self.runlog_sqlite_path = Some(path.into());
        self
    }

    /// Opt in to a sqlite-backed provenance hash-chain: at `build()` the App
    /// opens a [`SqliteProvenanceRepository`](klieo_provenance::SqliteProvenanceRepository)
    /// at `path` (`":memory:"` or a file) and wraps the resolved episodic-memory
    /// port in a [`ProvenanceEpisodic`](klieo_provenance::ProvenanceEpisodic)
    /// decorator. Thereafter every episode write also appends one entry to the
    /// chain under a fixed scope, stamped with a stable non-PII actor label.
    ///
    /// # Write amplification
    ///
    /// Each [`App::run`] episode (`Started`, `LlmCall`, `ToolCall`, …) incurs one
    /// additional provenance append. This is the accepted, documented cost of the
    /// durable chain; the append is best-effort and never fails the episode write.
    ///
    /// # Scope and actor
    ///
    /// Entries use scope [`PROVENANCE_SCOPE`] and actor [`PROVENANCE_ACTOR`] — a
    /// stable role label, never operator PII.
    ///
    /// Available with the `provenance-sqlite` feature.
    #[cfg(feature = "provenance-sqlite")]
    pub fn sqlite_provenance(mut self, path: impl Into<PathBuf>) -> Self {
        self.provenance_sqlite_path = Some(path.into());
        self
    }

    /// Register one tool. Repeated calls accumulate. The final
    /// `build()` consolidates them into a
    /// [`klieo_tools::ChainedInvoker`]. Mutually exclusive with
    /// [`AppBuilder::tools_invoker`].
    #[cfg(feature = "tools")]
    pub fn tool<T: Tool + 'static>(mut self, tool: T) -> Self {
        self.pending_tools.push(Arc::new(tool));
        self
    }

    /// Override the parent cancel token. Default: a fresh, uncancelled
    /// `CancellationToken::new()`.
    pub fn cancel_token(mut self, token: CancellationToken) -> Self {
        self.parent_cancel = Some(token);
        self
    }

    /// Set just the short-term-memory port. Composes with
    /// [`AppBuilder::long_term`] + [`AppBuilder::episodic`] to satisfy
    /// the memory triple. Useful for partial-shape impls like
    /// `MemoryNeo4j` (short + episodic) paired with `MemoryQdrant`
    /// (long).
    pub fn short_term(mut self, short_term: Arc<dyn ShortTermMemory>) -> Self {
        self.short_term = Some(short_term);
        self
    }

    /// Set just the long-term-memory port. See
    /// [`AppBuilder::short_term`] for composition semantics.
    pub fn long_term(mut self, long_term: Arc<dyn LongTermMemory>) -> Self {
        self.long_term = Some(long_term);
        self
    }

    /// Set just the episodic-memory port. See
    /// [`AppBuilder::short_term`] for composition semantics.
    pub fn episodic(mut self, episodic: Arc<dyn EpisodicMemory>) -> Self {
        self.episodic = Some(episodic);
        self
    }

    /// Configure Ollama as the LLM port. `base_url` accepts a
    /// scheme-prefixed URL (e.g. `"http://localhost:11434"`). Last
    /// provider shortcut wins; explicit [`AppBuilder::llm`] overrides
    /// every shortcut.
    ///
    /// Available with the `llm-ollama` feature.
    #[cfg(feature = "llm-ollama")]
    pub fn ollama(mut self, base_url: impl Into<String>, model: impl Into<String>) -> Self {
        self.llm_shortcut = Some(LlmShortcut::Ollama {
            base_url: base_url.into(),
            model: model.into(),
        });
        self
    }

    /// Override only the Ollama model on a builder already configured
    /// via [`AppBuilder::ollama`] (or [`App::local`]). Resets a
    /// non-Ollama provider shortcut to Ollama with the default base
    /// URL.
    #[cfg(feature = "llm-ollama")]
    pub fn model(mut self, model: impl Into<String>) -> Self {
        let base_url = match self.llm_shortcut.take() {
            Some(LlmShortcut::Ollama { base_url, .. }) => base_url,
            _ => "http://localhost:11434".to_string(),
        };
        self.llm_shortcut = Some(LlmShortcut::Ollama {
            base_url,
            model: model.into(),
        });
        self
    }

    /// Configure OpenAI Chat Completions as the LLM port.
    ///
    /// Available with the `llm-openai` feature.
    ///
    /// # Custom base URL
    ///
    /// The `(api_key, model)` shortcut uses OpenAI's default endpoint.  For an
    /// OpenAI-compatible gateway — Azure OpenAI, OpenRouter, a local proxy —
    /// construct the client with [`klieo_llm_openai::OpenAiClient::with_base_url`]
    /// and hand it in via [`AppBuilder::llm`]:
    ///
    /// ```no_run
    /// # use std::sync::Arc;
    /// # use klieo::App;
    /// # use klieo::llm_openai::OpenAiClient;
    /// let app = App::builder()
    ///     .llm(Arc::new(
    ///         OpenAiClient::new("sk-…", "gpt-4o")
    ///             .with_base_url("https://my-gateway/v1"),
    ///     ));
    /// ```
    #[cfg(feature = "llm-openai")]
    pub fn openai(mut self, api_key: impl Into<SecretString>, model: impl Into<String>) -> Self {
        self.llm_shortcut = Some(LlmShortcut::OpenAi {
            api_key: api_key.into(),
            model: model.into(),
        });
        self
    }

    /// Configure Anthropic Messages as the LLM port.
    ///
    /// Available with the `llm-anthropic` feature.
    ///
    /// # Custom base URL and prompt cache
    ///
    /// The `(api_key, model)` shortcut uses Anthropic's default endpoint with
    /// prompt caching **off** (secure-by-default: opt-in only after confirming
    /// the prompt does not contain secrets or regulated content).  To customise
    /// either setting, construct the client directly and pass it via
    /// [`AppBuilder::llm`]:
    ///
    /// ```no_run
    /// # use std::sync::Arc;
    /// # use klieo::App;
    /// # use klieo::llm_anthropic::AnthropicClient;
    /// // Custom gateway + prompt cache opted in:
    /// let app = App::builder()
    ///     .llm(Arc::new(
    ///         AnthropicClient::new("sk-ant-…", "claude-sonnet-4-6")
    ///             .with_base_url("https://my-proxy/anthropic")
    ///             .with_prompt_cache_enabled(),
    ///     ));
    /// ```
    ///
    /// See [`klieo_llm_anthropic::AnthropicClient::with_prompt_cache_enabled`]
    /// and [`klieo_llm_anthropic::AnthropicClient::with_base_url`] for details.
    #[cfg(feature = "llm-anthropic")]
    pub fn anthropic(mut self, api_key: impl Into<SecretString>, model: impl Into<String>) -> Self {
        self.llm_shortcut = Some(LlmShortcut::Anthropic {
            api_key: api_key.into(),
            model: model.into(),
        });
        self
    }

    /// Configure Google Gemini as the LLM port.
    ///
    /// Available with the `llm-gemini` feature.
    #[cfg(feature = "llm-gemini")]
    pub fn gemini(mut self, api_key: impl Into<SecretString>, model: impl Into<String>) -> Self {
        self.llm_shortcut = Some(LlmShortcut::Gemini {
            api_key: api_key.into(),
            model: model.into(),
        });
        self
    }

    /// Opt in to model-registry enforcement: at `build()`, the configured model is
    /// checked against the registry at `path` — a sunset model fails the build, a
    /// deprecated or unpinned model logs a `governance` warning. No path → no check.
    pub fn model_registry(mut self, path: impl Into<std::path::PathBuf>) -> Self {
        self.model_registry_path = Some(path.into());
        self
    }

    /// Use SQLite-backed memory with the dummy embedder. `path` may
    /// be `":memory:"` for an ephemeral DB or a file path for
    /// cross-run persistence.
    ///
    /// Available with the `memory-sqlite` feature.
    #[cfg(feature = "memory-sqlite")]
    pub fn sqlite(mut self, path: impl Into<std::path::PathBuf>) -> Self {
        self.sqlite_path = Some(path.into());
        self
    }

    /// Use a Qdrant long-term vector store with an explicit
    /// [`QdrantConfig`](klieo_memory_qdrant::QdrantConfig) and embedder.
    /// At `build()` this sets the `long_term` port only — pair it with
    /// [`AppBuilder::sqlite`] or [`AppBuilder::neo4j`] for the
    /// short-term + episodic ports.
    ///
    /// Mutually exclusive with [`AppBuilder::graph_rag`] (which manages
    /// its own vector store) — combining them fails at `build()`.
    ///
    /// Available with the `memory-qdrant` feature.
    #[cfg(feature = "memory-qdrant")]
    pub fn qdrant_with(
        mut self,
        config: klieo_memory_qdrant::QdrantConfig,
        embedder: Arc<dyn klieo_embed_common::Embedder>,
    ) -> Self {
        self.memory_shortcut = Some(MemoryShortcut::Qdrant {
            config,
            embedder: Some(embedder),
        });
        self
    }

    /// Use a Qdrant long-term vector store at `url` with the default
    /// fastembed embedder. Convenience over [`AppBuilder::qdrant_with`]
    /// for the common case; for an API key, custom collection prefix, or
    /// a different embedder, use that method with a built
    /// [`QdrantConfig`](klieo_memory_qdrant::QdrantConfig).
    ///
    /// Mutually exclusive with [`AppBuilder::graph_rag`] — combining them
    /// fails at `build()`.
    ///
    /// Available with the `memory-qdrant` + `embed-fastembed` features
    /// (`embed-fastembed` provides the default `FastEmbedEmbedder`;
    /// `memory-qdrant` alone stays embedder-agnostic).
    #[cfg(all(feature = "memory-qdrant", feature = "embed-fastembed"))]
    pub fn qdrant(mut self, url: impl Into<String>) -> Self {
        self.memory_shortcut = Some(MemoryShortcut::Qdrant {
            config: klieo_memory_qdrant::QdrantConfig::new(url),
            embedder: None,
        });
        self
    }

    /// Use a Neo4j short-term + episodic store described by an explicit
    /// [`Neo4jConfig`](klieo_memory_neo4j::Neo4jConfig). At `build()`
    /// this sets the `short_term` + `episodic` ports only — pair it with
    /// [`AppBuilder::sqlite`] or [`AppBuilder::qdrant`] for the
    /// long-term port.
    ///
    /// Available with the `memory-neo4j` feature.
    #[cfg(feature = "memory-neo4j")]
    pub fn neo4j_with(mut self, config: klieo_memory_neo4j::Neo4jConfig) -> Self {
        self.memory_shortcut = Some(MemoryShortcut::Neo4j(Box::new(config)));
        self
    }

    /// Use a Neo4j short-term + episodic store at `uri` with the given
    /// credentials and default pool settings. Convenience over
    /// [`AppBuilder::neo4j_with`]; for tuned pool size or fetch size,
    /// use that method with a built
    /// [`Neo4jConfig`](klieo_memory_neo4j::Neo4jConfig).
    ///
    /// Available with the `memory-neo4j` feature.
    #[cfg(feature = "memory-neo4j")]
    pub fn neo4j(
        self,
        uri: impl Into<String>,
        user: impl Into<String>,
        password: impl Into<secrecy::SecretString>,
    ) -> Self {
        self.neo4j_with(klieo_memory_neo4j::Neo4jConfig::new(uri, user, password))
    }

    /// Install the GraphRAG stack with zero-infrastructure defaults: an
    /// in-process graph + vector store, the default fastembed embedder,
    /// provenance recording, and the projector all on. At `build()` the
    /// composed graph-aware port replaces the App's long-term memory.
    ///
    /// Override individual defaults via [`AppBuilder::graph_rag_with`].
    ///
    /// Available with the `graph-rag` feature.
    #[cfg(feature = "graph-rag")]
    pub fn graph_rag(self) -> Self {
        self.graph_rag_with(crate::graph_rag::GraphRagConfig::in_memory())
    }

    /// Install the GraphRAG stack described by `cfg`. See
    /// [`crate::graph_rag::GraphRagConfig`] for the in-memory and remote
    /// tiers and the chainable opt-out knobs.
    ///
    /// Available with the `graph-rag` feature.
    #[cfg(feature = "graph-rag")]
    pub fn graph_rag_with(mut self, cfg: crate::graph_rag::GraphRagConfig) -> Self {
        self.graph_rag = Some(cfg);
        self
    }

    /// Use the in-process [`klieo_bus_memory::MemoryBus`]. Last bus
    /// shortcut wins; explicit [`AppBuilder::bus`] overrides every
    /// shortcut.
    ///
    /// Available with the `bus-memory` feature.
    #[cfg(feature = "bus-memory")]
    pub fn memory_bus(mut self) -> Self {
        self.bus_shortcut = Some(BusShortcut::Memory);
        self
    }

    /// Use a NATS JetStream bus. Resolves the connection during
    /// [`AppBuilder::build`].
    ///
    /// Available with the `bus-nats` feature.
    #[cfg(feature = "bus-nats")]
    pub fn nats(mut self, config: klieo_bus_nats::NatsBusConfig) -> Self {
        self.bus_shortcut = Some(BusShortcut::Nats(Box::new(config)));
        self
    }

    /// Register a stdio MCP server as a tool source.
    ///
    /// `id` is the server identifier used to namespace tool names
    /// (`mcp:<id>.<tool_name>`). `cmd` is the binary to spawn; `args`
    /// are its arguments. `build()` calls [`klieo_tools_mcp::McpToolset::connect_stdio`]
    /// and adds the resulting tools to the catalogue alongside any
    /// `.tool()` tools.
    ///
    /// Mutually exclusive with `.tools_invoker()` — combining them
    /// returns `Error::AppBuildError` at `build()` time.
    ///
    /// Available with the `mcp` feature.
    #[cfg(feature = "mcp")]
    pub fn mcp_stdio(
        mut self,
        id: impl Into<String>,
        cmd: impl Into<String>,
        args: Vec<String>,
    ) -> Self {
        self.pending_mcp.push(McpSpec::Stdio(McpStdioSpec {
            id: id.into(),
            cmd: cmd.into(),
            args,
        }));
        self
    }

    /// Register a remote MCP server reached over Streamable HTTP as a tool
    /// source.
    ///
    /// `id` namespaces the tool names (`mcp:<id>.<tool_name>`); `url` is
    /// the server endpoint (`https`, or loopback `http` for local dev);
    /// `opts` carry the auth env-var name and optional CA bundle. `build()`
    /// calls [`klieo_tools_mcp::McpToolset::connect_http`] and adds the
    /// resulting tools to the catalogue alongside any `.tool()` tools.
    ///
    /// Mutually exclusive with `.tools_invoker()` — combining them returns
    /// [`Error::AppBuildError`] at `build()` time.
    ///
    /// Available with the `http` feature.
    #[cfg(feature = "http")]
    pub fn mcp_http(
        mut self,
        id: impl Into<String>,
        url: impl Into<String>,
        opts: klieo_tools_mcp::HttpConnectOptions,
    ) -> Self {
        self.pending_mcp.push(McpSpec::Http(McpHttpSpec {
            id: id.into(),
            url: url.into(),
            opts,
        }));
        self
    }

    /// Assemble the [`App`]. Resolves feature-gated shortcuts into
    /// their typed equivalents, validates every required port, and
    /// fails with [`Error::AppBuildError`] if any are missing.
    pub async fn build(mut self) -> Result<App, Error> {
        self.enforce_model_registry()?;
        self.reject_qdrant_graph_rag_conflict()?;

        // Capture before resolve_shortcuts() drains sqlite_path: the
        // remote provenance database reuses the App's sqlite path.
        #[cfg(feature = "graph-rag")]
        let graph_rag_sqlite_path = self.sqlite_path.clone();

        self.resolve_shortcuts().await?;

        let llm = self.llm.ok_or(Error::AppBuildError { missing: "llm" })?;
        #[cfg_attr(
            not(any(feature = "graph-rag", feature = "provenance-sqlite")),
            allow(unused_mut)
        )]
        let mut memory = self
            .memory
            .ok_or(Error::AppBuildError { missing: "memory" })?;
        let bus = self.bus.ok_or(Error::AppBuildError { missing: "bus" })?;

        // Resolved once and shared: the projector's child token must
        // derive from the same parent token the App exposes, so the App's
        // own shutdown reaches the projector without cancelling siblings.
        let parent_cancel = self.parent_cancel.unwrap_or_default();

        // Populated only when `.graph_rag*` was configured; threaded into
        // `App::graph_explorer_*` below. Captured from `wired` before
        // `install_graph_rag` moves `wired.graph` into the projector.
        #[cfg(feature = "graph-rag")]
        let mut graph_explorer_graph: Option<Arc<dyn KnowledgeGraph>> = None;
        #[cfg(feature = "graph-rag")]
        let mut graph_explorer_recall: Option<Arc<GraphAwareLongTerm>> = None;
        #[cfg(feature = "graph-rag")]
        let mut graph_explorer_scope: Option<Scope> = None;

        #[cfg(feature = "graph-rag")]
        let mut graph_rag = match self.graph_rag.take() {
            Some(cfg) => {
                let wired = cfg.wire(llm.clone(), graph_rag_sqlite_path).await?;
                memory.long_term = wired.long_term.clone();
                graph_explorer_graph = Some(wired.graph.clone());
                graph_explorer_recall = Some(wired.graph_aware.clone());
                graph_explorer_scope = Some(wired.projection_scope.clone());
                Some(install_graph_rag(wired, &mut memory, &parent_cancel))
            }
            None => None,
        };

        #[cfg(feature = "provenance-sqlite")]
        install_sqlite_provenance(self.provenance_sqlite_path, &mut memory)?;

        let (tools, catalogue) = resolve_tools(
            self.tools_invoker,
            #[cfg(feature = "tools")]
            self.pending_tools,
        )?;

        #[cfg(feature = "runlog-sqlite")]
        let runlog_store = resolve_runlog_store(self.runlog_sqlite_path).await?;

        let audit_redactor = resolve_audit_redactor(self.audit_redactor);

        // Recorded recall queries can carry PII. When graph-rag is on but no
        // redactor resolved, the per-run `RecallRecorder` falls back to
        // `PassthroughRedactor` — queries are length-bounded but NOT
        // content-redacted. Warn once here, not per `context()`.
        #[cfg(feature = "graph-rag")]
        if graph_explorer_recall.is_some() && audit_redactor.is_none() {
            tracing::warn!(
                "graph-rag recall queries will be recorded with the length bound only and \
                 no content redaction; enable the `ops` feature or set `audit_redactor` \
                 to scrub PII from recorded MemoryRecall queries",
            );
        }

        Ok(App {
            llm,
            memory,
            bus,
            tools,
            catalogue,
            parent_cancel,
            audit_redactor,
            #[cfg(feature = "runlog")]
            capture_sink: build_capture_sink(self.runlog_capture_provider),
            #[cfg(feature = "runlog-sqlite")]
            runlog_store,
            #[cfg(feature = "graph-rag")]
            graph_rag_metrics: graph_rag.as_ref().map(|g| g.metrics.clone()),
            #[cfg(feature = "graph-rag")]
            graph_projector: graph_rag
                .as_mut()
                .and_then(|g| g.projector.take())
                .map(|handle| Arc::new(std::sync::Mutex::new(Some(handle)))),
            #[cfg(feature = "graph-rag")]
            graph_projector_cancel: graph_rag.as_ref().and_then(|g| g.cancel.clone()),
            #[cfg(feature = "graph-rag")]
            graph_explorer_graph,
            #[cfg(feature = "graph-rag")]
            graph_explorer_recall,
            #[cfg(feature = "graph-rag")]
            graph_explorer_scope,
        })
    }

    /// Reject the one memory configuration that silently fights itself:
    /// a Qdrant memory-shortcut alongside a `graph_rag` config. Both
    /// install a long-term vector store, so the second would clobber the
    /// first. Neo4j-shortcut + `graph_rag` is fine (disjoint ports) and
    /// is not blocked. No-op unless both `memory-qdrant` and `graph-rag`
    /// are compiled in.
    #[cfg(all(feature = "memory-qdrant", feature = "graph-rag"))]
    fn reject_qdrant_graph_rag_conflict(&self) -> Result<(), Error> {
        let has_qdrant_shortcut =
            matches!(self.memory_shortcut, Some(MemoryShortcut::Qdrant { .. }));
        if has_qdrant_shortcut && self.graph_rag.is_some() {
            return Err(Error::Config(
                klieo_core::error::ConfigError::InvalidValue {
                    key: "memory".to_string(),
                    reason:
                        "graph_rag manages the long-term vector store; do not also call \
                         .qdrant() — pass the Qdrant URL via GraphRagConfig::remote(qdrant_url, ..)"
                            .to_string(),
                },
            ));
        }
        Ok(())
    }

    /// No-op stub when the conflicting feature pair is not both active.
    #[cfg(not(all(feature = "memory-qdrant", feature = "graph-rag")))]
    fn reject_qdrant_graph_rag_conflict(&self) -> Result<(), Error> {
        Ok(())
    }

    /// Enforce the opt-in model registry against the configured model: load the
    /// registry, fail the build on a sunset model, warn on deprecated/unpinned.
    /// No-op when no registry path was configured.
    fn enforce_model_registry(&self) -> Result<(), Error> {
        let Some(path) = self.model_registry_path.clone() else {
            return Ok(());
        };
        let registry = match klieo_model_registry::ModelRegistry::load_from_path(&path) {
            Ok(r) => r,
            Err(e) => {
                tracing::error!(target: "governance", error = %e, "model registry load failed");
                return Err(Error::AppBuildError {
                    missing: "model-registry",
                });
            }
        };
        match shortcut_model(self.llm_shortcut.as_ref()) {
            Some(pin) => match registry.status(&pin) {
                Some(klieo_model_registry::DeprecationStatus::Sunset(since)) => {
                    return Err(Error::ModelSunset {
                        model: pin.to_string(),
                        since: since.to_string(),
                    });
                }
                Some(klieo_model_registry::DeprecationStatus::DeprecatedSince(since)) => {
                    tracing::warn!(target: "governance", model = %pin, %since, "configured model is deprecated");
                }
                Some(klieo_model_registry::DeprecationStatus::Active) => {}
                None => {
                    tracing::warn!(target: "governance", model = %pin, "configured model is unpinned/unknown in the registry")
                }
                Some(_) => {
                    tracing::warn!(target: "governance", model = %pin, "unrecognized model status; treating as non-fatal")
                }
            },
            None => {
                tracing::warn!(target: "governance", "model not observable (raw LlmClient injected); registry not applied")
            }
        }
        Ok(())
    }

    async fn resolve_shortcuts(&mut self) -> Result<(), Error> {
        self.resolve_llm_shortcut();
        self.resolve_sqlite().await?;
        self.resolve_memory_partials()?;
        #[cfg(any(feature = "memory-qdrant", feature = "memory-neo4j"))]
        self.resolve_memory_shortcut().await?;
        self.resolve_bus_shortcut().await?;
        #[cfg(feature = "mcp")]
        self.resolve_mcp().await?;
        Ok(())
    }

    fn resolve_llm_shortcut(&mut self) {
        if self.llm.is_some() {
            return;
        }
        match self.llm_shortcut.take() {
            None => {}
            #[cfg(feature = "llm-ollama")]
            Some(LlmShortcut::Ollama { base_url, model }) => {
                self.llm = Some(Arc::new(klieo_llm_ollama::OllamaClient::new(
                    base_url, model,
                )));
            }
            #[cfg(feature = "llm-openai")]
            Some(LlmShortcut::OpenAi { api_key, model }) => {
                self.llm = Some(Arc::new(klieo_llm_openai::OpenAiClient::new(
                    api_key, model,
                )));
            }
            #[cfg(feature = "llm-anthropic")]
            Some(LlmShortcut::Anthropic { api_key, model }) => {
                self.llm = Some(Arc::new(klieo_llm_anthropic::AnthropicClient::new(
                    api_key, model,
                )));
            }
            #[cfg(feature = "llm-gemini")]
            Some(LlmShortcut::Gemini { api_key, model }) => {
                self.llm = Some(Arc::new(klieo_llm_gemini::GeminiClient::new(
                    api_key, model,
                )));
            }
        }
    }

    #[cfg(feature = "memory-sqlite")]
    async fn resolve_sqlite(&mut self) -> Result<(), Error> {
        if self.memory.is_some() {
            return Ok(());
        }
        if let Some(path) = self.sqlite_path.take() {
            let mem = klieo_memory_sqlite::MemorySqlite::new(
                path,
                Arc::new(klieo_memory_sqlite::DummyEmbedder),
            )
            .await?;
            self.memory = Some(mem.into());
        }
        Ok(())
    }

    #[cfg(not(feature = "memory-sqlite"))]
    #[allow(clippy::unused_async)]
    async fn resolve_sqlite(&mut self) -> Result<(), Error> {
        Ok(())
    }

    /// Compose `short_term` + `long_term` + `episodic` partials into
    /// [`MemoryHandles`] when [`AppBuilder::memory`] and
    /// [`AppBuilder::sqlite`] were not set. Reports the first missing
    /// trait if some — but not all — partials are present.
    fn resolve_memory_partials(&mut self) -> Result<(), Error> {
        if self.memory.is_some() {
            return Ok(());
        }
        let any_partial =
            self.short_term.is_some() || self.long_term.is_some() || self.episodic.is_some();
        if !any_partial {
            return Ok(());
        }
        let short_term = self.short_term.take().ok_or(Error::AppBuildError {
            missing: "memory.short_term",
        })?;
        let long_term = self.long_term.take().ok_or(Error::AppBuildError {
            missing: "memory.long_term",
        })?;
        let episodic = self.episodic.take().ok_or(Error::AppBuildError {
            missing: "memory.episodic",
        })?;
        self.memory = Some(MemoryHandles::new(short_term, long_term, episodic));
        Ok(())
    }

    /// Resolve a memory-backend shortcut into a connected backend and
    /// compose its covered ports onto the assembled [`MemoryHandles`].
    ///
    /// A shortcut covers only a subset of the triple (Qdrant: long-term;
    /// Neo4j: short-term + episodic), so it composes onto a base triple
    /// established by [`AppBuilder::sqlite`], [`AppBuilder::memory`], or
    /// the per-port partials. With no base triple there is nothing to
    /// compose onto — fail with a guiding error rather than silently
    /// leaving the uncovered ports unset.
    #[cfg(any(feature = "memory-qdrant", feature = "memory-neo4j"))]
    async fn resolve_memory_shortcut(&mut self) -> Result<(), Error> {
        let Some(shortcut) = self.memory_shortcut.take() else {
            return Ok(());
        };
        let memory = self.memory.as_mut().ok_or(Error::AppBuildError {
            missing: "memory (a backend shortcut composes onto a base triple; \
                      also set .sqlite() or .memory())",
        })?;
        let resolved = resolve_memory_backend(shortcut).await?;
        apply_ports(resolved, memory);
        Ok(())
    }

    async fn resolve_bus_shortcut(&mut self) -> Result<(), Error> {
        if self.bus.is_some() {
            return Ok(());
        }
        match self.bus_shortcut.take() {
            None => {}
            #[cfg(feature = "bus-memory")]
            Some(BusShortcut::Memory) => {
                self.bus = Some(klieo_bus_memory::MemoryBus::new().into());
            }
            #[cfg(feature = "bus-nats")]
            Some(BusShortcut::Nats(config)) => {
                let bus = klieo_bus_nats::NatsBus::connect(*config).await?;
                self.bus = Some(bus.into());
            }
        }
        Ok(())
    }

    #[cfg(feature = "mcp")]
    async fn resolve_mcp(&mut self) -> Result<(), Error> {
        if self.tools_invoker.is_some() && !self.pending_mcp.is_empty() {
            tracing::error!(
                op = "resolve_mcp",
                "conflicting builder options: mcp_stdio()/mcp_http() combined with tools_invoker()"
            );
            return Err(Error::AppBuildError {
                missing: "tools (cannot combine .mcp_stdio()/.mcp_http() with .tools_invoker())",
            });
        }
        for spec in self.pending_mcp.drain(..).collect::<Vec<_>>() {
            let tools = match spec {
                McpSpec::Stdio(stdio) => connect_mcp_stdio(stdio).await?,
                #[cfg(feature = "http")]
                McpSpec::Http(http) => connect_mcp_http(http).await?,
            };
            for tool in tools {
                self.pending_tools.push(tool);
            }
        }
        Ok(())
    }
}

/// Connect one stdio MCP server, mapping connect failure to [`Error::Tool`].
#[cfg(feature = "mcp")]
async fn connect_mcp_stdio(spec: McpStdioSpec) -> Result<Vec<Arc<dyn Tool>>, Error> {
    klieo_tools_mcp::McpToolset::connect_stdio(
        klieo_tools_mcp::McpServerId::new(&spec.id),
        &spec.cmd,
        klieo_tools_mcp::StdioConnectOptions {
            args: spec.args,
            ..Default::default()
        },
    )
    .await
    .map_err(|e| {
        tracing::error!(op = "mcp_stdio", server_id = %spec.id, cmd = %spec.cmd, err = %e, "MCP connect failed");
        Error::Tool(e)
    })
}

/// Connect one streamable-HTTP MCP server, mapping connect failure to
/// [`Error::Tool`]. The URL is logged (non-secret); the auth secret never
/// enters [`HttpConnectOptions`] and so cannot leak here.
#[cfg(feature = "http")]
async fn connect_mcp_http(spec: McpHttpSpec) -> Result<Vec<Arc<dyn Tool>>, Error> {
    klieo_tools_mcp::McpToolset::connect_http(
        klieo_tools_mcp::McpServerId::new(&spec.id),
        &spec.url,
        spec.opts,
    )
    .await
    .map_err(|e| {
        tracing::error!(op = "mcp_http", server_id = %spec.id, url = %spec.url, err = %e, "MCP connect failed");
        Error::Tool(e)
    })
}

/// The model a shortcut configures, as a `ModelPin`, if any. The raw
/// `.llm(Arc<dyn LlmClient>)` path returns `None` — its model string is not
/// observable here.
fn shortcut_model(shortcut: Option<&LlmShortcut>) -> Option<klieo_model_registry::ModelPin> {
    let (provider, model): (&str, &str) = match shortcut? {
        #[cfg(feature = "llm-ollama")]
        LlmShortcut::Ollama { model, .. } => ("ollama", model),
        #[cfg(feature = "llm-openai")]
        LlmShortcut::OpenAi { model, .. } => ("openai", model),
        #[cfg(feature = "llm-anthropic")]
        LlmShortcut::Anthropic { model, .. } => ("anthropic", model),
        #[cfg(feature = "llm-gemini")]
        LlmShortcut::Gemini { model, .. } => ("gemini", model),
        // No LLM provider feature enabled: `LlmShortcut` has zero variants,
        // but `&LlmShortcut` is still a reference type (always inhabited to
        // the exhaustiveness checker), so a catch-all is required here.
        #[cfg(not(any(
            feature = "llm-ollama",
            feature = "llm-openai",
            feature = "llm-anthropic",
            feature = "llm-gemini"
        )))]
        _ => return None,
    };
    #[cfg(any(
        feature = "llm-ollama",
        feature = "llm-openai",
        feature = "llm-anthropic",
        feature = "llm-gemini"
    ))]
    Some(klieo_model_registry::ModelPin::new(provider, model))
}

/// Holds the results that GraphRAG wiring produces once the long-term port
/// is installed: always the shared recall metrics, plus the projector task
/// and its cancel token when the projector is enabled.
#[cfg(feature = "graph-rag")]
struct InstalledGraphRag {
    metrics: Arc<klieo_memory_graph::RecallMetrics>,
    projector: Option<tokio::task::JoinHandle<()>>,
    cancel: Option<CancellationToken>,
}

/// Install the wired GraphRAG stack into `memory`. When the projector is
/// enabled, wrap the episodic port so every recorded episode broadcasts
/// to a freshly spawned [`klieo_graph_projector::EpisodeProjector`] that
/// indexes into the same provenance-wrapped graph the long-term port
/// writes through, so projected and remembered facts share one chain.
///
/// The projector's cancel token is a child of the App's parent token, so
/// dropping or cancelling this App's projector never cancels sibling runs
/// that share the same parent.
#[cfg(feature = "graph-rag")]
fn install_graph_rag(
    wired: crate::graph_rag::WiredGraphRag,
    memory: &mut MemoryHandles,
    parent_cancel: &CancellationToken,
) -> InstalledGraphRag {
    if !wired.projector_enabled {
        return InstalledGraphRag {
            metrics: wired.metrics,
            projector: None,
            cancel: None,
        };
    }
    let child = parent_cancel.child_token();
    let (projectable, rx) =
        klieo_graph_projector::ProjectableEpisodic::new(memory.episodic.clone());
    memory.episodic = Arc::new(projectable);
    let projector = Arc::new(
        klieo_graph_projector::EpisodeProjector::builder()
            .metrics(wired.metrics.clone())
            .build(wired.graph, wired.extractor, wired.projection_scope),
    );
    let handle = projector.spawn(rx, child.clone());
    InstalledGraphRag {
        metrics: wired.metrics,
        projector: Some(handle),
        cancel: Some(child),
    }
}

/// An explicit [`AppBuilder::audit_redactor`] always wins. Otherwise,
/// when the `ops` feature is active, default to
/// [`klieo_ops::redactor::DefaultRedactor`] so PII-flagged tools get
/// shape-preserving redaction out of the box. Without `ops` and without
/// an explicit redactor, returns `None` and dispatch falls back to the
/// fail-closed opaque digest for flagged tools.
fn resolve_audit_redactor(
    explicit: Option<Arc<dyn AuditRedactor>>,
) -> Option<Arc<dyn AuditRedactor>> {
    if explicit.is_some() {
        return explicit;
    }
    #[cfg(feature = "ops")]
    {
        Some(Arc::new(klieo_ops::redactor::DefaultRedactor::new()))
    }
    #[cfg(not(feature = "ops"))]
    {
        None
    }
}

/// Identity [`AuditRedactor`] used by [`App::recall_redactor`] only when no
/// real redactor is configured anywhere in the App (no explicit
/// [`AppBuilder::audit_redactor`] and the `ops` feature is not compiled
/// in). It exists so `RecallRecorder::new`'s mandatory redactor parameter
/// always has something to call; `RecallRecorder`'s own length bound is
/// what protects the stored query in that case.
#[cfg(feature = "graph-rag")]
struct PassthroughRedactor;

#[cfg(feature = "graph-rag")]
impl AuditRedactor for PassthroughRedactor {
    fn redact(&self, value: &serde_json::Value) -> serde_json::Value {
        value.clone()
    }
}

/// Mint the opt-in live-capture sink from the recorded provider, tagging it so
/// captured calls carry the cost sidecar the projector prices. `None` provider
/// (no [`AppBuilder::runlog_capture`]) yields no sink.
#[cfg(feature = "runlog")]
fn build_capture_sink(provider: Option<String>) -> Option<Arc<klieo_runlog::RunLogCaptureSink>> {
    provider
        .map(|provider| Arc::new(klieo_runlog::RunLogCaptureSink::new().with_provider(provider)))
}

/// Scope under which `App::sqlite_provenance` records episode-mirror entries.
#[cfg(feature = "provenance-sqlite")]
pub const PROVENANCE_SCOPE: &str = "klieo-episodic";

/// Stable, non-PII actor label stamped on every episode-mirror provenance
/// entry recorded by `App::sqlite_provenance`. Never operator identity.
#[cfg(feature = "provenance-sqlite")]
pub const PROVENANCE_ACTOR: &str = "klieo-agent";

/// Open the opt-in sqlite provenance repository at the recorded path and wrap
/// `memory.episodic` in a [`klieo_provenance::ProvenanceEpisodic`] decorator so
/// every episode write also appends to the chain. `None` path (no
/// [`AppBuilder::sqlite_provenance`]) leaves `memory` untouched. A repository
/// open failure is a build-time configuration error surfaced via [`Error::wrap`]
/// — distinct from the per-episode append failures, which the decorator logs and
/// swallows so the primary episode write never fails.
#[cfg(feature = "provenance-sqlite")]
fn install_sqlite_provenance(
    path: Option<PathBuf>,
    memory: &mut MemoryHandles,
) -> Result<(), Error> {
    let Some(path) = path else {
        return Ok(());
    };
    let repo = klieo_provenance::SqliteProvenanceRepository::open(path)
        .map_err(|e| Error::wrap("open sqlite provenance repository", e))?;
    memory.episodic = Arc::new(klieo_provenance::ProvenanceEpisodic::new(
        memory.episodic.clone(),
        Arc::new(repo),
        PROVENANCE_SCOPE,
        PROVENANCE_ACTOR,
    ));
    Ok(())
}

/// Open the opt-in episodes-only [`SqliteRunLogStore`](klieo_runlog::SqliteRunLogStore)
/// at the recorded path. `None` path (no [`AppBuilder::sqlite_runlog`]) yields no
/// store. A store-open failure is a build-time configuration error, surfaced via
/// [`Error::wrap`] — distinct from the per-run side-write failures, which are
/// logged and swallowed in [`App::persist_run_log`].
#[cfg(feature = "runlog-sqlite")]
async fn resolve_runlog_store(
    path: Option<PathBuf>,
) -> Result<Option<Arc<dyn RunLogStore>>, Error> {
    let Some(path) = path else {
        return Ok(None);
    };
    let store = klieo_runlog::SqliteRunLogStore::new(path)
        .await
        .map_err(|e| Error::wrap("open sqlite runlog store", e))?;
    Ok(Some(Arc::new(store)))
}

fn resolve_tools(
    invoker: Option<Arc<dyn ToolInvoker>>,
    #[cfg(feature = "tools")] pending: Vec<Arc<dyn Tool>>,
) -> Result<(Arc<dyn ToolInvoker>, Vec<ToolDef>), Error> {
    #[cfg(feature = "tools")]
    {
        let has_pending = !pending.is_empty();
        match (invoker, has_pending) {
            (Some(_), true) => Err(Error::AppBuildError {
                missing: "tools (cannot combine .tool() with .tools_invoker())",
            }),
            (Some(inv), false) => {
                let cat = inv.catalogue();
                Ok((inv, cat))
            }
            (None, _) => {
                let mut chained = klieo_tools::ChainedInvoker::new();
                for t in pending {
                    chained
                        .add_tool(t)
                        .map_err(|e| Error::wrap("tool registration failed", e))?;
                }
                let cat = chained.catalogue();
                Ok((Arc::new(chained), cat))
            }
        }
    }
    #[cfg(not(feature = "tools"))]
    {
        let inv = invoker.ok_or(Error::AppBuildError { missing: "tools" })?;
        let cat = inv.catalogue();
        Ok((inv, cat))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use klieo_core::test_utils::{FakeLlmClient, FakeLlmStep, FakeToolInvoker};

    fn fake_llm() -> Arc<dyn LlmClient> {
        Arc::new(FakeLlmClient::new("fake"))
    }

    #[cfg(feature = "llm-ollama")]
    #[test]
    fn shortcut_model_maps_ollama() {
        let s = LlmShortcut::Ollama {
            base_url: "x".into(),
            model: "qwen2.5:14b".into(),
        };
        assert_eq!(
            shortcut_model(Some(&s)),
            Some(klieo_model_registry::ModelPin::new("ollama", "qwen2.5:14b"))
        );
    }

    #[test]
    fn shortcut_model_none_for_raw_llm() {
        assert_eq!(shortcut_model(None), None);
    }

    fn fake_tools() -> Arc<dyn ToolInvoker> {
        Arc::new(FakeToolInvoker::new())
    }

    /// Three independent sqlite memory triples used as the "prior
    /// default" and the canned resolved handles for the pure
    /// `apply_ports` seam test. Each `MemorySqlite` mints distinct
    /// `Arc`s so `Arc::ptr_eq` distinguishes changed from unchanged.
    #[cfg(feature = "memory-sqlite")]
    async fn sqlite_triple() -> klieo_memory_sqlite::MemorySqlite {
        klieo_memory_sqlite::MemorySqlite::new(
            ":memory:",
            Arc::new(klieo_memory_sqlite::DummyEmbedder),
        )
        .await
        .unwrap()
    }

    #[cfg(all(feature = "memory-sqlite", feature = "memory-qdrant"))]
    #[tokio::test]
    async fn apply_ports_long_term_only_leaves_others_unchanged() {
        let prior = sqlite_triple().await;
        let resolved = sqlite_triple().await;
        let prior_short = prior.short_term.clone();
        let prior_episodic = prior.episodic.clone();
        let resolved_long = resolved.long_term.clone();
        let mut handles: MemoryHandles = prior.into();

        apply_ports(
            ResolvedPorts::LongTermOnly(resolved_long.clone()),
            &mut handles,
        );

        assert!(
            Arc::ptr_eq(&handles.long_term, &resolved_long),
            "Qdrant-resolved result must set long_term"
        );
        assert!(
            Arc::ptr_eq(&handles.short_term, &prior_short),
            "long-term-only resolution must leave short_term untouched"
        );
        assert!(
            Arc::ptr_eq(&handles.episodic, &prior_episodic),
            "long-term-only resolution must leave episodic untouched"
        );
    }

    #[cfg(all(feature = "memory-sqlite", feature = "memory-neo4j"))]
    #[tokio::test]
    async fn apply_ports_short_term_and_episodic_leaves_long_term_unchanged() {
        let prior = sqlite_triple().await;
        let resolved = sqlite_triple().await;
        let prior_long = prior.long_term.clone();
        let resolved_short = resolved.short_term.clone();
        let resolved_episodic = resolved.episodic.clone();
        let mut handles: MemoryHandles = prior.into();

        apply_ports(
            ResolvedPorts::ShortTermAndEpisodic {
                short_term: resolved_short.clone(),
                episodic: resolved_episodic.clone(),
            },
            &mut handles,
        );

        assert!(
            Arc::ptr_eq(&handles.short_term, &resolved_short),
            "Neo4j-resolved result must set short_term"
        );
        assert!(
            Arc::ptr_eq(&handles.episodic, &resolved_episodic),
            "Neo4j-resolved result must set episodic"
        );
        assert!(
            Arc::ptr_eq(&handles.long_term, &prior_long),
            "Neo4j-resolved result must leave long_term at the prior default"
        );
    }

    #[cfg(all(
        feature = "memory-qdrant",
        feature = "embed-fastembed",
        feature = "graph-rag"
    ))]
    #[tokio::test]
    async fn qdrant_shortcut_with_graph_rag_is_config_conflict() {
        let err = App::local()
            .model("dummy")
            .qdrant("http://127.0.0.1:6334")
            .graph_rag()
            .build()
            .await
            .unwrap_err();
        assert!(
            matches!(err, Error::Config(_)),
            "expected Error::Config for qdrant+graph_rag conflict, got {err:?}"
        );
    }

    #[tokio::test]
    async fn build_missing_llm_errors() {
        let err = App::builder()
            .memory(
                klieo_memory_sqlite::MemorySqlite::new(
                    ":memory:",
                    Arc::new(klieo_memory_sqlite::DummyEmbedder),
                )
                .await
                .unwrap(),
            )
            .bus(klieo_bus_memory::MemoryBus::new())
            .tools_invoker(fake_tools())
            .build()
            .await
            .unwrap_err();
        assert!(matches!(err, Error::AppBuildError { missing: "llm" }));
    }

    #[tokio::test]
    async fn build_missing_memory_errors() {
        let err = App::builder()
            .llm(fake_llm())
            .bus(klieo_bus_memory::MemoryBus::new())
            .tools_invoker(fake_tools())
            .build()
            .await
            .unwrap_err();
        assert!(matches!(err, Error::AppBuildError { missing: "memory" }));
    }

    #[tokio::test]
    async fn build_missing_bus_errors() {
        let err = App::builder()
            .llm(fake_llm())
            .memory(
                klieo_memory_sqlite::MemorySqlite::new(
                    ":memory:",
                    Arc::new(klieo_memory_sqlite::DummyEmbedder),
                )
                .await
                .unwrap(),
            )
            .tools_invoker(fake_tools())
            .build()
            .await
            .unwrap_err();
        assert!(matches!(err, Error::AppBuildError { missing: "bus" }));
    }

    #[cfg(all(feature = "provenance-sqlite", feature = "memory-sqlite"))]
    #[tokio::test]
    async fn sqlite_provenance_wraps_episodic_and_records_through_it() {
        use klieo_core::{Episode, RunId};

        let app = App::builder()
            .llm(fake_llm())
            .memory(sqlite_triple().await)
            .bus(klieo_bus_memory::MemoryBus::new())
            .tools_invoker(fake_tools())
            .sqlite_provenance(":memory:")
            .build()
            .await
            .unwrap();

        let ctx = app.context("prov-agent");
        let run = RunId::new();
        ctx.episodic
            .record(
                run,
                Episode::Started {
                    agent: "prov-agent".into(),
                },
            )
            .await
            .expect("record through the provenance-wrapped episodic port");

        let replayed = ctx.episodic.replay(run).await.unwrap();
        assert_eq!(
            replayed.len(),
            1,
            "the decorated episodic port must still persist the episode"
        );
    }

    #[cfg(all(feature = "provenance-sqlite", feature = "memory-sqlite"))]
    #[tokio::test]
    async fn sqlite_provenance_open_failure_surfaces_as_build_error() {
        // A path inside a non-existent directory cannot be opened.
        let err = App::builder()
            .llm(fake_llm())
            .memory(sqlite_triple().await)
            .bus(klieo_bus_memory::MemoryBus::new())
            .tools_invoker(fake_tools())
            .sqlite_provenance("/nonexistent-dir-klieo-prov/chain.db")
            .build()
            .await
            .unwrap_err();
        assert!(
            matches!(err, Error::Other { .. }),
            "provenance open failure must surface as a wrapped build error, got {err:?}"
        );
    }

    #[cfg(feature = "graph-rag")]
    #[tokio::test]
    async fn metrics_none_when_graph_rag_not_configured() {
        let app = App::local().model("dummy").build().await.unwrap();
        assert!(
            app.graph_rag_metrics().is_none(),
            "an App built without .graph_rag* must expose no recall metrics"
        );
    }

    #[cfg(feature = "graph-rag")]
    #[tokio::test]
    async fn dropped_app_cancels_projector() {
        use crate::embed_common::FakeEmbedder;
        let cfg = crate::graph_rag::GraphRagConfig::in_memory()
            .embedder(Arc::new(FakeEmbedder::new(384)), "test-fake");
        let cancel = {
            let app = App::local()
                .model("dummy")
                .graph_rag_with(cfg)
                .build()
                .await
                .unwrap();
            app.graph_projector_cancel.clone().unwrap()
        };
        assert!(
            cancel.is_cancelled(),
            "dropping the App must cancel the projector token"
        );
    }

    #[cfg(feature = "graph-rag")]
    #[tokio::test]
    async fn graph_explorer_returns_handles_when_graph_rag_configured() {
        use crate::embed_common::FakeEmbedder;
        let cfg = crate::graph_rag::GraphRagConfig::in_memory()
            .embedder(Arc::new(FakeEmbedder::new(384)), "test-fake");
        let app = App::local()
            .model("dummy")
            .graph_rag_with(cfg)
            .build()
            .await
            .unwrap();
        assert!(
            app.graph_explorer().is_some(),
            "an App built with .graph_rag* must expose graph explorer handles"
        );
    }

    #[cfg(feature = "graph-rag")]
    #[tokio::test]
    async fn graph_explorer_is_none_without_graph_rag() {
        let app = App::local().model("dummy").build().await.unwrap();
        assert!(
            app.graph_explorer().is_none(),
            "an App built without .graph_rag* must expose no graph explorer handles"
        );
    }

    #[cfg(feature = "graph-rag")]
    #[tokio::test]
    async fn context_records_memory_recall_when_graph_rag_configured() {
        use crate::embed_common::FakeEmbedder;
        use klieo_core::Episode;

        let cfg = crate::graph_rag::GraphRagConfig::in_memory()
            .embedder(Arc::new(FakeEmbedder::new(384)), "test-fake");
        let app = App::local()
            .model("dummy")
            .graph_rag_with(cfg)
            .build()
            .await
            .unwrap();
        let ctx = app.context("recall-test-agent");

        ctx.long_term
            .recall(
                Scope::Workspace("recall-test".to_string()),
                "hello world query",
                3,
            )
            .await
            .expect("recall through the per-run context's long-term port");

        let episodes = app
            .memory()
            .episodic
            .replay(ctx.run_id)
            .await
            .expect("replay this run's episodes");
        let recalls: Vec<_> = episodes
            .iter()
            .filter(|e| matches!(e, Episode::MemoryRecall { .. }))
            .collect();
        assert_eq!(
            recalls.len(),
            1,
            "context() must install a per-run RecallRecorder when graph-rag is configured"
        );
        match recalls[0] {
            Episode::MemoryRecall { query, k, .. } => {
                assert_eq!(
                    query, "hello world query",
                    "no PII pattern here — query stored as-is"
                );
                assert_eq!(*k, 3);
            }
            other => panic!("expected MemoryRecall, got {other:?}"),
        }
    }

    /// Security regression guard: a caller-supplied redactor must actually
    /// flow App → `recall_redactor()` → `RecallRecorder` → recorded episode,
    /// not the `PassthroughRedactor` fallback. `ConstRedactor` replaces any
    /// input with `"[const]"`, so the recorded query carrying a known token
    /// must come back as that fixed value with the token gone.
    #[cfg(feature = "graph-rag")]
    #[tokio::test]
    async fn context_records_redacted_query_with_configured_redactor() {
        use crate::embed_common::FakeEmbedder;
        use klieo_core::Episode;

        const SECRET_TOKEN: &str = "AKIA1234567890";

        let cfg = crate::graph_rag::GraphRagConfig::in_memory()
            .embedder(Arc::new(FakeEmbedder::new(384)), "test-fake");
        let app = App::local()
            .model("dummy")
            .audit_redactor(Arc::new(ConstRedactor))
            .graph_rag_with(cfg)
            .build()
            .await
            .unwrap();
        let ctx = app.context("redaction-test-agent");

        ctx.long_term
            .recall(
                Scope::Workspace("redaction-test".to_string()),
                &format!("query containing {SECRET_TOKEN}"),
                3,
            )
            .await
            .expect("recall through the per-run context's long-term port");

        let episodes = app
            .memory()
            .episodic
            .replay(ctx.run_id)
            .await
            .expect("replay this run's episodes");
        let recalls: Vec<_> = episodes
            .iter()
            .filter(|e| matches!(e, Episode::MemoryRecall { .. }))
            .collect();
        assert_eq!(
            recalls.len(),
            1,
            "exactly one MemoryRecall must be recorded"
        );
        match recalls[0] {
            Episode::MemoryRecall { query, .. } => {
                assert!(
                    !query.contains(SECRET_TOKEN),
                    "the configured redactor must scrub the token from the recorded query"
                );
                assert_eq!(
                    query, "[const]",
                    "the configured ConstRedactor's fixed value must reach the recorded episode"
                );
            }
            other => panic!("expected MemoryRecall, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn build_local_with_only_model_succeeds() {
        let app = App::local().model("dummy-model").build().await.unwrap();
        assert!(app.tools_catalogue().is_empty());
        let ctx = app.context("test-agent");
        assert_eq!(ctx.agent_name, "test-agent");
    }

    #[tokio::test]
    async fn context_mints_fresh_run_id_per_call() {
        let app = App::local().model("dummy").build().await.unwrap();
        let a = app.context("agent");
        let b = app.context("agent");
        assert_ne!(a.run_id, b.run_id);
    }

    #[tokio::test]
    async fn cancel_token_propagates_to_minted_context() {
        let app = App::local().model("dummy").build().await.unwrap();
        let ctx = app.context("agent");
        assert!(!ctx.cancel.is_cancelled());
        app.cancel_token().cancel();
        assert!(ctx.cancel.is_cancelled());
    }

    struct ConstRedactor;

    impl AuditRedactor for ConstRedactor {
        fn redact(&self, _value: &serde_json::Value) -> serde_json::Value {
            serde_json::json!("[const]")
        }
    }

    #[cfg(feature = "ops")]
    #[tokio::test]
    async fn ops_feature_wires_default_audit_redactor() {
        let app = App::local().model("dummy").build().await.unwrap();
        assert!(
            app.audit_redactor.is_some(),
            "the ops feature must default a redactor so PII-flagged tools \
             are masked rather than falling back to the opaque digest"
        );
    }

    #[tokio::test]
    async fn explicit_audit_redactor_overrides_default() {
        let app = App::local()
            .model("dummy")
            .audit_redactor(Arc::new(ConstRedactor))
            .build()
            .await
            .unwrap();
        let redactor = app
            .audit_redactor
            .as_ref()
            .expect("explicit redactor must be retained");
        assert_eq!(
            redactor.redact(&serde_json::json!("anything")),
            serde_json::json!("[const]")
        );
    }

    #[cfg(feature = "data-dir")]
    #[test]
    fn local_at_data_dir_resolves_and_creates_parent_dir() {
        // Smoke: the public fn must resolve a data dir on this platform
        // and idempotently create the `klieo` parent directory. We do
        // NOT call .build() — that would write an empty klieo.db to
        // the real user data dir.
        let _builder =
            App::local_at_data_dir().expect("dirs::data_dir resolvable on this platform");
        let parent = dirs::data_dir()
            .expect("data_dir already validated above")
            .join("klieo");
        assert!(
            parent.is_dir(),
            "expected klieo data dir to be created: {parent:?}",
        );
        // Idempotency: a second call must not error.
        let _builder_again = App::local_at_data_dir().expect("data_dir fn must be idempotent");
    }

    #[tokio::test]
    async fn port_accessors_expose_configured_handles() {
        let llm = fake_llm();
        let app = App::builder()
            .llm(Arc::clone(&llm))
            .memory(
                klieo_memory_sqlite::MemorySqlite::new(
                    ":memory:",
                    Arc::new(klieo_memory_sqlite::DummyEmbedder),
                )
                .await
                .unwrap(),
            )
            .bus(klieo_bus_memory::MemoryBus::new())
            .tools_invoker(fake_tools())
            .build()
            .await
            .unwrap();

        assert!(Arc::ptr_eq(&app.llm(), &llm));

        let ctx = app.context("ports-test");
        assert!(Arc::ptr_eq(&app.memory().short_term, &ctx.short_term));
        assert!(Arc::ptr_eq(&app.memory().long_term, &ctx.long_term));
        assert!(Arc::ptr_eq(&app.memory().episodic, &ctx.episodic));
        assert!(Arc::ptr_eq(&app.bus().pubsub, &ctx.pubsub));
        assert!(Arc::ptr_eq(&app.bus().kv, &ctx.kv));
        assert!(Arc::ptr_eq(&app.bus().request_reply, &ctx.request_reply));
        assert!(Arc::ptr_eq(&app.bus().jobs, &ctx.jobs));

        assert!(Arc::ptr_eq(&app.tools_invoker(), &ctx.tools));
    }

    #[tokio::test]
    async fn cannot_combine_tool_with_tools_invoker() {
        // Use klieo-tools' own Tool impl from a sibling crate. Manually
        // wire a pending tool via the builder field by going through
        // .tool() with an Arc-wrapped Tool object built via the
        // chained-invoker path.
        let mut builder = App::local().model("dummy");
        // Push a pending tool via the public API: a simple anonymous
        // Tool impl is overkill here — use the trivial fact that
        // .tools_invoker() + a non-empty pending list collides.
        builder.pending_tools.push(Arc::new(EchoTool));
        let err = builder
            .tools_invoker(fake_tools())
            .build()
            .await
            .unwrap_err();
        assert!(matches!(
            err,
            Error::AppBuildError {
                missing: "tools (cannot combine .tool() with .tools_invoker())"
            }
        ));
    }

    struct EchoTool;

    #[async_trait::async_trait]
    impl Tool for EchoTool {
        fn name(&self) -> &str {
            "echo"
        }
        fn description(&self) -> &str {
            "echo"
        }
        fn json_schema(&self) -> &serde_json::Value {
            static SCHEMA: std::sync::OnceLock<serde_json::Value> = std::sync::OnceLock::new();
            SCHEMA.get_or_init(|| serde_json::json!({"type": "object"}))
        }
        async fn invoke(
            &self,
            _args: serde_json::Value,
            _ctx: klieo_core::ToolCtx,
        ) -> Result<serde_json::Value, klieo_core::ToolError> {
            Ok(serde_json::Value::Null)
        }
    }

    #[tokio::test]
    async fn partial_memory_composes_into_handles() {
        let mem = klieo_memory_sqlite::MemorySqlite::new(
            ":memory:",
            Arc::new(klieo_memory_sqlite::DummyEmbedder),
        )
        .await
        .unwrap();
        let app = App::builder()
            .llm(fake_llm())
            .short_term(mem.short_term.clone())
            .long_term(mem.long_term.clone())
            .episodic(mem.episodic.clone())
            .bus(klieo_bus_memory::MemoryBus::new())
            .tools_invoker(fake_tools())
            .build()
            .await
            .unwrap();
        let ctx = app.context("partial");
        assert!(Arc::ptr_eq(&ctx.short_term, &mem.short_term));
        assert!(Arc::ptr_eq(&ctx.long_term, &mem.long_term));
        assert!(Arc::ptr_eq(&ctx.episodic, &mem.episodic));
    }

    #[tokio::test]
    async fn partial_memory_missing_long_term_errors() {
        let mem = klieo_memory_sqlite::MemorySqlite::new(
            ":memory:",
            Arc::new(klieo_memory_sqlite::DummyEmbedder),
        )
        .await
        .unwrap();
        let err = App::builder()
            .llm(fake_llm())
            .short_term(mem.short_term.clone())
            .episodic(mem.episodic.clone())
            .bus(klieo_bus_memory::MemoryBus::new())
            .tools_invoker(fake_tools())
            .build()
            .await
            .unwrap_err();
        assert!(matches!(
            err,
            Error::AppBuildError {
                missing: "memory.long_term"
            }
        ));
    }

    #[tokio::test]
    async fn explicit_memory_overrides_partials() {
        let primary = klieo_memory_sqlite::MemorySqlite::new(
            ":memory:",
            Arc::new(klieo_memory_sqlite::DummyEmbedder),
        )
        .await
        .unwrap();
        let secondary = klieo_memory_sqlite::MemorySqlite::new(
            ":memory:",
            Arc::new(klieo_memory_sqlite::DummyEmbedder),
        )
        .await
        .unwrap();
        let primary_st = primary.short_term.clone();
        let app = App::builder()
            .llm(fake_llm())
            .memory(primary)
            .short_term(secondary.short_term)
            .bus(klieo_bus_memory::MemoryBus::new())
            .tools_invoker(fake_tools())
            .build()
            .await
            .unwrap();
        let ctx = app.context("override");
        assert!(Arc::ptr_eq(&ctx.short_term, &primary_st));
    }

    #[cfg(feature = "llm-openai")]
    #[tokio::test]
    async fn openai_shortcut_sets_llm() {
        let app = App::local()
            .openai("test-key".to_string(), "gpt-4o-mini")
            .build()
            .await
            .unwrap();
        let ctx = app.context("a");
        assert!(
            ctx.llm.name().starts_with("openai"),
            "got {}",
            ctx.llm.name()
        );
    }

    #[cfg(feature = "llm-anthropic")]
    #[tokio::test]
    async fn anthropic_shortcut_sets_llm() {
        let app = App::local()
            .anthropic("test-key".to_string(), "claude-3-5-haiku-latest")
            .build()
            .await
            .unwrap();
        let ctx = app.context("a");
        assert!(
            ctx.llm.name().starts_with("anthropic"),
            "got {}",
            ctx.llm.name()
        );
    }

    #[cfg(feature = "llm-gemini")]
    #[tokio::test]
    async fn gemini_shortcut_sets_llm() {
        let app = App::local()
            .gemini("test-key".to_string(), "gemini-2.0-flash")
            .build()
            .await
            .unwrap();
        let ctx = app.context("a");
        assert!(ctx.llm.name().contains("gemini"), "got {}", ctx.llm.name());
    }

    #[tokio::test]
    async fn last_llm_shortcut_wins() {
        let app = App::local()
            .ollama("http://localhost:11434", "qwen")
            .ollama("http://other:11434", "llama")
            .build()
            .await
            .unwrap();
        // Ollama client doesn't expose model via LlmClient; just verify
        // that build succeeded under the second config (no panic, no
        // error) which proves the second .ollama() call replaced the
        // first.
        let ctx = app.context("a");
        assert!(
            ctx.llm.name().starts_with("ollama"),
            "got {}",
            ctx.llm.name()
        );
    }

    #[cfg(feature = "mcp")]
    #[tokio::test]
    async fn mcp_stdio_registers_entry_verified_via_conflict_guard() {
        // mcp_stdio() pushes a McpStdioSpec into pending_mcp. The conflict
        // guard in resolve_mcp_stdio() fires immediately (before any connect
        // attempt) when tools_invoker is also set, confirming the entry was
        // recorded and the guard reads it.
        struct DummyInvoker;
        #[async_trait::async_trait]
        impl klieo_core::ToolInvoker for DummyInvoker {
            fn catalogue(&self) -> Vec<klieo_core::ToolDef> {
                vec![]
            }
            async fn invoke(
                &self,
                _name: &str,
                _args: serde_json::Value,
                _ctx: klieo_core::ToolCtx,
            ) -> Result<serde_json::Value, klieo_core::error::ToolError> {
                Ok(serde_json::Value::Null)
            }
        }

        let err = App::local()
            .mcp_stdio("test-srv", "/bin/echo", vec![])
            .tools_invoker(Arc::new(DummyInvoker))
            .build()
            .await
            .unwrap_err();
        assert!(
            matches!(err, klieo_core::Error::AppBuildError { .. }),
            "expected AppBuildError for conflict, got {err:?}"
        );
    }

    #[cfg(feature = "mcp")]
    #[tokio::test]
    async fn mcp_stdio_errors_on_missing_binary() {
        let err = App::local()
            .mcp_stdio("test-server", "/nonexistent/binary/path", vec![])
            .build()
            .await
            .unwrap_err();
        // connect_stdio → child-process spawn fails → ToolError → Error::Tool
        assert!(
            matches!(err, klieo_core::Error::Tool(_)),
            "expected Error::Tool, got {err:?}"
        );
    }

    #[cfg(feature = "mcp")]
    #[tokio::test]
    async fn mcp_stdio_combined_with_tools_invoker_errors_at_build() {
        struct DummyInvoker;
        #[async_trait::async_trait]
        impl klieo_core::ToolInvoker for DummyInvoker {
            fn catalogue(&self) -> Vec<klieo_core::ToolDef> {
                vec![]
            }
            async fn invoke(
                &self,
                _name: &str,
                _args: serde_json::Value,
                _ctx: klieo_core::ToolCtx,
            ) -> Result<serde_json::Value, klieo_core::error::ToolError> {
                Ok(serde_json::Value::Null)
            }
        }

        let err = App::local()
            .tools_invoker(Arc::new(DummyInvoker))
            .mcp_stdio("srv", "/bin/echo", vec![])
            .build()
            .await
            .unwrap_err();
        assert!(
            matches!(err, klieo_core::Error::AppBuildError { .. }),
            "expected AppBuildError, got {err:?}"
        );
    }

    #[cfg(feature = "http")]
    #[tokio::test]
    async fn mcp_http_combined_with_tools_invoker_errors_at_build() {
        struct DummyInvoker;
        #[async_trait::async_trait]
        impl klieo_core::ToolInvoker for DummyInvoker {
            fn catalogue(&self) -> Vec<klieo_core::ToolDef> {
                vec![]
            }
            async fn invoke(
                &self,
                _name: &str,
                _args: serde_json::Value,
                _ctx: klieo_core::ToolCtx,
            ) -> Result<serde_json::Value, klieo_core::error::ToolError> {
                Ok(serde_json::Value::Null)
            }
        }

        let err = App::local()
            .mcp_http(
                "remote",
                "https://mcp.example.com/mcp",
                klieo_tools_mcp::HttpConnectOptions::default(),
            )
            .tools_invoker(Arc::new(DummyInvoker))
            .build()
            .await
            .unwrap_err();
        assert!(
            matches!(err, klieo_core::Error::AppBuildError { .. }),
            "expected AppBuildError for conflict, got {err:?}"
        );
    }

    #[cfg(feature = "http")]
    #[tokio::test]
    async fn mcp_http_rejects_plain_http_remote_url_at_build() {
        let err = App::local()
            .mcp_http(
                "remote",
                "http://mcp.example.com/mcp",
                klieo_tools_mcp::HttpConnectOptions::default(),
            )
            .build()
            .await
            .unwrap_err();
        // validate_url rejects non-loopback plain http → ToolError::InvalidArgs
        // → Error::Tool before any network I/O.
        assert!(
            matches!(err, klieo_core::Error::Tool(_)),
            "expected Error::Tool for plain-http rejection, got {err:?}"
        );
    }

    #[cfg(feature = "bus-nats")]
    #[tokio::test]
    async fn nats_shortcut_errors_on_unreachable_server() {
        let cfg = klieo_bus_nats::NatsBusConfig {
            url: "nats://127.0.0.1:14223".to_string(),
            ..klieo_bus_nats::NatsBusConfig::default()
        };
        let err = App::builder()
            .llm(fake_llm())
            .memory(
                klieo_memory_sqlite::MemorySqlite::new(
                    ":memory:",
                    Arc::new(klieo_memory_sqlite::DummyEmbedder),
                )
                .await
                .unwrap(),
            )
            .nats(cfg)
            .tools_invoker(fake_tools())
            .build()
            .await
            .unwrap_err();
        assert!(matches!(err, Error::Bus(_)), "got {err:?}");
    }

    #[tokio::test]
    async fn run_delegates_to_agent_with_fresh_context() {
        let app = App::builder()
            .llm(Arc::new(
                FakeLlmClient::new("fake").with_steps(vec![FakeLlmStep::Text("done".into())]),
            ))
            .memory(
                klieo_memory_sqlite::MemorySqlite::new(
                    ":memory:",
                    Arc::new(klieo_memory_sqlite::DummyEmbedder),
                )
                .await
                .unwrap(),
            )
            .bus(klieo_bus_memory::MemoryBus::new())
            .tools_invoker(fake_tools())
            .build()
            .await
            .unwrap();
        let agent =
            klieo_core::SimpleAgent::new("greeter", "be brief", app.tools_catalogue().to_vec());
        let out = app.run(&agent, "hi".into()).await.unwrap();
        assert_eq!(out, "done");
    }

    #[cfg(all(
        feature = "llm-ollama",
        feature = "memory-sqlite",
        feature = "bus-memory",
        feature = "tools",
    ))]
    #[tokio::test]
    async fn build_local_at_file_path_succeeds() {
        let db_path = std::env::temp_dir().join("klieo_test_local_at.db");
        let _ = std::fs::remove_file(&db_path);
        let app = App::local_at(&db_path)
            .model("dummy-model")
            .build()
            .await
            .unwrap();
        assert!(app.tools_catalogue().is_empty());
        let ctx = app.context("test-agent");
        assert_eq!(ctx.agent_name, "test-agent");
        assert!(
            db_path.exists(),
            "sqlite file should have been created at {db_path:?}"
        );
        let _ = std::fs::remove_file(&db_path);
    }
}