agentty 0.15.0

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
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
//! Session loading and derived snapshot attributes from persisted rows.

use std::collections::{BTreeMap, HashMap};
use std::path::Path;

use ag_git::GitClient;

use super::{draft, session_folder};
use crate::app::{SessionManager, orchestration};
use crate::domain::agent::{
    AgentModel, AgentSelection, ReasoningLevel, SpeedMode, parse_persisted_session_agent_model,
};
use crate::domain::question::QuestionItem;
use crate::domain::session::{
    DailyActivity, QueuedMessage, ReviewRequest, ReviewRequestSummary, Session, SessionDiffState,
    SessionDiffStats, SessionFollowUpTask, SessionHandles, SessionId, SessionRole, SessionSize,
    SessionStats, Status, activity_day_key_with_offset,
};
use crate::domain::session_message::{SessionMessage, SessionMessageKind, SessionTranscript};
use crate::domain::transient_message::TransientMessageStore;
use crate::infra::clock::Clock;
use crate::infra::db::{
    AppRepositories, DbError, SessionDetailRow, SessionListRow, SessionMessageRow,
};
use crate::infra::fs::FsClient;

/// Inputs required to load one project's session and activity snapshots.
pub(crate) struct SessionLoadInput<'a> {
    /// Project identifier used to scope persisted session rows.
    pub(crate) active_project_id: i64,
    /// Session whose transcript-scale details should be loaded.
    pub(crate) active_session_id: Option<&'a str>,
    /// Root directory containing Agentty-managed session worktrees.
    pub(crate) base: &'a Path,
    /// Clock used to resolve the local offset for each activity event.
    pub(crate) clock: &'a dyn Clock,
    /// Repository bundle used to load persisted session state.
    pub(crate) db: &'a AppRepositories,
    /// Filesystem boundary used to check session worktree availability.
    pub(crate) fs_client: &'a dyn FsClient,
    /// Active project directory used to derive display metadata.
    pub(crate) working_dir: &'a Path,
}

/// Mutable context threaded through the per-row session-load helper.
///
/// Keeps the per-row helper signature short while still letting it append
/// loaded sessions, mutate handles, and update worktree availability.
struct LoadSessionContext<'a> {
    active_session_id: Option<&'a str>,
    base: &'a Path,
    db: &'a AppRepositories,
    fs_client: &'a dyn FsClient,
    handles: &'a mut HashMap<SessionId, SessionHandles>,
    orchestration_metadata: &'a HashMap<String, orchestration::OrchestrationSessionMetadata>,
    project_name: &'a str,
    session_worktree_availability: &'a mut HashMap<SessionId, bool>,
    sessions: &'a mut Vec<Session>,
}

/// Precomputed fields needed to assemble one loaded session snapshot.
struct LoadedSessionInput {
    controller_session_id: Option<SessionId>,
    draft_attachments: Vec<crate::domain::turn_prompt::TurnPromptAttachment>,
    follow_up_tasks: Vec<SessionFollowUpTask>,
    folder: std::path::PathBuf,
    parent_session_id: Option<SessionId>,
    orchestration_progress: Option<String>,
    project_name: String,
    reasoning_level_override: Option<ReasoningLevel>,
    review_request: Option<ReviewRequest>,
    role: SessionRole,
    row: SessionListRow,
    session_agent: AgentSelection,
    session_id: SessionId,
    session_prompt: String,
    session_queued_messages: Vec<QueuedMessage>,
    session_questions: Vec<QuestionItem>,
    session_summary: Option<String>,
    session_status: Status,
    session_transcript: Option<SessionTranscript>,
    size: SessionSize,
    speed_mode: SpeedMode,
}

/// Migrates every non-terminal session across all saved projects away from
/// retired persisted model ids.
///
/// Query and persistence failures are best-effort so startup remains usable
/// with a degraded database. Individual UI and API loads repeat the same
/// migration for the row they read.
pub(crate) async fn migrate_active_sessions_off_retired_models(db: &AppRepositories) {
    let Ok(rows) = db.sessions().load_active_session_agent_models().await else {
        return;
    };

    for row in rows {
        let session_status = row.status.parse::<Status>().unwrap_or(Status::Done);
        migrate_session_off_retired_model(db, &row.id, &row.agent, &row.model, session_status)
            .await;
    }
}

/// Resolves one persisted provider/model pair and persists the replacement
/// when its model is retired and the session is still active.
///
/// Terminal rows (`Merged`, `Done`, `Canceled`) keep the retired model id in
/// the database as a historical record. Persistence failures are ignored so
/// session reads still return the in-memory replacement.
pub(crate) async fn migrate_session_off_retired_model(
    db: &AppRepositories,
    session_id: &str,
    persisted_agent: &str,
    persisted_model: &str,
    session_status: Status,
) -> AgentSelection {
    let session_agent = parse_persisted_session_agent_model(Some(persisted_agent), persisted_model);
    if matches!(
        session_status,
        Status::Merged | Status::Done | Status::Canceled
    ) || AgentModel::retired_replacement(persisted_model).is_none()
    {
        return session_agent;
    }

    let session_agent_kind = session_agent.kind().to_string();
    db.sessions()
        .update_active_session_agent_model(
            session_id,
            &session_agent_kind,
            session_agent.model().as_str(),
        )
        .await
        .ok();

    session_agent
}

impl SessionManager {
    /// Loads session models from the database using the provided filesystem
    /// boundary to decide which session folders exist.
    ///
    /// Existing handles are reused in place to preserve `Arc` identity so
    /// that background workers holding cloned references continue to work.
    ///
    /// When a handle already exists, live handle output is treated as
    /// authoritative for the returned in-memory snapshot to avoid clobbering
    /// fresh runtime output with stale persisted rows. Active statuses are also
    /// preserved from live handles, while terminal persisted statuses (`Done`,
    /// `Canceled`) override stale in-memory status.
    ///
    /// Retired persisted model ids are upgraded to their current replacement
    /// models while rows are loaded. Sessions that are still active also have
    /// the replacement persisted so future turns run on the current model;
    /// terminal sessions keep their retired model id in the database as a
    /// historical record.
    ///
    /// New handles are inserted for sessions that don't have entries yet.
    ///
    /// Transcript-scale fields are loaded only for `active_session_id`; other
    /// rows receive empty detail fields until the session is opened.
    ///
    /// Returns loaded sessions, local-day activity counts aggregated from
    /// persisted session-creation activity history, and cached worktree
    /// availability keyed by session id.
    pub(crate) async fn load_sessions_with_fs_client(
        input: SessionLoadInput<'_>,
        handles: &mut HashMap<SessionId, SessionHandles>,
    ) -> (Vec<Session>, Vec<DailyActivity>, HashMap<SessionId, bool>) {
        Self::try_load_sessions_with_fs_client(input, handles)
            .await
            .unwrap_or_default()
    }

    /// Loads session snapshots while preserving a session-list read failure.
    ///
    /// Refresh callers use this fallible path so a transient database error
    /// cannot be mistaken for an empty project and tear down live workers.
    ///
    /// # Errors
    /// Returns an error when the project's session rows cannot be loaded.
    pub(crate) async fn try_load_sessions_with_fs_client(
        input: SessionLoadInput<'_>,
        handles: &mut HashMap<SessionId, SessionHandles>,
    ) -> Result<(Vec<Session>, Vec<DailyActivity>, HashMap<SessionId, bool>), DbError> {
        let SessionLoadInput {
            active_project_id,
            active_session_id,
            base,
            clock,
            db,
            fs_client,
            working_dir,
        } = input;
        let project_name = working_dir
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or_default()
            .to_string();

        let db_rows = db
            .sessions()
            .load_sessions_for_project(active_project_id)
            .await?;
        let activity_timestamps = db
            .activity()
            .load_session_activity_timestamps()
            .await
            .unwrap_or_default();
        let stats_activity = Self::daily_activity_from_timestamps(activity_timestamps, clock);
        let orchestration_metadata =
            orchestration::session_metadata_for_project(db, active_project_id).await;
        let mut sessions: Vec<Session> = Vec::new();
        let mut session_worktree_availability = HashMap::new();

        let mut load_context = LoadSessionContext {
            base,
            db,
            project_name: &project_name,
            handles,
            fs_client,
            active_session_id,
            orchestration_metadata: &orchestration_metadata,
            sessions: &mut sessions,
            session_worktree_availability: &mut session_worktree_availability,
        };
        for row in db_rows {
            Self::push_loaded_session_row(&mut load_context, row).await;
        }

        Ok((sessions, stats_activity, session_worktree_availability))
    }

    /// Aggregates persisted activity timestamps using the clock-provided
    /// offset active for each event.
    fn daily_activity_from_timestamps(
        timestamps: Vec<i64>,
        clock: &dyn Clock,
    ) -> Vec<DailyActivity> {
        let mut activity_by_day = BTreeMap::<i64, u32>::new();
        for timestamp_seconds in timestamps {
            let utc_offset_seconds = clock.local_utc_offset_seconds(timestamp_seconds);
            let day_key = activity_day_key_with_offset(timestamp_seconds, utc_offset_seconds);
            let session_count = activity_by_day.entry(day_key).or_default();
            *session_count = session_count.saturating_add(1);
        }

        activity_by_day
            .into_iter()
            .map(|(day_key, session_count)| DailyActivity {
                day_key,
                session_count,
            })
            .collect()
    }

    /// Loads one persisted session row into `sessions`, reusing existing
    /// handles when present and registering a new handle otherwise.
    async fn push_loaded_session_row(
        load_context: &mut LoadSessionContext<'_>,
        row: SessionListRow,
    ) {
        let LoadSessionContext {
            base,
            db,
            project_name,
            handles,
            orchestration_metadata,
            fs_client,
            active_session_id,
            sessions,
            session_worktree_availability,
        } = load_context;
        let session_id = SessionId::from(row.id.clone());
        let folder = session_folder(base, &session_id);
        let persisted_status = row.status.parse::<Status>().unwrap_or(Status::Done);
        let persisted_size = row.size.parse::<SessionSize>().unwrap_or_default();
        let has_session_folder = fs_client.is_dir(folder.clone());
        let live_handle_status = handles
            .get(&session_id)
            .and_then(|existing| existing.status.lock().ok().map(|status| *status));

        if should_skip_missing_folder_session(
            has_session_folder,
            row.is_draft,
            persisted_status,
            live_handle_status,
        ) {
            return;
        }
        session_worktree_availability.insert(session_id.clone(), has_session_folder);

        let (session_detail, loaded_transcript) =
            load_active_session_detail(db, *active_session_id, &row.id).await;
        let (session_status, session_transcript) =
            if let Some(existing_handle) = handles.get(&session_id) {
                status_and_transcript_from_existing_handle(
                    existing_handle,
                    persisted_status,
                    loaded_transcript.as_ref(),
                )
            } else {
                let transcript = insert_loaded_session_handle(
                    handles,
                    session_id.clone(),
                    persisted_status,
                    loaded_transcript,
                );

                (persisted_status, transcript)
            };
        let session_agent =
            migrate_session_off_retired_model(db, &row.id, &row.agent, &row.model, session_status)
                .await;
        let review_request = parse_review_request(&row);
        let draft_attachments =
            draft::load_staged_draft_attachments(*fs_client, base, &session_id).await;
        let questions = session_detail
            .as_ref()
            .and_then(|detail| detail.questions.as_deref())
            .and_then(parse_questions_json)
            .unwrap_or_default();
        let reasoning_level_override = row
            .reasoning_level_override
            .as_deref()
            .and_then(|value| value.parse::<ReasoningLevel>().ok());
        let speed_mode = row.speed_mode.parse::<SpeedMode>().unwrap_or_default();
        let session_queued_messages = handles
            .get(&session_id)
            .map(SessionHandles::queued_message_snapshot)
            .unwrap_or_default();
        let (role, orchestration_metadata) =
            Self::loaded_orchestration_metadata(&row, orchestration_metadata);
        sessions.push(Self::build_loaded_session(LoadedSessionInput {
            controller_session_id: orchestration_metadata.controller_session_id,
            draft_attachments,
            follow_up_tasks: Vec::new(),
            folder,
            parent_session_id: row.parent_session_id.clone().map(SessionId::from),
            orchestration_progress: orchestration_metadata.progress,
            project_name: (*project_name).to_string(),
            reasoning_level_override,
            review_request,
            role,
            row,
            session_agent,
            session_id,
            session_prompt: session_detail
                .as_ref()
                .map(|detail| detail.prompt.clone())
                .unwrap_or_default(),
            session_queued_messages,
            session_questions: questions,
            session_summary: session_detail.and_then(|detail| detail.summary),
            session_status,
            session_transcript,
            size: persisted_size,
            speed_mode,
        }));
    }

    fn loaded_orchestration_metadata(
        row: &SessionListRow,
        metadata: &HashMap<String, orchestration::OrchestrationSessionMetadata>,
    ) -> (SessionRole, orchestration::OrchestrationSessionMetadata) {
        let role = row
            .role
            .as_deref()
            .and_then(|value| value.parse::<SessionRole>().ok())
            .unwrap_or_default();
        let metadata = metadata.get(&row.id).cloned().unwrap_or_default();

        (role, metadata)
    }

    /// Computes diff-derived session metadata from one worktree folder using
    /// the injected filesystem and Git boundaries.
    ///
    /// Missing folders and Git failures return [`SessionDiffStats::Unknown`]
    /// so callers retain diagnostic diff access without overwriting the last
    /// known line totals.
    pub(crate) async fn session_diff_stats_for_folder(
        fs_client: &dyn FsClient,
        git_client: &dyn GitClient,
        folder: &Path,
        base_branch: &str,
    ) -> SessionDiffStats {
        if !fs_client.is_dir(folder.to_path_buf()) {
            return SessionDiffStats::Unknown;
        }

        let folder = folder.to_path_buf();
        let base_branch = base_branch.to_string();
        let Ok(diff) = git_client.diff(folder, base_branch).await else {
            return SessionDiffStats::Unknown;
        };

        SessionDiffStats::from_diff(&diff)
    }

    /// Loads transcript-scale detail for one session into the in-memory
    /// snapshot and runtime handles when the user opens that session.
    pub(crate) async fn load_session_detail_into_state(
        &mut self,
        db: &AppRepositories,
        session_id: &str,
    ) {
        let Some(detail) = db
            .sessions()
            .load_session_detail(session_id)
            .await
            .ok()
            .flatten()
        else {
            return;
        };
        let Ok(transcript) = load_session_transcript(db, session_id).await else {
            return;
        };

        self.apply_session_detail(session_id, detail, transcript);
    }

    /// Builds one in-memory session snapshot from a database row plus the
    /// transient fields computed during reload.
    fn build_loaded_session(input: LoadedSessionInput) -> Session {
        let mut session = Session {
            agent: input.session_agent,
            base_branch: input.row.base_branch,
            created_at: input.row.created_at,
            controller_session_id: input.controller_session_id,
            draft_attachments: input.draft_attachments,
            folder: input.folder,
            follow_up_tasks: input.follow_up_tasks,
            id: input.session_id,
            in_progress_started_at: input.row.in_progress_started_at,
            in_progress_total_seconds: input.row.in_progress_total_seconds,
            is_draft: input.row.is_draft,
            orchestration_progress: input.orchestration_progress,
            parent_session_id: input.parent_session_id,
            personality_id: input.row.personality_id,
            project_name: input.project_name,
            prompt: input.session_prompt,
            queued_messages: input.session_queued_messages,
            reasoning_level_override: input.reasoning_level_override,
            published_upstream_ref: input.row.published_upstream_ref,
            questions: input.session_questions,
            review_request: input.review_request,
            role: input.role,
            size: input.size,
            speed_mode: input.speed_mode,
            stats: SessionStats {
                added_lines: input.row.added_lines.cast_unsigned(),
                deleted_lines: input.row.deleted_lines.cast_unsigned(),
                diff_state: match input.row.has_diff {
                    Some(true) => SessionDiffState::Present,
                    Some(false) => SessionDiffState::Empty,
                    None => SessionDiffState::Unknown,
                },
                input_tokens: input.row.input_tokens.cast_unsigned(),
                output_tokens: input.row.output_tokens.cast_unsigned(),
            },
            status: input.session_status,
            summary: input.session_summary,
            title: input.row.title,
            transcript: input.session_transcript,
            updated_at: input.row.updated_at,
            transient_messages: TransientMessageStore::default(),
        };
        session.hydrate_summary_transient();

        session
    }

    /// Applies one lazily loaded detail row and message transcript to the
    /// session snapshot and its shared runtime handle without clobbering live
    /// in-process transcript messages.
    fn apply_session_detail(
        &mut self,
        session_id: &str,
        detail: SessionDetailRow,
        transcript: SessionTranscript,
    ) {
        let session_transcript = self
            .state
            .handle(session_id)
            .and_then(|handles| sync_handle_transcript_with_loaded(handles, Some(&transcript)))
            .or_else(|| Some(transcript).filter(|transcript| !transcript.is_empty()));

        let Some(session) = self.state.session_mut_for_id(session_id) else {
            return;
        };

        session.prompt = detail.prompt;
        if let Some(questions) = detail.questions {
            session.questions = parse_questions_json(&questions).unwrap_or_default();
        }
        session.summary = detail.summary;
        session.transcript = session_transcript;
        session.hydrate_summary_transient();
    }
}

/// Loads active-session detail metadata and transcript text for the selected
/// row only.
async fn load_active_session_detail(
    db: &AppRepositories,
    active_session_id: Option<&str>,
    row_id: &str,
) -> (Option<SessionDetailRow>, Option<SessionTranscript>) {
    if active_session_id.is_none_or(|active_id| active_id != row_id) {
        return (None, None);
    }

    let Some(detail) = db
        .sessions()
        .load_session_detail(row_id)
        .await
        .ok()
        .flatten()
    else {
        return (None, None);
    };
    let transcript = load_session_transcript(db, row_id).await.ok();

    (Some(detail), transcript)
}

/// Reads status/transcript from an existing handle while hydrating an empty
/// transcript from lazily loaded detail when the session has become active.
fn status_and_transcript_from_existing_handle(
    existing_handle: &SessionHandles,
    persisted_status: Status,
    loaded_transcript: Option<&SessionTranscript>,
) -> (Status, Option<SessionTranscript>) {
    let status_from_handle = existing_handle
        .status
        .lock()
        .ok()
        .map_or(persisted_status, |status| *status);
    let merged_status = merge_loaded_session_status(persisted_status, status_from_handle);

    if let Ok(mut handle_status) = existing_handle.status.lock() {
        *handle_status = merged_status;
    }
    let transcript_from_handle =
        sync_handle_transcript_with_loaded(existing_handle, loaded_transcript);

    (merged_status, transcript_from_handle)
}

/// Inserts a new runtime handle using active-session detail when it is
/// available and returns the transcript snapshot stored in that handle.
fn insert_loaded_session_handle(
    handles: &mut HashMap<SessionId, SessionHandles>,
    session_id: SessionId,
    persisted_status: Status,
    loaded_transcript: Option<SessionTranscript>,
) -> Option<SessionTranscript> {
    let session_transcript = loaded_transcript.filter(|transcript| !transcript.is_empty());
    let session_handle = if let Some(transcript) = session_transcript.clone() {
        SessionHandles::new_with_transcript(persisted_status, transcript)
    } else {
        SessionHandles::new_unloaded(persisted_status)
    };
    handles.insert(session_id, session_handle);

    session_transcript
}

/// Loads ordered session messages into the render transcript snapshot.
async fn load_session_transcript(
    db: &AppRepositories,
    session_id: &str,
) -> Result<SessionTranscript, DbError> {
    let messages = db.sessions().load_session_messages(session_id).await?;

    Ok(SessionTranscript::new(session_messages_from_rows(messages)))
}

/// Synchronizes a handle from loaded rows while preserving complete live
/// transcripts and replacing partial unhydrated snapshots.
fn sync_handle_transcript_with_loaded(
    handles: &SessionHandles,
    loaded_transcript: Option<&SessionTranscript>,
) -> Option<SessionTranscript> {
    handles.transcript_snapshot_with_loaded(loaded_transcript)
}

/// Converts database message rows into domain messages, skipping unknown
/// message kinds left by older database revisions.
fn session_messages_from_rows(rows: Vec<SessionMessageRow>) -> Vec<SessionMessage> {
    rows.into_iter()
        .filter_map(|row| {
            row.kind
                .parse::<SessionMessageKind>()
                .ok()
                .map(|kind| SessionMessage::new(row.position, kind, row.content))
        })
        .collect()
}

/// Returns whether one persisted session row should be skipped because its
/// worktree folder is missing and no merge-cleanup transition is still active.
fn should_skip_missing_folder_session(
    has_session_folder: bool,
    is_draft_session: bool,
    persisted_status: Status,
    live_handle_status: Option<Status>,
) -> bool {
    if has_session_folder {
        return false;
    }

    if matches!(
        persisted_status,
        Status::Merged | Status::Done | Status::Canceled
    ) {
        return false;
    }

    if is_draft_session && persisted_status == Status::Draft {
        return false;
    }

    !matches!(
        live_handle_status,
        Some(Status::Merging | Status::Merged | Status::Done | Status::Canceled)
    )
}

/// Merges one loaded status with the existing live-handle status.
///
/// Existing handle status is kept for active transitions to prevent stale DB
/// snapshots from clobbering in-memory updates. Persisted read-only and
/// terminal statuses (`Merged`, `Done`, `Canceled`) take precedence so remote
/// merge truth and explicit terminal transitions still appear after refresh.
fn merge_loaded_session_status(status_from_db: Status, status_from_handle: Status) -> Status {
    if matches!(
        status_from_db,
        Status::Merged | Status::Done | Status::Canceled
    ) {
        return status_from_db;
    }

    status_from_handle
}

/// Parses normalized review-request metadata from one loaded database row.
///
/// Incomplete or invalid persisted metadata is ignored so stale partial rows do
/// not block session loading.
fn parse_review_request(row: &SessionListRow) -> Option<ReviewRequest> {
    let review_request_row = row.review_request.as_ref()?;
    let forge_kind = parse_optional_enum(Some(review_request_row.forge_kind.as_str())).ok()?;
    let state = parse_optional_enum(Some(review_request_row.state.as_str())).ok()?;

    Some(ReviewRequest {
        last_refreshed_at: review_request_row.last_refreshed_at,
        summary: ReviewRequestSummary {
            display_id: review_request_row.display_id.clone(),
            forge_kind,
            source_branch: review_request_row.source_branch.clone(),
            state,
            status_summary: review_request_row.status_summary.clone(),
            target_branch: review_request_row.target_branch.clone(),
            title: review_request_row.title.clone(),
            web_url: review_request_row.web_url.clone(),
        },
    })
}

/// Converts one optional persisted string into a parsed enum value.
fn parse_optional_enum<T>(value: Option<&str>) -> Result<T, ()>
where
    T: std::str::FromStr,
{
    value.ok_or(())?.parse().map_err(|_| ())
}

/// Parses persisted question JSON with backward compatibility.
///
/// Attempts to deserialize as `Vec<QuestionItem>` first (new format). Falls
/// back to `Vec<String>` (legacy format) and converts each entry into a
/// `QuestionItem` without predefined options.
fn parse_questions_json(raw_json: &str) -> Option<Vec<QuestionItem>> {
    if raw_json.is_empty() {
        return None;
    }

    if let Ok(items) = serde_json::from_str::<Vec<QuestionItem>>(raw_json) {
        return Some(items);
    }

    serde_json::from_str::<Vec<String>>(raw_json)
        .ok()
        .map(|texts| {
            texts
                .into_iter()
                .map(|text| QuestionItem {
                    options: Vec::new(),
                    text,
                })
                .collect()
        })
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;
    use std::path::{Path, PathBuf};
    use std::time::{Instant, SystemTime};

    use ag_git::{GitError, MockGitClient};

    use super::*;
    use crate::domain::session::{ForgeKind, ReviewRequestState, ReviewRequestSummary};
    use crate::infra::clock::RealClock;
    use crate::infra::db::SessionReviewRequestRow;
    use crate::infra::fs;

    /// Clock fixture that supplies event-specific offsets for activity rows.
    struct ActivityOffsetClock;

    impl Clock for ActivityOffsetClock {
        fn local_utc_offset_seconds(&self, timestamp_seconds: i64) -> i64 {
            if timestamp_seconds < 86_400 {
                3_600
            } else {
                -3_600
            }
        }

        fn now_instant(&self) -> Instant {
            Instant::now()
        }

        fn now_system_time(&self) -> SystemTime {
            SystemTime::UNIX_EPOCH
        }
    }

    fn session_replay_text(session: &Session) -> String {
        session
            .transcript
            .as_ref()
            .and_then(SessionTranscript::replay_text)
            .unwrap_or_default()
    }

    fn assistant_transcript(content: impl AsRef<str>) -> SessionTranscript {
        SessionTranscript::new(vec![SessionMessage::conversation(
            0,
            SessionMessageKind::AssistantAnswer,
            content.as_ref(),
        )])
    }

    fn assistant_replay_text(content: impl AsRef<str>) -> String {
        assistant_transcript(content)
            .replay_text()
            .expect("assistant transcript should have replay text")
    }

    #[test]
    fn daily_activity_uses_clock_offset_for_each_timestamp() {
        // Arrange
        let timestamps = vec![86_399, 86_400, 86_399];
        let clock = ActivityOffsetClock;

        // Act
        let activity = SessionManager::daily_activity_from_timestamps(timestamps, &clock);
        let monotonic_time = clock.now_instant();
        let system_time = clock.now_system_time();

        // Assert
        assert!(monotonic_time <= Instant::now());
        assert_eq!(system_time, SystemTime::UNIX_EPOCH);
        assert_eq!(
            activity,
            vec![
                DailyActivity {
                    day_key: 0,
                    session_count: 1,
                },
                DailyActivity {
                    day_key: 1,
                    session_count: 2,
                },
            ]
        );
    }

    #[tokio::test]
    async fn session_diff_stats_preserve_binary_presence_and_git_errors() {
        // Arrange
        let folder = PathBuf::from("/tmp/session");
        let existing_folder_client = create_folder_lookup_mock(vec![folder.clone()]);
        let missing_folder_client = create_folder_lookup_mock(Vec::new());
        let mut binary_diff_client = MockGitClient::new();
        binary_diff_client.expect_diff().times(1).returning(|_, _| {
            Box::pin(async {
                Ok("diff --git a/image.png b/image.png\nBinary files differ\n".to_string())
            })
        });
        let mut failing_diff_client = MockGitClient::new();
        failing_diff_client
            .expect_diff()
            .times(1)
            .returning(|_, _| {
                Box::pin(async { Err(GitError::OutputParse("diff failed".to_string())) })
            });

        // Act
        let binary_stats = SessionManager::session_diff_stats_for_folder(
            &existing_folder_client,
            &binary_diff_client,
            &folder,
            "main",
        )
        .await;
        let error_stats = SessionManager::session_diff_stats_for_folder(
            &existing_folder_client,
            &failing_diff_client,
            &folder,
            "main",
        )
        .await;
        let missing_folder_stats = SessionManager::session_diff_stats_for_folder(
            &missing_folder_client,
            &MockGitClient::new(),
            &folder,
            "main",
        )
        .await;

        // Assert
        assert_eq!(
            binary_stats,
            SessionDiffStats::Known {
                added_lines: 0,
                deleted_lines: 0,
                has_diff: true,
                session_size: SessionSize::Xs,
            }
        );
        assert_eq!(error_stats, SessionDiffStats::Unknown);
        assert_eq!(missing_folder_stats, SessionDiffStats::Unknown);
    }

    /// Returns a filesystem mock that reports the supplied directories as
    /// existing and treats missing staged-draft metadata files as absent.
    fn create_folder_lookup_mock(existing_folders: Vec<PathBuf>) -> fs::MockFsClient {
        let mut mock_fs_client = fs::MockFsClient::new();
        mock_fs_client
            .expect_is_dir()
            .times(0..)
            .returning(move |path| existing_folders.contains(&path));
        mock_fs_client.expect_read_file().times(0..).returning(|_| {
            Box::pin(async {
                Err(fs::FsError::Io(std::io::Error::from(
                    std::io::ErrorKind::NotFound,
                )))
            })
        });

        mock_fs_client
    }

    /// Ensures reload keeps live handle output and active status when
    /// persisted row data is stale.
    #[tokio::test]
    async fn test_load_sessions_preserves_live_handle_output_and_status() {
        // Arrange
        let db = AppRepositories::in_memory().await.expect("db should open");
        let project_id = db
            .projects()
            .upsert_project("/tmp/test", None)
            .await
            .expect("failed to upsert project");

        let session_id = "test-session";
        db.sessions()
            .insert_session(
                session_id,
                "gemini-3.7-flash",
                "main",
                "InProgress",
                project_id,
            )
            .await
            .expect("failed to insert session");
        db.sessions()
            .append_session_message(session_id, SessionMessageKind::AssistantAnswer, "DB Output")
            .await
            .expect("failed to append persisted message");
        db.sessions()
            .mark_session_diff_unknown(session_id)
            .await
            .expect("failed to mark session diff unknown");

        let base_path = Path::new("/virtual/session-base");
        let session_dir = session_folder(base_path, session_id);
        let mock_fs_client = create_folder_lookup_mock(vec![session_dir]);

        let mut handles: HashMap<SessionId, SessionHandles> = HashMap::new();
        let live_output = "Live Output".to_string();
        let live_status = Status::Review;
        handles.insert(
            session_id.to_string().into(),
            SessionHandles::new_with_transcript(live_status, assistant_transcript(&live_output)),
        );

        // Act
        let (sessions, _, _) = SessionManager::load_sessions_with_fs_client(
            SessionLoadInput {
                active_project_id: project_id,
                active_session_id: None,
                base: base_path,
                clock: &RealClock,
                db: &db,
                fs_client: &mock_fs_client,
                working_dir: Path::new("/tmp/test"),
            },
            &mut handles,
        )
        .await;

        // Assert
        let session = sessions
            .iter()
            .find(|session| session.id == session_id)
            .expect("missing reloaded session");
        assert_eq!(
            session_replay_text(session),
            assistant_replay_text(&live_output)
        );
        assert_eq!(session.status, live_status);
        assert_eq!(session.stats.diff_state, SessionDiffState::Unknown);

        let handle = handles
            .get(session_id)
            .expect("missing existing runtime handle");
        let handle_output = handle
            .transcript
            .lock()
            .expect("failed to lock handle transcript")
            .replay_text()
            .unwrap_or_default();
        let handle_status = *handle.status.lock().expect("failed to lock handle status");
        assert_eq!(handle_output, assistant_replay_text(&live_output));
        assert_eq!(handle_status, live_status);
    }

    /// Ensures reload caches worktree availability alongside loaded session
    /// rows.
    #[tokio::test]
    async fn test_load_sessions_reports_worktree_availability() {
        // Arrange
        let db = AppRepositories::in_memory().await.expect("db should open");
        let project_id = db
            .projects()
            .upsert_project("/tmp/test", None)
            .await
            .expect("failed to upsert project");
        let session_with_worktree_id = "worktree-available";
        let session_without_worktree_id = "draft-missing";
        db.sessions()
            .insert_session(
                session_with_worktree_id,
                "gemini-3.7-flash",
                "main",
                "Draft",
                project_id,
            )
            .await
            .expect("failed to insert session with worktree");
        db.sessions()
            .insert_draft_session(
                session_without_worktree_id,
                "gemini-3.7-flash",
                "main",
                "Draft",
                project_id,
            )
            .await
            .expect("failed to insert draft session");

        let base_path = Path::new("/virtual/session-base");
        let mock_fs_client =
            create_folder_lookup_mock(vec![session_folder(base_path, session_with_worktree_id)]);
        let mut handles: HashMap<SessionId, SessionHandles> = HashMap::new();

        // Act
        let (_, _, session_worktree_availability) = SessionManager::load_sessions_with_fs_client(
            SessionLoadInput {
                active_project_id: project_id,
                active_session_id: None,
                base: base_path,
                clock: &RealClock,
                db: &db,
                fs_client: &mock_fs_client,
                working_dir: Path::new("/tmp/test"),
            },
            &mut handles,
        )
        .await;

        // Assert
        assert_eq!(
            session_worktree_availability.get(session_with_worktree_id),
            Some(&true)
        );
        assert_eq!(
            session_worktree_availability.get(session_without_worktree_id),
            Some(&false)
        );
    }

    /// Ensures reload reads the persisted summary for active sessions.
    #[tokio::test]
    async fn test_load_sessions_reads_persisted_summary_for_active_session() {
        // Arrange
        let db = AppRepositories::in_memory().await.expect("db should open");
        let project_id = db
            .projects()
            .upsert_project("/tmp/test", None)
            .await
            .expect("failed to upsert project");

        let session_id = "test-session";
        db.sessions()
            .insert_session(session_id, "gemini-3.7-flash", "main", "Review", project_id)
            .await
            .expect("failed to insert session");
        db.sessions()
            .update_session_prompt(session_id, "persisted prompt")
            .await
            .expect("failed to update session prompt");
        db.sessions()
            .update_session_questions(
                session_id,
                r#"[{"text":"persisted question?","options":["Yes"]}]"#,
            )
            .await
            .expect("failed to update session questions");
        db.sessions()
            .update_session_summary(session_id, "persisted summary")
            .await
            .expect("failed to update session summary");
        db.sessions()
            .append_session_message(
                session_id,
                SessionMessageKind::AssistantAnswer,
                "persisted output",
            )
            .await
            .expect("failed to append session message");

        let base_path = Path::new("/virtual/session-base");
        let session_dir = session_folder(base_path, session_id);
        let mock_fs_client = create_folder_lookup_mock(vec![session_dir]);

        let mut handles: HashMap<SessionId, SessionHandles> = HashMap::new();
        handles.insert(
            session_id.to_string().into(),
            SessionHandles::new_with_transcript(
                Status::Review,
                assistant_transcript("Live Output"),
            ),
        );

        // Act
        let (sessions, _, _) = SessionManager::load_sessions_with_fs_client(
            SessionLoadInput {
                active_project_id: project_id,
                active_session_id: Some(session_id),
                base: base_path,
                clock: &RealClock,
                db: &db,
                fs_client: &mock_fs_client,
                working_dir: Path::new("/tmp/test"),
            },
            &mut handles,
        )
        .await;

        // Assert
        let session = sessions
            .iter()
            .find(|session| session.id == session_id)
            .expect("missing reloaded session");
        assert_eq!(
            session_replay_text(session),
            assistant_replay_text("Live Output")
        );
        assert_eq!(session.prompt, "persisted prompt");
        assert_eq!(
            session.questions,
            vec![QuestionItem {
                options: vec!["Yes".to_string()],
                text: "persisted question?".to_string(),
            }]
        );
        assert_eq!(session.summary.as_deref(), Some("persisted summary"));
    }

    /// Ensures inactive session refresh skips transcript-scale fields.
    #[tokio::test]
    async fn test_load_sessions_defers_persisted_detail_for_inactive_session() {
        // Arrange
        let db = AppRepositories::in_memory().await.expect("db should open");
        let project_id = db
            .projects()
            .upsert_project("/tmp/test", None)
            .await
            .expect("failed to upsert project");

        let session_id = "inactive-session";
        db.sessions()
            .insert_session(session_id, "gemini-3.7-flash", "main", "Review", project_id)
            .await
            .expect("failed to insert session");
        db.sessions()
            .update_session_prompt(session_id, "large prompt")
            .await
            .expect("failed to update prompt");
        db.sessions()
            .update_session_questions(session_id, r#"["Need detail?"]"#)
            .await
            .expect("failed to update questions");
        db.sessions()
            .update_session_summary(session_id, "large summary")
            .await
            .expect("failed to update summary");
        db.sessions()
            .append_session_message(
                session_id,
                SessionMessageKind::AssistantAnswer,
                "large output",
            )
            .await
            .expect("failed to append message");

        let base_path = Path::new("/virtual/session-base");
        let session_dir = session_folder(base_path, session_id);
        let mock_fs_client = create_folder_lookup_mock(vec![session_dir]);
        let mut handles: HashMap<SessionId, SessionHandles> = HashMap::new();

        // Act
        let (sessions, _, _) = SessionManager::load_sessions_with_fs_client(
            SessionLoadInput {
                active_project_id: project_id,
                active_session_id: None,
                base: base_path,
                clock: &RealClock,
                db: &db,
                fs_client: &mock_fs_client,
                working_dir: Path::new("/tmp/test"),
            },
            &mut handles,
        )
        .await;

        // Assert
        let session = sessions
            .iter()
            .find(|session| session.id == session_id)
            .expect("missing reloaded session");
        assert_eq!(session_replay_text(session), "");
        assert_eq!(session.prompt, "");
        assert_eq!(session.questions, [] as [ag_protocol::QuestionItem; 0]);
        assert!(session.summary.is_none());

        let handle = handles.get(session_id).expect("missing runtime handle");
        let handle_output = handle
            .transcript
            .lock()
            .expect("failed to lock transcript")
            .replay_text();
        assert_eq!(handle_output, None);
    }

    /// Ensures active reload hydrates an existing empty handle from persisted
    /// transcript detail.
    #[tokio::test]
    async fn test_load_sessions_hydrates_empty_handle_for_active_session() {
        // Arrange
        let db = AppRepositories::in_memory().await.expect("db should open");
        let project_id = db
            .projects()
            .upsert_project("/tmp/test", None)
            .await
            .expect("failed to upsert project");

        let session_id = "active-session";
        db.sessions()
            .insert_session(session_id, "gemini-3.7-flash", "main", "Review", project_id)
            .await
            .expect("failed to insert session");
        db.sessions()
            .append_session_message(
                session_id,
                SessionMessageKind::AssistantAnswer,
                "persisted output",
            )
            .await
            .expect("failed to append message");

        let base_path = Path::new("/virtual/session-base");
        let session_dir = session_folder(base_path, session_id);
        let mock_fs_client = create_folder_lookup_mock(vec![session_dir]);
        let mut handles: HashMap<SessionId, SessionHandles> = HashMap::new();
        handles.insert(
            session_id.to_string().into(),
            SessionHandles::new_unloaded(Status::Review),
        );

        // Act
        let (sessions, _, _) = SessionManager::load_sessions_with_fs_client(
            SessionLoadInput {
                active_project_id: project_id,
                active_session_id: Some(session_id),
                base: base_path,
                clock: &RealClock,
                db: &db,
                fs_client: &mock_fs_client,
                working_dir: Path::new("/tmp/test"),
            },
            &mut handles,
        )
        .await;

        // Assert
        let session = sessions
            .iter()
            .find(|session| session.id == session_id)
            .expect("missing reloaded session");
        assert_eq!(
            session_replay_text(session),
            assistant_replay_text("persisted output")
        );

        let handle = handles.get(session_id).expect("missing runtime handle");
        let handle_output = handle
            .transcript
            .lock()
            .expect("failed to lock transcript")
            .replay_text()
            .unwrap_or_default();
        assert_eq!(handle_output, assistant_replay_text("persisted output"));
    }

    /// Ensures transcript loading returns database failures instead of
    /// converting them into empty transcript text.
    #[tokio::test]
    async fn test_load_session_transcript_returns_query_errors() {
        // Arrange
        let (db, pool) = AppRepositories::in_memory_with_pool()
            .await
            .expect("db should open");
        sqlx::query!("DROP TABLE session_message")
            .execute(&pool)
            .await
            .expect("failed to drop session_message table");

        // Act
        let error = load_session_transcript(&db, "missing-session")
            .await
            .expect_err("transcript load should fail");

        // Assert
        assert!(matches!(error, DbError::Query(_)));
    }

    /// Ensures terminal persisted statuses replace stale active handle status
    /// during reload.
    #[tokio::test]
    async fn test_load_sessions_terminal_db_status_overrides_handle_status() {
        // Arrange
        let db = AppRepositories::in_memory().await.expect("db should open");
        let project_id = db
            .projects()
            .upsert_project("/tmp/test", None)
            .await
            .expect("failed to upsert project");

        let session_id = "test-session";
        db.sessions()
            .insert_session(session_id, "gemini-3.7-flash", "main", "Done", project_id)
            .await
            .expect("failed to insert session");

        let base_path = Path::new("/virtual/session-base");
        let session_dir = session_folder(base_path, session_id);
        let mock_fs_client = create_folder_lookup_mock(vec![session_dir]);

        let mut handles: HashMap<SessionId, SessionHandles> = HashMap::new();
        handles.insert(
            session_id.to_string().into(),
            SessionHandles::new_with_transcript(Status::Review, assistant_transcript("output")),
        );

        // Act
        let (sessions, _, _) = SessionManager::load_sessions_with_fs_client(
            SessionLoadInput {
                active_project_id: project_id,
                active_session_id: None,
                base: base_path,
                clock: &RealClock,
                db: &db,
                fs_client: &mock_fs_client,
                working_dir: Path::new("/tmp/test"),
            },
            &mut handles,
        )
        .await;

        // Assert
        let session = sessions
            .iter()
            .find(|session| session.id == session_id)
            .expect("missing reloaded session");
        assert_eq!(session.status, Status::Done);

        let handle = handles
            .get(session_id)
            .expect("missing existing runtime handle");
        let handle_status = *handle.status.lock().expect("failed to lock handle status");
        assert_eq!(handle_status, Status::Done);
    }

    /// Ensures still-active sessions on a retired model are switched to the
    /// replacement model both in memory and in the database.
    #[tokio::test]
    async fn test_load_sessions_switches_active_session_off_retired_model() {
        // Arrange
        let db = AppRepositories::in_memory().await.expect("db should open");
        let project_id = db
            .projects()
            .upsert_project("/tmp/test", None)
            .await
            .expect("failed to upsert project");
        let session_id = "retired-active-session";
        db.sessions()
            .insert_session(session_id, "gemini-3.1-pro", "main", "Review", project_id)
            .await
            .expect("failed to insert session");
        let base_path = Path::new("/virtual/session-base");
        let mock_fs_client = create_folder_lookup_mock(vec![session_folder(base_path, session_id)]);
        let mut handles: HashMap<SessionId, SessionHandles> = HashMap::new();

        // Act
        let (sessions, _, _) = SessionManager::load_sessions_with_fs_client(
            SessionLoadInput {
                active_project_id: project_id,
                active_session_id: None,
                base: base_path,
                clock: &RealClock,
                db: &db,
                fs_client: &mock_fs_client,
                working_dir: Path::new("/tmp/test"),
            },
            &mut handles,
        )
        .await;

        // Assert
        let session = sessions
            .iter()
            .find(|session| session.id == session_id)
            .expect("missing reloaded session");
        assert_eq!(session.agent.model(), AgentModel::Gemini31Pro);
        let row = db
            .sessions()
            .load_session(session_id)
            .await
            .expect("failed to load session row")
            .expect("missing session row");
        assert_eq!(row.model, "gemini-3.1-pro-preview");
        assert_eq!(row.agent, "antigravity");
    }

    /// Ensures automatic model migration does not make an old session appear
    /// recently active.
    #[tokio::test]
    async fn test_migrate_session_preserves_updated_at() {
        // Arrange
        let (db, pool) = AppRepositories::in_memory_with_pool()
            .await
            .expect("db should open");
        let project_id = db
            .projects()
            .upsert_project("/tmp/test", None)
            .await
            .expect("failed to upsert project");
        let session_id = "retired-timestamp-session";
        db.sessions()
            .insert_session(session_id, "claude-opus-4-6", "main", "Review", project_id)
            .await
            .expect("failed to insert session");
        sqlx::query(
            r"
UPDATE session
SET updated_at = ?
WHERE id = ?
",
        )
        .bind(123_i64)
        .bind(session_id)
        .execute(&pool)
        .await
        .expect("failed to set historical timestamp");

        // Act
        migrate_session_off_retired_model(
            &db,
            session_id,
            "claude",
            "claude-opus-4-6",
            Status::Review,
        )
        .await;

        // Assert
        let row = db
            .sessions()
            .load_session(session_id)
            .await
            .expect("failed to load migrated session")
            .expect("missing migrated session");
        assert_eq!(row.agent, "claude");
        assert_eq!(row.model, "claude-opus-5");
        assert_eq!(row.updated_at, 123);
    }

    /// Ensures startup migration covers active sessions outside the currently
    /// loaded project while retaining terminal-session history.
    #[tokio::test]
    async fn test_migrate_active_sessions_off_retired_models_covers_inactive_projects() {
        // Arrange
        let db = AppRepositories::in_memory().await.expect("db should open");
        let active_project_id = db
            .projects()
            .upsert_project("/tmp/active", None)
            .await
            .expect("failed to upsert active project");
        let inactive_project_id = db
            .projects()
            .upsert_project("/tmp/inactive", None)
            .await
            .expect("failed to upsert inactive project");
        db.sessions()
            .insert_session(
                "active-project-session",
                "claude-opus-4-6",
                "main",
                "Review",
                active_project_id,
            )
            .await
            .expect("failed to insert active-project session");
        db.sessions()
            .insert_session(
                "inactive-project-session",
                "gemini-3.5-flash",
                "main",
                "Review",
                inactive_project_id,
            )
            .await
            .expect("failed to insert inactive-project session");
        db.sessions()
            .insert_session(
                "inactive-project-finished",
                "gemini-3.5-flash",
                "main",
                "Done",
                inactive_project_id,
            )
            .await
            .expect("failed to insert finished inactive-project session");

        // Act
        migrate_active_sessions_off_retired_models(&db).await;

        // Assert
        let active_project_row = db
            .sessions()
            .load_session("active-project-session")
            .await
            .expect("failed to load active-project session")
            .expect("missing active-project session");
        let inactive_project_row = db
            .sessions()
            .load_session("inactive-project-session")
            .await
            .expect("failed to load inactive-project session")
            .expect("missing inactive-project session");
        let finished_row = db
            .sessions()
            .load_session("inactive-project-finished")
            .await
            .expect("failed to load finished inactive-project session")
            .expect("missing finished inactive-project session");
        assert_eq!(active_project_row.model, "claude-opus-5");
        assert_eq!(active_project_row.agent, "claude");
        assert_eq!(inactive_project_row.model, "gemini-3.5-flash-lite");
        assert_eq!(inactive_project_row.agent, "antigravity");
        assert_eq!(finished_row.model, "gemini-3.5-flash");
    }

    /// Ensures a terminal transition after the migration read wins the race
    /// and preserves the retired model id as history.
    #[tokio::test]
    async fn test_migrate_session_preserves_retired_model_after_terminal_transition() {
        // Arrange
        let db = AppRepositories::in_memory().await.expect("db should open");
        let project_id = db
            .projects()
            .upsert_project("/tmp/test", None)
            .await
            .expect("failed to upsert project");
        let race_cases = [
            ("race-merged", "Merged"),
            ("race-done", "Done"),
            ("race-canceled", "Canceled"),
        ];
        for (session_id, _) in race_cases {
            db.sessions()
                .insert_session(session_id, "claude-opus-4-6", "main", "Review", project_id)
                .await
                .expect("failed to insert active session");
        }
        let stale_rows = db
            .sessions()
            .load_active_session_agent_models()
            .await
            .expect("failed to load active sessions");
        for (session_id, terminal_status) in race_cases {
            db.sessions()
                .update_session_status_with_timing_at(session_id, terminal_status, 1)
                .await
                .expect("failed to persist terminal transition");
        }

        // Act
        for row in stale_rows {
            let stale_status = row
                .status
                .parse::<Status>()
                .expect("active status should parse");
            migrate_session_off_retired_model(&db, &row.id, &row.agent, &row.model, stale_status)
                .await;
        }

        // Assert
        for (session_id, terminal_status) in race_cases {
            let row = db
                .sessions()
                .load_session(session_id)
                .await
                .expect("failed to load transitioned session")
                .expect("missing transitioned session");
            assert_eq!(row.status, terminal_status);
            assert_eq!(row.agent, "claude");
            assert_eq!(row.model, "claude-opus-4-6");
        }
    }

    /// Ensures startup remains usable when active-session migration cannot
    /// query a degraded database.
    #[tokio::test]
    async fn test_migrate_active_sessions_off_retired_models_ignores_query_failures() {
        // Arrange
        let (db, pool) = AppRepositories::in_memory_with_pool()
            .await
            .expect("db should open");
        sqlx::query("DROP TABLE session")
            .execute(&pool)
            .await
            .expect("session table should be dropped");

        // Act
        migrate_active_sessions_off_retired_models(&db).await;

        // Assert
        assert!(
            db.sessions()
                .load_active_session_agent_models()
                .await
                .is_err()
        );
    }

    /// Ensures finished sessions keep their retired model id in the database
    /// as history while loading with the replacement model in memory.
    #[tokio::test]
    async fn test_load_sessions_keeps_retired_model_in_db_for_finished_session() {
        // Arrange
        let db = AppRepositories::in_memory().await.expect("db should open");
        let project_id = db
            .projects()
            .upsert_project("/tmp/test", None)
            .await
            .expect("failed to upsert project");
        let session_id = "retired-finished-session";
        db.sessions()
            .insert_session(session_id, "claude-opus-4-6", "main", "Done", project_id)
            .await
            .expect("failed to insert session");
        let base_path = Path::new("/virtual/session-base");
        let mock_fs_client = create_folder_lookup_mock(Vec::new());
        let mut handles: HashMap<SessionId, SessionHandles> = HashMap::new();

        // Act
        let (sessions, _, _) = SessionManager::load_sessions_with_fs_client(
            SessionLoadInput {
                active_project_id: project_id,
                active_session_id: None,
                base: base_path,
                clock: &RealClock,
                db: &db,
                fs_client: &mock_fs_client,
                working_dir: Path::new("/tmp/test"),
            },
            &mut handles,
        )
        .await;

        // Assert
        let session = sessions
            .iter()
            .find(|session| session.id == session_id)
            .expect("missing reloaded session");
        assert_eq!(session.agent.model(), AgentModel::ClaudeOpus5);
        let row = db
            .sessions()
            .load_session(session_id)
            .await
            .expect("failed to load session row")
            .expect("missing session row");
        assert_eq!(row.model, "claude-opus-4-6");
    }

    /// Ensures persisted review-request metadata is mapped onto loaded session
    /// snapshots.
    #[tokio::test]
    async fn test_load_sessions_maps_review_request_metadata() {
        // Arrange
        let db = AppRepositories::in_memory().await.expect("db should open");
        let project_id = db
            .projects()
            .upsert_project("/tmp/test", None)
            .await
            .expect("failed to upsert project");
        let review_request = ReviewRequest {
            last_refreshed_at: 999,
            summary: ReviewRequestSummary {
                display_id: "#17".to_string(),
                forge_kind: ForgeKind::GitHub,
                source_branch: "feature/forge".to_string(),
                state: ReviewRequestState::Closed,
                status_summary: Some("closed by maintainer".to_string()),
                target_branch: "main".to_string(),
                title: "Add forge review support".to_string(),
                web_url: "https://github.com/team/project/pull/17".to_string(),
            },
        };

        let session_id = "test-session";
        db.sessions()
            .insert_session(session_id, "gemini-3.7-flash", "main", "Done", project_id)
            .await
            .expect("failed to insert session");
        db.reviews()
            .update_session_review_request(session_id, Some(review_request.clone()))
            .await
            .expect("failed to persist review request metadata");

        let base_path = Path::new("/virtual/session-base");
        let mock_fs_client = create_folder_lookup_mock(Vec::new());
        let mut handles: HashMap<SessionId, SessionHandles> = HashMap::new();

        // Act
        let (sessions, _, _) = SessionManager::load_sessions_with_fs_client(
            SessionLoadInput {
                active_project_id: project_id,
                active_session_id: None,
                base: base_path,
                clock: &RealClock,
                db: &db,
                fs_client: &mock_fs_client,
                working_dir: Path::new("/tmp/test"),
            },
            &mut handles,
        )
        .await;

        // Assert
        let session = sessions
            .iter()
            .find(|session| session.id == session_id)
            .expect("missing reloaded session");
        assert_eq!(session.review_request, Some(review_request));
    }

    #[test]
    /// Verifies read-only and terminal DB statuses override stale in-memory
    /// handle statuses.
    fn merge_loaded_session_status_prefers_read_only_and_terminal_status_from_db() {
        // Arrange
        let status_from_handle = Status::Draft;

        // Act
        let merged_status = merge_loaded_session_status(Status::Merged, status_from_handle);
        let done_status = merge_loaded_session_status(Status::Done, status_from_handle);

        // Assert
        assert_eq!(merged_status, Status::Merged);
        assert_eq!(done_status, Status::Done);
    }

    #[test]
    /// Verifies non-terminal DB statuses do not overwrite in-memory status.
    fn merge_loaded_session_status_prefers_handle_for_non_terminal_db_status() {
        // Arrange
        let status_from_db = Status::Review;
        let status_from_handle = Status::InProgress;

        // Act
        let merged_status = merge_loaded_session_status(status_from_db, status_from_handle);

        // Assert
        assert_eq!(merged_status, Status::InProgress);
    }

    #[test]
    /// Verifies loaded message rows do not replace an existing live
    /// transcript snapshot.
    fn sync_handle_transcript_with_loaded_keeps_existing_live_transcript() {
        // Arrange
        let live_transcript = SessionTranscript::new(vec![
            SessionMessage::conversation(0, SessionMessageKind::UserPrompt, "prompt"),
            SessionMessage::conversation(1, SessionMessageKind::AssistantAnswer, "answer"),
        ]);
        let handles = SessionHandles::new_with_transcript(Status::Review, live_transcript.clone());
        let loaded_transcript = assistant_transcript("loaded answer");

        // Act
        let transcript = sync_handle_transcript_with_loaded(&handles, Some(&loaded_transcript));

        // Assert
        assert_eq!(transcript, Some(live_transcript.clone()));
        assert_eq!(
            handles.transcript.lock().ok().as_deref(),
            Some(&live_transcript)
        );
    }

    #[test]
    /// Verifies persisted history merges with a partial workflow notice
    /// appended before a lazy transcript was hydrated.
    fn sync_handle_transcript_with_loaded_merges_partial_unloaded_transcript() {
        // Arrange
        let handles = SessionHandles::new_unloaded(Status::Review);
        handles
            .transcript
            .lock()
            .expect("transcript lock should not be poisoned")
            .clone_from(&SessionTranscript::new(vec![SessionMessage::new(
                2,
                SessionMessageKind::WorkflowNotice,
                "\n[Sync] Successfully synced onto main\n",
            )]));
        let loaded_transcript = SessionTranscript::new(vec![
            SessionMessage::conversation(0, SessionMessageKind::UserPrompt, "original prompt"),
            SessionMessage::conversation(1, SessionMessageKind::AssistantAnswer, "original answer"),
        ]);
        let expected_transcript = SessionTranscript::new(vec![
            SessionMessage::conversation(0, SessionMessageKind::UserPrompt, "original prompt"),
            SessionMessage::conversation(1, SessionMessageKind::AssistantAnswer, "original answer"),
            SessionMessage::new(
                2,
                SessionMessageKind::WorkflowNotice,
                "\n[Sync] Successfully synced onto main\n",
            ),
        ]);

        // Act
        let transcript = sync_handle_transcript_with_loaded(&handles, Some(&loaded_transcript));

        // Assert
        assert_eq!(transcript, Some(expected_transcript.clone()));
        assert_eq!(
            handles.transcript.lock().ok().as_deref(),
            Some(&expected_transcript)
        );
    }

    #[test]
    /// Verifies hydration deduplicates a persisted live append while retaining
    /// an unpersisted message whose temporary position conflicts.
    fn sync_handle_transcript_with_loaded_merges_matching_and_conflicting_messages() {
        // Arrange
        let handles = SessionHandles::new_unloaded(Status::Review);
        let persisted_notice = SessionMessage::new(
            2,
            SessionMessageKind::WorkflowNotice,
            "\n[Sync] Successfully synced onto main\n",
        );
        handles
            .transcript
            .lock()
            .expect("transcript lock should not be poisoned")
            .clone_from(&SessionTranscript::new(vec![
                SessionMessage::new(
                    0,
                    SessionMessageKind::WorkflowNotice,
                    "\n[Sync Error] persistence failed\n",
                ),
                persisted_notice.clone(),
            ]));
        let loaded_transcript = SessionTranscript::new(vec![
            SessionMessage::conversation(0, SessionMessageKind::UserPrompt, "original prompt"),
            SessionMessage::conversation(1, SessionMessageKind::AssistantAnswer, "original answer"),
            persisted_notice.clone(),
        ]);

        // Act
        let transcript = sync_handle_transcript_with_loaded(&handles, Some(&loaded_transcript))
            .expect("merged transcript should be available");

        // Assert
        assert_eq!(
            transcript.messages(),
            &[
                SessionMessage::conversation(0, SessionMessageKind::UserPrompt, "original prompt"),
                SessionMessage::conversation(
                    1,
                    SessionMessageKind::AssistantAnswer,
                    "original answer"
                ),
                persisted_notice,
                SessionMessage::new(
                    3,
                    SessionMessageKind::WorkflowNotice,
                    "\n[Sync Error] persistence failed\n"
                ),
            ]
        );
    }

    #[test]
    /// Verifies missing-folder rows stay visible while merge cleanup has
    /// removed the worktree before `Done` persistence finishes.
    fn should_skip_missing_folder_session_keeps_live_merging_session() {
        // Arrange
        let has_session_folder = false;
        let persisted_status = Status::Merging;
        let live_handle_status = Some(Status::Merging);

        // Act
        let should_skip = should_skip_missing_folder_session(
            has_session_folder,
            false,
            persisted_status,
            live_handle_status,
        );

        // Assert
        assert!(!should_skip);
    }

    #[test]
    /// Verifies missing-folder rows stay visible when either persistence or
    /// live state has already recorded a remote merge.
    fn should_skip_missing_folder_session_keeps_merged_session() {
        // Arrange, Act
        let persisted_merged_should_skip =
            should_skip_missing_folder_session(false, false, Status::Merged, Some(Status::Review));
        let live_merged_should_skip =
            should_skip_missing_folder_session(false, false, Status::Review, Some(Status::Merged));

        // Assert
        assert!(!persisted_merged_should_skip);
        assert!(!live_merged_should_skip);
    }

    #[test]
    /// Verifies missing-folder non-terminal rows are still filtered when no
    /// merge-cleanup transition is active.
    fn should_skip_missing_folder_session_skips_orphaned_active_session() {
        // Arrange
        let has_session_folder = false;
        let persisted_status = Status::Review;
        let live_handle_status = None;

        // Act
        let should_skip = should_skip_missing_folder_session(
            has_session_folder,
            false,
            persisted_status,
            live_handle_status,
        );

        // Assert
        assert!(should_skip);
    }

    #[test]
    /// Verifies missing-folder draft sessions stay visible before their
    /// deferred worktree is created.
    fn should_skip_missing_folder_session_keeps_new_draft_session() {
        // Arrange
        let has_session_folder = false;
        let persisted_status = Status::Draft;
        let live_handle_status = None;

        // Act
        let should_skip = should_skip_missing_folder_session(
            has_session_folder,
            true,
            persisted_status,
            live_handle_status,
        );

        // Assert
        assert!(!should_skip);
    }

    #[test]
    /// Verifies invalid review-request rows are ignored during session load.
    fn parse_review_request_returns_none_for_invalid_row() {
        // Arrange
        let row = SessionListRow {
            added_lines: 0,
            agent: "codex".to_string(),
            base_branch: "main".to_string(),
            created_at: 0,
            deleted_lines: 0,
            has_diff: Some(false),
            id: "session-a".to_string(),
            in_progress_started_at: None,
            in_progress_total_seconds: 0,
            input_tokens: 0,
            is_draft: false,
            model: "gpt-5.6-sol".to_string(),
            output_tokens: 0,
            parent_session_id: None,
            personality_id: None,
            project_id: Some(1),
            reasoning_level_override: None,
            published_upstream_ref: None,
            review_request: Some(SessionReviewRequestRow {
                display_id: "#42".to_string(),
                forge_kind: "UnknownForge".to_string(),
                last_refreshed_at: 0,
                source_branch: "feature/forge".to_string(),
                state: "Open".to_string(),
                status_summary: None,
                target_branch: "main".to_string(),
                title: "Add forge review support".to_string(),
                web_url: "https://github.com/agentty-xyz/agentty/pull/42".to_string(),
            }),
            role: None,
            size: "XS".to_string(),
            speed_mode: "normal".to_string(),
            status: "Review".to_string(),
            title: None,
            updated_at: 0,
        };

        // Act
        let review_request = parse_review_request(&row);

        // Assert
        assert_eq!(review_request, None);
    }

    #[test]
    fn test_parse_questions_json_new_format() {
        // Arrange
        let json = r#"[{"text":"Pick one?","options":["A","B"]}]"#;

        // Act
        let result = parse_questions_json(json);

        // Assert
        let items = result.expect("expected Some");
        assert_eq!(items.len(), 1);
        assert_eq!(items[0].text, "Pick one?");
        assert_eq!(items[0].options, vec!["A", "B"]);
    }

    #[test]
    fn test_parse_questions_json_legacy_format() {
        // Arrange
        let json = r#"["Need target?","Need tests?"]"#;

        // Act
        let result = parse_questions_json(json);

        // Assert
        let items = result.expect("expected Some");
        assert_eq!(items.len(), 2);
        assert_eq!(items[0].text, "Need target?");
        assert_eq!(items[0].options, [] as [std::string::String; 0]);
        assert_eq!(items[1].text, "Need tests?");
        assert_eq!(items[1].options, [] as [std::string::String; 0]);
    }

    #[test]
    fn test_parse_questions_json_empty_string_returns_none() {
        // Arrange / Act
        let result = parse_questions_json("");

        // Assert
        assert!(result.is_none());
    }

    #[test]
    fn test_parse_questions_json_invalid_json_returns_none() {
        // Arrange / Act
        let result = parse_questions_json("{not valid json");

        // Assert
        assert!(result.is_none());
    }
}