saya-cli 0.3.1

Database-aware AI agent for the terminal: full-screen TUI, schema discovery, and bounded read-only SQL over PostgreSQL, MySQL, SQLite, DuckDB, and Snowflake.
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
//! Tests for the `KnowledgeSupplied` event — spec P1b.
//!
//! Two layers:
//! - **The pure mapping** [`crate::agent::knowledge_event::knowledge_supplied_event`] — the
//!   three-state decision (Off / Skipped / Ran) and the claim mapping, unit-tested
//!   without a live database (tests 3, 4, 5, 7, 8 and the content of test 1).
//! - **The assembled turn** via [`super::run_prompt_with_inputs`] with an
//!   injected mock provider and an idle registry — proves the emit is before
//!   the provider request (test 2), that exactly one event names the supplied
//!   claims (test 1), and that a store failure still emits and still runs the
//!   turn (test 6). The provider and registry are injected because
//!   `run_prompt_with_sink` builds a live provider and a live (connecting)
//!   registry from config, which a unit test cannot supply; the inner
//!   `run_prompt_with_inputs` is the seam.

use super::super::knowledge_event::knowledge_supplied_event;
use super::super::turn_inputs::TurnInputs;
use super::*;
use crate::connection::{ConnectionEntry, ConnectionRegistry};
use async_trait::async_trait;
use saya_agent::{
    AgentEvent, AgentEventSink, ChatMessage, ChatProvider, ChatRequest, ChatResponse,
    KnowledgeOutcome, LearningSkipReason, OverrideFindingDto, ProposedClaimDto, ProviderError,
    SuppliedClaimDto, SuppliedContractDto, ToolCall,
};
use saya_config::{
    AiProvider, ColorChoice, MemoryMode, OutputFormat, ResolvedAi, ResolvedConfig, ResolvedMemory,
};
use saya_store::{KnowledgeItemRequest, KnowledgeItemStore, SchemaStore, SqliteStateStore};
use saya_types::{
    ClaimId, ClaimOrigin, ClaimPayload, ClaimStatus, Column, ConnectionError, Database,
    DatabaseObjectKind, DatabaseObjectRef, DatabaseProfile, KnowledgeSlot, KnowledgeState,
    ProfileIdentity, QueryRequest, QueryResult, Schema, SchemaTree, SqlDialect, Table,
};
use std::{
    collections::BTreeMap,
    fs,
    path::{Path, PathBuf},
    sync::{Arc, Mutex},
    time::{SystemTime, UNIX_EPOCH},
};

use crate::config::runtime::RuntimeConfig;
use crate::contracts::{RecallOutcomeKind, RecallReceipt};

// ---------------------------------------------------------------------------
// shared harness
// ---------------------------------------------------------------------------

/// A connector that never touches a live database: recall reads the store, not
/// the connector, so the registry only needs an entry to carry an identity.
struct IdleConnector;

#[async_trait]
impl saya_connectors::DatabaseConnector for IdleConnector {
    fn dialect(&self) -> SqlDialect {
        SqlDialect::DuckDb
    }
    async fn connect(&self) -> Result<(), ConnectionError> {
        Ok(())
    }
    async fn schema(&self) -> Result<SchemaTree, ConnectionError> {
        Ok(SchemaTree {
            databases: vec![Database {
                name: "catalog".into(),
                schemas: vec![Schema {
                    name: "public".into(),
                    tables: vec![orders_table()],
                }],
            }],
        })
    }
    async fn execute(&self, req: QueryRequest) -> Result<QueryResult, ConnectionError> {
        Ok(QueryResult::empty(req.sql))
    }
}

fn temp_root(label: &str) -> PathBuf {
    let stamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    let root = std::env::temp_dir().join(format!(
        "saya-runtime-p1b-{label}-{}-{stamp}",
        std::process::id()
    ));
    fs::create_dir_all(&root).unwrap();
    root
}

fn identity_for(name: &str) -> ProfileIdentity {
    crate::profile_identity::profile_identity(
        name,
        &DatabaseProfile::DuckDb {
            path: "runtime-p1b.duckdb".into(),
            read_only: Some(true),
        },
        Path::new("/runtime-p1b-test/connections.toml"),
    )
}

fn registry_for(name: &str, identity: &ProfileIdentity) -> ConnectionRegistry {
    let mut registry = ConnectionRegistry::new(name);
    registry.insert(
        name,
        ConnectionEntry {
            connector: Box::new(IdleConnector),
            dialect: SqlDialect::DuckDb,
            profile_id: Some(identity.as_str().to_string()),
        },
    );
    registry
}

async fn store_at(db: &Path, identity: &ProfileIdentity) -> SqliteStateStore {
    let store = SqliteStateStore::new(db);
    store
        .upsert_schema(identity.as_str(), &SchemaTree::default())
        .await
        .unwrap();
    store
}

fn object(identity: &ProfileIdentity, name: &str) -> DatabaseObjectRef {
    DatabaseObjectRef::new(
        identity.clone(),
        "catalog",
        "public",
        name,
        DatabaseObjectKind::Table,
    )
    .unwrap()
}

fn orders_table() -> Table {
    Table {
        name: "orders".into(),
        columns: vec![
            Column {
                name: "id".into(),
                data_type: "bigint".into(),
                nullable: false,
            },
            Column {
                name: "created_at".into(),
                data_type: "timestamp".into(),
                nullable: false,
            },
        ],
    }
}

fn live_fingerprint(tree: &Table) -> saya_types::SchemaFingerprint {
    saya_types::SchemaFingerprint::of_table(DatabaseObjectKind::Table, tree)
}

fn orders_schema(identity: &ProfileIdentity) -> (ProfileIdentity, SchemaTree) {
    let table = orders_table();
    let tree = SchemaTree {
        databases: vec![Database {
            name: "catalog".into(),
            schemas: vec![Schema {
                name: "public".into(),
                tables: vec![table],
            }],
        }],
    };
    (identity.clone(), tree)
}

async fn remember_default_time_column(
    store: &SqliteStateStore,
    obj: &DatabaseObjectRef,
    _fingerprint: &saya_types::SchemaFingerprint,
    column: &str,
    status: ClaimStatus,
    origin: ClaimOrigin,
) -> ClaimId {
    use saya_types::{KnowledgeSlot, SchemaBinding};
    let payload = ClaimPayload::default_time_column(column, None).unwrap();
    let state = match status {
        ClaimStatus::Confirmed => KnowledgeState::Active,
        ClaimStatus::Candidate => KnowledgeState::Pending,
        _ => KnowledgeState::Dismissed,
    };
    let slot = KnowledgeSlot::TableDefaultTime;
    let binding = SchemaBinding::derive(&slot, &payload).expect("default_time slot/payload agree");
    let request = KnowledgeItemRequest {
        object: obj.clone(),
        slot,
        value: payload,
        source: origin,
        state,
        schema_binding_json: serde_json::to_string(&binding).unwrap(),
        fingerprint: crate::commands::unobserved_fingerprint(),
    };
    store.put_knowledge_item(request).await.unwrap();
    // Read the store-assigned `ki-` id back so the event-naming assertion
    // compares against exactly what recall supplied.
    ClaimId::parse(
        &store
            .knowledge_for_object(obj)
            .await
            .expect("knowledge items listed")
            .into_iter()
            .find(|i| i.slot == KnowledgeSlot::TableDefaultTime)
            .expect("default_time item stored")
            .id,
    )
    .expect("ki id")
}

/// A minimal `RuntimeConfig` carrying only what `run_prompt_with_inputs` reads
/// (`resolved.memory`, `max_rows`, `max_iterations`). The provider and registry
/// are injected via `TurnInputs`, so the live-build fields are never used.
fn test_runtime(memory: ResolvedMemory) -> RuntimeConfig {
    RuntimeConfig {
        resolved: ResolvedConfig {
            profile_name: None,
            profile: None,
            ai: ResolvedAi {
                provider: AiProvider::Ollama,
                model: "test-model".into(),
                base_url: None,
                api_key: None,
                allow_data_sharing: true,
                temperature: 0.0,
                timeout_seconds: 60,
                idle_timeout_seconds: 90,
                max_output_tokens: 4096,
                context_byte_budget: 256 * 1024,
            },
            max_rows: 100,
            read_only: true,
            max_iterations: 4,
            query_timeout_seconds: 5,
            output_format: OutputFormat::Text,
            output_color: ColorChoice::Auto,
            memory,
            ignored_project_overrides: Vec::new(),
        },
        connections: Default::default(),
        config_path: None,
        connections_path: None,
        cache_scope: PathBuf::from("/tmp/saya-runtime-p1b"),
        secret_values: BTreeMap::new(),
    }
}

fn default_memory() -> ResolvedMemory {
    ResolvedMemory {
        mode: MemoryMode::Off,
        max_contracts: 5,
        max_claims_per_contract: 12,
        max_context_bytes: 16384,
    }
}

/// `assisted` memory: permits candidate writes and recalls active + candidate knowledge.
fn assisted_memory() -> ResolvedMemory {
    ResolvedMemory {
        mode: MemoryMode::Assisted,
        max_contracts: 5,
        max_claims_per_contract: 12,
        max_context_bytes: 16384,
    }
}

/// A sink that records every event in order. `knowledge_log`, when shared with
/// the provider, is the ordering oracle: the sink pushes `"knowledge"` when it
/// sees `KnowledgeSupplied`, the provider pushes `"provider"` when it is
/// called, and the order in the log proves the emit preceded the request.
struct RecordingSink {
    events: Arc<Mutex<Vec<AgentEvent>>>,
    knowledge_log: Arc<Mutex<Vec<&'static str>>>,
}

#[async_trait]
impl AgentEventSink for RecordingSink {
    async fn emit(&self, event: AgentEvent) {
        if matches!(event, AgentEvent::KnowledgeSupplied { .. }) {
            self.knowledge_log.lock().unwrap().push("knowledge");
        }
        self.events.lock().unwrap().push(event);
    }
}

/// A provider that returns one text answer, recording `"provider"` into the
/// shared log at call time so the ordering test can prove the emit came first.
struct AnswerProvider {
    answer: &'static str,
    log: Arc<Mutex<Vec<&'static str>>>,
}

#[async_trait]
impl ChatProvider for AnswerProvider {
    fn name(&self) -> &str {
        "answer"
    }
    async fn complete(&self, _request: ChatRequest) -> Result<ChatResponse, ProviderError> {
        self.log.lock().unwrap().push("provider");
        Ok(ChatResponse {
            message: ChatMessage::text("assistant", self.answer),
        })
    }
}

// ===========================================================================
// Test 1: a turn that supplies claims emits exactly one KnowledgeSupplied,
// naming those claims.
// ===========================================================================

#[tokio::test]
async fn a_turn_supplying_claims_emits_one_event_naming_those_claims() {
    let root = temp_root("t1_supply");
    let db = root.join("state.sqlite3");
    let identity = identity_for("analytics");
    let store = store_at(&db, &identity).await;
    // Seed a confirmed default_time_column claim under a matching live schema.
    let obj = object(&identity, "orders");
    let tree = orders_schema(&identity);
    store
        .upsert_schema(identity.as_str(), &tree.1)
        .await
        .unwrap();
    let fp = live_fingerprint(&orders_table());
    let claim_id = remember_default_time_column(
        &store,
        &obj,
        &fp,
        "created_at",
        ClaimStatus::Confirmed,
        ClaimOrigin::UserExplicit,
    )
    .await;

    let events = Arc::new(Mutex::new(Vec::new()));
    let log = Arc::new(Mutex::new(Vec::new()));
    let sink = RecordingSink {
        events: events.clone(),
        knowledge_log: log.clone(),
    };
    let provider = AnswerProvider {
        answer: "done",
        log: log.clone(),
    };
    let inputs = TurnInputs {
        ai: ResolvedAi {
            provider: AiProvider::Ollama,
            model: "test-model".into(),
            base_url: None,
            api_key: None,
            allow_data_sharing: true,
            temperature: 0.0,
            timeout_seconds: 60,
            idle_timeout_seconds: 90,
            max_output_tokens: 4096,
            context_byte_budget: 256 * 1024,
        },
        provider: Box::new(provider),
        registry: registry_for("analytics", &identity),
        failures: Vec::new(),
    };
    let runtime = test_runtime(assisted_memory());
    run_prompt_with_inputs(
        &runtime,
        inputs,
        "orders by month",
        saya_agent::ApprovalPolicy::ReadOnly,
        false,
        Vec::new(),
        &sink,
        saya_agent::CancellationToken::new(),
        Some(store),
        None,
        None,
    )
    .await
    .unwrap();

    let captured = events.lock().unwrap();
    // Exactly one KnowledgeSupplied.
    let count = captured
        .iter()
        .filter(|e| matches!(e, AgentEvent::KnowledgeSupplied { .. }))
        .count();
    assert_eq!(count, 1, "exactly one KnowledgeSupplied: {captured:?}");
    // It names the supplied claim.
    let event = captured
        .iter()
        .find_map(|e| match e {
            AgentEvent::KnowledgeSupplied { contracts, .. } => Some(contracts),
            _ => None,
        })
        .expect("KnowledgeSupplied present");
    assert_eq!(event.len(), 1, "one object supplied: {event:?}");
    assert_eq!(event[0].object, "catalog.public.orders");
    assert_eq!(event[0].profile, "analytics", "name, not identity");
    assert_eq!(event[0].claims.len(), 1);
    assert_eq!(event[0].claims[0].claim_id, claim_id);
    assert_eq!(event[0].claims[0].value, "created_at");
    assert_eq!(event[0].claims[0].status, ClaimStatus::Confirmed);
    let _ = fs::remove_dir_all(root);
}

// ===========================================================================
// Test 2: the event is emitted BEFORE any provider request. Asserted against
// the sink's event sequence AND a shared log the provider writes at call time,
// not merely that the event appears (the bug this slice prevents is emitting
// after the answer).
// ===========================================================================

#[tokio::test]
async fn knowledge_supplied_precedes_the_provider_request() {
    let root = temp_root("t2_order");
    let db = root.join("state.sqlite3");
    let identity = identity_for("analytics");
    let store = store_at(&db, &identity).await;
    let obj = object(&identity, "orders");
    let tree = orders_schema(&identity);
    store
        .upsert_schema(identity.as_str(), &tree.1)
        .await
        .unwrap();
    let fp = live_fingerprint(&orders_table());
    remember_default_time_column(
        &store,
        &obj,
        &fp,
        "created_at",
        ClaimStatus::Confirmed,
        ClaimOrigin::UserExplicit,
    )
    .await;

    let events = Arc::new(Mutex::new(Vec::new()));
    let log = Arc::new(Mutex::new(Vec::new()));
    let sink = RecordingSink {
        events: events.clone(),
        knowledge_log: log.clone(),
    };
    let provider = AnswerProvider {
        answer: "done",
        log: log.clone(),
    };
    let inputs = TurnInputs {
        ai: ResolvedAi {
            provider: AiProvider::Ollama,
            model: "test-model".into(),
            base_url: None,
            api_key: None,
            allow_data_sharing: true,
            temperature: 0.0,
            timeout_seconds: 60,
            idle_timeout_seconds: 90,
            max_output_tokens: 4096,
            context_byte_budget: 256 * 1024,
        },
        provider: Box::new(provider),
        registry: registry_for("analytics", &identity),
        failures: Vec::new(),
    };
    let runtime = test_runtime(default_memory());
    run_prompt_with_inputs(
        &runtime,
        inputs,
        "orders by month",
        saya_agent::ApprovalPolicy::ReadOnly,
        false,
        Vec::new(),
        &sink,
        saya_agent::CancellationToken::new(),
        Some(store),
        None,
        None,
    )
    .await
    .unwrap();

    // The shared log records the order of the two events: the sink pushed
    // "knowledge" on KnowledgeSupplied, then the provider pushed "provider"
    // when `complete` was called. "knowledge" first proves the emit preceded
    // the provider request — the point of the slice.
    let log = log.lock().unwrap();
    assert_eq!(
        log.first(),
        Some(&"knowledge"),
        "KnowledgeSupplied was emitted before the provider was called: {log:?}"
    );
    assert!(
        log.contains(&"provider"),
        "the provider was called after the emit: {log:?}"
    );
    let knowledge_idx = log
        .iter()
        .position(|e| *e == "knowledge")
        .expect("knowledge present");
    let provider_idx = log
        .iter()
        .position(|e| *e == "provider")
        .expect("provider present");
    assert!(
        knowledge_idx < provider_idx,
        "emit index {knowledge_idx} must precede provider index {provider_idx}: {log:?}"
    );

    // And in the sink's own event sequence, KnowledgeSupplied precedes the
    // first loop event (AssistantText from the provider's answer).
    let captured = events.lock().unwrap();
    let knowledge_event_idx = captured
        .iter()
        .position(|e| matches!(e, AgentEvent::KnowledgeSupplied { .. }))
        .expect("KnowledgeSupplied in sink");
    let first_loop_idx = captured
        .iter()
        .position(|e| {
            matches!(
                e,
                AgentEvent::AssistantText { .. }
                    | AgentEvent::ToolRequested { .. }
                    | AgentEvent::Complete
            )
        })
        .expect("a loop event after the provider call");
    assert!(
        knowledge_event_idx < first_loop_idx,
        "KnowledgeSupplied (idx {knowledge_event_idx}) must precede the first loop event (idx {first_loop_idx}): {captured:?}"
    );
    let _ = fs::remove_dir_all(root);
}

// ===========================================================================
// Tests 3 & 4: the three-state decision (Off / Skipped / Ran), as pure tests
// on `knowledge_supplied_event`. The runtime calls this; the three states are
// distinguishable here without a live database.
// ===========================================================================

#[test]
fn recall_off_emits_the_off_outcome() {
    // recall = off: SAYA did not look. Distinct from the privacy gate.
    let receipt = RecallReceipt::configured_off();
    assert_eq!(receipt.kind, RecallOutcomeKind::ConfiguredOff);
    let event = knowledge_supplied_event(&receipt);
    assert!(matches!(
        event,
        AgentEvent::KnowledgeSupplied {
            outcome: KnowledgeOutcome::Off,
            contracts,
            dropped_by_bounds: 0,
        } if contracts.is_empty()
    ));
}

#[test]
fn privacy_gate_closed_emits_the_skipped_outcome() {
    // Privacy gate closed: SAYA was not allowed to look. No store query.
    let receipt = RecallReceipt::privacy_gate_closed();
    assert_eq!(receipt.kind, RecallOutcomeKind::PrivacyGateClosed);
    let event = knowledge_supplied_event(&receipt);
    assert!(matches!(
        event,
        AgentEvent::KnowledgeSupplied {
            outcome: KnowledgeOutcome::Skipped,
            contracts,
            dropped_by_bounds: 0,
        } if contracts.is_empty()
    ));
}

#[test]
fn recall_ran_and_found_nothing_emits_ran_distinct_from_off_and_skipped() {
    // Recall ran and matched nothing: a Ran receipt with empty supplied. This
    // is the third state — distinct from Off (did not look) and Skipped (not
    // allowed to look). The three outcomes must not collapse.
    let receipt = RecallReceipt::ran_empty(false);
    let event = knowledge_supplied_event(&receipt);
    assert!(matches!(
        event,
        AgentEvent::KnowledgeSupplied {
            outcome: KnowledgeOutcome::Ran { store_unavailable: false },
            contracts,
            dropped_by_bounds: 0,
        } if contracts.is_empty()
    ));
    // The three are distinguishable.
    let off = knowledge_supplied_event(&RecallReceipt::configured_off());
    let skipped = knowledge_supplied_event(&RecallReceipt::privacy_gate_closed());
    let ran = knowledge_supplied_event(&receipt);
    assert_ne!(outcome_of(&off), outcome_of(&skipped));
    assert_ne!(outcome_of(&skipped), outcome_of(&ran));
    assert_ne!(outcome_of(&off), outcome_of(&ran));
}

fn outcome_of(event: &AgentEvent) -> KnowledgeOutcome {
    match event {
        AgentEvent::KnowledgeSupplied { outcome, .. } => *outcome,
        _ => panic!("not a KnowledgeSupplied event"),
    }
}

// ===========================================================================
// Test 5: a candidate claim's status survives into the event, distinct from
// confirmed.
// ===========================================================================

#[test]
fn a_candidate_claims_status_survives_into_the_event() {
    let claim_id = ClaimId::parse("c-candidate-001").unwrap();
    let receipt = RecallReceipt {
        kind: RecallOutcomeKind::Ran {
            store_unavailable: false,
        },
        supplied: vec![crate::contracts::SuppliedContract {
            profile: "analytics".into(),
            object: "catalog.public.orders".into(),
            schema_state: "current",
            claims: vec![crate::contracts::SuppliedClaim {
                claim_id: claim_id.clone(),
                kind: "default_time_column",
                value: "created_at".into(),
                column: Some("created_at".into()),
                status: ClaimStatus::Candidate,
            }],
        }],
        dropped_by_bounds: 0,
    };
    let event = knowledge_supplied_event(&receipt);
    let contracts = match event {
        AgentEvent::KnowledgeSupplied { contracts, .. } => contracts,
        _ => panic!("expected KnowledgeSupplied"),
    };
    assert_eq!(contracts.len(), 1);
    assert_eq!(contracts[0].claims.len(), 1);
    assert_eq!(contracts[0].claims[0].claim_id, claim_id);
    // The candidate status survives as Candidate, not flattened to confirmed.
    assert_eq!(contracts[0].claims[0].status, ClaimStatus::Candidate);
    // Distinct from a confirmed claim's status.
    assert_ne!(contracts[0].claims[0].status, ClaimStatus::Confirmed);
}

// ===========================================================================
// Test 6: store unavailable still runs the turn and still emits (a Ran event
// with store_unavailable: true). Driven through the runtime with an
// unopenable store so recall fails soft.
// ===========================================================================

#[tokio::test]
async fn store_unavailable_still_runs_the_turn_and_emits() {
    let root = temp_root("t6_store_unavailable");
    fs::write(root.join("blocker"), b"x").unwrap();
    let bad_path = root.join("blocker/state.sqlite3");
    let store = SqliteStateStore::new(&bad_path); // parent is a file → unopenable
    let identity = identity_for("analytics");

    let events = Arc::new(Mutex::new(Vec::new()));
    let log = Arc::new(Mutex::new(Vec::new()));
    let sink = RecordingSink {
        events: events.clone(),
        knowledge_log: log.clone(),
    };
    let provider = AnswerProvider {
        answer: "done anyway",
        log: log.clone(),
    };
    let inputs = TurnInputs {
        ai: ResolvedAi {
            provider: AiProvider::Ollama,
            model: "test-model".into(),
            base_url: None,
            api_key: None,
            allow_data_sharing: true,
            temperature: 0.0,
            timeout_seconds: 60,
            idle_timeout_seconds: 90,
            max_output_tokens: 4096,
            context_byte_budget: 256 * 1024,
        },
        provider: Box::new(provider),
        registry: registry_for("analytics", &identity),
        failures: Vec::new(),
    };
    let runtime = test_runtime(assisted_memory());
    let result = run_prompt_with_inputs(
        &runtime,
        inputs,
        "orders by month",
        saya_agent::ApprovalPolicy::ReadOnly,
        false,
        Vec::new(),
        &sink,
        saya_agent::CancellationToken::new(),
        Some(store),
        None,
        None,
    )
    .await;

    // The turn still completes despite the store failure (recall is fail-soft).
    assert!(
        result.is_ok(),
        "turn completes despite store failure: {result:?}"
    );
    let captured = events.lock().unwrap();
    // The event records the failure as Ran { store_unavailable: true }, not as
    // an error and not as silence.
    let event = captured
        .iter()
        .find_map(|e| match e {
            AgentEvent::KnowledgeSupplied { outcome, .. } => Some(*outcome),
            _ => None,
        })
        .expect("KnowledgeSupplied emitted despite store failure");
    assert_eq!(
        event,
        KnowledgeOutcome::Ran {
            store_unavailable: true
        },
        "store failure is Ran{{store_unavailable: true}}, not silence: {captured:?}"
    );
    let _ = fs::remove_dir_all(root);
}

// ===========================================================================
// Test 7: no opaque ProfileIdentity value appears in a serialized event.
// Asserted directly on the serialized JSON — the identity is a hash over
// connection material and must not reach output.
// ===========================================================================

#[test]
fn no_opaque_profile_identity_value_appears_in_the_event() {
    let identity = identity_for("analytics");
    let receipt = RecallReceipt {
        kind: RecallOutcomeKind::Ran {
            store_unavailable: false,
        },
        supplied: vec![crate::contracts::SuppliedContract {
            profile: "analytics".into(),
            object: "catalog.public.orders".into(),
            schema_state: "current",
            claims: vec![crate::contracts::SuppliedClaim {
                claim_id: ClaimId::parse("c-abc123").unwrap(),
                kind: "default_time_column",
                value: "created_at".into(),
                column: None,
                status: ClaimStatus::Confirmed,
            }],
        }],
        dropped_by_bounds: 0,
    };
    let event = knowledge_supplied_event(&receipt);
    let json = serde_json::to_string(&event).expect("serializes");
    // The opaque identity string appears nowhere in the serialized event.
    assert!(
        !json.contains(identity.as_str()),
        "opaque identity leaked into the serialized event: {json}"
    );
    // The human-facing name does appear, in place of the identity.
    assert!(
        json.contains("analytics"),
        "the profile name (not the identity) is what the event carries: {json}"
    );
}

// ===========================================================================
// Test 8: the event round-trips through serde with its `type` tag.
// ===========================================================================

#[test]
fn knowledge_supplied_round_trips_through_serde_with_type_tag() {
    let event = AgentEvent::knowledge_supplied(
        KnowledgeOutcome::Ran {
            store_unavailable: true,
        },
        vec![SuppliedContractDto {
            profile: "analytics".into(),
            object: "catalog.public.orders".into(),
            schema_state: "needs_review".into(),
            claims: vec![SuppliedClaimDto {
                claim_id: ClaimId::parse("c-roundtrip").unwrap(),
                kind: "default_time_column".into(),
                value: "created_at".into(),
                column: Some("created_at".into()),
                status: ClaimStatus::Candidate,
            }],
        }],
        3,
    );
    let json = serde_json::to_string(&event).expect("serializes");
    // The outer tag is `knowledge_supplied` (snake_case, per AgentEvent's
    // `#[serde(tag = "type", rename_all = "snake_case")]`).
    assert!(
        json.contains(r#""type":"knowledge_supplied""#),
        "carries the type tag: {json}"
    );
    let back: AgentEvent = serde_json::from_str(&json).expect("deserializes back");
    assert_eq!(back, event, "round-trips with the claims and status intact");

    // The three outcomes each round-trip too.
    for (outcome, expected) in [
        (KnowledgeOutcome::Off, r#""off""#),
        (KnowledgeOutcome::Skipped, r#""skipped""#),
        (
            KnowledgeOutcome::Ran {
                store_unavailable: false,
            },
            r#"{"ran":{"store_unavailable":false}}"#,
        ),
    ] {
        let text = serde_json::to_string(&outcome).expect("serializes");
        assert_eq!(text, expected, "outcome {outcome:?} serializes as expected");
        let back: KnowledgeOutcome = serde_json::from_str(&text).expect("deserializes back");
        assert_eq!(back, outcome, "outcome {outcome:?} round-trips");
    }
}

// ===========================================================================
// Chunk 4: Post-turn structured extraction runtime integration tests
// ===========================================================================

struct TurnAndExtractionProvider {
    turn_step: Mutex<usize>,
    turn_steps: Vec<ChatResponse>,
    extraction_response: Result<ChatResponse, ProviderError>,
    extraction_calls: Mutex<usize>,
}

#[async_trait]
impl ChatProvider for TurnAndExtractionProvider {
    fn name(&self) -> &str {
        "turn-and-extraction-provider"
    }
    async fn complete(&self, request: ChatRequest) -> Result<ChatResponse, ProviderError> {
        // The extraction request is the one whose system prompt identifies SAYA's
        // post-turn extractor (`build_extraction_prompt` opens with that line). A
        // turn request's system prompt is the connection context, which never
        // contains this phrase, so the two are distinguished by content — the one
        // stable marker the production prompt guarantees.
        let is_extraction = request
            .messages
            .first()
            .map(|m| m.content.contains("precision schema knowledge extractor"))
            .unwrap_or(false);
        if is_extraction {
            let mut calls = self.extraction_calls.lock().unwrap();
            *calls += 1;
            self.extraction_response.clone()
        } else {
            let mut step = self.turn_step.lock().unwrap();
            let idx = *step;
            *step += 1;
            if idx < self.turn_steps.len() {
                Ok(self.turn_steps[idx].clone())
            } else {
                Ok(ChatResponse {
                    message: ChatMessage::text("assistant", "done"),
                })
            }
        }
    }
}

/// 1. Integration test: agent runs, completes answer, harness executes extraction,
/// writes to store, and sink receives KnowledgeProposed.
#[tokio::test]
async fn test_runtime_runs_post_turn_extraction_and_emits_proposed_event() {
    let root = temp_root("post_turn_extract");
    let db = root.join("state.sqlite3");
    let identity = identity_for("analytics");
    let store = store_at(&db, &identity).await;

    let events = Arc::new(Mutex::new(Vec::new()));
    let sink = RecordingSink {
        events: events.clone(),
        knowledge_log: Arc::new(Mutex::new(Vec::new())),
    };
    let inputs = TurnInputs {
        ai: ResolvedAi {
            provider: AiProvider::Ollama,
            model: "test-model".into(),
            base_url: None,
            api_key: None,
            allow_data_sharing: true,
            temperature: 0.0,
            timeout_seconds: 60,
            idle_timeout_seconds: 90,
            max_output_tokens: 4096,
            context_byte_budget: 256 * 1024,
        },
        provider: Box::new(TurnAndExtractionProvider {
            turn_step: Mutex::new(0),
            turn_steps: vec![
                ChatResponse {
                    message: ChatMessage {
                        role: "assistant".into(),
                        content: String::new(),
                        tool_calls: vec![ToolCall {
                            id: "call-1".into(),
                            name: "bounded_sql_query".into(),
                            arguments: serde_json::json!({
                                "connection": "analytics",
                                "sql": "SELECT id, status FROM catalog.public.orders",
                            }),
                        }],
                        tool_call_id: None,
                    },
                },
                ChatResponse {
                    message: ChatMessage::text(
                        "assistant",
                        "The orders table contains customer orders.",
                    ),
                },
            ],
            extraction_response: Ok(ChatResponse {
                message: ChatMessage::text(
                    "assistant",
                    r#"{"proposals": [{"object_id": "T0", "slot": "table.alias", "value": "orders", "origin": "user_explicit"}]}"#,
                ),
            }),
            extraction_calls: Mutex::new(0),
        }),
        registry: registry_for("analytics", &identity),
        failures: Vec::new(),
    };
    let runtime = test_runtime(assisted_memory());
    let out = run_prompt_with_inputs(
        &runtime,
        inputs,
        "table orders has alias orders",
        saya_agent::ApprovalPolicy::ReadOnly,
        false,
        Vec::new(),
        &sink,
        saya_agent::CancellationToken::new(),
        Some(store.clone()),
        None,
        None,
    )
    .await
    .expect("turn completes");

    assert_eq!(out.answer, "The orders table contains customer orders.");

    // The event assertions run under the sink lock; the store query below
    // awaits, so the guard is dropped before it (holding a std `Mutex` guard
    // across an await is a clippy error and a real footgun).
    {
        let captured = events.lock().unwrap();
        let proposed: Vec<&ProposedClaimDto> = captured
            .iter()
            .filter_map(|event| match event {
                AgentEvent::KnowledgeProposed { claim } => Some(claim),
                _ => None,
            })
            .collect();
        assert_eq!(proposed.len(), 1, "exactly one KnowledgeProposed emitted");
        assert_eq!(proposed[0].profile, "analytics");
        assert_eq!(proposed[0].object, "catalog.public.orders");
        assert_eq!(proposed[0].kind, "table_alias");
        assert_eq!(proposed[0].value, "orders");
        // The user explicitly asserted the alias, so per spec F Chunk 3 +
        // `ClaimOrigin::may_confirm_directly` the proposal lands `Active`, which
        // the DTO reports as `Confirmed` — a user assertion is the act of
        // confirmation, not a candidate pending it.
        assert_eq!(proposed[0].status, ClaimStatus::Confirmed);
    }

    let obj = object(&identity, "orders");
    // Phase F persists to `knowledge_items` (D-3's projection), not the legacy
    // `contract_claims` table the retired `contract_propose` wrote to — so the
    // end-to-end persistence is asserted through the knowledge-items read.
    let stored = store.knowledge_for_object(&obj).await.unwrap();
    assert_eq!(stored.len(), 1, "persisted in knowledge_items");
    assert_eq!(stored[0].slot, KnowledgeSlot::TableAlias);
    assert_eq!(stored[0].state, KnowledgeState::Active);
    assert_eq!(stored[0].source, ClaimOrigin::UserExplicit);

    let _ = fs::remove_dir_all(root);
}

/// 2. Mock provider returns error during extraction; agent output is returned successfully and unaffected (Safety Property 1).
#[tokio::test]
async fn test_runtime_extraction_failure_never_fails_turn() {
    let root = temp_root("extract_fail_safe");
    let db = root.join("state.sqlite3");
    let identity = identity_for("analytics");
    let store = store_at(&db, &identity).await;

    let events = Arc::new(Mutex::new(Vec::new()));
    let sink = RecordingSink {
        events: events.clone(),
        knowledge_log: Arc::new(Mutex::new(Vec::new())),
    };
    let inputs = TurnInputs {
        ai: ResolvedAi {
            provider: AiProvider::Ollama,
            model: "test-model".into(),
            base_url: None,
            api_key: None,
            allow_data_sharing: true,
            temperature: 0.0,
            timeout_seconds: 60,
            idle_timeout_seconds: 90,
            max_output_tokens: 4096,
            context_byte_budget: 256 * 1024,
        },
        provider: Box::new(TurnAndExtractionProvider {
            turn_step: Mutex::new(0),
            turn_steps: vec![
                ChatResponse {
                    message: ChatMessage {
                        role: "assistant".into(),
                        content: String::new(),
                        tool_calls: vec![ToolCall {
                            id: "call-1".into(),
                            name: "bounded_sql_query".into(),
                            arguments: serde_json::json!({
                                "connection": "analytics",
                                "sql": "SELECT id, status FROM catalog.public.orders",
                            }),
                        }],
                        tool_call_id: None,
                    },
                },
                ChatResponse {
                    message: ChatMessage::text(
                        "assistant",
                        "The orders table was inspected successfully.",
                    ),
                },
            ],
            extraction_response: Err(ProviderError::configuration("http 500 error")),
            extraction_calls: Mutex::new(0),
        }),
        registry: registry_for("analytics", &identity),
        failures: Vec::new(),
    };
    let runtime = test_runtime(assisted_memory());
    let out = run_prompt_with_inputs(
        &runtime,
        inputs,
        "table orders has alias orders",
        saya_agent::ApprovalPolicy::ReadOnly,
        false,
        Vec::new(),
        &sink,
        saya_agent::CancellationToken::new(),
        Some(store.clone()),
        None,
        None,
    )
    .await
    .expect("turn completes despite extraction failure (fail-soft)");

    assert_eq!(out.answer, "The orders table was inspected successfully.");

    let captured = events.lock().unwrap();
    let proposed_count = captured
        .iter()
        .filter(|e| matches!(e, AgentEvent::KnowledgeProposed { .. }))
        .count();
    assert_eq!(
        proposed_count, 0,
        "no proposals emitted when extraction fails"
    );

    let _ = fs::remove_dir_all(root);
}

/// 3. When memory.mode = MemoryMode::Off, zero extraction requests occur.
#[tokio::test]
async fn test_runtime_extraction_skipped_when_memory_mode_off() {
    let root = temp_root("extract_off");
    let db = root.join("state.sqlite3");
    let identity = identity_for("analytics");
    let store = store_at(&db, &identity).await;

    let events = Arc::new(Mutex::new(Vec::new()));
    let sink = RecordingSink {
        events: events.clone(),
        knowledge_log: Arc::new(Mutex::new(Vec::new())),
    };
    let provider = Arc::new(TurnAndExtractionProvider {
        turn_step: Mutex::new(0),
        turn_steps: vec![
            ChatResponse {
                message: ChatMessage {
                    role: "assistant".into(),
                    content: String::new(),
                    tool_calls: vec![ToolCall {
                        id: "call-1".into(),
                        name: "bounded_sql_query".into(),
                        arguments: serde_json::json!({
                            "connection": "analytics",
                            "sql": "SELECT id, status FROM catalog.public.orders",
                        }),
                    }],
                    tool_call_id: None,
                },
            },
            ChatResponse {
                message: ChatMessage::text("assistant", "query completed"),
            },
        ],
        extraction_response: Ok(ChatResponse {
            message: ChatMessage::text("assistant", r#"{"proposals": []}"#),
        }),
        extraction_calls: Mutex::new(0),
    });

    struct SharedProvider(Arc<TurnAndExtractionProvider>);
    #[async_trait]
    impl ChatProvider for SharedProvider {
        fn name(&self) -> &str {
            "shared"
        }
        async fn complete(&self, req: ChatRequest) -> Result<ChatResponse, ProviderError> {
            self.0.complete(req).await
        }
    }

    let inputs = TurnInputs {
        ai: ResolvedAi {
            provider: AiProvider::Ollama,
            model: "test-model".into(),
            base_url: None,
            api_key: None,
            allow_data_sharing: true,
            temperature: 0.0,
            timeout_seconds: 60,
            idle_timeout_seconds: 90,
            max_output_tokens: 4096,
            context_byte_budget: 256 * 1024,
        },
        provider: Box::new(SharedProvider(provider.clone())),
        registry: registry_for("analytics", &identity),
        failures: Vec::new(),
    };
    let mut mem = assisted_memory();
    mem.mode = saya_config::MemoryMode::Off;
    let runtime = test_runtime(mem);
    let out = run_prompt_with_inputs(
        &runtime,
        inputs,
        "table orders has alias orders",
        saya_agent::ApprovalPolicy::ReadOnly,
        false,
        Vec::new(),
        &sink,
        saya_agent::CancellationToken::new(),
        Some(store.clone()),
        None,
        None,
    )
    .await
    .expect("turn completes");

    assert_eq!(out.answer, "query completed");
    assert_eq!(
        *provider.extraction_calls.lock().unwrap(),
        0,
        "extraction was never called"
    );

    let _ = fs::remove_dir_all(root);
}

/// 4. Asserts contract_propose is absent from DatabaseTools::definitions(...).
#[test]
fn test_contract_propose_tool_not_advertised_to_model() {
    let tools = super::tools::DatabaseTools::definitions(true, true, true);
    let names: Vec<&str> = tools.iter().map(|t| t.name.as_str()).collect();
    assert!(
        !names.contains(&"contract_propose"),
        "contract_propose must not be advertised"
    );
    assert!(names.contains(&"schema_discovery"));
    assert!(names.contains(&"bounded_sql_query"));
    assert!(names.contains(&"contract_search"));
    assert!(names.contains(&"contract_read"));
}

/// 5. Supplied contract in recall receipt prevents duplicate candidate proposal from being emitted or stored during the turn (Safety Property 4).
#[tokio::test]
async fn test_anti_self_reinforcement_end_to_end() {
    let root = temp_root("anti_self_reinforce_e2e");
    let db = root.join("state.sqlite3");
    let identity = identity_for("analytics");
    let store = store_at(&db, &identity).await;

    // Seed confirmed claim on orders
    let obj = object(&identity, "orders");
    let tree = orders_schema(&identity);
    store
        .upsert_schema(identity.as_str(), &tree.1)
        .await
        .unwrap();
    let fp = live_fingerprint(&orders_table());
    let _ = remember_default_time_column(
        &store,
        &obj,
        &fp,
        "created_at",
        ClaimStatus::Confirmed,
        ClaimOrigin::UserExplicit,
    )
    .await;

    let events = Arc::new(Mutex::new(Vec::new()));
    let sink = RecordingSink {
        events: events.clone(),
        knowledge_log: Arc::new(Mutex::new(Vec::new())),
    };
    let inputs = TurnInputs {
        ai: ResolvedAi {
            provider: AiProvider::Ollama,
            model: "test-model".into(),
            base_url: None,
            api_key: None,
            allow_data_sharing: true,
            temperature: 0.0,
            timeout_seconds: 60,
            idle_timeout_seconds: 90,
            max_output_tokens: 4096,
            context_byte_budget: 256 * 1024,
        },
        provider: Box::new(TurnAndExtractionProvider {
            turn_step: Mutex::new(0),
            turn_steps: vec![
                ChatResponse {
                    message: ChatMessage {
                        role: "assistant".into(),
                        content: String::new(),
                        tool_calls: vec![ToolCall {
                            id: "call-1".into(),
                            name: "bounded_sql_query".into(),
                            arguments: serde_json::json!({
                                "connection": "analytics",
                                "sql": "SELECT id, created_at FROM catalog.public.orders",
                            }),
                        }],
                        tool_call_id: None,
                    },
                },
                ChatResponse {
                    message: ChatMessage::text("assistant", "Order dates checked."),
                },
            ],
            // The model re-infers the *same* default-time claim recall already
            // supplied (`default_time_column=created_at` → slot `table.default_time`,
            // value `created_at`), as `assistant_inferred`. Anti-self-reinforcement
            // drops it as an exact duplicate of the supplied claim — the property
            // this test exists for. A different-slot inference would NOT be dropped,
            // so the fixture must duplicate the supplied slot+value to exercise it.
            extraction_response: Ok(ChatResponse {
                message: ChatMessage::text(
                    "assistant",
                    r#"{"proposals": [{"object_id": "T0", "slot": "table.default_time", "value": "created_at", "origin": "assistant_inferred"}]}"#,
                ),
            }),
            extraction_calls: Mutex::new(0),
        }),
        registry: registry_for("analytics", &identity),
        failures: Vec::new(),
    };
    let runtime = test_runtime(assisted_memory());
    let out = run_prompt_with_inputs(
        &runtime,
        inputs,
        "show me orders",
        saya_agent::ApprovalPolicy::ReadOnly,
        false,
        Vec::new(),
        &sink,
        saya_agent::CancellationToken::new(),
        Some(store.clone()),
        None,
        None,
    )
    .await
    .expect("turn completes");

    assert_eq!(out.answer, "Order dates checked.");

    let captured = events.lock().unwrap();
    let proposed_count = captured
        .iter()
        .filter(|e| matches!(e, AgentEvent::KnowledgeProposed { .. }))
        .count();
    assert_eq!(
        proposed_count, 0,
        "anti-self-reinforcement dropped duplicate inference"
    );

    let _ = fs::remove_dir_all(root);
}

// ===========================================================================
// Test 11: runtime turn with mode = off builds ConfiguredOff receipt and
// emits KnowledgeOutcome::Off.
// ===========================================================================

#[tokio::test]
async fn runtime_turn_with_recall_off_emits_knowledge_outcome_off() {
    let events = Arc::new(Mutex::new(Vec::new()));
    let log = Arc::new(Mutex::new(Vec::new()));
    let sink = RecordingSink {
        events: events.clone(),
        knowledge_log: log.clone(),
    };
    let provider = AnswerProvider {
        answer: "done",
        log: log.clone(),
    };
    let identity = identity_for("analytics");
    let inputs = TurnInputs {
        ai: ResolvedAi {
            provider: AiProvider::Ollama,
            model: "test-model".into(),
            base_url: None,
            api_key: None,
            allow_data_sharing: true,
            temperature: 0.0,
            timeout_seconds: 60,
            idle_timeout_seconds: 90,
            max_output_tokens: 4096,
            context_byte_budget: 256 * 1024,
        },
        provider: Box::new(provider),
        registry: registry_for("analytics", &identity),
        failures: Vec::new(),
    };
    let mut memory = default_memory();
    memory.mode = saya_config::MemoryMode::Off;
    let runtime = test_runtime(memory);
    run_prompt_with_inputs(
        &runtime,
        inputs,
        "orders by month",
        saya_agent::ApprovalPolicy::ReadOnly,
        false,
        Vec::new(),
        &sink,
        saya_agent::CancellationToken::new(),
        None,
        None,
        None,
    )
    .await
    .unwrap();

    let captured = events.lock().unwrap();
    let outcome = captured
        .iter()
        .find_map(|e| match e {
            AgentEvent::KnowledgeSupplied { outcome, .. } => Some(*outcome),
            _ => None,
        })
        .expect("KnowledgeSupplied present");
    assert_eq!(outcome, KnowledgeOutcome::Off);
}

// ===========================================================================
// Test 12: runtime turn with closed privacy gate builds PrivacyGateClosed
// receipt and emits KnowledgeOutcome::Skipped.
// ===========================================================================

#[tokio::test]
async fn runtime_turn_with_closed_privacy_gate_emits_knowledge_outcome_skipped() {
    let events = Arc::new(Mutex::new(Vec::new()));
    let log = Arc::new(Mutex::new(Vec::new()));
    let sink = RecordingSink {
        events: events.clone(),
        knowledge_log: log.clone(),
    };
    let provider = AnswerProvider {
        answer: "done",
        log: log.clone(),
    };
    let identity = identity_for("analytics");
    let inputs = TurnInputs {
        ai: ResolvedAi {
            provider: AiProvider::Anthropic,
            model: "test-model".into(),
            base_url: None,
            api_key: None,
            allow_data_sharing: false, // privacy gate closed for cloud providers
            temperature: 0.0,
            timeout_seconds: 60,
            idle_timeout_seconds: 90,
            max_output_tokens: 4096,
            context_byte_budget: 256 * 1024,
        },
        provider: Box::new(provider),
        registry: registry_for("analytics", &identity),
        failures: Vec::new(),
    };
    let runtime = test_runtime(assisted_memory());
    run_prompt_with_inputs(
        &runtime,
        inputs,
        "orders by month",
        saya_agent::ApprovalPolicy::ReadOnly,
        false,
        Vec::new(),
        &sink,
        saya_agent::CancellationToken::new(),
        None,
        None,
        None,
    )
    .await
    .unwrap();

    let captured = events.lock().unwrap();
    let outcome = captured
        .iter()
        .find_map(|e| match e {
            AgentEvent::KnowledgeSupplied { outcome, .. } => Some(*outcome),
            _ => None,
        })
        .expect("KnowledgeSupplied present");
    assert_eq!(outcome, KnowledgeOutcome::Skipped);
}

// ===========================================================================
// Spec A1: surfacing an override from the SQL, not the model's confession.
//
// `detect_overrides` exists and is tested against the real generated SQL; this
// slice wires it into the turn and emits `KnowledgeOverridden`. These tests
// drive a turn through `run_prompt_with_inputs` with a provider that issues one
// `bounded_sql_query` call, so detection runs against the statement the model
// actually generated and the receipt recall supplied — not a unit oracle.
//
// The harness mirrors test 1 above: a confirmed `default_time_column` claim of
// `return_date` seeded under a matching cached `orders` schema (columns
// `id` + `created_at`), so recall supplies the claim as `Current`. The claim
// names `return_date` as the time column; the model's SQL references a
// *different* time-named column (`rental_date`) on the same object — the live
// override case the detector exists to catch.
// ===========================================================================

/// `mode = Assisted` supplies confirmed claims for override detection.
fn a1_memory() -> ResolvedMemory {
    ResolvedMemory {
        mode: MemoryMode::Assisted,
        max_contracts: 5,
        max_claims_per_contract: 12,
        max_context_bytes: 16384,
    }
}

/// `mode = Assisted` supplies both confirmed and candidate claims.
fn a1_include_candidates_memory() -> ResolvedMemory {
    ResolvedMemory {
        mode: MemoryMode::Assisted,
        max_contracts: 5,
        max_claims_per_contract: 12,
        max_context_bytes: 16384,
    }
}

/// A provider that issues one `bounded_sql_query` call with `sql` on the first
/// request and a text answer on every subsequent one — a one-query turn that
/// completes, so the runtime drains the override log and emits after the loop.
struct QueryProvider {
    sql: &'static str,
    calls: Mutex<usize>,
}

#[async_trait]
impl ChatProvider for QueryProvider {
    fn name(&self) -> &str {
        "query-once"
    }
    async fn complete(&self, _request: ChatRequest) -> Result<ChatResponse, ProviderError> {
        let mut calls = self.calls.lock().unwrap();
        if *calls == 0 {
            *calls = 1;
            Ok(ChatResponse {
                message: ChatMessage {
                    role: "assistant".into(),
                    content: String::new(),
                    tool_calls: vec![ToolCall {
                        id: "call".into(),
                        name: "bounded_sql_query".into(),
                        arguments: serde_json::json!({ "sql": self.sql }),
                    }],
                    tool_call_id: None,
                },
            })
        } else {
            Ok(ChatResponse {
                message: ChatMessage::text("assistant", "done"),
            })
        }
    }
}

/// The live override statement: a different time-named column referenced on the
/// claimed object, the claimed column absent.
const OVERRIDE_SQL: &str = "SELECT rental_date FROM orders WHERE rental_date > '2024-01-01'";

/// Seeds a confirmed `default_time_column` claim of `return_date` on
/// `catalog.public.orders` under a matching cached schema, returning the temp
/// root, the claim id, and the open store. Mirrors the test-1 harness.
///
/// D-4 NOTE: the claim's binding is `Column { return_date, Time }`, so the
/// cached schema must carry `return_date` as a temporal column for the item to
/// read `current` (and so reach the model, where override detection sees it).
/// The old whole-table fingerprint model classified the claim `Current` from
/// the fingerprint match alone; D-4 classifies from the binding, so the schema
/// must name the bound column.
async fn a1_turn_setup(
    status: ClaimStatus,
    origin: ClaimOrigin,
) -> (PathBuf, ClaimId, SqliteStateStore) {
    let root = temp_root("a1");
    let db = root.join("state.sqlite3");
    let identity = identity_for("analytics");
    let store = store_at(&db, &identity).await;
    let obj = object(&identity, "orders");
    let tree = SchemaTree {
        databases: vec![Database {
            name: "catalog".into(),
            schemas: vec![Schema {
                name: "public".into(),
                tables: vec![Table {
                    name: "orders".into(),
                    columns: vec![
                        Column {
                            name: "id".into(),
                            data_type: "bigint".into(),
                            nullable: false,
                        },
                        Column {
                            name: "return_date".into(),
                            data_type: "timestamp".into(),
                            nullable: false,
                        },
                    ],
                }],
            }],
        }],
    };
    store.upsert_schema(identity.as_str(), &tree).await.unwrap();
    let fp = live_fingerprint(&orders_table());
    let claim_id =
        remember_default_time_column(&store, &obj, &fp, "return_date", status, origin).await;
    (root, claim_id, store)
}

/// The single `KnowledgeOverridden` event in `captured`, if any. Detection
/// emits at most one event per turn carrying every finding.
fn one_overridden(captured: &[AgentEvent]) -> Option<&[OverrideFindingDto]> {
    captured.iter().find_map(|event| match event {
        AgentEvent::KnowledgeOverridden { findings } => Some(findings.as_slice()),
        _ => None,
    })
}

// Test 1: a turn whose SQL contradicts a supplied confirmed claim emits one
// `KnowledgeOverridden` naming it.
#[tokio::test]
async fn a_turn_contradicting_a_confirmed_claim_emits_one_knowledge_overridden() {
    let (root, claim_id, store) =
        a1_turn_setup(ClaimStatus::Confirmed, ClaimOrigin::UserExplicit).await;

    let events = Arc::new(Mutex::new(Vec::new()));
    let sink = RecordingSink {
        events: events.clone(),
        knowledge_log: Arc::new(Mutex::new(Vec::new())),
    };
    let inputs = TurnInputs {
        ai: ResolvedAi {
            provider: AiProvider::Ollama,
            model: "test-model".into(),
            base_url: None,
            api_key: None,
            allow_data_sharing: true,
            temperature: 0.0,
            timeout_seconds: 60,
            idle_timeout_seconds: 90,
            max_output_tokens: 4096,
            context_byte_budget: 256 * 1024,
        },
        provider: Box::new(QueryProvider {
            sql: OVERRIDE_SQL,
            calls: Mutex::new(0),
        }),
        registry: registry_for("analytics", &identity_for("analytics")),
        failures: Vec::new(),
    };
    let runtime = test_runtime(a1_memory());
    run_prompt_with_inputs(
        &runtime,
        inputs,
        "orders by month",
        saya_agent::ApprovalPolicy::ReadOnly,
        false,
        Vec::new(),
        &sink,
        saya_agent::CancellationToken::new(),
        // The store must be present so recall supplies the claim.
        Some(store),
        None,
        None,
    )
    .await
    .expect("turn completes");

    let captured = events.lock().unwrap();
    let findings = one_overridden(&captured).expect("one KnowledgeOverridden");
    assert_eq!(
        findings.len(),
        1,
        "exactly one finding, naming the contradicted claim: {captured:?}"
    );
    let f = &findings[0];
    assert_eq!(f.claim_id, claim_id, "names the supplied confirmed claim");
    assert_eq!(f.kind, "default_time_column");
    assert_eq!(f.claimed_value, "return_date", "where you specified Y");
    assert!(
        f.observed_columns.contains(&"rental_date".to_string()),
        "names the column actually referenced: {f:?}"
    );
    let _ = fs::remove_dir_all(root);
}

// Test 2: a turn whose SQL honours the claim emits nothing.
#[tokio::test]
async fn a_turn_honouring_the_claim_emits_no_knowledge_overridden() {
    let (root, _claim_id, store) =
        a1_turn_setup(ClaimStatus::Confirmed, ClaimOrigin::UserExplicit).await;
    // The claimed column `return_date` is referenced → the claim is honoured.
    let honoring_sql = "SELECT return_date FROM orders WHERE return_date > '2024-01-01'";

    let events = Arc::new(Mutex::new(Vec::new()));
    let sink = RecordingSink {
        events: events.clone(),
        knowledge_log: Arc::new(Mutex::new(Vec::new())),
    };
    let inputs = TurnInputs {
        ai: ResolvedAi {
            provider: AiProvider::Ollama,
            model: "test-model".into(),
            base_url: None,
            api_key: None,
            allow_data_sharing: true,
            temperature: 0.0,
            timeout_seconds: 60,
            idle_timeout_seconds: 90,
            max_output_tokens: 4096,
            context_byte_budget: 256 * 1024,
        },
        provider: Box::new(QueryProvider {
            sql: honoring_sql,
            calls: Mutex::new(0),
        }),
        registry: registry_for("analytics", &identity_for("analytics")),
        failures: Vec::new(),
    };
    let runtime = test_runtime(a1_memory());
    run_prompt_with_inputs(
        &runtime,
        inputs,
        "orders by month",
        saya_agent::ApprovalPolicy::ReadOnly,
        false,
        Vec::new(),
        &sink,
        saya_agent::CancellationToken::new(),
        Some(store),
        None,
        None,
    )
    .await
    .expect("turn completes");

    let captured = events.lock().unwrap();
    assert!(
        one_overridden(&captured).is_none(),
        "honouring the claim must emit no override event: {captured:?}"
    );
    let _ = fs::remove_dir_all(root);
}

// Test 3: unparseable SQL emits nothing.
#[tokio::test]
async fn a_turn_with_unparseable_sql_emits_no_knowledge_overridden() {
    let (root, _claim_id, store) =
        a1_turn_setup(ClaimStatus::Confirmed, ClaimOrigin::UserExplicit).await;
    // `sql_references` returns `None` for this; the detector fails closed.
    let unparseable_sql = "SELECT FROM WHERE";

    let events = Arc::new(Mutex::new(Vec::new()));
    let sink = RecordingSink {
        events: events.clone(),
        knowledge_log: Arc::new(Mutex::new(Vec::new())),
    };
    let inputs = TurnInputs {
        ai: ResolvedAi {
            provider: AiProvider::Ollama,
            model: "test-model".into(),
            base_url: None,
            api_key: None,
            allow_data_sharing: true,
            temperature: 0.0,
            timeout_seconds: 60,
            idle_timeout_seconds: 90,
            max_output_tokens: 4096,
            context_byte_budget: 256 * 1024,
        },
        provider: Box::new(QueryProvider {
            sql: unparseable_sql,
            calls: Mutex::new(0),
        }),
        registry: registry_for("analytics", &identity_for("analytics")),
        failures: Vec::new(),
    };
    let runtime = test_runtime(a1_memory());
    run_prompt_with_inputs(
        &runtime,
        inputs,
        "orders by month",
        saya_agent::ApprovalPolicy::ReadOnly,
        false,
        Vec::new(),
        &sink,
        saya_agent::CancellationToken::new(),
        Some(store),
        None,
        None,
    )
    .await
    .expect("turn completes");

    let captured = events.lock().unwrap();
    assert!(
        one_overridden(&captured).is_none(),
        "unparseable SQL must emit no override event: {captured:?}"
    );
    let _ = fs::remove_dir_all(root);
}

// Test 4: a candidate claim contradicted emits nothing (only confirmed claims
// can be overridden). `recall = IncludeCandidates` so the candidate IS supplied
// to the model — the detector's status guard is what suppresses the finding,
// not recall's filter.
#[tokio::test]
async fn a_candidate_claim_contradicted_emits_nothing() {
    let (root, _claim_id, store) =
        a1_turn_setup(ClaimStatus::Candidate, ClaimOrigin::UserExplicit).await;

    let events = Arc::new(Mutex::new(Vec::new()));
    let sink = RecordingSink {
        events: events.clone(),
        knowledge_log: Arc::new(Mutex::new(Vec::new())),
    };
    let inputs = TurnInputs {
        ai: ResolvedAi {
            provider: AiProvider::Ollama,
            model: "test-model".into(),
            base_url: None,
            api_key: None,
            allow_data_sharing: true,
            temperature: 0.0,
            timeout_seconds: 60,
            idle_timeout_seconds: 90,
            max_output_tokens: 4096,
            context_byte_budget: 256 * 1024,
        },
        provider: Box::new(QueryProvider {
            sql: OVERRIDE_SQL,
            calls: Mutex::new(0),
        }),
        registry: registry_for("analytics", &identity_for("analytics")),
        failures: Vec::new(),
    };
    let runtime = test_runtime(a1_include_candidates_memory());
    run_prompt_with_inputs(
        &runtime,
        inputs,
        "orders by month",
        saya_agent::ApprovalPolicy::ReadOnly,
        false,
        Vec::new(),
        &sink,
        saya_agent::CancellationToken::new(),
        Some(store),
        None,
        None,
    )
    .await
    .expect("turn completes");

    let captured = events.lock().unwrap();
    // The candidate IS supplied (IncludeCandidates), so KnowledgeSupplied is
    // present — but no KnowledgeOverridden fires: only a confirmed claim binds.
    assert!(
        captured
            .iter()
            .any(|e| matches!(e, AgentEvent::KnowledgeSupplied { .. })),
        "the candidate was supplied: {captured:?}"
    );
    assert!(
        one_overridden(&captured).is_none(),
        "a candidate claim is not overridable: {captured:?}"
    );
    let _ = fs::remove_dir_all(root);
}

// Test 6: no opaque profile identity leaks into the serialized event. The DTO
// has no identity field by construction; this asserts the event stream inherits
// that guarantee (mirrors the P2d identity-leak test).
#[tokio::test]
async fn no_identity_leaks_into_the_knowledge_overridden_event() {
    let (root, _claim_id, store) =
        a1_turn_setup(ClaimStatus::Confirmed, ClaimOrigin::UserExplicit).await;
    let identity_str = identity_for("analytics").as_str().to_string();

    let events = Arc::new(Mutex::new(Vec::new()));
    let sink = RecordingSink {
        events: events.clone(),
        knowledge_log: Arc::new(Mutex::new(Vec::new())),
    };
    let inputs = TurnInputs {
        ai: ResolvedAi {
            provider: AiProvider::Ollama,
            model: "test-model".into(),
            base_url: None,
            api_key: None,
            allow_data_sharing: true,
            temperature: 0.0,
            timeout_seconds: 60,
            idle_timeout_seconds: 90,
            max_output_tokens: 4096,
            context_byte_budget: 256 * 1024,
        },
        provider: Box::new(QueryProvider {
            sql: OVERRIDE_SQL,
            calls: Mutex::new(0),
        }),
        registry: registry_for("analytics", &identity_for("analytics")),
        failures: Vec::new(),
    };
    let runtime = test_runtime(a1_memory());
    run_prompt_with_inputs(
        &runtime,
        inputs,
        "orders by month",
        saya_agent::ApprovalPolicy::ReadOnly,
        false,
        Vec::new(),
        &sink,
        saya_agent::CancellationToken::new(),
        Some(store),
        None,
        None,
    )
    .await
    .expect("turn completes");

    let captured = events.lock().unwrap();
    let stream_json = serde_json::to_string(captured.as_slice()).unwrap_or_default();
    assert!(
        !stream_json.contains(&identity_str),
        "opaque identity leaked into the event stream: {stream_json}"
    );
    let _ = fs::remove_dir_all(root);
}

// ===========================================================================
// Spec packet-54: a turn whose post-turn extraction times out or errors must
// say so (KnowledgeLearningSkipped). Today it is silent — the red tests below
// assert the event fires AND the turn still completes. The gate-declined case
// emits nothing (decision 2).
//
// The timeout test sleeps *past* the production `EXTRACTION_TIMEOUT` constant
// (15s) — the spec mandates a documented, bounded constant and a test that
// sleeps past it, so this is one ~15s test by design, not a parameterized
// shortcut. The extraction call is distinguished from the turn call by the
// `precision schema knowledge extractor` system-prompt marker, the same stable
// marker `TurnAndExtractionProvider` relies on above.
// ===========================================================================

/// A provider that answers the turn normally but sleeps past the extraction
/// timeout when called for extraction, so the runtime's `tokio::time::timeout`
/// fires. Reuses the turn-steps + extraction-marker shape of
/// `TurnAndExtractionProvider`.
struct SleepingExtractionProvider {
    turn_step: Mutex<usize>,
    turn_steps: Vec<ChatResponse>,
    extraction_calls: Mutex<usize>,
}

#[async_trait]
impl ChatProvider for SleepingExtractionProvider {
    fn name(&self) -> &str {
        "sleeping-extraction-provider"
    }
    async fn complete(&self, request: ChatRequest) -> Result<ChatResponse, ProviderError> {
        let is_extraction = request
            .messages
            .first()
            .map(|m| m.content.contains("precision schema knowledge extractor"))
            .unwrap_or(false);
        if is_extraction {
            {
                let mut calls = self.extraction_calls.lock().unwrap();
                *calls += 1;
            }
            // Sleep past the production timeout so `tokio::time::timeout` fires.
            tokio::time::sleep(
                super::super::learning::EXTRACTION_TIMEOUT + std::time::Duration::from_secs(1),
            )
            .await;
            Ok(ChatResponse {
                message: ChatMessage::text("assistant", r#"{"proposals": []}"#),
            })
        } else {
            let mut step = self.turn_step.lock().unwrap();
            let idx = *step;
            *step += 1;
            if idx < self.turn_steps.len() {
                Ok(self.turn_steps[idx].clone())
            } else {
                Ok(ChatResponse {
                    message: ChatMessage::text("assistant", "done"),
                })
            }
        }
    }
}

/// One turn that issues a `bounded_sql_query` (object activity + non-trivial
/// answer) so the gate admits extraction, then the extraction call sleeps past
/// the timeout. Asserts `KnowledgeLearningSkipped { TimedOut }` is emitted and
/// the turn still completes with its answer (Safety Property 1: fail-soft).
#[tokio::test]
async fn a_turn_whose_extraction_times_out_emits_learning_skipped_and_completes() {
    let root = temp_root("p54_timeout");
    let db = root.join("state.sqlite3");
    let identity = identity_for("analytics");
    let store = store_at(&db, &identity).await;

    let events = Arc::new(Mutex::new(Vec::new()));
    let sink = RecordingSink {
        events: events.clone(),
        knowledge_log: Arc::new(Mutex::new(Vec::new())),
    };
    let inputs = TurnInputs {
        ai: ResolvedAi {
            provider: AiProvider::Ollama,
            model: "test-model".into(),
            base_url: None,
            api_key: None,
            allow_data_sharing: true,
            temperature: 0.0,
            timeout_seconds: 60,
            idle_timeout_seconds: 90,
            max_output_tokens: 4096,
            context_byte_budget: 256 * 1024,
        },
        provider: Box::new(SleepingExtractionProvider {
            turn_step: Mutex::new(0),
            turn_steps: vec![
                ChatResponse {
                    message: ChatMessage {
                        role: "assistant".into(),
                        content: String::new(),
                        tool_calls: vec![ToolCall {
                            id: "call-1".into(),
                            name: "bounded_sql_query".into(),
                            arguments: serde_json::json!({
                                "connection": "analytics",
                                "sql": "SELECT id, status FROM catalog.public.orders",
                            }),
                        }],
                        tool_call_id: None,
                    },
                },
                ChatResponse {
                    message: ChatMessage::text(
                        "assistant",
                        "The orders table contains customer orders.",
                    ),
                },
            ],
            extraction_calls: Mutex::new(0),
        }),
        registry: registry_for("analytics", &identity),
        failures: Vec::new(),
    };
    let runtime = test_runtime(assisted_memory());
    let out = run_prompt_with_inputs(
        &runtime,
        inputs,
        "table orders has alias orders",
        saya_agent::ApprovalPolicy::ReadOnly,
        false,
        Vec::new(),
        &sink,
        saya_agent::CancellationToken::new(),
        Some(store.clone()),
        None,
        None,
    )
    .await
    .expect("turn completes despite extraction timeout (fail-soft)");

    // The turn's answer is unaffected — extraction failure is not answer failure.
    assert_eq!(out.answer, "The orders table contains customer orders.");

    let captured = events.lock().unwrap();
    let skipped = captured.iter().find_map(|event| match event {
        AgentEvent::KnowledgeLearningSkipped { reason } => Some(*reason),
        _ => None,
    });
    assert_eq!(
        skipped,
        Some(LearningSkipReason::TimedOut),
        "timeout must emit KnowledgeLearningSkipped{{TimedOut}}: {captured:?}"
    );
    // No proposal was emitted — the timeout aborted extraction before ingest.
    let proposed_count = captured
        .iter()
        .filter(|e| matches!(e, AgentEvent::KnowledgeProposed { .. }))
        .count();
    assert_eq!(
        proposed_count, 0,
        "no proposals after timeout: {captured:?}"
    );
    let _ = fs::remove_dir_all(root);
}

/// A gate-declined turn emits **nothing** for learning (decision 2: a gate skip
/// stays silent). Uses an `Off` memory mode so `permit_candidate_writes` is
/// false and the extraction block is never entered — the same path a gate
/// decline would take when the runtime skips it. Asserts no
/// `KnowledgeLearningSkipped` and no `KnowledgeProposed` appears.
#[tokio::test]
async fn a_gate_declined_turn_emits_no_learning_event() {
    let root = temp_root("p54_gate_decline");
    let db = root.join("state.sqlite3");
    let identity = identity_for("analytics");
    let store = store_at(&db, &identity).await;

    let events = Arc::new(Mutex::new(Vec::new()));
    let sink = RecordingSink {
        events: events.clone(),
        knowledge_log: Arc::new(Mutex::new(Vec::new())),
    };
    let provider = Arc::new(SleepingExtractionProvider {
        turn_step: Mutex::new(0),
        // A trivial turn with no tool call and a short answer: the gate would
        // decline (no object activity, <15-char answer). Memory is Off, so the
        // extraction block is never entered regardless — proving the silent path.
        turn_steps: vec![ChatResponse {
            message: ChatMessage::text("assistant", "ok"),
        }],
        extraction_calls: Mutex::new(0),
    });
    struct SharedProvider(Arc<SleepingExtractionProvider>);
    #[async_trait]
    impl ChatProvider for SharedProvider {
        fn name(&self) -> &str {
            "shared-sleeping"
        }
        async fn complete(&self, req: ChatRequest) -> Result<ChatResponse, ProviderError> {
            self.0.complete(req).await
        }
    }
    let inputs = TurnInputs {
        ai: ResolvedAi {
            provider: AiProvider::Ollama,
            model: "test-model".into(),
            base_url: None,
            api_key: None,
            allow_data_sharing: true,
            temperature: 0.0,
            timeout_seconds: 60,
            idle_timeout_seconds: 90,
            max_output_tokens: 4096,
            context_byte_budget: 256 * 1024,
        },
        provider: Box::new(SharedProvider(provider.clone())),
        registry: registry_for("analytics", &identity),
        failures: Vec::new(),
    };
    let mut mem = assisted_memory();
    mem.mode = saya_config::MemoryMode::Off;
    let runtime = test_runtime(mem);
    let out = run_prompt_with_inputs(
        &runtime,
        inputs,
        "hi",
        saya_agent::ApprovalPolicy::ReadOnly,
        false,
        Vec::new(),
        &sink,
        saya_agent::CancellationToken::new(),
        Some(store),
        None,
        None,
    )
    .await
    .expect("turn completes");

    assert_eq!(out.answer, "ok");
    let captured = events.lock().unwrap();
    assert!(
        !captured
            .iter()
            .any(|e| matches!(e, AgentEvent::KnowledgeLearningSkipped { .. })),
        "a gate decline must stay silent: {captured:?}"
    );
    assert!(
        !captured
            .iter()
            .any(|e| matches!(e, AgentEvent::KnowledgeProposed { .. })),
        "no proposals on a gate-declined turn: {captured:?}"
    );
    // Extraction was never called — the gate/permit guard held.
    assert_eq!(
        *provider.extraction_calls.lock().unwrap(),
        0,
        "extraction never ran"
    );
    let _ = fs::remove_dir_all(root);
}

/// A turn whose extraction *errors* (provider failure) emits
/// `KnowledgeLearningSkipped { Failed }` — the non-timeout arm — and still
/// completes. Reuses `TurnAndExtractionProvider` with an `Err` extraction
/// response, the same harness `test_runtime_extraction_failure_never_fails_turn`
/// uses, but asserts the new event (the older test predates it and only
/// asserts no proposals).
#[tokio::test]
async fn a_turn_whose_extraction_errors_emits_learning_skipped_failed_and_completes() {
    let root = temp_root("p54_failed");
    let db = root.join("state.sqlite3");
    let identity = identity_for("analytics");
    let store = store_at(&db, &identity).await;

    let events = Arc::new(Mutex::new(Vec::new()));
    let sink = RecordingSink {
        events: events.clone(),
        knowledge_log: Arc::new(Mutex::new(Vec::new())),
    };
    let inputs = TurnInputs {
        ai: ResolvedAi {
            provider: AiProvider::Ollama,
            model: "test-model".into(),
            base_url: None,
            api_key: None,
            allow_data_sharing: true,
            temperature: 0.0,
            timeout_seconds: 60,
            idle_timeout_seconds: 90,
            max_output_tokens: 4096,
            context_byte_budget: 256 * 1024,
        },
        provider: Box::new(TurnAndExtractionProvider {
            turn_step: Mutex::new(0),
            turn_steps: vec![
                ChatResponse {
                    message: ChatMessage {
                        role: "assistant".into(),
                        content: String::new(),
                        tool_calls: vec![ToolCall {
                            id: "call-1".into(),
                            name: "bounded_sql_query".into(),
                            arguments: serde_json::json!({
                                "connection": "analytics",
                                "sql": "SELECT id, status FROM catalog.public.orders",
                            }),
                        }],
                        tool_call_id: None,
                    },
                },
                ChatResponse {
                    message: ChatMessage::text(
                        "assistant",
                        "The orders table was inspected successfully.",
                    ),
                },
            ],
            extraction_response: Err(ProviderError::configuration("http 500 error")),
            extraction_calls: Mutex::new(0),
        }),
        registry: registry_for("analytics", &identity),
        failures: Vec::new(),
    };
    let runtime = test_runtime(assisted_memory());
    let out = run_prompt_with_inputs(
        &runtime,
        inputs,
        "table orders has alias orders",
        saya_agent::ApprovalPolicy::ReadOnly,
        false,
        Vec::new(),
        &sink,
        saya_agent::CancellationToken::new(),
        Some(store),
        None,
        None,
    )
    .await
    .expect("turn completes despite extraction error (fail-soft)");

    assert_eq!(out.answer, "The orders table was inspected successfully.");

    let captured = events.lock().unwrap();
    let skipped = captured.iter().find_map(|event| match event {
        AgentEvent::KnowledgeLearningSkipped { reason } => Some(*reason),
        _ => None,
    });
    assert_eq!(
        skipped,
        Some(LearningSkipReason::Failed),
        "error must emit KnowledgeLearningSkipped{{Failed}}, not TimedOut: {captured:?}"
    );
    let _ = fs::remove_dir_all(&root);
    let _ = fs::remove_dir_all(root);
}