agix-telemetry 0.5.0

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

pub mod blob;
pub mod format;
pub mod override_doc;
pub mod pack;
mod private;
pub mod reader;
pub mod rerun;
mod stream;
pub mod writer;

use async_trait::async_trait;
use base::interface::model::{
    Model, ModelError, ModelEvent, ModelMessage, ModelStream, StreamParams, ToolDef, Usage,
};
use base::prompt::PromptBlock;
use base::provider::ApiType;
use base::recorder::{Divergence, RecorderConfig, RecorderMode};
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use tokio_util::sync::CancellationToken;

use blob::BlobId;
use format::{
    now_ms, CallRecord, Header, Outcome, Record, RecordedError, RecordedParams, FORMAT_VERSION,
};
use pack::RunPacker;
pub(crate) use private::{private_dir, private_file};
use reader::Recording;
use stream::{write_end, RecordingStream};
use writer::RecordingWriter;

/// The recording a call belongs to, or nothing.
///
/// A call that cannot name its session has no recording to belong to. A
/// shared name for such calls would file unrelated calls together, and since
/// a writer truncates the file it opens, concurrent sessions would erase
/// each other.
fn recording_name_of(config: &RecorderConfig, params: &StreamParams) -> Option<String> {
    if let Some(name) = &config.name {
        return Some(name.clone());
    }
    params.origin.as_ref().map(|o| o.session_id.clone())
}

/// Everything a set of recordings shares: the open writers and how far each
/// replay has got, keyed by recording name.
///
/// Held behind an `Arc` and shared by every [`RecorderModel`] that records into
/// the same root. Multi-provider routing hands out one `Model` per provider,
/// and each of them needs wrapping to be recorded at all — but they must not
/// each open their own writer for the same file, or the second one to write
/// truncates the first one's recording out from under it. One shared state, one
/// writer per name, appends serialized by that writer's lock.
#[derive(Default)]
pub struct Recorder {
    writers: Mutex<HashMap<String, Arc<RecordingWriter>>>,
    replays: Mutex<HashMap<String, ReplayState>>,
}

impl Recorder {
    pub fn new() -> Arc<Self> {
        Arc::new(Self::default())
    }

    /// Report any replay that did not run to the end of what was recorded.
    ///
    /// A run that made *fewer* calls than the recording holds passes every
    /// other check — nothing diverged, nothing ran out — while having quietly
    /// stopped doing part of the work. Overshooting is already an error at the
    /// call that overshoots; this is the other direction, and it can only be
    /// asked at the end. Returns one line per unfinished session, empty when
    /// every recorded call was replayed — or the only ones left are calls a
    /// replay may go without.
    pub fn unconsumed(&self) -> Vec<String> {
        let replays = self.replays.lock().unwrap_or_else(|e| e.into_inner());
        let mut out = Vec::new();
        for (name, state) in replays.iter() {
            for recorded in &state.recorded_sessions {
                let calls = state.calls_of(recorded);
                let total = calls.len();
                let replayed = state.replayed_of(recorded);
                let used = replayed.len();
                let owed = calls.iter().enumerate().any(|(at, c)| {
                    !replayed.contains(&at)
                        && !c.request.purpose.as_deref().is_some_and(may_go_unreplayed)
                });
                if owed {
                    out.push(format!(
                        "recording {name:?} session {recorded:?}: replayed {used} of {total} call(s)"
                    ));
                }
            }
        }
        out
    }
}

pub struct RecorderModel {
    inner: Arc<dyn Model>,
    config: Option<RecorderConfig>,
    engine_version: String,
    /// The provider id this instance fronts, as named in settings.json. The
    /// api type alone cannot tell two OpenAI-compatible endpoints apart.
    provider_id: Option<String>,
    shared: Arc<Recorder>,
}

/// One recording being replayed, sliced per session and, within a session,
/// per purpose.
///
/// A single cursor over the whole file works only when the file holds one
/// session. When a parent and its sub-agents record under one name their calls
/// interleave, and the order they interleave in is a scheduling detail that
/// will not repeat — so each live session walks only the calls that were made
/// by its counterpart, and the interleaving is allowed to differ.
///
/// The same holds inside a session. Its conversation calls come in an order
/// the turn loop fixes, but auxiliary calls — memory extraction, naming —
/// run in the background and land among them wherever they happened to
/// finish. So a conversation call takes the session's next recorded
/// conversation call, passing over auxiliary ones, and an auxiliary call
/// takes the earliest recorded call of its purpose not yet replayed.
struct ReplayState {
    recording: Recording,
    /// Recorded session ids in order of first appearance, which is the order
    /// live sessions bind to them when the ids themselves don't match.
    recorded_sessions: Vec<String>,
    /// Live session id → the recorded session it replays against.
    bound: HashMap<String, String>,
    /// Recorded session id → which of its calls (indices into
    /// [`Self::calls_of`]) have been handed out.
    ///
    /// Kept apart from `bound` so marking a call needs no second lookup into
    /// `bound` — one that could only be written as an `unwrap()` resting on an
    /// invariant held across two functions with nothing enforcing it.
    replayed: HashMap<String, HashSet<usize>>,
}

impl ReplayState {
    fn new(recording: Recording) -> Self {
        let mut recorded_sessions: Vec<String> = Vec::new();
        for call in &recording.calls {
            let session = call
                .request
                .session_id
                .clone()
                .unwrap_or_else(|| recording.header.session_id.clone());
            if !recorded_sessions.contains(&session) {
                recorded_sessions.push(session);
            }
        }
        Self {
            recording,
            recorded_sessions,
            bound: HashMap::new(),
            replayed: HashMap::new(),
        }
    }

    /// Which recorded session `live` replays against.
    ///
    /// An id that appears in the recording binds to itself — a replay driven
    /// with the same session ids it was recorded with is exact. Otherwise
    /// sessions bind in the order they first call, which is what a live run
    /// can guarantee: the parent necessarily streams before it can delegate.
    /// Returns the recorded session id, or `None` when the run has introduced
    /// more distinct sessions than the recording holds.
    fn bind(&mut self, live: &str) -> Option<String> {
        if let Some(recorded) = self.bound.get(live) {
            return Some(recorded.clone());
        }
        let recorded = if self.recorded_sessions.iter().any(|s| s == live) {
            live.to_string()
        } else {
            self.recorded_sessions
                .iter()
                .find(|s| !self.bound.values().any(|taken| taken == *s))?
                .clone()
        };
        self.bound.insert(live.to_string(), recorded.clone());
        Some(recorded)
    }

    fn replayed_of(&self, recorded_session: &str) -> HashSet<usize> {
        self.replayed
            .get(recorded_session)
            .cloned()
            .unwrap_or_default()
    }

    /// The earliest call of `recorded_session` with `purpose` (`None` for a
    /// conversation call) not yet handed out, as an index into
    /// [`Self::calls_of`].
    fn next_of(&self, recorded_session: &str, purpose: Option<&str>) -> Option<usize> {
        let replayed = self.replayed.get(recorded_session);
        self.calls_of(recorded_session)
            .iter()
            .enumerate()
            .find(|(at, c)| {
                c.request.purpose.as_deref() == purpose && !replayed.is_some_and(|r| r.contains(at))
            })
            .map(|(at, _)| at)
    }

    fn mark_replayed(&mut self, recorded_session: &str, at: usize) {
        self.replayed
            .entry(recorded_session.to_string())
            .or_default()
            .insert(at);
    }

    fn calls_of(&self, recorded_session: &str) -> Vec<&reader::RecordedCall> {
        self.recording
            .calls
            .iter()
            .filter(|c| {
                c.request
                    .session_id
                    .as_deref()
                    .unwrap_or(&self.recording.header.session_id)
                    == recorded_session
            })
            .collect()
    }
}

impl RecorderModel {
    pub fn new(
        inner: Arc<dyn Model>,
        config: Option<RecorderConfig>,
        engine_version: &str,
    ) -> Self {
        Self::shared(inner, config, engine_version, Recorder::new())
    }

    /// Wrap `inner` sharing `shared` with every other model recording into the
    /// same root — the constructor multi-provider routing uses, so a session's
    /// calls land in one recording however many providers served them.
    pub fn shared(
        inner: Arc<dyn Model>,
        config: Option<RecorderConfig>,
        engine_version: &str,
        shared: Arc<Recorder>,
    ) -> Self {
        Self {
            inner,
            config: config.or_else(Self::env_config),
            engine_version: engine_version.to_string(),
            provider_id: None,
            shared,
        }
    }

    pub fn with_provider_id(mut self, provider_id: impl Into<String>) -> Self {
        self.provider_id = Some(provider_id.into());
        self
    }

    /// `AGIX_RECORD=<name>` / `AGIX_REPLAY=<name>` with `AGIX_RECORDINGS_DIR`
    /// for the root. Absent all of them, the decorator is a pass-through.
    fn env_config() -> Option<RecorderConfig> {
        let root = std::env::var("AGIX_RECORDINGS_DIR")
            .ok()
            .map(PathBuf::from)?;
        let on_divergence = Self::default_divergence();
        if let Ok(name) = std::env::var("AGIX_RECORD") {
            Some(RecorderConfig {
                mode: RecorderMode::Record,
                name: Some(name),
                root,
                on_divergence,
            })
        } else if let Ok(name) = std::env::var("AGIX_REPLAY") {
            Some(RecorderConfig {
                mode: RecorderMode::Replay,
                name: Some(name),
                root,
                on_divergence,
            })
        } else {
            None
        }
    }

    fn writer_for(
        &self,
        config: &RecorderConfig,
        name: &str,
        params: &StreamParams,
    ) -> Arc<RecordingWriter> {
        let mut writers = self
            .shared
            .writers
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        writers
            .entry(name.to_string())
            .or_insert_with(|| {
                Arc::new(RecordingWriter::create(
                    &config.root,
                    Header {
                        version: FORMAT_VERSION,
                        name: name.to_string(),
                        session_id: params
                            .origin
                            .as_ref()
                            .map(|o| o.session_id.clone())
                            .unwrap_or_default(),
                        // Fixed by the first call, which is why a sub-agent has
                        // to know its lineage at spawn time rather than
                        // discovering it later.
                        parent: params
                            .origin
                            .as_ref()
                            .and_then(|o| o.parent_session_id.clone()),
                        agent_type: params.origin.as_ref().and_then(|o| o.agent_type.clone()),
                        created_at: now_ms(),
                        engine_version: self.engine_version.clone(),
                    },
                ))
            })
            .clone()
    }
}

/// When the recording `name` under `root` began (its header's `created_at`, milliseconds since
/// the epoch), reading only its first line. `None` when there is no such recording.
///
/// What a replaying session sets its clock to, so the date its prompt carries is the date the
/// recording's prompt carried.
pub fn recorded_at(root: &std::path::Path, name: &str) -> Option<u64> {
    use std::io::BufRead;
    let file = std::fs::File::open(root.join(name).join("calls.jsonl")).ok()?;
    let line = std::io::BufReader::new(file)
        .lines()
        .map_while(Result::ok)
        .find(|l| !l.trim().is_empty())?;
    match serde_json::from_str::<format::Record>(&line).ok()? {
        format::Record::Recording(header) => Some(header.created_at),
        _ => None,
    }
}

fn flag(name: &str) -> bool {
    std::env::var(name).is_ok_and(|v| v != "0" && !v.is_empty())
}

/// The environment facts that decide the default divergence policy. Split from
/// the lookups so the policy is a pure function that can be tested without
/// mutating process-global environment variables.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct DivergenceInputs {
    forced_strict: bool,
    forced_warn: bool,
    in_test: bool,
    in_ci: bool,
}

fn resolve_divergence(inputs: DivergenceInputs) -> Divergence {
    if inputs.forced_strict {
        return Divergence::Strict;
    }
    if inputs.forced_warn {
        return Divergence::Warn;
    }
    // Strict wherever a divergence means a broken test; lenient only for a
    // human driving a replay by hand, so a brand-new case still runs before
    // anyone has recorded it.
    if inputs.in_test || inputs.in_ci {
        Divergence::Strict
    } else {
        Divergence::Warn
    }
}

impl RecorderModel {
    /// The divergence policy a harness should ask for rather than re-derive.
    ///
    /// Public because a harness that builds an explicit [`RecorderConfig`]
    /// never reaches [`RecorderModel::env_config`], and re-deriving this is
    /// how the equivalent flag once shipped as a silent no-op.
    ///
    /// Overrides, highest precedence first: `AGIX_REPLAY_STRICT=1`, then
    /// `AGIX_REPLAY_WARN=1`.
    pub fn default_divergence() -> Divergence {
        resolve_divergence(DivergenceInputs {
            forced_strict: flag("AGIX_REPLAY_STRICT"),
            forced_warn: flag("AGIX_REPLAY_WARN"),
            in_test: std::env::var("CARGO_TEST_RUNNER").is_ok()
                || std::env::var("AGIX_RECORDER_AUTO_DETECT").is_ok(),
            in_ci: flag("CI"),
        })
    }
}

/// The parts of a request that identify it, as blob ids. Computed for both a
/// live request and a recorded one so replay can compare them without loading
/// content that matches.
struct RequestShape {
    params: RecordedParams,
    system: Vec<BlobId>,
    tools: BlobId,
    messages: Vec<BlobId>,
}

impl RequestShape {
    fn of(
        prompt_blocks: &[PromptBlock],
        tools: &[ToolDef],
        messages: &[ModelMessage],
        params: &StreamParams,
    ) -> Self {
        Self {
            params: RecordedParams {
                model: params.model.clone(),
                max_tokens: params.max_tokens,
                thinking_mode: params.thinking_mode.clone(),
                effort: params.effort,
                cache_edits: params.cache_edits.clone(),
                search_max_uses: params.provider_search.map(|s| s.max_uses),
            },
            system: prompt_blocks.iter().map(BlobId::of_value).collect(),
            tools: BlobId::of_value(&tools),
            messages: messages.iter().map(BlobId::of_value).collect(),
        }
    }
}

/// Field-level differences between what was recorded and what the live run
/// produced. Empty means the two agree.
fn diverges(recorded: &CallRecord, live: &RequestShape) -> Vec<String> {
    let mut out = Vec::new();
    if recorded.params != live.params {
        out.push(format!(
            "params: recorded {:?}, live {:?}",
            recorded.params, live.params
        ));
    }
    if recorded.system.len() != live.system.len() {
        out.push(format!(
            "system: recorded {} blocks, live {}",
            recorded.system.len(),
            live.system.len()
        ));
    } else {
        for (i, (a, b)) in recorded.system.iter().zip(&live.system).enumerate() {
            if a != b {
                out.push(format!("system[{i}]: recorded {a}, live {b}"));
            }
        }
    }
    if recorded.tools != live.tools {
        out.push(format!(
            "tools: recorded {}, live {}",
            recorded.tools, live.tools
        ));
    }
    if recorded.messages.len() != live.messages.len() {
        out.push(format!(
            "messages: recorded {} messages, live {}",
            recorded.messages.len(),
            live.messages.len()
        ));
    } else {
        for (i, (a, b)) in recorded.messages.iter().zip(&live.messages).enumerate() {
            if a != b {
                out.push(format!("messages[{i}]: recorded {a}, live {b}"));
            }
        }
    }
    out
}

#[async_trait]
impl Model for RecorderModel {
    fn api_type(&self) -> ApiType {
        self.inner.api_type()
    }

    fn provenance(&self) -> Option<String> {
        self.inner.provenance()
    }

    fn meters_its_calls(&self) -> bool {
        self.inner.meters_its_calls()
    }

    async fn stream(
        &self,
        prompt_blocks: Vec<PromptBlock>,
        tools: Vec<ToolDef>,
        messages: Vec<ModelMessage>,
        params: StreamParams,
        cancel: CancellationToken,
    ) -> Result<ModelStream, ModelError> {
        let Some(config) = self.config.clone() else {
            return self
                .inner
                .stream(prompt_blocks, tools, messages, params, cancel)
                .await;
        };
        let Some(name) = recording_name_of(&config, &params) else {
            return self
                .inner
                .stream(prompt_blocks, tools, messages, params, cancel)
                .await;
        };

        match config.mode {
            RecorderMode::Replay => {
                let shape = RequestShape::of(&prompt_blocks, &tools, &messages, &params);
                let live_session = params
                    .origin
                    .as_ref()
                    .map(|o| o.session_id.as_str())
                    .unwrap_or_default();
                let purpose = params.origin.as_ref().and_then(|o| o.purpose());
                self.replay(&config, &name, live_session, purpose, shape)
            }
            RecorderMode::Record => {
                let writer = self.writer_for(&config, &name, &params);
                self.record(writer, prompt_blocks, tools, messages, params, cancel)
                    .await
            }
            // Rerun drives the provider from a recording rather than from a
            // live session, so it does not sit on this path — see
            // [`rerun::rerun_one`], which the daemon's `session.rerunCall`
            // drives. A session that somehow runs under this mode
            // just talks to the model, which is the only honest thing to do
            // here: intercepting would mean answering a live request with a
            // response recorded for some other request.
            RecorderMode::Rerun => {
                self.inner
                    .stream(prompt_blocks, tools, messages, params, cancel)
                    .await
            }
        }
    }
}

/// Blob writes are synchronous disk IO; on a multi-thread runtime they are
/// told to the scheduler so other tasks move off this worker meanwhile.
fn off_the_reactor<T>(f: impl FnOnce() -> T) -> T {
    match tokio::runtime::Handle::try_current().map(|h| h.runtime_flavor()) {
        Ok(tokio::runtime::RuntimeFlavor::MultiThread) => tokio::task::block_in_place(f),
        _ => f(),
    }
}

impl RecorderModel {
    async fn record(
        &self,
        writer: Arc<RecordingWriter>,
        prompt_blocks: Vec<PromptBlock>,
        tools: Vec<ToolDef>,
        messages: Vec<ModelMessage>,
        params: StreamParams,
        cancel: CancellationToken,
    ) -> Result<ModelStream, ModelError> {
        let call_seq = writer.next_seq();
        let started = std::time::Instant::now();

        // Written before the stream opens, and flushed: a process killed
        // mid-response still leaves behind the request that was in flight.
        if let Err(e) = off_the_reactor(|| {
            self.write_call(
                &writer,
                call_seq,
                &prompt_blocks,
                &tools,
                &messages,
                &params,
            )
        }) {
            tracing::warn!(error = %e, "recorder: failed to write call record, continuing unrecorded");
        }

        let result = self
            .inner
            .stream(prompt_blocks, tools, messages, params, cancel)
            .await;

        match result {
            Ok(inner) => Ok(Box::new(RecordingStream {
                inner,
                writer,
                packer: RunPacker::new(),
                call_seq,
                started,
                stop_reason: String::new(),
                usage: Usage::default(),
                finished: false,
            })),
            Err(e) => {
                write_end(
                    &writer,
                    call_seq,
                    Outcome::Error {
                        error: RecordedError::from(&e),
                    },
                    None,
                    None,
                    started,
                );
                Err(e)
            }
        }
    }

    fn write_call(
        &self,
        writer: &RecordingWriter,
        call_seq: u64,
        prompt_blocks: &[PromptBlock],
        tools: &[ToolDef],
        messages: &[ModelMessage],
        params: &StreamParams,
    ) -> std::io::Result<()> {
        let blobs = writer.blobs();
        let system = prompt_blocks
            .iter()
            .map(|b| blobs.put(b))
            .collect::<Result<Vec<_>, _>>()?;
        let tools_id = blobs.put(&tools)?;
        let message_ids = messages
            .iter()
            .map(|m| blobs.put(m))
            .collect::<Result<Vec<_>, _>>()?;

        let (turn, step) = params
            .origin
            .as_ref()
            .map(|o| o.turn_step())
            .unwrap_or((0, 0));

        writer.append(&Record::Call(Box::new(CallRecord {
            seq: call_seq,
            ts: now_ms(),
            session_id: params.origin.as_ref().map(|o| o.session_id.clone()),
            parent_session_id: params
                .origin
                .as_ref()
                .and_then(|o| o.parent_session_id.clone()),
            agent_type: params.origin.as_ref().and_then(|o| o.agent_type.clone()),
            turn_id: params.origin.as_ref().and_then(|o| o.turn_id.clone()),
            turn,
            step,
            purpose: params
                .origin
                .as_ref()
                .and_then(|o| o.purpose())
                .map(str::to_string),
            // The provider as configured, when routing named one. Falling back
            // to the api type keeps single-provider recordings readable, but it
            // cannot distinguish two OpenAI-compatible endpoints — which is why
            // the routed path supplies the id.
            provider: self.provider_id.clone().unwrap_or_else(|| {
                match self.inner.api_type() {
                    ApiType::Anthropic => "anthropic",
                    ApiType::OpenAIChat => "openai_chat",
                    ApiType::OpenAIResponses => "openai_responses",
                }
                .into()
            }),
            api_type: self.inner.api_type(),
            params: RecordedParams {
                model: params.model.clone(),
                max_tokens: params.max_tokens,
                thinking_mode: params.thinking_mode.clone(),
                effort: params.effort,
                cache_edits: params.cache_edits.clone(),
                search_max_uses: params.provider_search.map(|s| s.max_uses),
            },
            input_map: params.input_map.clone(),
            system,
            tools: tools_id,
            messages: message_ids,
        })))?;
        writer.flush()
    }

    fn replay(
        &self,
        config: &RecorderConfig,
        name: &str,
        live_session: &str,
        purpose: Option<&str>,
        shape: RequestShape,
    ) -> Result<ModelStream, ModelError> {
        let mut replays = self
            .shared
            .replays
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let state = match replays.get_mut(name) {
            Some(state) => state,
            None => {
                let recording = reader::load_for_replay(&config.root.join(name), name)?;
                replays
                    .entry(name.to_string())
                    .or_insert(ReplayState::new(recording))
            }
        };

        let sessions = state.recorded_sessions.len();
        let Some(recorded_session) = state.bind(live_session) else {
            return Err(ModelError::protocol(format!(
                "recorder: recording {name:?} holds {sessions} session(s), \
                 live run introduced another ({live_session:?})"
            )));
        };
        let Some(at) = state.next_of(&recorded_session, purpose) else {
            let same_kind = state
                .calls_of(&recorded_session)
                .iter()
                .filter(|c| c.request.purpose.as_deref() == purpose)
                .count();
            return Err(exhausted_error(name, &recorded_session, purpose, same_kind));
        };
        let call = state.calls_of(&recorded_session)[at].clone();
        state.mark_replayed(&recorded_session, at);

        let differences = diverges(&call.request, &shape);
        if !differences.is_empty() {
            let report = format!(
                "recorder: call #{} of session {:?} diverges from recording {:?}:\n  {}",
                at + 1,
                recorded_session,
                name,
                differences.join("\n  ")
            );
            match config.on_divergence {
                Divergence::Strict => return Err(ModelError::protocol(report)),
                Divergence::Warn => tracing::warn!("{report}"),
            }
        }

        if let Some(end) = &call.end {
            if let Outcome::Error { error } = &end.outcome {
                return Err(error.clone().into_model_error());
            }
        }

        let events: Vec<Result<ModelEvent, ModelError>> =
            call.response.iter().cloned().map(Ok).collect();
        Ok(Box::new(futures::stream::iter(events)))
    }
}

fn exhausted_error(
    name: &str,
    recorded_session: &str,
    purpose: Option<&str>,
    same_kind: usize,
) -> ModelError {
    match purpose {
        Some(wanted) if may_go_unreplayed(wanted) => ModelError::not_recorded(format!(
            "recording {name:?} has no unreplayed {wanted:?} call for session \
             {recorded_session:?}"
        )),
        Some(wanted) => ModelError::protocol(format!(
            "recorder: recording {name:?} has {same_kind} {wanted:?} call(s) for \
             session {recorded_session:?}, live run asked for #{}",
            same_kind + 1
        )),
        None => ModelError::protocol(format!(
            "recorder: recording {name:?} has {same_kind} conversation call(s) for \
             session {recorded_session:?}, live run asked for #{}",
            same_kind + 1
        )),
    }
}

/// Whether a call of this purpose may be missing on either side of a replay.
///
/// Naming a session is not part of its conversation: a recording made where
/// the scene did not name, or before naming was recorded at all, still
/// replays a run that does — the run just goes unnamed — and a recorded
/// title call a run does not ask for is left unreplayed without the run
/// being reported as having stopped short.
fn may_go_unreplayed(purpose: &str) -> bool {
    purpose == base::interface::model::call_purpose::TITLE
}

#[cfg(test)]
mod tests {
    use super::*;
    use base::interface::model::ModelErrorKind;
    use base::interface::model::ThinkingMode;
    use base::interface::model::{call_purpose, CallOrigin};
    use base::prompt::BlockRole;
    use futures::StreamExt;

    /// Replays a fixed script, or fails to open when `open_error` is set.
    struct ScriptedModel {
        events: Vec<ModelEvent>,
        open_error: bool,
    }

    impl ScriptedModel {
        fn ok(events: Vec<ModelEvent>) -> Arc<dyn Model> {
            Arc::new(Self {
                events,
                open_error: false,
            })
        }

        fn overloaded() -> Arc<dyn Model> {
            Arc::new(Self {
                events: vec![],
                open_error: true,
            })
        }
    }

    #[async_trait]
    impl Model for ScriptedModel {
        fn api_type(&self) -> ApiType {
            ApiType::Anthropic
        }
        async fn stream(
            &self,
            _: Vec<PromptBlock>,
            _: Vec<ToolDef>,
            _: Vec<ModelMessage>,
            _: StreamParams,
            _: CancellationToken,
        ) -> Result<ModelStream, ModelError> {
            if self.open_error {
                return Err(ModelError::overloaded());
            }
            let events: Vec<Result<ModelEvent, ModelError>> =
                self.events.iter().cloned().map(Ok).collect();
            Ok(Box::new(futures::stream::iter(events)))
        }
    }

    fn script() -> Vec<ModelEvent> {
        vec![
            ModelEvent::TextDelta { text: "Hel".into() },
            ModelEvent::TextDelta { text: "lo".into() },
            ModelEvent::TextDelta { text: "!".into() },
            ModelEvent::EndTurn {
                stop_reason: "end_turn".into(),
                usage: Usage {
                    input_tokens: 11,
                    output_tokens: 3,
                    ..Default::default()
                },
            },
        ]
    }

    fn config(
        mode: RecorderMode,
        root: &std::path::Path,
        on_divergence: Divergence,
    ) -> RecorderConfig {
        RecorderConfig {
            mode,
            name: Some("run".into()),
            root: root.to_path_buf(),
            on_divergence,
        }
    }

    fn prompt(text: &str) -> Vec<PromptBlock> {
        vec![PromptBlock {
            role: BlockRole::System,
            content: text.into(),
            cache_strategy: None,
            name: None,
            origin: Default::default(),
        }]
    }

    fn tools() -> Vec<ToolDef> {
        vec![ToolDef::new("Bash", "run", serde_json::json!({}))]
    }

    fn params(session: &str, step: u32) -> StreamParams {
        StreamParams {
            model: "test-model".into(),
            max_tokens: 100,
            thinking_mode: ThinkingMode::Off,
            effort: None,
            cache_edits: vec![],
            origin: Some(CallOrigin::turn(session, 0, step)),
            input_map: None,
            provider_search: None,
            usage_tap: Default::default(),
        }
    }

    async fn drain(stream: ModelStream) -> Vec<ModelEvent> {
        stream.filter_map(|e| async { e.ok() }).collect().await
    }

    #[tokio::test]
    async fn unconfigured_recorder_writes_nothing() {
        let root = tempfile::tempdir().unwrap();
        let recorder = RecorderModel::new(ScriptedModel::ok(script()), None, "test");
        let stream = recorder
            .stream(
                prompt("sys"),
                tools(),
                vec![],
                params("S1", 0),
                CancellationToken::new(),
            )
            .await
            .unwrap();
        assert_eq!(drain(stream).await.len(), 4);
        assert_eq!(std::fs::read_dir(root.path()).unwrap().count(), 0);
    }

    #[tokio::test]
    async fn record_then_replay_reproduces_the_event_stream() {
        let root = tempfile::tempdir().unwrap();

        let recorder = RecorderModel::new(
            ScriptedModel::ok(script()),
            Some(config(
                RecorderMode::Record,
                root.path(),
                Divergence::Strict,
            )),
            "test",
        );
        let recorded = drain(
            recorder
                .stream(
                    prompt("sys"),
                    tools(),
                    vec![],
                    params("S1", 0),
                    CancellationToken::new(),
                )
                .await
                .unwrap(),
        )
        .await;
        drop(recorder);

        // The replaying model must never reach the inner one.
        let replayer = RecorderModel::new(
            ScriptedModel::ok(vec![]),
            Some(config(
                RecorderMode::Replay,
                root.path(),
                Divergence::Strict,
            )),
            "test",
        );
        let replayed = drain(
            replayer
                .stream(
                    prompt("sys"),
                    tools(),
                    vec![],
                    params("S1", 0),
                    CancellationToken::new(),
                )
                .await
                .unwrap(),
        )
        .await;

        assert_eq!(format!("{replayed:?}"), format!("{recorded:?}"));
        assert_eq!(replayed.len(), 4);
    }

    #[tokio::test]
    async fn token_boundaries_survive_a_record_replay_round_trip() {
        let root = tempfile::tempdir().unwrap();
        let recorder = RecorderModel::new(
            ScriptedModel::ok(script()),
            Some(config(
                RecorderMode::Record,
                root.path(),
                Divergence::Strict,
            )),
            "test",
        );
        drain(
            recorder
                .stream(
                    prompt("sys"),
                    tools(),
                    vec![],
                    params("S1", 0),
                    CancellationToken::new(),
                )
                .await
                .unwrap(),
        )
        .await;
        drop(recorder);

        let recording = reader::load(&root.path().join("run")).unwrap();
        let texts: Vec<&str> = recording.calls[0]
            .response
            .iter()
            .filter_map(|e| match e {
                ModelEvent::TextDelta { text } => Some(text.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(texts, vec!["Hel", "lo", "!"], "deltas must not be merged");
    }

    #[tokio::test]
    async fn a_recorded_failure_replays_as_a_failure() {
        let root = tempfile::tempdir().unwrap();
        let recorder = RecorderModel::new(
            ScriptedModel::overloaded(),
            Some(config(
                RecorderMode::Record,
                root.path(),
                Divergence::Strict,
            )),
            "test",
        );
        let err = recorder
            .stream(
                prompt("sys"),
                tools(),
                vec![],
                params("S1", 0),
                CancellationToken::new(),
            )
            .await
            .err()
            .expect("expected an error");
        assert_eq!(err.kind, ModelErrorKind::Overloaded);
        drop(recorder);

        let replayer = RecorderModel::new(
            ScriptedModel::ok(script()),
            Some(config(
                RecorderMode::Replay,
                root.path(),
                Divergence::Strict,
            )),
            "test",
        );
        let replayed = replayer
            .stream(
                prompt("sys"),
                tools(),
                vec![],
                params("S1", 0),
                CancellationToken::new(),
            )
            .await;
        assert!(
            matches!(replayed, Err(ref e) if e.kind == ModelErrorKind::Overloaded),
            "a recorded overload must replay as an overload, not as a success"
        );
    }

    #[tokio::test]
    async fn divergence_names_the_field_that_moved() {
        let root = tempfile::tempdir().unwrap();
        let recorder = RecorderModel::new(
            ScriptedModel::ok(script()),
            Some(config(
                RecorderMode::Record,
                root.path(),
                Divergence::Strict,
            )),
            "test",
        );
        drain(
            recorder
                .stream(
                    prompt("original system prompt"),
                    tools(),
                    vec![],
                    params("S1", 0),
                    CancellationToken::new(),
                )
                .await
                .unwrap(),
        )
        .await;
        drop(recorder);

        let replayer = RecorderModel::new(
            ScriptedModel::ok(vec![]),
            Some(config(
                RecorderMode::Replay,
                root.path(),
                Divergence::Strict,
            )),
            "test",
        );
        let err = replayer
            .stream(
                prompt("a different system prompt"),
                tools(),
                vec![],
                params("S1", 0),
                CancellationToken::new(),
            )
            .await
            .err()
            .expect("expected an error");
        let message = err.to_string();
        assert!(
            message.contains("system[0]"),
            "the report must point at the field, got: {message}"
        );
    }

    #[tokio::test]
    async fn warn_mode_plays_the_recording_despite_divergence() {
        let root = tempfile::tempdir().unwrap();
        let recorder = RecorderModel::new(
            ScriptedModel::ok(script()),
            Some(config(
                RecorderMode::Record,
                root.path(),
                Divergence::Strict,
            )),
            "test",
        );
        drain(
            recorder
                .stream(
                    prompt("original"),
                    tools(),
                    vec![],
                    params("S1", 0),
                    CancellationToken::new(),
                )
                .await
                .unwrap(),
        )
        .await;
        drop(recorder);

        let replayer = RecorderModel::new(
            ScriptedModel::ok(vec![]),
            Some(config(RecorderMode::Replay, root.path(), Divergence::Warn)),
            "test",
        );
        let replayed = drain(
            replayer
                .stream(
                    prompt("changed"),
                    tools(),
                    vec![],
                    params("S1", 0),
                    CancellationToken::new(),
                )
                .await
                .unwrap(),
        )
        .await;
        assert_eq!(replayed.len(), 4);
    }

    #[tokio::test]
    async fn a_stream_dropped_mid_response_records_a_cancelled_outcome() {
        let root = tempfile::tempdir().unwrap();
        let recorder = RecorderModel::new(
            ScriptedModel::ok(script()),
            Some(config(
                RecorderMode::Record,
                root.path(),
                Divergence::Strict,
            )),
            "test",
        );
        {
            let mut stream = recorder
                .stream(
                    prompt("sys"),
                    tools(),
                    vec![],
                    params("S1", 0),
                    CancellationToken::new(),
                )
                .await
                .unwrap();
            let _first = stream.next().await;
        }
        drop(recorder);

        let recording = reader::load(&root.path().join("run")).unwrap();
        let end = recording.calls[0]
            .end
            .as_ref()
            .expect("call must be closed");
        assert_eq!(end.outcome, Outcome::Cancelled);
    }

    #[tokio::test]
    async fn a_stream_dropped_after_its_final_event_records_the_call_as_answered() {
        let root = tempfile::tempdir().unwrap();
        let recorder = RecorderModel::new(
            ScriptedModel::ok(script()),
            Some(config(
                RecorderMode::Record,
                root.path(),
                Divergence::Strict,
            )),
            "test",
        );
        {
            let mut stream = recorder
                .stream(
                    prompt("sys"),
                    tools(),
                    vec![],
                    params("S1", 0),
                    CancellationToken::new(),
                )
                .await
                .unwrap();
            while let Some(event) = stream.next().await {
                if matches!(event, Ok(ModelEvent::EndTurn { .. })) {
                    break;
                }
            }
        }
        drop(recorder);

        let recording = reader::load(&root.path().join("run")).unwrap();
        let end = recording.calls[0]
            .end
            .as_ref()
            .expect("call must be closed");
        assert_eq!(end.outcome, Outcome::Ok);
        assert!(end.stop_reason.is_some());
    }

    #[tokio::test]
    async fn the_request_is_on_disk_before_the_response_arrives() {
        let root = tempfile::tempdir().unwrap();
        let recorder = RecorderModel::new(
            ScriptedModel::ok(script()),
            Some(config(
                RecorderMode::Record,
                root.path(),
                Divergence::Strict,
            )),
            "test",
        );
        let _stream = recorder
            .stream(
                prompt("sys"),
                tools(),
                vec![],
                params("S1", 0),
                CancellationToken::new(),
            )
            .await
            .unwrap();

        let content = std::fs::read_to_string(root.path().join("run").join("calls.jsonl")).unwrap();
        assert!(
            content.contains(r#""type":"call""#),
            "the request must be durable before the stream is consumed"
        );
    }

    #[tokio::test]
    async fn unchanged_request_parts_are_stored_once() {
        let root = tempfile::tempdir().unwrap();
        let recorder = RecorderModel::new(
            ScriptedModel::ok(script()),
            Some(config(
                RecorderMode::Record,
                root.path(),
                Divergence::Strict,
            )),
            "test",
        );
        for step in 0..3 {
            drain(
                recorder
                    .stream(
                        prompt("stable system prompt"),
                        tools(),
                        vec![],
                        params("S1", step),
                        CancellationToken::new(),
                    )
                    .await
                    .unwrap(),
            )
            .await;
        }
        drop(recorder);

        let recording = reader::load(&root.path().join("run")).unwrap();
        assert_eq!(recording.calls.len(), 3);
        // One blob for the single system block, one for the tool table.
        let blobs = std::fs::read_dir(root.path().join("run").join("blobs"))
            .unwrap()
            .count();
        assert_eq!(blobs, 2, "identical request parts must dedup across calls");
    }

    #[tokio::test]
    async fn each_session_records_into_its_own_directory() {
        let root = tempfile::tempdir().unwrap();
        let recorder = RecorderModel::new(
            ScriptedModel::ok(script()),
            Some(RecorderConfig {
                mode: RecorderMode::Record,
                name: None,
                root: root.path().to_path_buf(),
                on_divergence: Divergence::Strict,
            }),
            "test",
        );
        for session in ["parent", "subagent"] {
            drain(
                recorder
                    .stream(
                        prompt("sys"),
                        tools(),
                        vec![],
                        params(session, 0),
                        CancellationToken::new(),
                    )
                    .await
                    .unwrap(),
            )
            .await;
        }
        drop(recorder);

        assert!(root.path().join("parent").join("calls.jsonl").exists());
        assert!(root.path().join("subagent").join("calls.jsonl").exists());
        assert_eq!(
            reader::load(&root.path().join("parent"))
                .unwrap()
                .calls
                .len(),
            1
        );
    }

    /// The header is what lets a directory of recordings be read as one tree.
    #[tokio::test]
    async fn a_sub_agents_header_names_its_parent_and_kind() {
        let root = tempfile::tempdir().unwrap();
        let recorder = RecorderModel::new(
            ScriptedModel::ok(vec![]),
            Some(RecorderConfig {
                mode: RecorderMode::Record,
                name: None,
                root: root.path().to_path_buf(),
                on_divergence: Divergence::Strict,
            }),
            "test",
        );
        let mut child = params("child", 0);
        child.origin = child
            .origin
            .map(|o| o.with_lineage(Some("parent".into()), Some("code-reviewer".into())));
        drain(
            recorder
                .stream(
                    prompt("sys"),
                    tools(),
                    vec![],
                    child,
                    CancellationToken::new(),
                )
                .await
                .unwrap(),
        )
        .await;
        drop(recorder);

        let header = reader::load(&root.path().join("child")).unwrap().header;
        assert_eq!(header.parent.as_deref(), Some("parent"));
        assert_eq!(header.agent_type.as_deref(), Some("code-reviewer"));
    }

    /// An auxiliary call belongs to the session that made it, not to a shared
    /// name that concurrent sessions would then truncate out from under it.
    #[tokio::test]
    async fn an_auxiliary_call_is_filed_under_its_own_session() {
        let root = tempfile::tempdir().unwrap();
        let recorder = RecorderModel::new(
            ScriptedModel::ok(vec![]),
            Some(RecorderConfig {
                mode: RecorderMode::Record,
                name: None,
                root: root.path().to_path_buf(),
                on_divergence: Divergence::Strict,
            }),
            "test",
        );
        let mut aux = params("S9", 0);
        aux.origin = Some(CallOrigin::auxiliary("S9", "compact"));
        drain(
            recorder
                .stream(
                    prompt("sys"),
                    tools(),
                    vec![],
                    aux,
                    CancellationToken::new(),
                )
                .await
                .unwrap(),
        )
        .await;
        drop(recorder);

        assert!(
            !root.path().join("unattributed").exists(),
            "auxiliary calls must not land in a shared directory"
        );
        let call = &reader::load(&root.path().join("S9")).unwrap().calls[0].request;
        assert_eq!(call.purpose.as_deref(), Some("compact"));
        assert_eq!(
            (call.turn, call.step),
            (0, 0),
            "a call outside a turn has no turn coordinates to report"
        );
    }

    /// A parent and its sub-agent recording under one name interleave on disk,
    /// and the order they interleave in is scheduling luck. Replay must hand
    /// each session its own calls in its own order, not the file's order.
    #[tokio::test]
    async fn interleaved_sessions_replay_as_separate_slices() {
        let root = tempfile::tempdir().unwrap();
        let config = |mode| RecorderConfig {
            mode,
            // One shared name: this is the setup that interleaves.
            name: Some("run".into()),
            root: root.path().to_path_buf(),
            on_divergence: Divergence::Strict,
        };

        let recorder = RecorderModel::new(
            ScriptedModel::ok(vec![ModelEvent::TextDelta { text: "x".into() }]),
            Some(config(RecorderMode::Record)),
            "test",
        );
        // parent, child, child, parent — the child's calls land between the
        // parent's, exactly as a real delegation would.
        for (session, step) in [("P", 0), ("C", 0), ("C", 1), ("P", 1)] {
            let mut p = params(session, step);
            p.origin = Some(CallOrigin::turn(session, 0, step));
            drain(
                recorder
                    .stream(prompt("sys"), tools(), vec![], p, CancellationToken::new())
                    .await
                    .unwrap(),
            )
            .await;
        }
        drop(recorder);

        let recording = reader::load(&root.path().join("run")).unwrap();
        assert_eq!(recording.calls.len(), 4);

        // Replaying the child first must still get the child's two calls, even
        // though the parent's call is first in the file.
        let replayer = RecorderModel::new(
            ScriptedModel::ok(vec![]),
            Some(config(RecorderMode::Replay)),
            "test",
        );
        for step in [0, 1] {
            let mut p = params("C", step);
            p.origin = Some(CallOrigin::turn("C", 0, step));
            let events = drain(
                replayer
                    .stream(prompt("sys"), tools(), vec![], p, CancellationToken::new())
                    .await
                    .unwrap(),
            )
            .await;
            assert_eq!(events.len(), 1, "child call #{step} should replay");
        }
        // A third child call is one more than the child ever made.
        let mut extra = params("C", 2);
        extra.origin = Some(CallOrigin::turn("C", 0, 2));
        let Err(err) = replayer
            .stream(
                prompt("sys"),
                tools(),
                vec![],
                extra,
                CancellationToken::new(),
            )
            .await
        else {
            panic!("a third child call has nothing to replay against")
        };
        assert!(
            err.to_string()
                .contains("2 conversation call(s) for session"),
            "the error should name the session that ran out: {err}"
        );
    }

    /// Live session ids are freshly random every run, so the ids in a recording
    /// are never the ids of the run replaying it. Binding therefore falls back
    /// to first-call order — and since that is the *production* path, exact-id
    /// matching alone proving out is not enough.
    #[tokio::test]
    async fn sessions_with_new_ids_bind_in_first_call_order() {
        let root = tempfile::tempdir().unwrap();
        let config = |mode| RecorderConfig {
            mode,
            name: Some("run".into()),
            root: root.path().to_path_buf(),
            on_divergence: Divergence::Warn,
        };

        let recorder = RecorderModel::new(
            ScriptedModel::ok(vec![ModelEvent::TextDelta { text: "x".into() }]),
            Some(config(RecorderMode::Record)),
            "test",
        );
        // Parent calls first, then its child — the order a live run guarantees.
        for (session, step) in [("REC-parent", 0), ("REC-child", 0), ("REC-parent", 1)] {
            let mut p = params(session, step);
            p.origin = Some(CallOrigin::turn(session, 0, step));
            drain(
                recorder
                    .stream(prompt("sys"), tools(), vec![], p, CancellationToken::new())
                    .await
                    .unwrap(),
            )
            .await;
        }
        drop(recorder);

        let replayer = RecorderModel::new(
            ScriptedModel::ok(vec![]),
            Some(config(RecorderMode::Replay)),
            "test",
        );
        // Entirely different ids, same order of first call.
        let mut consumed = Vec::new();
        for (session, step) in [("LIVE-a", 0), ("LIVE-b", 0), ("LIVE-a", 1)] {
            let mut p = params(session, step);
            p.origin = Some(CallOrigin::turn(session, 0, step));
            let events = drain(
                replayer
                    .stream(prompt("sys"), tools(), vec![], p, CancellationToken::new())
                    .await
                    .unwrap(),
            )
            .await;
            consumed.push(events.len());
        }
        assert_eq!(
            consumed,
            vec![1, 1, 1],
            "each live session should have replayed its counterpart's calls"
        );

        // `LIVE-a` claimed the parent (2 calls), so a third call on it is one
        // past the end — proof it bound to the parent and not the child.
        let mut extra = params("LIVE-a", 2);
        extra.origin = Some(CallOrigin::turn("LIVE-a", 0, 2));
        let Err(err) = replayer
            .stream(
                prompt("sys"),
                tools(),
                vec![],
                extra,
                CancellationToken::new(),
            )
            .await
        else {
            panic!("the parent's slice holds only two calls")
        };
        assert!(
            err.to_string().contains("REC-parent"),
            "the error should name the recorded session it bound to: {err}"
        );
    }

    /// An override edits the replayed response without touching the recording,
    /// which is what makes "what if the model had said X" a reviewable file
    /// rather than a destroyed fixture.
    #[tokio::test]
    async fn an_override_replaces_a_response_and_leaves_the_recording_alone() {
        let root = tempfile::tempdir().unwrap();
        let config = |mode| RecorderConfig {
            mode,
            name: Some("run".into()),
            root: root.path().to_path_buf(),
            on_divergence: Divergence::Strict,
        };

        let recorder = RecorderModel::new(
            ScriptedModel::ok(vec![ModelEvent::TextDelta {
                text: "recorded".into(),
            }]),
            Some(config(RecorderMode::Record)),
            "test",
        );
        drain(
            recorder
                .stream(
                    prompt("sys"),
                    tools(),
                    vec![],
                    params("S1", 0),
                    CancellationToken::new(),
                )
                .await
                .unwrap(),
        )
        .await;
        drop(recorder);

        let before = std::fs::read_to_string(root.path().join("run").join("calls.jsonl")).unwrap();
        std::fs::write(
            root.path().join("run").join(override_doc::OVERRIDE_FILE),
            r#"{"patches":[{"at":0,"response":[{"kind":"text_delta","text":"edited"}]}]}"#,
        )
        .unwrap();

        let replayer = RecorderModel::new(
            ScriptedModel::ok(vec![]),
            Some(config(RecorderMode::Replay)),
            "test",
        );
        let events = drain(
            replayer
                .stream(
                    prompt("sys"),
                    tools(),
                    vec![],
                    params("S1", 0),
                    CancellationToken::new(),
                )
                .await
                .unwrap(),
        )
        .await;
        assert_eq!(
            format!("{events:?}"),
            format!(
                "{:?}",
                vec![ModelEvent::TextDelta {
                    text: "edited".into()
                }]
            )
        );
        assert_eq!(
            std::fs::read_to_string(root.path().join("run").join("calls.jsonl")).unwrap(),
            before,
            "the recording itself must be untouched"
        );
    }

    /// A run that stops short of the recording passes every per-call check.
    /// The only place to notice is at the end.
    #[tokio::test]
    async fn a_replay_that_stops_short_is_reported_at_the_end() {
        let root = tempfile::tempdir().unwrap();
        let config = |mode| RecorderConfig {
            mode,
            name: Some("run".into()),
            root: root.path().to_path_buf(),
            on_divergence: Divergence::Strict,
        };

        let recorder = RecorderModel::new(
            ScriptedModel::ok(vec![]),
            Some(config(RecorderMode::Record)),
            "test",
        );
        for step in [0, 1] {
            drain(
                recorder
                    .stream(
                        prompt("sys"),
                        tools(),
                        vec![],
                        params("S1", step),
                        CancellationToken::new(),
                    )
                    .await
                    .unwrap(),
            )
            .await;
        }
        drop(recorder);

        let shared = Recorder::new();
        let replayer = RecorderModel::shared(
            ScriptedModel::ok(vec![]),
            Some(config(RecorderMode::Replay)),
            "test",
            shared.clone(),
        );
        // Only one of the two recorded calls.
        drain(
            replayer
                .stream(
                    prompt("sys"),
                    tools(),
                    vec![],
                    params("S1", 0),
                    CancellationToken::new(),
                )
                .await
                .unwrap(),
        )
        .await;

        let unconsumed = shared.unconsumed();
        assert_eq!(unconsumed.len(), 1, "got {unconsumed:?}");
        assert!(
            unconsumed[0].contains("replayed 1 of 2"),
            "got {unconsumed:?}"
        );
    }

    /// A call that cannot name a session has no recording to belong to, and
    /// must pass straight through rather than inventing one.
    #[tokio::test]
    async fn a_call_with_no_session_is_not_recorded() {
        let root = tempfile::tempdir().unwrap();
        let recorder = RecorderModel::new(
            ScriptedModel::ok(vec![]),
            Some(RecorderConfig {
                mode: RecorderMode::Record,
                name: None,
                root: root.path().to_path_buf(),
                on_divergence: Divergence::Strict,
            }),
            "test",
        );
        let mut anonymous = params("ignored", 0);
        anonymous.origin = None;
        drain(
            recorder
                .stream(
                    prompt("sys"),
                    tools(),
                    vec![],
                    anonymous,
                    CancellationToken::new(),
                )
                .await
                .unwrap(),
        )
        .await;
        drop(recorder);

        assert_eq!(
            std::fs::read_dir(root.path()).unwrap().count(),
            0,
            "nothing should have been written"
        );
    }

    #[tokio::test]
    async fn replaying_past_the_end_of_a_recording_says_so() {
        let root = tempfile::tempdir().unwrap();
        let recorder = RecorderModel::new(
            ScriptedModel::ok(script()),
            Some(config(
                RecorderMode::Record,
                root.path(),
                Divergence::Strict,
            )),
            "test",
        );
        drain(
            recorder
                .stream(
                    prompt("sys"),
                    tools(),
                    vec![],
                    params("S1", 0),
                    CancellationToken::new(),
                )
                .await
                .unwrap(),
        )
        .await;
        drop(recorder);

        let replayer = RecorderModel::new(
            ScriptedModel::ok(vec![]),
            Some(config(
                RecorderMode::Replay,
                root.path(),
                Divergence::Strict,
            )),
            "test",
        );
        for _ in 0..1 {
            drain(
                replayer
                    .stream(
                        prompt("sys"),
                        tools(),
                        vec![],
                        params("S1", 0),
                        CancellationToken::new(),
                    )
                    .await
                    .unwrap(),
            )
            .await;
        }
        let err = replayer
            .stream(
                prompt("sys"),
                tools(),
                vec![],
                params("S1", 1),
                CancellationToken::new(),
            )
            .await
            .err()
            .expect("expected an error");
        assert!(err.to_string().contains("asked for #2"), "{err}");
    }

    fn title_params(session: &str) -> StreamParams {
        let mut p = params(session, 0);
        p.origin = Some(CallOrigin::auxiliary(
            session,
            base::interface::model::call_purpose::TITLE,
        ));
        p
    }

    fn text(events: &[ModelEvent]) -> String {
        events
            .iter()
            .filter_map(|e| match e {
                ModelEvent::TextDelta { text } => Some(text.as_str()),
                _ => None,
            })
            .collect()
    }

    /// Each call answered by a model of its own, all into one recording.
    async fn record_calls(root: &std::path::Path, calls: Vec<(StreamParams, &str)>) {
        record_prompted_calls(
            root,
            calls
                .into_iter()
                .map(|(params, answer)| (params, "sys", answer))
                .collect(),
        )
        .await;
    }

    async fn record_prompted_calls(root: &std::path::Path, calls: Vec<(StreamParams, &str, &str)>) {
        let shared = Recorder::new();
        for (params, system, answer) in calls {
            let recorder = RecorderModel::shared(
                ScriptedModel::ok(vec![ModelEvent::TextDelta {
                    text: answer.into(),
                }]),
                Some(config(RecorderMode::Record, root, Divergence::Strict)),
                "test",
                shared.clone(),
            );
            drain(
                recorder
                    .stream(
                        prompt(system),
                        tools(),
                        vec![],
                        params,
                        CancellationToken::new(),
                    )
                    .await
                    .unwrap(),
            )
            .await;
        }
    }

    /// Naming is not part of the conversation: a recording made without it
    /// replays a run that names, and even a strict replay only reports the
    /// naming call as absent instead of as a divergence or an overshoot.
    #[tokio::test]
    async fn a_title_call_the_recording_lacks_is_not_recorded_even_under_strict_replay() {
        let root = tempfile::tempdir().unwrap();
        record_calls(root.path(), vec![(params("S1", 0), "answer")]).await;

        let shared = Recorder::new();
        let replayer = RecorderModel::shared(
            ScriptedModel::overloaded(),
            Some(config(
                RecorderMode::Replay,
                root.path(),
                Divergence::Strict,
            )),
            "test",
            shared.clone(),
        );
        let turn = drain(
            replayer
                .stream(
                    prompt("sys"),
                    tools(),
                    vec![],
                    params("S1", 0),
                    CancellationToken::new(),
                )
                .await
                .unwrap(),
        )
        .await;
        assert_eq!(text(&turn), "answer");

        match replayer
            .stream(
                prompt("sys"),
                tools(),
                vec![],
                title_params("S1"),
                CancellationToken::new(),
            )
            .await
        {
            Err(e) if e.kind == ModelErrorKind::NotRecorded => {}
            Err(e) => panic!("expected NotRecorded, got {e}"),
            Ok(_) => panic!("a title call the recording lacks was answered"),
        }
        assert!(shared.unconsumed().is_empty(), "{:?}", shared.unconsumed());
    }

    #[tokio::test]
    async fn a_recorded_title_call_replays_in_its_place() {
        let root = tempfile::tempdir().unwrap();
        record_calls(
            root.path(),
            vec![
                (params("S1", 0), "answer"),
                (title_params("S1"), "a title"),
                (params("S1", 1), "second"),
            ],
        )
        .await;
        let calls = reader::load(&root.path().join("run")).unwrap().calls;
        assert_eq!(calls[1].request.purpose.as_deref(), Some("title"));

        let shared = Recorder::new();
        let replayer = RecorderModel::shared(
            ScriptedModel::overloaded(),
            Some(config(
                RecorderMode::Replay,
                root.path(),
                Divergence::Strict,
            )),
            "test",
            shared.clone(),
        );
        let mut answers = Vec::new();
        for params in [params("S1", 0), title_params("S1"), params("S1", 1)] {
            let events = drain(
                replayer
                    .stream(
                        prompt("sys"),
                        tools(),
                        vec![],
                        params,
                        CancellationToken::new(),
                    )
                    .await
                    .unwrap(),
            )
            .await;
            answers.push(text(&events));
        }
        assert_eq!(answers, ["answer", "a title", "second"]);
        assert!(shared.unconsumed().is_empty(), "{:?}", shared.unconsumed());
    }

    /// The other direction: a run that does not name is not handed the
    /// recorded title as the answer to its next call, and is not reported as
    /// having stopped short for leaving it unasked.
    #[tokio::test]
    async fn a_recorded_title_call_the_run_does_not_ask_for_is_passed_over() {
        let root = tempfile::tempdir().unwrap();
        record_calls(
            root.path(),
            vec![
                (params("S1", 0), "answer"),
                (title_params("S1"), "a title"),
                (params("S1", 1), "second"),
                (title_params("S1"), "a late title"),
            ],
        )
        .await;

        let shared = Recorder::new();
        let replayer = RecorderModel::shared(
            ScriptedModel::overloaded(),
            Some(config(
                RecorderMode::Replay,
                root.path(),
                Divergence::Strict,
            )),
            "test",
            shared.clone(),
        );
        let mut answers = Vec::new();
        for step in [0, 1] {
            let events = drain(
                replayer
                    .stream(
                        prompt("sys"),
                        tools(),
                        vec![],
                        params("S1", step),
                        CancellationToken::new(),
                    )
                    .await
                    .unwrap(),
            )
            .await;
            answers.push(text(&events));
        }
        assert_eq!(answers, ["answer", "second"]);
        assert!(shared.unconsumed().is_empty(), "{:?}", shared.unconsumed());
    }

    fn aux_params(session: &str, purpose: &str) -> StreamParams {
        let mut p = params(session, 0);
        p.origin = Some(CallOrigin::auxiliary(session, purpose));
        p
    }

    /// A strict replayer whose inner model would answer `"live"` — a replay
    /// that reaches it shows up in the answer.
    fn strict_replayer(root: &std::path::Path, shared: Arc<Recorder>) -> RecorderModel {
        RecorderModel::shared(
            ScriptedModel::ok(vec![ModelEvent::TextDelta {
                text: "live".into(),
            }]),
            Some(config(RecorderMode::Replay, root, Divergence::Strict)),
            "test",
            shared,
        )
    }

    async fn ask(
        replayer: &RecorderModel,
        system: &str,
        params: StreamParams,
    ) -> Result<String, ModelError> {
        let stream = replayer
            .stream(
                prompt(system),
                tools(),
                vec![],
                params,
                CancellationToken::new(),
            )
            .await?;
        Ok(text(&drain(stream).await))
    }

    /// Memory extraction runs in the background, so its call can land between
    /// a turn and that turn's naming call. The naming call still finds its
    /// recording, and the next turn is not handed the extraction's answer.
    #[tokio::test]
    async fn a_title_call_recorded_after_a_memory_extraction_replays_from_the_recording() {
        let root = tempfile::tempdir().unwrap();
        record_calls(
            root.path(),
            vec![
                (params("S1", 0), "answer"),
                (aux_params("S1", call_purpose::MEMORY), "memories"),
                (title_params("S1"), "a title"),
                (params("S1", 1), "second"),
            ],
        )
        .await;

        let shared = Recorder::new();
        let replayer = strict_replayer(root.path(), shared.clone());
        let mut answers = Vec::new();
        for params in [
            params("S1", 0),
            title_params("S1"),
            params("S1", 1),
            aux_params("S1", call_purpose::MEMORY),
        ] {
            answers.push(ask(&replayer, "sys", params).await.unwrap());
        }
        assert_eq!(answers, ["answer", "a title", "second", "memories"]);
        assert!(shared.unconsumed().is_empty(), "{:?}", shared.unconsumed());
    }

    #[tokio::test]
    async fn auxiliary_calls_replayed_in_another_order_each_get_their_own_response() {
        let root = tempfile::tempdir().unwrap();
        record_calls(
            root.path(),
            vec![
                (aux_params("S1", call_purpose::MEMORY), "first memories"),
                (params("S1", 0), "answer"),
                (aux_params("S1", call_purpose::COMPACT), "summary"),
                (aux_params("S1", call_purpose::MEMORY), "second memories"),
                (title_params("S1"), "a title"),
            ],
        )
        .await;

        let shared = Recorder::new();
        let replayer = strict_replayer(root.path(), shared.clone());
        let mut answers = Vec::new();
        for params in [
            title_params("S1"),
            aux_params("S1", call_purpose::COMPACT),
            params("S1", 0),
            aux_params("S1", call_purpose::MEMORY),
            aux_params("S1", call_purpose::MEMORY),
        ] {
            answers.push(ask(&replayer, "sys", params).await.unwrap());
        }
        assert_eq!(
            answers,
            [
                "a title",
                "summary",
                "answer",
                "first memories",
                "second memories"
            ]
        );
        assert!(shared.unconsumed().is_empty(), "{:?}", shared.unconsumed());
    }

    #[tokio::test]
    async fn conversation_calls_out_of_their_recorded_order_diverge_under_strict_replay() {
        let root = tempfile::tempdir().unwrap();
        record_prompted_calls(
            root.path(),
            vec![
                (params("S1", 0), "first prompt", "first"),
                (aux_params("S1", call_purpose::MEMORY), "sys", "memories"),
                (params("S1", 1), "second prompt", "second"),
            ],
        )
        .await;

        let replayer = strict_replayer(root.path(), Recorder::new());
        let err = ask(&replayer, "second prompt", params("S1", 1))
            .await
            .expect_err("a conversation call out of order must diverge");
        assert!(
            err.to_string().contains("diverges") && err.to_string().contains("system[0]"),
            "{err}"
        );
    }

    #[tokio::test]
    async fn an_auxiliary_call_the_recording_lacks_fails_without_reaching_the_model() {
        let root = tempfile::tempdir().unwrap();
        record_calls(
            root.path(),
            vec![(params("S1", 0), "answer"), (params("S1", 1), "second")],
        )
        .await;

        let replayer = strict_replayer(root.path(), Recorder::new());
        assert_eq!(
            ask(&replayer, "sys", params("S1", 0)).await.unwrap(),
            "answer"
        );
        match ask(&replayer, "sys", aux_params("S1", call_purpose::MEMORY)).await {
            Err(e) if e.kind == ModelErrorKind::Protocol => {
                assert!(e.message.contains("\"memory\""), "{}", e.message)
            }
            Err(e) => panic!("expected an internal error, got {e}"),
            Ok(answer) => panic!("a memory call the recording lacks was answered: {answer:?}"),
        }
        assert_eq!(
            ask(&replayer, "sys", params("S1", 1)).await.unwrap(),
            "second",
            "the failed auxiliary call must not take the next conversation call"
        );
    }

    #[tokio::test]
    async fn a_recorded_memory_extraction_the_run_does_not_ask_for_is_reported_at_the_end() {
        let root = tempfile::tempdir().unwrap();
        record_calls(
            root.path(),
            vec![
                (params("S1", 0), "answer"),
                (aux_params("S1", call_purpose::MEMORY), "memories"),
            ],
        )
        .await;

        let shared = Recorder::new();
        let replayer = strict_replayer(root.path(), shared.clone());
        assert_eq!(
            ask(&replayer, "sys", params("S1", 0)).await.unwrap(),
            "answer"
        );
        let unconsumed = shared.unconsumed();
        assert_eq!(unconsumed.len(), 1, "got {unconsumed:?}");
        assert!(
            unconsumed[0].contains("replayed 1 of 2"),
            "got {unconsumed:?}"
        );
    }
}