locode-engine 0.1.17

The sample-dispatch-append loop and Session driving API of the locode coding agent
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
//! locode-engine — the sample→dispatch→append loop and the [`Session`] driving API
//! (ADR-0005, ADR-0004, ADR-0014).
//!
//! A [`Session`] drives one run to a terminal [`locode_protocol::Status`] against any
//! [`locode_provider::Provider`], dispatching tool calls through a
//! [`locode_tools::Registry`], emitting `stream-json` events to an [`EventSink`], and
//! returning one [`locode_protocol::Report`]. Proven end-to-end against
//! `MockProvider` with zero network.

mod approve;
mod config;
mod queue;
mod run;
mod session;
mod sink;
mod terminal;

pub use approve::{AllowAll, ApprovalRequest, Approver, Decision};
pub use config::EngineConfig;
pub use queue::{InputQueue, MID_RUN_PREAMBLE};
pub use session::Session;
pub use sink::{EventSink, FnSink, NullSink};
// The type `Session::cancel_handle` returns (ADR-0018) — re-exported so
// frontends need no direct tokio-util dependency.
pub use tokio_util::sync::CancellationToken;

#[cfg(test)]
mod tests {
    // Test tools return `&'static str` literals from `description`; the trait ties it
    // to `&self` so real tools can return a stored field.
    #![allow(clippy::unnecessary_literal_bound)]

    use super::*;
    use async_trait::async_trait;
    use locode_protocol::{
        ContentBlock, Conversation, Event, Message, ReasoningFormat, Role, Status, Usage,
        reconstruct_conversation,
    };
    use locode_provider::{
        Completion, ConversationRequest, MockProvider, Provider, ProviderError, StopReason,
    };
    use locode_tools::{Registry, Tool, ToolCtx, ToolError, ToolKind, ToolOutput};
    use serde::Serialize;
    use serde_json::{Value, json};
    use std::sync::{Arc, Mutex};
    use std::time::Duration;

    // ---- trivial in-test tools ----

    #[derive(Serialize)]
    struct EchoOut {
        echoed: String,
    }
    impl ToolOutput for EchoOut {
        fn to_prompt_text(&self) -> String {
            self.echoed.clone()
        }
    }

    struct Echo;
    #[async_trait]
    impl Tool for Echo {
        type Args = Value;
        type Output = EchoOut;
        fn kind(&self) -> ToolKind {
            ToolKind::Shell
        }
        fn description(&self) -> &str {
            "echo"
        }
        async fn run(&self, _ctx: &ToolCtx, args: Value) -> Result<EchoOut, ToolError> {
            Ok(EchoOut {
                echoed: args.to_string(),
            })
        }
    }

    struct Boom;
    #[async_trait]
    impl Tool for Boom {
        type Args = Value;
        type Output = EchoOut;
        fn kind(&self) -> ToolKind {
            ToolKind::Shell
        }
        fn description(&self) -> &str {
            "boom"
        }
        async fn run(&self, _ctx: &ToolCtx, _args: Value) -> Result<EchoOut, ToolError> {
            Err(ToolError::Fatal("boom aborted the turn".into()))
        }
    }

    // ---- harness ----

    fn text_turn(text: &str) -> Completion {
        Completion {
            content: vec![ContentBlock::Text { text: text.into() }],
            usage: Usage::default(),
            stop: StopReason::EndTurn,
        }
    }

    fn tool_turn(id: &str, name: &str) -> Completion {
        Completion {
            content: vec![ContentBlock::ToolUse {
                id: id.into(),
                name: name.into(),
                input: json!({}),
            }],
            usage: Usage::default(),
            stop: StopReason::ToolUse,
        }
    }

    fn config() -> EngineConfig {
        EngineConfig {
            session_id: "sess-1".into(),
            harness: "grok".into(),
            api_schema: "mock".into(),
            model: "mock-1".into(),
            max_turns: None,
            resample_retries: 2,
            resample_backoff: Duration::ZERO, // no real sleeps in tests
            // Project-instruction loading off by default in the loop tests: cwd is the
            // crate dir, so a live loader would inject this repo's own AGENTS.md and
            // perturb the exact event/message assertions. The injection path has its own
            // dedicated tests below (`project_instructions_*`).
            instructions: locode_instructions::InstructionsConfig {
                enabled: false,
                ..Default::default()
            },
            ..EngineConfig::default()
        }
    }

    /// Build a session with a scripted provider + registry, collecting events.
    fn session_with(
        script: Vec<Result<Completion, ProviderError>>,
        registry: Registry,
        cfg: EngineConfig,
    ) -> (Session, Arc<Mutex<Vec<Event>>>) {
        let events = Arc::new(Mutex::new(Vec::new()));
        let sink_events = Arc::clone(&events);
        let sink = Box::new(FnSink(move |event| {
            sink_events.lock().unwrap().push(event);
        }));
        let provider = Arc::new(MockProvider::with_results(script));
        let session = Session::new(provider, registry, vec![], cfg, sink);
        (session, events)
    }

    fn echo_registry() -> Registry {
        let mut reg = Registry::new();
        reg.register("echo", Echo);
        reg
    }

    fn dump(events: &Arc<Mutex<Vec<Event>>>) -> Vec<Event> {
        events.lock().unwrap().clone()
    }

    // ---- terminal-state matrix ----

    #[tokio::test]
    async fn completed_with_no_tools() {
        let (mut s, events) =
            session_with(vec![Ok(text_turn("all done"))], Registry::new(), config());
        let report = s.run_text("hi").await;
        assert_eq!(report.status, Status::Completed);
        assert_eq!(report.final_message.as_deref(), Some("all done"));
        assert_eq!(report.turns, 1);
        assert!(report.tool_calls.is_empty());
        assert_eq!(report.api_schema, "mock");
        // Init, Message(user), Message(assistant), Result.
        let evs = dump(&events);
        assert!(matches!(evs.first(), Some(Event::Init { .. })));
        assert!(matches!(evs.last(), Some(Event::Result { .. })));
    }

    // ---- streaming (ADR-0021 slice 1) ----

    #[tokio::test]
    async fn streaming_run_emits_text_deltas_and_the_whole_message() {
        let mut cfg = config();
        cfg.streaming = true;
        let (mut s, events) = session_with(
            vec![Ok(text_turn("hello streamed world"))],
            Registry::new(),
            cfg,
        );
        let report = s.run_text("hi").await;
        assert_eq!(report.status, Status::Completed);
        assert_eq!(
            report.final_message.as_deref(),
            Some("hello streamed world")
        );

        let evs = dump(&events);
        // The deltas concatenate exactly to the finalized assistant text...
        let delta_text: String = evs
            .iter()
            .filter_map(|e| match e {
                Event::MessageDelta { text } => Some(text.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(delta_text, "hello streamed world", "{evs:?}");
        // ...and there was more than one (proving it actually streamed).
        let n_deltas = evs
            .iter()
            .filter(|e| matches!(e, Event::MessageDelta { .. }))
            .count();
        assert!(n_deltas > 1, "expected multiple deltas, got {n_deltas}");
        // The whole assistant Message is STILL appended — deltas don't replace it.
        assert!(
            evs.iter().any(|e| matches!(
                e,
                Event::Message { message } if message.role == Role::Assistant
            )),
            "whole assistant Message still emitted: {evs:?}"
        );
        // Deltas precede the finalized assistant Message in the stream.
        let first_delta = evs
            .iter()
            .position(|e| matches!(e, Event::MessageDelta { .. }))
            .expect("a delta");
        let asst_msg = evs
            .iter()
            .position(
                |e| matches!(e, Event::Message { message } if message.role == Role::Assistant),
            )
            .expect("assistant message");
        assert!(
            first_delta < asst_msg,
            "deltas come before the whole message"
        );
    }

    #[tokio::test]
    async fn non_streaming_run_emits_no_deltas() {
        let (mut s, events) =
            session_with(vec![Ok(text_turn("no stream"))], Registry::new(), config());
        let _ = s.run_text("hi").await;
        let evs = dump(&events);
        assert!(
            !evs.iter().any(|e| matches!(e, Event::MessageDelta { .. })),
            "default (non-streaming) run must not emit deltas: {evs:?}"
        );
    }

    #[tokio::test]
    async fn streaming_and_non_streaming_reports_match() {
        let (mut a, _ea) = session_with(
            vec![Ok(text_turn("same result"))],
            Registry::new(),
            config(),
        );
        let mut cfg = config();
        cfg.streaming = true;
        let (mut b, _eb) = session_with(vec![Ok(text_turn("same result"))], Registry::new(), cfg);
        let ra = a.run_text("go").await;
        let rb = b.run_text("go").await;
        // Streaming is display-only: the Report is identical either way.
        assert_eq!(ra.status, rb.status);
        assert_eq!(ra.final_message, rb.final_message);
        assert_eq!(ra.turns, rb.turns);
        assert_eq!(ra.tool_calls.len(), rb.tool_calls.len());
    }

    #[tokio::test]
    async fn tool_call_then_complete() {
        let (mut s, _e) = session_with(
            vec![Ok(tool_turn("c1", "echo")), Ok(text_turn("done"))],
            echo_registry(),
            config(),
        );
        let report = s.run_text("go").await;
        assert_eq!(report.status, Status::Completed);
        assert_eq!(report.turns, 2);
        assert_eq!(report.tool_calls.len(), 1);
        assert!(report.tool_calls[0].ok);
        assert_eq!(report.tool_calls[0].name, "echo");
    }

    #[tokio::test]
    async fn hits_max_turns_after_dispatch() {
        // Always asks for a tool → never completes; ceiling of 2.
        let mut cfg = config();
        cfg.max_turns = Some(2);
        let (mut s, _e) = session_with(
            vec![
                Ok(tool_turn("c1", "echo")),
                Ok(tool_turn("c2", "echo")),
                Ok(tool_turn("c3", "echo")),
            ],
            echo_registry(),
            cfg,
        );
        let report = s.run_text("go").await;
        assert_eq!(report.status, Status::MaxTurns);
        assert_eq!(report.turns, 2);
        assert_eq!(report.tool_calls.len(), 2);
    }

    #[tokio::test]
    async fn model_error_after_bounded_retry() {
        // Retryable every time → 1 + resample_retries attempts, then ModelError.
        let script = vec![
            Err(ProviderError::Transport("reset".into())),
            Err(ProviderError::Transport("reset".into())),
            Err(ProviderError::Transport("reset".into())),
        ];
        let (mut s, events) = session_with(script, Registry::new(), config());
        let report = s.run_text("go").await;
        assert_eq!(report.status, Status::ModelError);
        assert!(report.error.is_some());
        assert_eq!(report.turns, 0);
        // Two non-terminal Error retry notes emitted (resample_retries == 2).
        let retries = dump(&events)
            .iter()
            .filter(|e| matches!(e, Event::Error { .. }))
            .count();
        assert_eq!(retries, 2);
    }

    #[tokio::test]
    async fn model_error_non_retryable_is_immediate() {
        let (mut s, events) = session_with(
            vec![Err(ProviderError::ContextOverflow)],
            Registry::new(),
            config(),
        );
        let report = s.run_text("go").await;
        assert_eq!(report.status, Status::ModelError);
        let retries = dump(&events)
            .iter()
            .filter(|e| matches!(e, Event::Error { .. }))
            .count();
        assert_eq!(retries, 0, "a non-retryable error must not resample");
    }

    #[tokio::test]
    async fn fatal_tool_error_ends_the_run() {
        let mut reg = Registry::new();
        reg.register("boom", Boom);
        let (mut s, _e) = session_with(vec![Ok(tool_turn("c1", "boom"))], reg, config());
        let report = s.run_text("go").await;
        assert_eq!(report.status, Status::Error);
        assert!(report.error.is_some());
        // The boom call still produced a paired (is_error) record.
        assert_eq!(report.tool_calls.len(), 1);
        assert!(!report.tool_calls[0].ok);
    }

    /// An empty completion (no text, no tool calls — e.g. a reasoning-only
    /// turn truncated by `max_output_tokens`) is resampled, not labeled
    /// Completed (ADR-0005 amendment 2026-07-19; grok's `is_empty` rule).
    #[tokio::test]
    async fn empty_completion_resamples_then_succeeds() {
        let empty = Completion {
            content: vec![ContentBlock::Reasoning {
                format: ReasoningFormat::Anthropic,
                text: "thinking only".into(),
                signature: Some("sig".into()),
                payload: None,
            }],
            usage: Usage::default(),
            stop: StopReason::MaxTokens,
        };
        let (mut session, _events) = session_with(
            vec![Ok(empty), Ok(text_turn("recovered"))],
            echo_registry(),
            config(),
        );
        let report = session.run_text("go").await;
        assert_eq!(report.status, Status::Completed);
        assert_eq!(report.final_message.as_deref(), Some("recovered"));
        assert_eq!(report.stop_reason.as_deref(), Some("end_turn"));
    }

    /// A `max_tokens` stop whose LAST block is a `tool_use` cut that call's
    /// arguments short. The Anthropic wire surfaces the loss as an empty
    /// `input`, so dispatching would report a missing required field and blame
    /// the model; the loop names the real cause instead and keeps going.
    /// Text typed mid-run rides the tool-result batch of the iteration that
    /// drains it — **after** the results, which the Responses wire's lowering
    /// makes load-bearing (ADR-0028).
    #[tokio::test]
    async fn queued_input_rides_the_tool_result_batch_after_the_results() {
        let (mut session, events) = session_with(
            vec![Ok(tool_turn("c1", "echo")), Ok(text_turn("done"))],
            echo_registry(),
            config(),
        );
        let queue = session.input_queue();
        queue.push("actually, use tabs");

        let report = session.run_text("go").await;
        assert_eq!(report.status, Status::Completed);

        let batch = dump(&events)
            .into_iter()
            .find_map(|e| match e {
                Event::Message { message }
                    if message.role == Role::User
                        && message
                            .content
                            .iter()
                            .any(|b| matches!(b, ContentBlock::ToolResult { .. })) =>
                {
                    Some(message)
                }
                _ => None,
            })
            .expect("a tool-result batch was appended");

        let kinds: Vec<&str> = batch
            .content
            .iter()
            .map(|b| match b {
                ContentBlock::ToolResult { .. } => "result",
                ContentBlock::Text { .. } => "text",
                _ => "other",
            })
            .collect();
        assert_eq!(
            kinds,
            vec!["result", "text"],
            "the queued text must follow the results, never precede them"
        );

        let text = batch
            .content
            .iter()
            .find_map(|b| match b {
                ContentBlock::Text { text } => Some(text.clone()),
                _ => None,
            })
            .expect("the queued text landed");
        assert!(
            text.starts_with(crate::MID_RUN_PREAMBLE),
            "the mid-run path is marked: {text}"
        );
        assert!(text.contains("actually, use tabs"));
        assert!(queue.is_empty(), "draining consumes");
    }

    /// A run whose turn emits no tool calls has no batch to carry the text, so
    /// the item stays queued for the frontend's next-prompt fallback.
    #[tokio::test]
    async fn queued_input_with_no_tool_calls_stays_for_the_fallback() {
        let (mut session, _events) = session_with(
            vec![Ok(text_turn("nothing to do"))],
            echo_registry(),
            config(),
        );
        let queue = session.input_queue();
        queue.push("one more thing");

        let report = session.run_text("go").await;
        assert_eq!(report.status, Status::Completed);
        assert_eq!(
            queue.pending(),
            vec!["one more thing".to_string()],
            "no carrier this run — the frontend submits it as an ordinary prompt"
        );
    }

    #[tokio::test]
    async fn truncated_tool_call_is_not_executed_and_names_the_cause() {
        let truncated = Completion {
            content: vec![ContentBlock::ToolUse {
                id: "c1".into(),
                name: "echo".into(),
                input: json!({}), // what the wire returns for a cut-off call
            }],
            usage: Usage::default(),
            stop: StopReason::MaxTokens,
        };
        let (mut session, events) = session_with(
            vec![Ok(truncated), Ok(text_turn("smaller this time"))],
            echo_registry(),
            config(),
        );
        let report = session.run_text("write a huge file").await;

        // Soft: the model gets the error and the loop continues (ADR-0004).
        assert_eq!(report.status, Status::Completed);
        assert_eq!(report.final_message.as_deref(), Some("smaller this time"));
        assert!(
            report.tool_calls.is_empty(),
            "a call that never ran is not recorded, matching the cancel path"
        );

        let explained = dump(&events).iter().any(|e| match e {
            Event::Message { message } => message.content.iter().any(|b| {
                matches!(
                    b,
                    ContentBlock::ToolResult { tool_use_id, is_error: true, content, .. }
                        if tool_use_id == "c1"
                            && content.iter().any(|c| matches!(
                                c,
                                locode_protocol::ResultChunk::Text { text }
                                    if text.contains("output-token limit")
                                        && text.contains("max_tokens")
                                        && text.contains("Do not repeat the call unchanged")
                            ))
                )
            }),
            _ => false,
        });
        assert!(
            explained,
            "the model must see the truncation, not a 'missing field' decode error"
        );
    }

    /// The guard keys off the last **content block**, not the stop reason
    /// alone: a `tool_use` the model finished before the cut still runs, so
    /// truncation of a trailing text block never swallows a valid call.
    #[tokio::test]
    async fn truncation_after_a_finished_tool_call_still_dispatches() {
        let cut_after_call = Completion {
            content: vec![
                ContentBlock::ToolUse {
                    id: "c1".into(),
                    name: "echo".into(),
                    input: json!({"complete": true}),
                },
                ContentBlock::Text {
                    text: "and then I was cut off mid-sent".into(),
                },
            ],
            usage: Usage::default(),
            stop: StopReason::MaxTokens,
        };
        let (mut session, _events) = session_with(
            vec![Ok(cut_after_call), Ok(text_turn("done"))],
            echo_registry(),
            config(),
        );
        let report = session.run_text("go").await;

        assert_eq!(report.status, Status::Completed);
        assert_eq!(report.tool_calls.len(), 1, "the finished call still ran");
        assert!(report.tool_calls[0].ok);
    }

    #[tokio::test]
    async fn persistent_empty_completions_are_model_error() {
        let empty = || Completion {
            content: vec![],
            usage: Usage::default(),
            stop: StopReason::MaxTokens,
        };
        // resample_retries = 2 → initial + 2 resamples, all empty → ModelError.
        let (mut session, _events) = session_with(
            vec![Ok(empty()), Ok(empty()), Ok(empty())],
            echo_registry(),
            config(),
        );
        let report = session.run_text("go").await;
        assert_eq!(report.status, Status::ModelError);
        assert!(
            report
                .error
                .as_deref()
                .unwrap_or("")
                .contains("empty completion"),
            "error names the cause: {:?}",
            report.error
        );
        assert_eq!(report.stop_reason, None, "no completion was accepted");
    }

    // ---- transcript hygiene ----

    #[tokio::test]
    async fn mid_batch_abort_synthesizes_results() {
        // One assistant turn asks for TWO tools: boom (Fatal) then echo. echo must
        // not run, yet both tool_use ids must be answered in the transcript.
        let mut reg = Registry::new();
        reg.register("boom", Boom);
        reg.register("echo", Echo);
        let completion = Completion {
            content: vec![
                ContentBlock::ToolUse {
                    id: "c_boom".into(),
                    name: "boom".into(),
                    input: json!({}),
                },
                ContentBlock::ToolUse {
                    id: "c_echo".into(),
                    name: "echo".into(),
                    input: json!({}),
                },
            ],
            usage: Usage::default(),
            stop: StopReason::ToolUse,
        };
        let (mut s, events) = session_with(vec![Ok(completion)], reg, config());
        let report = s.run_text("go").await;
        assert_eq!(report.status, Status::Error);

        // The appended tool-result message pairs BOTH ids.
        let evs = dump(&events);
        let answered: Vec<String> = evs
            .iter()
            .filter_map(|e| match e {
                Event::Message { message } if message.role == Role::User => Some(&message.content),
                _ => None,
            })
            .flatten()
            .filter_map(|b| match b {
                ContentBlock::ToolResult { tool_use_id, .. } => Some(tool_use_id.clone()),
                _ => None,
            })
            .collect();
        assert!(answered.iter().any(|id| id == "c_boom"));
        assert!(
            answered.iter().any(|id| id == "c_echo"),
            "the un-run echo must be paired"
        );
        // boom recorded (ran, fatal); echo NOT recorded (never executed).
        assert_eq!(report.tool_calls.len(), 1);
    }

    // ---- replay + stream fidelity ----

    #[tokio::test]
    async fn thinking_block_is_appended_verbatim() {
        let completion = Completion {
            content: vec![
                ContentBlock::Reasoning {
                    format: ReasoningFormat::Anthropic,
                    text: "reasoning".into(),
                    signature: Some("sig-xyz".into()),
                    payload: None,
                },
                ContentBlock::Text {
                    text: "answer".into(),
                },
            ],
            usage: Usage::default(),
            stop: StopReason::EndTurn,
        };
        let (mut s, events) = session_with(vec![Ok(completion)], Registry::new(), config());
        let report = s.run_text("think").await;
        assert_eq!(report.status, Status::Completed);
        assert_eq!(report.final_message.as_deref(), Some("answer"));
        // The emitted assistant message preserves the Thinking block + signature.
        let has_thinking = dump(&events).iter().any(|e| match e {
            Event::Message { message } if message.role == Role::Assistant => {
                message.content.iter().any(|b| {
                    matches!(
                        b,
                        ContentBlock::Reasoning { signature: Some(sig), .. } if sig == "sig-xyz"
                    )
                })
            }
            _ => false,
        });
        assert!(
            has_thinking,
            "thinking + signature must survive into history"
        );
    }

    #[tokio::test]
    async fn events_reconstruct_the_history() {
        let (mut s, events) = session_with(
            vec![Ok(tool_turn("c1", "echo")), Ok(text_turn("done"))],
            echo_registry(),
            config(),
        );
        let _ = s.run_text("go").await;
        let rebuilt: Conversation = reconstruct_conversation(&dump(&events));
        // user + assistant(tool_use) + user(tool_result) + assistant(text).
        let roles: Vec<Role> = rebuilt.messages.iter().map(|m| m.role).collect();
        assert_eq!(
            roles,
            vec![Role::User, Role::Assistant, Role::User, Role::Assistant]
        );
    }

    // ---- the approval seam (ADR-0017) ----

    use std::sync::atomic::{AtomicUsize, Ordering};

    /// A tool that counts its executions — proves a denied call never ran.
    struct Counting(Arc<AtomicUsize>);
    #[async_trait]
    impl Tool for Counting {
        type Args = Value;
        type Output = EchoOut;
        fn kind(&self) -> ToolKind {
            ToolKind::Shell
        }
        fn description(&self) -> &str {
            "counting"
        }
        async fn run(&self, _ctx: &ToolCtx, _args: Value) -> Result<EchoOut, ToolError> {
            self.0.fetch_add(1, Ordering::SeqCst);
            Ok(EchoOut {
                echoed: "ran".into(),
            })
        }
    }

    type SeenKinds = Arc<Mutex<Vec<(String, Option<ToolKind>)>>>;

    /// Denies tools whose name is in the list; allows everything else. Records
    /// the `kind` seen on each request so tests can assert it is populated.
    struct DenyNamed {
        deny: Vec<&'static str>,
        seen_kinds: SeenKinds,
    }
    #[async_trait]
    impl Approver for DenyNamed {
        async fn decide(&self, request: &ApprovalRequest<'_>) -> Decision {
            self.seen_kinds
                .lock()
                .unwrap()
                .push((request.tool_name.to_owned(), request.kind));
            if self.deny.contains(&request.tool_name) {
                Decision::Deny {
                    reason: format!("{} is not allowed here", request.tool_name),
                }
            } else {
                Decision::Allow
            }
        }
    }

    fn approvals(events: &Arc<Mutex<Vec<Event>>>) -> Vec<(String, String, String)> {
        dump(events)
            .iter()
            .filter_map(|e| match e {
                Event::Approval {
                    tool_use_id,
                    tool_name,
                    decision,
                    ..
                } => Some((tool_use_id.clone(), tool_name.clone(), decision.clone())),
                _ => None,
            })
            .collect()
    }

    #[tokio::test]
    async fn deny_is_a_soft_paired_error_and_the_run_continues() {
        let ran = Arc::new(AtomicUsize::new(0));
        let mut reg = Registry::new();
        reg.register("counting", Counting(Arc::clone(&ran)));
        let (s, events) = session_with(
            vec![Ok(tool_turn("c1", "counting")), Ok(text_turn("done"))],
            reg,
            config(),
        );
        let seen = Arc::new(Mutex::new(Vec::new()));
        let mut s = s.with_approver(Arc::new(DenyNamed {
            deny: vec!["counting"],
            seen_kinds: Arc::clone(&seen),
        }));
        let report = s.run_text("go").await;

        // Soft: the run continued to Completed; the tool never executed.
        assert_eq!(report.status, Status::Completed);
        assert_eq!(ran.load(Ordering::SeqCst), 0, "denied tool must not run");

        // The record: ok=false, denial_reason set (and only here), no output.
        assert_eq!(report.tool_calls.len(), 1);
        let record = &report.tool_calls[0];
        assert!(!record.ok);
        assert_eq!(
            record.denial_reason.as_deref(),
            Some("counting is not allowed here")
        );
        assert_eq!(record.kind, "shell", "kind still recorded on denial");

        // The transcript: a paired is_error result carrying the reason.
        let denied_result = dump(&events).iter().any(|e| match e {
            Event::Message { message } => message.content.iter().any(|b| {
                matches!(
                    b,
                    ContentBlock::ToolResult { tool_use_id, is_error: true, content, .. }
                        if tool_use_id == "c1"
                            && content.iter().any(|c| matches!(
                                c,
                                locode_protocol::ResultChunk::Text { text }
                                    if text == "tool call denied: counting is not allowed here"
                            ))
                )
            }),
            _ => false,
        });
        assert!(denied_result, "the model sees the denial reason, paired");

        // The trace: a deny Approval event for c1.
        assert_eq!(
            approvals(&events),
            vec![("c1".into(), "counting".into(), "deny".into())]
        );
    }

    #[tokio::test]
    async fn deny_then_allow_within_one_batch_keeps_order_and_pairing() {
        let ran = Arc::new(AtomicUsize::new(0));
        let mut reg = Registry::new();
        reg.register("blocked", Counting(Arc::clone(&ran)));
        reg.register("echo", Echo);
        let batch = Completion {
            content: vec![
                ContentBlock::ToolUse {
                    id: "c1".into(),
                    name: "blocked".into(),
                    input: json!({}),
                },
                ContentBlock::ToolUse {
                    id: "c2".into(),
                    name: "echo".into(),
                    input: json!({}),
                },
            ],
            usage: Usage::default(),
            stop: StopReason::ToolUse,
        };
        let (s, events) = session_with(vec![Ok(batch), Ok(text_turn("done"))], reg, config());
        let mut s = s.with_approver(Arc::new(DenyNamed {
            deny: vec!["blocked"],
            seen_kinds: Arc::new(Mutex::new(Vec::new())),
        }));
        let report = s.run_text("go").await;
        assert_eq!(report.status, Status::Completed);
        assert_eq!(ran.load(Ordering::SeqCst), 0);

        // Both calls answered, in call order, denied first.
        let pairs: Vec<(String, bool)> = dump(&events)
            .iter()
            .filter_map(|e| match e {
                Event::Message { message } if message.role == Role::User => Some(&message.content),
                _ => None,
            })
            .flatten()
            .filter_map(|b| match b {
                ContentBlock::ToolResult {
                    tool_use_id,
                    is_error,
                    ..
                } => Some((tool_use_id.clone(), *is_error)),
                _ => None,
            })
            .collect();
        assert_eq!(pairs, vec![("c1".into(), true), ("c2".into(), false)]);

        // Records: denied (with reason) then executed (without).
        assert_eq!(report.tool_calls.len(), 2);
        assert!(report.tool_calls[0].denial_reason.is_some());
        assert_eq!(report.tool_calls[0].kind, "shell");
        assert!(report.tool_calls[1].ok);
        assert_eq!(report.tool_calls[1].denial_reason, None);

        // Approval trace: deny then allow, in order.
        assert_eq!(
            approvals(&events),
            vec![
                ("c1".into(), "blocked".into(), "deny".into()),
                ("c2".into(), "echo".into(), "allow".into()),
            ]
        );
    }

    #[tokio::test]
    async fn approval_request_carries_the_registry_kind() {
        let seen = Arc::new(Mutex::new(Vec::new()));
        let (s, _e) = session_with(
            vec![Ok(tool_turn("c1", "echo")), Ok(text_turn("done"))],
            echo_registry(),
            config(),
        );
        let mut s = s.with_approver(Arc::new(DenyNamed {
            deny: vec![],
            seen_kinds: Arc::clone(&seen),
        }));
        let _ = s.run_text("go").await;
        let seen = seen.lock().unwrap();
        assert_eq!(seen.len(), 1);
        assert_eq!(seen[0].0, "echo");
        assert_eq!(
            seen[0].1,
            Some(ToolKind::Shell),
            "kind resolves from the registry pre-dispatch"
        );
    }

    /// An approver that suspends on a oneshot until an external task resolves
    /// it — the exact shape of a TUI prompt. Proves the engine awaits the
    /// decision without deadlocking the run.
    #[tokio::test]
    async fn async_approver_suspends_the_call_until_resolved() {
        struct OneshotApprover(Mutex<Option<tokio::sync::oneshot::Receiver<Decision>>>);
        #[async_trait]
        impl Approver for OneshotApprover {
            async fn decide(&self, _request: &ApprovalRequest<'_>) -> Decision {
                let rx = self.0.lock().unwrap().take().expect("one decision");
                rx.await.expect("decider dropped")
            }
        }

        let (tx, rx) = tokio::sync::oneshot::channel();
        let (s, _e) = session_with(
            vec![Ok(tool_turn("c1", "echo")), Ok(text_turn("done"))],
            echo_registry(),
            config(),
        );
        let mut s = s.with_approver(Arc::new(OneshotApprover(Mutex::new(Some(rx)))));

        // Resolve the prompt from "the UI" after the run has started.
        let ui = tokio::spawn(async move {
            tokio::task::yield_now().await;
            let _ = tx.send(Decision::Allow);
        });
        let report = s.run_text("go").await;
        ui.await.expect("ui task");
        assert_eq!(report.status, Status::Completed);
        assert_eq!(report.tool_calls.len(), 1);
        assert!(report.tool_calls[0].ok);
    }

    #[tokio::test]
    async fn allowed_calls_emit_approval_events_by_default() {
        // The default AllowAll approver still journals every resolution.
        let (mut s, events) = session_with(
            vec![Ok(tool_turn("c1", "echo")), Ok(text_turn("done"))],
            echo_registry(),
            config(),
        );
        let report = s.run_text("go").await;
        assert_eq!(report.status, Status::Completed);
        assert_eq!(
            approvals(&events),
            vec![("c1".into(), "echo".into(), "allow".into())]
        );
        // And denial_reason is absent on ordinary success records.
        assert_eq!(report.tool_calls[0].denial_reason, None);
    }

    // ---- cancellation (ADR-0018) ----

    /// A provider that streams part of a reply and *then* fails retryably — the
    /// shape a lossy stream has (ADR-0007 amendment 2026-07-27). The first
    /// attempt half-streams, the second succeeds.
    struct HalfStreamsThenFails {
        attempts: std::sync::atomic::AtomicU32,
    }
    #[async_trait]
    impl Provider for HalfStreamsThenFails {
        #[allow(clippy::unnecessary_literal_bound)]
        fn api_schema(&self) -> &str {
            "mock"
        }
        async fn complete(
            &self,
            _request: &ConversationRequest,
        ) -> Result<Completion, ProviderError> {
            unreachable!("this test runs streaming")
        }
        async fn stream(
            &self,
            _request: &ConversationRequest,
            on_delta: &mut (dyn FnMut(locode_provider::CompletionDelta) + Send),
        ) -> Result<Completion, ProviderError> {
            let n = self
                .attempts
                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            if n == 0 {
                on_delta(locode_provider::CompletionDelta::Text("Hel".into()));
                on_delta(locode_provider::CompletionDelta::Text("lo wor".into()));
                return Err(ProviderError::Transport("lossy stream".into()));
            }
            on_delta(locode_provider::CompletionDelta::Text("Hello world".into()));
            Ok(Completion {
                content: vec![ContentBlock::Text {
                    text: "Hello world".into(),
                }],
                usage: Usage::default(),
                stop: locode_provider::StopReason::EndTurn,
            })
        }
    }

    /// A stream that dies part-way is resampled from the start, so the deltas it
    /// already emitted are void. The engine must say so — otherwise a consumer
    /// buffering them renders the reply twice. Emitted only when something was
    /// actually streamed: a failure before the first delta has nothing to annul.
    #[tokio::test]
    async fn a_partial_stream_that_resamples_annuls_its_deltas() {
        let mut cfg = config();
        cfg.streaming = true;
        let provider = std::sync::Arc::new(HalfStreamsThenFails {
            attempts: std::sync::atomic::AtomicU32::new(0),
        });
        let events = Arc::new(Mutex::new(Vec::new()));
        let sink_events = Arc::clone(&events);
        let sink = Box::new(FnSink(move |event| {
            sink_events.lock().unwrap().push(event);
        }));
        let mut session = Session::new(provider, Registry::new(), vec![], cfg, sink);
        let report = session.run_text("go").await;
        assert_eq!(report.status, Status::Completed, "the retry succeeded");

        let evs = dump(&events);
        let resets = evs
            .iter()
            .filter(|e| matches!(e, Event::MessageDeltaReset { .. }))
            .count();
        assert_eq!(resets, 1, "exactly one annulment, for the failed attempt");

        // Order matters: the annulment must precede the retry's deltas, or a
        // consumer clears the buffer *after* refilling it.
        let reset_at = evs
            .iter()
            .position(|e| matches!(e, Event::MessageDeltaReset { .. }))
            .expect("reset emitted");
        let last_delta = evs
            .iter()
            .rposition(|e| matches!(e, Event::MessageDelta { .. }))
            .expect("the retry streamed");
        assert!(
            reset_at < last_delta,
            "reset must come before the re-stream"
        );
    }

    /// A provider whose sample never returns on its own — cancellation is the
    /// only way out (models a long in-flight request).
    struct HangingProvider;
    #[async_trait]
    impl Provider for HangingProvider {
        #[allow(clippy::unnecessary_literal_bound)]
        fn api_schema(&self) -> &str {
            "mock"
        }
        async fn complete(
            &self,
            _request: &ConversationRequest,
        ) -> Result<Completion, ProviderError> {
            tokio::time::sleep(Duration::from_hours(1)).await;
            Err(ProviderError::Transport("unreachable".into()))
        }
    }

    /// A tool that parks on its ctx cancel token and returns cleanly once it
    /// fires — the cooperative-cancel shape the host implements for real.
    struct WaitsForCancel;
    #[async_trait]
    impl Tool for WaitsForCancel {
        type Args = Value;
        type Output = EchoOut;
        fn kind(&self) -> ToolKind {
            ToolKind::Shell
        }
        fn description(&self) -> &str {
            "waits"
        }
        async fn run(&self, ctx: &ToolCtx, _args: Value) -> Result<EchoOut, ToolError> {
            ctx.cancel.cancelled().await;
            Ok(EchoOut {
                echoed: "stopped cooperatively".into(),
            })
        }
    }

    #[tokio::test]
    async fn cancel_mid_sample_yields_cancelled_report() {
        let events = Arc::new(Mutex::new(Vec::new()));
        let sink_events = Arc::clone(&events);
        let sink = Box::new(FnSink(move |event| {
            sink_events.lock().unwrap().push(event);
        }));
        let mut s = Session::new(
            Arc::new(HangingProvider),
            Registry::new(),
            vec![],
            config(),
            sink,
        );
        let handle = s.cancel_handle();
        let canceller = tokio::spawn(async move {
            tokio::time::sleep(Duration::from_millis(20)).await;
            handle.cancel();
            handle.cancel(); // idempotent double-cancel
        });
        let report = s.run_text("go").await;
        canceller.await.expect("canceller");

        assert_eq!(report.status, Status::Cancelled);
        assert_eq!(report.error, None, "cancelled is a stop, not a fault");
        assert_eq!(report.final_message, None, "no assistant text this run");
        assert_eq!(report.turns, 0, "no completion was accepted");
        // No assistant message was appended: history is user-prompt only.
        let roles: Vec<Role> = s.history().iter().map(|m| m.role).collect();
        assert_eq!(roles, vec![Role::User]);
        // The stream still terminates in a Result carrying the same report.
        let evs = dump(&events);
        assert!(
            matches!(evs.last(), Some(Event::Result { report }) if report.status == Status::Cancelled)
        );
    }

    #[tokio::test]
    async fn cancel_mid_batch_pairs_the_rest_synthetically() {
        // One turn asks for TWO tools: a cooperative waiter, then echo. The
        // cancel fires while the waiter runs → its own result is real; echo is
        // never run (no approval consult, no record) but still paired.
        let mut reg = Registry::new();
        reg.register("waits", WaitsForCancel);
        reg.register("echo", Echo);
        let batch = Completion {
            content: vec![
                ContentBlock::ToolUse {
                    id: "c_wait".into(),
                    name: "waits".into(),
                    input: json!({}),
                },
                ContentBlock::ToolUse {
                    id: "c_echo".into(),
                    name: "echo".into(),
                    input: json!({}),
                },
            ],
            usage: Usage::default(),
            stop: StopReason::ToolUse,
        };
        let (s, events) = session_with(vec![Ok(batch)], reg, config());
        let mut s = s; // provider script has ONE turn: cancel must end the run
        let handle = s.cancel_handle();
        let canceller = tokio::spawn(async move {
            tokio::time::sleep(Duration::from_millis(20)).await;
            handle.cancel();
        });
        let report = s.run_text("go").await;
        canceller.await.expect("canceller");

        assert_eq!(report.status, Status::Cancelled);
        // The waiter executed (cooperatively) and is the only record; no
        // cancellation synthetic ever carries denial_reason.
        assert_eq!(report.tool_calls.len(), 1);
        assert_eq!(report.tool_calls[0].id, "c_wait");
        assert!(report.tool_calls[0].ok);
        assert_eq!(report.tool_calls[0].denial_reason, None);

        // Both tool_use ids are answered: real result + cancellation synthetic.
        let pairs: Vec<(String, bool)> = dump(&events)
            .iter()
            .filter_map(|e| match e {
                Event::Message { message } if message.role == Role::User => Some(&message.content),
                _ => None,
            })
            .flatten()
            .filter_map(|b| match b {
                ContentBlock::ToolResult {
                    tool_use_id,
                    is_error,
                    ..
                } => Some((tool_use_id.clone(), *is_error)),
                _ => None,
            })
            .collect();
        assert_eq!(
            pairs,
            vec![("c_wait".into(), false), ("c_echo".into(), true)]
        );
        // Only the executed call was consulted for approval.
        assert_eq!(
            approvals(&events),
            vec![("c_wait".into(), "waits".into(), "allow".into())]
        );
    }

    /// The token is per-run (ADR-0018 Decision 1): a cancelled run 1 must not
    /// poison run 2, and run 2 continues the same conversation (with ADR-0016).
    #[tokio::test]
    async fn cancelled_session_continues_on_the_next_run_with_a_fresh_token() {
        let mut reg = Registry::new();
        reg.register("waits", WaitsForCancel);
        let (s, _e) = session_with(
            vec![Ok(tool_turn("c1", "waits")), Ok(text_turn("second run"))],
            reg,
            config(),
        );
        let mut s = s;
        let handle1 = s.cancel_handle();
        let canceller = tokio::spawn(async move {
            tokio::time::sleep(Duration::from_millis(20)).await;
            handle1.cancel();
        });
        let r1 = s.run_text("q1").await;
        canceller.await.expect("canceller");
        assert_eq!(r1.status, Status::Cancelled);

        // The retired handle stays cancelled, but the session got a fresh
        // token at run end — run 2 must not see the old cancel.
        assert!(!s.cancel_handle().is_cancelled());
        let r2 = s.run_text("q2").await;
        assert_eq!(r2.status, Status::Completed);
        assert_eq!(r2.final_message.as_deref(), Some("second run"));
        // Continuity intact: q1's turns are still in the history.
        assert!(s.history().len() >= 4, "history: {:?}", s.history().len());
    }

    // ---- session continuity (ADR-0016) ----

    /// A scripted provider that also records each request's message array, so a
    /// test can assert what the model actually saw on a follow-up run.
    struct CapturingProvider {
        inner: MockProvider,
        requests: Arc<Mutex<Vec<Vec<Message>>>>,
    }
    #[async_trait]
    impl Provider for CapturingProvider {
        #[allow(clippy::unnecessary_literal_bound)]
        fn api_schema(&self) -> &str {
            "mock"
        }
        async fn complete(
            &self,
            request: &ConversationRequest,
        ) -> Result<Completion, ProviderError> {
            self.requests.lock().unwrap().push(request.messages.clone());
            self.inner.complete(request).await
        }
    }

    /// Like `session_with`, but the provider records every request's messages.
    #[allow(clippy::type_complexity)]
    fn capturing_session_with(
        script: Vec<Result<Completion, ProviderError>>,
        registry: Registry,
    ) -> (
        Session,
        Arc<Mutex<Vec<Vec<Message>>>>,
        Arc<Mutex<Vec<Event>>>,
    ) {
        let requests = Arc::new(Mutex::new(Vec::new()));
        let events = Arc::new(Mutex::new(Vec::new()));
        let sink_events = Arc::clone(&events);
        let sink = Box::new(FnSink(move |event| {
            sink_events.lock().unwrap().push(event);
        }));
        let provider = Arc::new(CapturingProvider {
            inner: MockProvider::with_results(script),
            requests: Arc::clone(&requests),
        });
        let session = Session::new(provider, registry, vec![], config(), sink);
        (session, requests, events)
    }

    fn user_text(message: &Message) -> Option<&str> {
        match (message.role, message.content.as_slice()) {
            (Role::User, [ContentBlock::Text { text }]) => Some(text.as_str()),
            _ => None,
        }
    }

    #[tokio::test]
    async fn second_run_continues_the_conversation() {
        let (mut s, requests, _e) = capturing_session_with(
            vec![
                Ok(text_turn("first answer")),
                Ok(text_turn("second answer")),
            ],
            Registry::new(),
        );
        let r1 = s.run_text("q1").await;
        let r2 = s.run_text("q2").await;
        assert_eq!(r1.status, Status::Completed);
        assert_eq!(r2.status, Status::Completed);
        assert_eq!(r2.final_message.as_deref(), Some("second answer"));

        // Run 2's request contains run 1's full exchange, then the new prompt.
        let reqs = requests.lock().unwrap();
        assert_eq!(reqs.len(), 2);
        let run2 = &reqs[1];
        assert_eq!(run2.len(), 3, "user q1, assistant, user q2: {run2:?}");
        assert_eq!(user_text(&run2[0]), Some("q1"));
        assert_eq!(run2[1].role, Role::Assistant);
        assert_eq!(user_text(&run2[2]), Some("q2"));

        // The public accessor exposes the same transcript (empty test preamble).
        let roles: Vec<Role> = s.history().iter().map(|m| m.role).collect();
        assert_eq!(
            roles,
            vec![Role::User, Role::Assistant, Role::User, Role::Assistant]
        );
    }

    // ---- project-instruction injection (ADR-0023, Task 30) ----

    /// A capturing session over a custom config (for the injection path).
    fn capturing_with_cfg(
        script: Vec<Result<Completion, ProviderError>>,
        cfg: EngineConfig,
    ) -> (Session, Arc<Mutex<Vec<Vec<Message>>>>) {
        let requests = Arc::new(Mutex::new(Vec::new()));
        let provider = Arc::new(CapturingProvider {
            inner: MockProvider::with_results(script),
            requests: Arc::clone(&requests),
        });
        let session = Session::new(provider, Registry::new(), vec![], cfg, Box::new(NullSink));
        (session, requests)
    }

    /// A config with project instructions **enabled**, rooted at `cwd`, global file off
    /// (never read the real `~/.locode` in tests).
    fn instr_config(cwd: std::path::PathBuf) -> EngineConfig {
        EngineConfig {
            cwd,
            instructions: locode_instructions::InstructionsConfig {
                global_file: false,
                ..Default::default()
            },
            ..config()
        }
    }

    /// The injected `<system-reminder>` text within a request's messages, if present.
    fn reminder_text(msgs: &[Message]) -> Option<String> {
        msgs.iter()
            .find_map(|m| match (m.role, m.content.as_slice()) {
                (Role::User, [ContentBlock::Text { text }])
                    if text.starts_with("<system-reminder>") =>
                {
                    Some(text.clone())
                }
                _ => None,
            })
    }

    fn reminder_count(msgs: &[Message]) -> usize {
        msgs.iter()
            .filter(|m| {
                matches!(
                    (m.role, m.content.as_slice()),
                    (Role::User, [ContentBlock::Text { text }]) if text.starts_with("<system-reminder>")
                )
            })
            .count()
    }

    #[tokio::test]
    async fn project_instructions_injected_once_before_prompt() {
        let dir = tempfile::tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();
        std::fs::create_dir(root.join(".git")).unwrap();
        std::fs::write(root.join("AGENTS.md"), "be terse").unwrap();

        let (mut s, requests) = capturing_with_cfg(
            vec![Ok(text_turn("ok1")), Ok(text_turn("ok2"))],
            instr_config(root),
        );
        s.run_text("q1").await;
        s.run_text("q2").await;

        let reqs = requests.lock().unwrap();
        // Run 1: injected, with the file content, positioned before the user prompt.
        let run1 = &reqs[0];
        let rem = reminder_text(run1).expect("instructions injected on run 1");
        assert!(rem.contains("## From:"), "labeled: {rem}");
        assert!(rem.contains("be terse"), "content present: {rem}");
        let rem_idx = run1
            .iter()
            .position(|m| reminder_text(std::slice::from_ref(m)).is_some());
        let q1_idx = run1.iter().position(|m| user_text(m) == Some("q1"));
        assert!(rem_idx < q1_idx, "reminder comes before the prompt");

        // Run 2: NOT re-injected — still exactly the one from run 1 (once per session).
        assert_eq!(reminder_count(&reqs[1]), 1, "not re-injected on run 2");
    }

    /// A session whose transcript is `replayed` — what resume does (the recovered
    /// history becomes the preamble).
    fn resumed_with_cfg(
        script: Vec<Result<Completion, ProviderError>>,
        cfg: EngineConfig,
        replayed: Vec<Message>,
    ) -> (Session, Arc<Mutex<Vec<Vec<Message>>>>) {
        let requests = Arc::new(Mutex::new(Vec::new()));
        let provider = Arc::new(CapturingProvider {
            inner: MockProvider::with_results(script),
            requests: Arc::clone(&requests),
        });
        let session = Session::new(provider, Registry::new(), replayed, cfg, Box::new(NullSink));
        (session, requests)
    }

    /// ADR-0023's Refresh rule says instructions are "never double-injected on
    /// fork/resume". A remembered hash cannot deliver that — a resumed session starts
    /// with the field empty and re-sends instructions the replayed transcript already
    /// carries. The check reads the conversation instead.
    #[tokio::test]
    async fn resuming_does_not_re_inject_unchanged_instructions() {
        let dir = tempfile::tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();
        std::fs::create_dir(root.join(".git")).unwrap();
        std::fs::write(root.join("AGENTS.md"), "be terse").unwrap();

        let (mut first, requests) =
            capturing_with_cfg(vec![Ok(text_turn("ok"))], instr_config(root.clone()));
        first.run_text("q1").await;
        let replayed = requests.lock().unwrap()[0].clone();
        assert_eq!(reminder_count(&replayed), 1, "precondition: injected once");

        let (mut resumed, resumed_requests) =
            resumed_with_cfg(vec![Ok(text_turn("ok2"))], instr_config(root), replayed);
        resumed.run_text("q2").await;
        let reqs = resumed_requests.lock().unwrap();
        assert_eq!(
            reminder_count(&reqs[0]),
            1,
            "still the one from before the resume, not a second copy: {:#?}",
            reqs[0]
        );
    }

    /// …but an `AGENTS.md` edited between sessions *is* re-injected, with the replace
    /// banner that says the earlier copy no longer applies.
    #[tokio::test]
    async fn resuming_re_injects_instructions_that_changed_while_away() {
        let dir = tempfile::tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();
        std::fs::create_dir(root.join(".git")).unwrap();
        std::fs::write(root.join("AGENTS.md"), "be terse").unwrap();

        let (mut first, requests) =
            capturing_with_cfg(vec![Ok(text_turn("ok"))], instr_config(root.clone()));
        first.run_text("q1").await;
        let replayed = requests.lock().unwrap()[0].clone();

        std::fs::write(root.join("AGENTS.md"), "be verbose").unwrap();
        let (mut resumed, resumed_requests) =
            resumed_with_cfg(vec![Ok(text_turn("ok2"))], instr_config(root), replayed);
        resumed.run_text("q2").await;
        let reqs = resumed_requests.lock().unwrap();
        assert_eq!(reminder_count(&reqs[0]), 2, "the new body joins the old");
        let latest = reqs[0]
            .iter()
            .rev()
            .find_map(|m| reminder_text(std::slice::from_ref(m)))
            .expect("a reminder");
        assert!(latest.contains("be verbose"), "{latest}");
        assert!(
            latest.contains("replace all previously provided"),
            "banner present: {latest}"
        );
    }

    /// The other half of ADR-0023's Refresh rule: instructions dropped from the
    /// conversation come back. A remembered hash would keep saying "already sent".
    #[tokio::test]
    async fn instructions_dropped_from_the_transcript_are_re_injected() {
        let dir = tempfile::tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();
        std::fs::create_dir(root.join(".git")).unwrap();
        std::fs::write(root.join("AGENTS.md"), "be terse").unwrap();

        let (mut first, requests) =
            capturing_with_cfg(vec![Ok(text_turn("ok"))], instr_config(root.clone()));
        first.run_text("q1").await;
        // Compaction: keep the conversation, drop the reminder.
        let compacted: Vec<Message> = requests.lock().unwrap()[0]
            .iter()
            .filter(|m| reminder_text(std::slice::from_ref(m)).is_none())
            .cloned()
            .collect();

        let (mut after, after_requests) =
            resumed_with_cfg(vec![Ok(text_turn("ok2"))], instr_config(root), compacted);
        after.run_text("q2").await;
        assert_eq!(
            reminder_count(&after_requests.lock().unwrap()[0]),
            1,
            "re-injected after being compacted away"
        );
    }

    /// A skills config rooted at `cwd` that never reads the real `~/.locode`
    /// (`discover` resolves the home root itself, so the temp repo is the only source
    /// as long as no skill exists in the developer's home — the project root is what
    /// this asserts on).
    fn skills_config(cwd: std::path::PathBuf) -> EngineConfig {
        EngineConfig {
            cwd: cwd.clone(),
            skills: locode_skills::SkillsConfig::enabled(),
            ..instr_config(cwd)
        }
    }

    fn write_skill(root: &std::path::Path, name: &str, description: &str) {
        let dir = root.join(".agents/skills").join(name);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join("SKILL.md"),
            format!("---\nname: {name}\ndescription: {description}\n---\n# {name}\n"),
        )
        .unwrap();
    }

    /// Injected once, before the prompt; and a second turn with no change sends nothing
    /// new — the whole-body comparison is what makes the steady state quiet.
    #[tokio::test]
    async fn skills_listing_injected_once_then_quiet() {
        let dir = tempfile::tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();
        std::fs::create_dir(root.join(".git")).unwrap();
        write_skill(&root, "commit", "Make a commit");

        let (mut s, requests) = capturing_with_cfg(
            vec![Ok(text_turn("a")), Ok(text_turn("b"))],
            skills_config(root),
        );
        s.run_text("q1").await;
        s.run_text("q2").await;

        let reqs = requests.lock().unwrap();
        let listing = reqs[0]
            .iter()
            .filter_map(|m| reminder_text(std::slice::from_ref(m)))
            .find(|t| t.contains("skills are available"))
            .expect("listing injected");
        assert!(listing.contains(r#"<skill name="commit""#), "{listing}");
        assert!(listing.contains("Make a commit"), "{listing}");
        assert!(
            listing.contains("SKILL.md\">"),
            "the path attribute: {listing}"
        );

        let count = |msgs: &[Message]| {
            msgs.iter()
                .filter(|m| {
                    reminder_text(std::slice::from_ref(m))
                        .is_some_and(|t| t.contains("skills are available"))
                })
                .count()
        };
        assert_eq!(count(&reqs[1]), 1, "unchanged ⇒ not re-sent");
    }

    /// Adding a skill re-sends the **whole** listing, not just the new entry — the
    /// defect the per-skill delta in Claude Code and grok produces (ADR-0025 §3.1).
    ///
    /// Also pins the timing consequence of §3.2: the scan runs *after* a run finishes,
    /// so a skill created while the user is typing is picked up by the **next** run's
    /// post-run scan and injected on the turn after that. Writing it during a run — the
    /// case the design optimizes for — costs no extra turn.
    #[tokio::test]
    async fn adding_a_skill_re_sends_the_entire_listing() {
        let dir = tempfile::tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();
        std::fs::create_dir(root.join(".git")).unwrap();
        write_skill(&root, "commit", "Make a commit");

        let (mut s, requests) = capturing_with_cfg(
            vec![Ok(text_turn("a")), Ok(text_turn("b")), Ok(text_turn("c"))],
            skills_config(root.clone()),
        );
        s.run_text("q1").await;
        write_skill(&root, "review", "Review a diff"); // after run 1's post-run scan
        s.run_text("q2").await; // still the cached body; run 2's scan picks it up
        s.run_text("q3").await;

        let reqs = requests.lock().unwrap();
        let listing = |msgs: &[Message]| {
            msgs.iter()
                .filter_map(|m| reminder_text(std::slice::from_ref(m)))
                .rfind(|t| t.contains("skills are available"))
        };
        assert!(
            !listing(&reqs[1]).unwrap().contains(r#"name="review""#),
            "not yet — the scan that would see it runs at the end of this run"
        );
        let third = listing(&reqs[2]).expect("re-sent");
        assert!(
            third.contains(r#"name="commit""#),
            "old skill included: {third}"
        );
        assert!(
            third.contains(r#"name="review""#),
            "new skill included: {third}"
        );
    }

    /// Removing the last skill says so, rather than going quiet and leaving a stale
    /// instruction standing (ADR-0025 §3.1 — codex's behavior, not the other two's).
    #[tokio::test]
    async fn removing_the_last_skill_announces_it() {
        let dir = tempfile::tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();
        std::fs::create_dir(root.join(".git")).unwrap();
        write_skill(&root, "commit", "Make a commit");

        let (mut s, requests) = capturing_with_cfg(
            vec![Ok(text_turn("a")), Ok(text_turn("b")), Ok(text_turn("c"))],
            skills_config(root.clone()),
        );
        s.run_text("q1").await;
        std::fs::remove_dir_all(root.join(".agents/skills/commit")).unwrap();
        s.run_text("q2").await; // run 2's post-run scan observes the removal
        s.run_text("q3").await;

        let reqs = requests.lock().unwrap();
        let last = reqs[2]
            .iter()
            .filter_map(|m| reminder_text(std::slice::from_ref(m)))
            .next_back()
            .expect("a reminder");
        assert!(last.contains("No skills are currently available"), "{last}");
    }

    /// A project with no skills at all must not open with a pointless denial.
    #[tokio::test]
    async fn no_skills_ever_means_no_message_at_all() {
        let dir = tempfile::tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();
        std::fs::create_dir(root.join(".git")).unwrap();

        let (mut s, requests) = capturing_with_cfg(vec![Ok(text_turn("a"))], skills_config(root));
        s.run_text("q1").await;

        let reqs = requests.lock().unwrap();
        assert!(
            !reqs[0]
                .iter()
                .any(|m| reminder_text(std::slice::from_ref(m))
                    .is_some_and(|t| t.contains("skills"))),
            "silence, not a denial"
        );
    }

    #[tokio::test]
    async fn project_instructions_absent_when_disabled() {
        let dir = tempfile::tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();
        std::fs::create_dir(root.join(".git")).unwrap();
        std::fs::write(root.join("AGENTS.md"), "be terse").unwrap();
        let mut cfg = instr_config(root);
        cfg.instructions.enabled = false;

        let (mut s, requests) = capturing_with_cfg(vec![Ok(text_turn("ok"))], cfg);
        s.run_text("q").await;
        assert!(reminder_text(&requests.lock().unwrap()[0]).is_none());
    }

    #[tokio::test]
    async fn project_instructions_absent_when_no_agents_md() {
        let dir = tempfile::tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();
        // Empty tempdir — no `.git`, no `AGENTS.md` → nothing discovered.
        let (mut s, requests) = capturing_with_cfg(vec![Ok(text_turn("ok"))], instr_config(root));
        s.run_text("q").await;
        assert!(reminder_text(&requests.lock().unwrap()[0]).is_none());
    }

    #[tokio::test]
    async fn project_instructions_replace_banner_on_edit() {
        let dir = tempfile::tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();
        std::fs::create_dir(root.join(".git")).unwrap();
        let agents = root.join("AGENTS.md");
        std::fs::write(&agents, "v1 rules").unwrap();

        let (mut s, requests) = capturing_with_cfg(
            vec![Ok(text_turn("ok1")), Ok(text_turn("ok2"))],
            instr_config(root),
        );
        s.run_text("q1").await;
        std::fs::write(&agents, "v2 rules").unwrap(); // edit between runs
        s.run_text("q2").await;

        let reqs = requests.lock().unwrap();
        let run2 = &reqs[1];
        let banner = run2
            .iter()
            .find_map(|m| match (m.role, m.content.as_slice()) {
                (Role::User, [ContentBlock::Text { text }])
                    if text.contains("replace all previously provided") =>
                {
                    Some(text.clone())
                }
                _ => None,
            })
            .expect("replace banner on edit");
        assert!(banner.contains("v2 rules"), "new content: {banner}");
        assert!(!banner.contains("v1 rules"), "not the old content");
        // Both the original (v1) and the replacement (v2) reminders are in the transcript.
        assert_eq!(reminder_count(run2), 2);
    }

    #[tokio::test]
    async fn project_instructions_removal_banner_on_delete() {
        let dir = tempfile::tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();
        std::fs::create_dir(root.join(".git")).unwrap();
        let agents = root.join("AGENTS.md");
        std::fs::write(&agents, "rules").unwrap();

        let (mut s, requests) = capturing_with_cfg(
            vec![Ok(text_turn("ok1")), Ok(text_turn("ok2"))],
            instr_config(root),
        );
        s.run_text("q1").await;
        std::fs::remove_file(&agents).unwrap(); // delete between runs
        s.run_text("q2").await;

        let reqs = requests.lock().unwrap();
        assert!(
            reqs[1].iter().any(|m| matches!(
                (m.role, m.content.as_slice()),
                (Role::User, [ContentBlock::Text { text }]) if text.contains("no longer apply")
            )),
            "removal notice on delete"
        );
    }

    #[tokio::test]
    async fn project_instructions_not_reinjected_when_unchanged() {
        let dir = tempfile::tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();
        std::fs::create_dir(root.join(".git")).unwrap();
        std::fs::write(root.join("AGENTS.md"), "stable").unwrap();

        let (mut s, requests) = capturing_with_cfg(
            vec![
                Ok(text_turn("ok1")),
                Ok(text_turn("ok2")),
                Ok(text_turn("ok3")),
            ],
            instr_config(root),
        );
        s.run_text("q1").await;
        s.run_text("q2").await;
        s.run_text("q3").await;
        // Exactly one injection across three unchanged turns.
        assert_eq!(reminder_count(&requests.lock().unwrap()[2]), 1);
    }

    #[tokio::test]
    async fn init_emitted_once_across_runs_with_one_result_each() {
        let (mut s, events) = session_with(
            vec![Ok(text_turn("one")), Ok(text_turn("two"))],
            Registry::new(),
            config(),
        );
        let _ = s.run_text("q1").await;
        let _ = s.run_text("q2").await;
        let evs = dump(&events);
        let inits = evs
            .iter()
            .filter(|e| matches!(e, Event::Init { .. }))
            .count();
        let results = evs
            .iter()
            .filter(|e| matches!(e, Event::Result { .. }))
            .count();
        assert_eq!(inits, 1, "Init is once per session, not per run");
        assert_eq!(results, 2, "one Result per run");
        assert!(
            matches!(evs.first(), Some(Event::Init { .. })),
            "Init still opens the stream"
        );
    }

    #[tokio::test]
    async fn report_counts_are_per_run_not_cumulative() {
        // Run 1: tool turn + text (2 turns, 1 tool call, 10/5 tokens).
        // Run 2: text only (1 turn, 0 tool calls, 20/7 tokens).
        let mut t1 = tool_turn("c1", "echo");
        t1.usage = Usage {
            input_tokens: 10,
            output_tokens: 5,
            ..Usage::default()
        };
        let t2 = text_turn("done one");
        let mut t3 = text_turn("done two");
        t3.usage = Usage {
            input_tokens: 20,
            output_tokens: 7,
            ..Usage::default()
        };
        let (mut s, _e) = session_with(vec![Ok(t1), Ok(t2), Ok(t3)], echo_registry(), config());
        let r1 = s.run_text("q1").await;
        let r2 = s.run_text("q2").await;
        assert_eq!(r1.turns, 2);
        assert_eq!(r1.tool_calls.len(), 1);
        assert_eq!(r2.turns, 1, "run 2 counts its own turns only");
        assert!(r2.tool_calls.is_empty());
        assert_eq!(r2.usage.input_tokens, 20, "usage is per-run");
        assert_eq!(r2.usage.output_tokens, 7);
    }

    /// Golden: a two-run stream (`Init M+ Result M+ Result`) reconstructs the
    /// full cross-run conversation (ADR-0014 amendment 2026-07-21).
    #[tokio::test]
    async fn two_run_stream_reconstructs_the_full_conversation() {
        let (mut s, events) = session_with(
            vec![
                Ok(tool_turn("c1", "echo")),
                Ok(text_turn("done one")),
                Ok(text_turn("done two")),
            ],
            echo_registry(),
            config(),
        );
        let _ = s.run_text("q1").await;
        let _ = s.run_text("q2").await;
        let rebuilt: Conversation = reconstruct_conversation(&dump(&events));
        // Run 1: user, assistant(tool_use), user(tool_result), assistant(text);
        // run 2: user, assistant(text).
        let roles: Vec<Role> = rebuilt.messages.iter().map(|m| m.role).collect();
        assert_eq!(
            roles,
            vec![
                Role::User,
                Role::Assistant,
                Role::User,
                Role::Assistant,
                Role::User,
                Role::Assistant,
            ]
        );
        // And the reconstruction matches the session's own history exactly.
        assert_eq!(rebuilt.messages.as_slice(), s.history());
    }

    /// Continuing after a `ModelError` run is allowed unconditionally
    /// (ADR-0016 Resolution): the history simply didn't advance.
    #[tokio::test]
    async fn continues_after_model_error() {
        let (mut s, requests, _e) = capturing_session_with(
            vec![Err(ProviderError::ContextOverflow), Ok(text_turn("ok now"))],
            Registry::new(),
        );
        let r1 = s.run_text("q1").await;
        let r2 = s.run_text("q2").await;
        assert_eq!(r1.status, Status::ModelError);
        assert_eq!(r2.status, Status::Completed);
        // Run 2's request: q1's user message survived; no phantom assistant turn.
        let reqs = requests.lock().unwrap();
        let run2 = &reqs[1];
        assert_eq!(run2.len(), 2, "user q1 + user q2: {run2:?}");
        assert_eq!(user_text(&run2[0]), Some("q1"));
        assert_eq!(user_text(&run2[1]), Some("q2"));
    }

    /// Continuing after a fatal tool `Error` run: the transcript was fully
    /// paired before the break, so the next sample sees a valid history.
    #[tokio::test]
    async fn continues_after_fatal_tool_error_with_valid_pairing() {
        let mut reg = Registry::new();
        reg.register("boom", Boom);
        let (mut s, requests, _e) = capturing_session_with(
            vec![Ok(tool_turn("c1", "boom")), Ok(text_turn("recovered"))],
            reg,
        );
        let r1 = s.run_text("q1").await;
        let r2 = s.run_text("q2").await;
        assert_eq!(r1.status, Status::Error);
        assert_eq!(r2.status, Status::Completed);

        // Run 2's request replays the failed run intact: the boom tool_use is
        // answered by its (is_error) tool_result.
        let reqs = requests.lock().unwrap();
        let run2 = &reqs[1];
        assert_eq!(run2.len(), 4, "q1, assistant, tool_result, q2: {run2:?}");
        assert!(
            run2[1]
                .content
                .iter()
                .any(|b| matches!(b, ContentBlock::ToolUse { id, .. } if id == "c1"))
        );
        assert!(run2[2].content.iter().any(|b| matches!(
            b,
            ContentBlock::ToolResult { tool_use_id, is_error: true, .. } if tool_use_id == "c1"
        )));
        assert_eq!(user_text(&run2[3]), Some("q2"));
    }

    #[tokio::test]
    async fn usage_is_summed_across_turns() {
        let mut first = tool_turn("c1", "echo");
        first.usage = Usage {
            input_tokens: 10,
            output_tokens: 5,
            ..Usage::default()
        };
        let mut second = text_turn("done");
        second.usage = Usage {
            input_tokens: 20,
            output_tokens: 7,
            ..Usage::default()
        };
        let (mut s, _e) = session_with(vec![Ok(first), Ok(second)], echo_registry(), config());
        let report = s.run_text("go").await;
        assert_eq!(report.usage.input_tokens, 30);
        assert_eq!(report.usage.output_tokens, 12);
    }

    /// Switching the model swaps the provider and **announces** the change instead of
    /// rewriting the preamble.
    ///
    /// A pack's system prompt may name the model, and after a switch that line is
    /// stale — but rewriting the `System` message would desync the conversation from
    /// the trace, whose `Init` record already captured the original preamble. Appending
    /// is the same discipline project instructions and skills follow.
    #[tokio::test]
    async fn setting_the_model_announces_it_without_touching_the_preamble() {
        let preamble = vec![Message {
            role: Role::System,
            content: vec![ContentBlock::Text {
                text: "You are powered by the model old-1.".into(),
            }],
        }];
        let provider = Arc::new(MockProvider::with_results(vec![Ok(text_turn("ok"))]));
        let mut s = Session::new(
            provider.clone(),
            Registry::new(),
            preamble.clone(),
            config(),
            Box::new(NullSink),
        );

        let notice = s.set_model(provider, "new-2");
        s.announce(notice);

        assert_eq!(
            s.history()[0],
            preamble[0],
            "the preamble is untouched — the trace already recorded it"
        );
        let last = s.history().last().expect("announcement appended");
        assert_eq!(last.role, Role::User);
        let ContentBlock::Text { text } = &last.content[0] else {
            panic!("text block")
        };
        assert!(text.starts_with("<system-reminder>"), "{text}");
        assert!(text.contains("is now new-2"), "{text}");
        assert!(
            text.contains("out of date"),
            "corrects the stale line: {text}"
        );
    }

    /// `context_usage` is the **final** turn's, not the sum.
    ///
    /// Every turn's request re-sends the whole conversation, so summing counts the same
    /// history once per turn — a number that only grows and says nothing about how full
    /// the context is. The last turn's request *is* the whole conversation.
    #[tokio::test]
    async fn context_usage_is_the_final_turn_not_the_sum() {
        let mut first = tool_turn("c1", "echo");
        first.usage = Usage {
            input_tokens: 10,
            output_tokens: 5,
            ..Usage::default()
        };
        let mut second = text_turn("done");
        second.usage = Usage {
            input_tokens: 20,
            output_tokens: 7,
            cache_read_tokens: Some(4),
            cache_creation_tokens: Some(3),
            ..Usage::default()
        };
        let (mut s, _e) = session_with(vec![Ok(first), Ok(second)], echo_registry(), config());
        let report = s.run_text("go").await;

        assert_eq!(report.context_usage.input_tokens, 20, "the last turn only");
        assert_eq!(report.context_usage.output_tokens, 7);
        assert_eq!(
            report.context_usage.context_tokens(),
            20 + 4 + 3 + 7,
            "both cache counters are prompt tokens"
        );
        assert_eq!(report.usage.input_tokens, 30, "the sum is still the sum");
    }
}