agentty 0.10.5

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
//! Session loading and derived snapshot attributes from persisted rows.

use std::collections::HashMap;
use std::path::Path;

use super::{draft, session_folder};
use crate::app::SessionManager;
use crate::domain::agent::{AgentKind, AgentModel, ReasoningLevel};
use crate::domain::question::QuestionItem;
use crate::domain::session::{
    DailyActivity, PublishedBranchSyncStatus, ReviewRequest, ReviewRequestSummary, Session,
    SessionFollowUpTask, SessionHandles, SessionId, SessionSize, SessionStats, Status,
};
use crate::infra::db::{AppRepositories, SessionDetailRow, SessionListRow};
use crate::infra::fs::FsClient;
use crate::infra::git::GitClient;

/// 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,
    follow_up_tasks_by_session: &'a mut HashMap<SessionId, Vec<SessionFollowUpTask>>,
    fs_client: &'a dyn FsClient,
    handles: &'a mut HashMap<SessionId, SessionHandles>,
    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 {
    draft_attachments: Vec<crate::domain::turn_prompt::TurnPromptAttachment>,
    follow_up_tasks: Vec<SessionFollowUpTask>,
    folder: std::path::PathBuf,
    parent_session_id: Option<SessionId>,
    project_name: String,
    reasoning_level_override: Option<ReasoningLevel>,
    review_request: Option<ReviewRequest>,
    row: SessionListRow,
    session_model: AgentModel,
    session_id: SessionId,
    session_output: String,
    session_prompt: String,
    session_queued_messages: Vec<String>,
    session_questions: Vec<QuestionItem>,
    session_summary: Option<String>,
    session_status: Status,
    size: SessionSize,
}

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.
    ///
    /// 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(
        base: &Path,
        db: &AppRepositories,
        active_project_id: i64,
        working_dir: &Path,
        handles: &mut HashMap<SessionId, SessionHandles>,
        fs_client: &dyn FsClient,
        active_session_id: Option<&str>,
    ) -> (Vec<Session>, Vec<DailyActivity>, HashMap<SessionId, bool>) {
        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
            .unwrap_or_default();
        let persisted_follow_up_tasks = db
            .sessions()
            .load_session_follow_up_tasks()
            .await
            .unwrap_or_default();
        let stats_activity = db
            .activity()
            .load_session_activity()
            .await
            .unwrap_or_default();
        let mut sessions: Vec<Session> = Vec::new();
        let mut follow_up_tasks_by_session = HashMap::<SessionId, Vec<_>>::new();
        let mut session_worktree_availability = HashMap::new();

        for persisted_follow_up_task in persisted_follow_up_tasks {
            follow_up_tasks_by_session
                .entry(SessionId::from(persisted_follow_up_task.session_id.clone()))
                .or_default()
                .push(persisted_follow_up_task.into_session_follow_up_task());
        }
        let mut load_context = LoadSessionContext {
            base,
            db,
            project_name: &project_name,
            handles,
            fs_client,
            active_session_id,
            sessions: &mut sessions,
            follow_up_tasks_by_session: &mut follow_up_tasks_by_session,
            session_worktree_availability: &mut session_worktree_availability,
        };
        for row in db_rows {
            Self::push_loaded_session_row(&mut load_context, row).await;
        }

        (sessions, stats_activity, session_worktree_availability)
    }

    /// 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,
            fs_client,
            active_session_id,
            sessions,
            follow_up_tasks_by_session,
            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_model = AgentModel::parse_persisted(&row.model)
            .unwrap_or_else(|_| AgentKind::Antigravity.default_model());

        let session_detail = if active_session_id.is_some_and(|active_id| active_id == row.id) {
            db.sessions()
                .load_session_detail(&row.id)
                .await
                .ok()
                .flatten()
        } else {
            None
        };

        let (session_output, session_status) =
            if let Some(existing_handle) = handles.get(&session_id) {
                output_and_status_from_existing_handle(
                    existing_handle,
                    persisted_status,
                    session_detail.as_ref(),
                )
            } else {
                let output = insert_loaded_session_handle(
                    handles,
                    session_id.clone(),
                    persisted_status,
                    session_detail.as_ref(),
                );

                (output, persisted_status)
            };
        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 follow_up_tasks = follow_up_tasks_by_session
            .remove(&session_id)
            .unwrap_or_default();
        let session_queued_messages = handles
            .get(&session_id)
            .map(SessionHandles::queued_message_transcripts)
            .unwrap_or_default();
        sessions.push(Self::build_loaded_session(LoadedSessionInput {
            draft_attachments,
            follow_up_tasks,
            folder,
            parent_session_id: row.parent_session_id.clone().map(SessionId::from),
            project_name: (*project_name).to_string(),
            reasoning_level_override,
            review_request,
            row,
            session_model,
            session_id,
            session_output,
            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,
            size: persisted_size,
        }));
    }

    /// Computes diff-derived session size and line-count totals from one
    /// worktree folder using the injected filesystem boundary.
    pub(crate) async fn session_diff_stats_for_folder(
        fs_client: &dyn FsClient,
        git_client: &dyn GitClient,
        folder: &Path,
        base_branch: &str,
    ) -> (SessionSize, u64, u64) {
        if !fs_client.is_dir(folder.to_path_buf()) {
            return (SessionSize::Xs, 0, 0);
        }

        let folder = folder.to_path_buf();
        let base_branch = base_branch.to_string();
        let diff = git_client
            .diff(folder, base_branch)
            .await
            .ok()
            .unwrap_or_default();

        let (added_lines, deleted_lines) = SessionStats::line_change_counts(&diff);

        (SessionSize::from_diff(&diff), added_lines, deleted_lines)
    }

    /// 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;
        };

        self.apply_session_detail(session_id, detail);
    }

    /// Builds one in-memory session snapshot from a database row plus the
    /// transient fields computed during reload.
    fn build_loaded_session(input: LoadedSessionInput) -> Session {
        Session {
            base_branch: input.row.base_branch,
            created_at: input.row.created_at,
            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,
            model: input.session_model,
            output: input.session_output,
            parent_session_id: input.parent_session_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,
            published_branch_sync_status: PublishedBranchSyncStatus::Idle,
            questions: input.session_questions,
            review_request: input.review_request,
            size: input.size,
            stats: SessionStats {
                added_lines: input.row.added_lines.cast_unsigned(),
                deleted_lines: input.row.deleted_lines.cast_unsigned(),
                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,
            updated_at: input.row.updated_at,
            workflow_notice: None,
        }
    }

    /// Applies one lazily loaded detail row to the session snapshot and its
    /// shared runtime handle without clobbering live in-process output.
    fn apply_session_detail(&mut self, session_id: &str, detail: SessionDetailRow) {
        let session_output = if let Some(handles) = self.state.handles.get(session_id)
            && let Ok(mut handle_output) = handles.output.lock()
        {
            if handle_output.is_empty() {
                handle_output.clone_from(&detail.output);
            }

            handle_output.clone()
        } else {
            detail.output.clone()
        };

        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.output = session_output;
    }
}

/// Reads output/status from an existing handle while hydrating empty output
/// from lazily loaded detail when the session has become active.
fn output_and_status_from_existing_handle(
    existing_handle: &SessionHandles,
    persisted_status: Status,
    session_detail: Option<&SessionDetailRow>,
) -> (String, Status) {
    let output_from_handle =
        existing_handle
            .output
            .lock()
            .ok()
            .map_or_else(String::new, |mut output| {
                if output.is_empty()
                    && let Some(detail) = session_detail
                {
                    output.push_str(&detail.output);
                }

                output.clone()
            });
    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;
    }

    (output_from_handle, merged_status)
}

/// Inserts a new runtime handle using active-session detail when it is
/// available and returns the output snapshot stored in that handle.
fn insert_loaded_session_handle(
    handles: &mut HashMap<SessionId, SessionHandles>,
    session_id: SessionId,
    persisted_status: Status,
    session_detail: Option<&SessionDetailRow>,
) -> String {
    let output = session_detail
        .map(|detail| detail.output.clone())
        .unwrap_or_default();
    handles.insert(
        session_id,
        SessionHandles::new(output.clone(), persisted_status),
    );

    output
}

/// 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::Done | Status::Canceled) {
        return false;
    }

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

    !matches!(
        live_handle_status,
        Some(Status::Merging | 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 terminal statuses
/// (`Done`, `Canceled`) take precedence so explicit DB 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::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 super::*;
    use crate::domain::session::{ForgeKind, ReviewRequestState, ReviewRequestSummary};
    use crate::infra::db::SessionReviewRequestRow;
    use crate::infra::fs;

    /// 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;
        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-flash-preview",
                "main",
                "InProgress",
                project_id,
            )
            .await
            .expect("failed to insert session");
        db.sessions()
            .append_session_output(session_id, "DB Output")
            .await
            .expect("failed to append persisted output");

        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(live_output.clone(), live_status),
        );

        // Act
        let (sessions, _, _) = SessionManager::load_sessions_with_fs_client(
            base_path,
            &db,
            project_id,
            Path::new("/tmp/test"),
            &mut handles,
            &mock_fs_client,
            None,
        )
        .await;

        // Assert
        let session = sessions
            .iter()
            .find(|session| session.id == session_id)
            .expect("missing reloaded session");
        assert_eq!(session.output, live_output);
        assert_eq!(session.status, live_status);

        let handle = handles
            .get(session_id)
            .expect("missing existing runtime handle");
        let handle_output = handle
            .output
            .lock()
            .expect("failed to lock handle output")
            .clone();
        let handle_status = *handle.status.lock().expect("failed to lock handle status");
        assert_eq!(handle_output, 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;
        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-flash-preview",
                "main",
                "Draft",
                project_id,
            )
            .await
            .expect("failed to insert session with worktree");
        db.sessions()
            .insert_draft_session(
                session_without_worktree_id,
                "gemini-3-flash-preview",
                "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(
            base_path,
            &db,
            project_id,
            Path::new("/tmp/test"),
            &mut handles,
            &mock_fs_client,
            None,
        )
        .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;
        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-flash-preview",
                "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_output(session_id, "persisted output")
            .await
            .expect("failed to append session output");

        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("Live Output".to_string(), Status::Review),
        );

        // Act
        let (sessions, _, _) = SessionManager::load_sessions_with_fs_client(
            base_path,
            &db,
            project_id,
            Path::new("/tmp/test"),
            &mut handles,
            &mock_fs_client,
            Some(session_id),
        )
        .await;

        // Assert
        let session = sessions
            .iter()
            .find(|session| session.id == session_id)
            .expect("missing reloaded session");
        assert_eq!(session.output, "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;
        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-flash-preview",
                "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_output(session_id, "large output")
            .await
            .expect("failed to append output");

        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(
            base_path,
            &db,
            project_id,
            Path::new("/tmp/test"),
            &mut handles,
            &mock_fs_client,
            None,
        )
        .await;

        // Assert
        let session = sessions
            .iter()
            .find(|session| session.id == session_id)
            .expect("missing reloaded session");
        assert!(session.output.is_empty());
        assert!(session.prompt.is_empty());
        assert!(session.questions.is_empty());
        assert!(session.summary.is_none());

        let handle = handles.get(session_id).expect("missing runtime handle");
        let handle_output = handle.output.lock().expect("failed to lock output");
        assert!(handle_output.is_empty());
    }

    /// 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;
        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-flash-preview",
                "main",
                "Review",
                project_id,
            )
            .await
            .expect("failed to insert session");
        db.sessions()
            .append_session_output(session_id, "persisted output")
            .await
            .expect("failed to append output");

        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(String::new(), Status::Review),
        );

        // Act
        let (sessions, _, _) = SessionManager::load_sessions_with_fs_client(
            base_path,
            &db,
            project_id,
            Path::new("/tmp/test"),
            &mut handles,
            &mock_fs_client,
            Some(session_id),
        )
        .await;

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

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

    /// 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;
        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-flash-preview",
                "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("output".to_string(), Status::Review),
        );

        // Act
        let (sessions, _, _) = SessionManager::load_sessions_with_fs_client(
            base_path,
            &db,
            project_id,
            Path::new("/tmp/test"),
            &mut handles,
            &mock_fs_client,
            None,
        )
        .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 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;
        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-flash-preview",
                "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(
            base_path,
            &db,
            project_id,
            Path::new("/tmp/test"),
            &mut handles,
            &mock_fs_client,
            None,
        )
        .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 terminal DB statuses override stale in-memory handle statuses.
    fn merge_loaded_session_status_prefers_terminal_status_from_db() {
        // Arrange
        let status_from_db = Status::Done;
        let status_from_handle = Status::Draft;

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

        // Assert
        assert_eq!(merged_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 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 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,
            base_branch: "main".to_string(),
            created_at: 0,
            deleted_lines: 0,
            id: "session-a".to_string(),
            in_progress_started_at: None,
            in_progress_total_seconds: 0,
            input_tokens: 0,
            is_draft: false,
            model: "gpt-5.5".to_string(),
            output_tokens: 0,
            parent_session_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(),
            }),
            size: "XS".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!(items[0].options.is_empty());
        assert_eq!(items[1].text, "Need tests?");
        assert!(items[1].options.is_empty());
    }

    #[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());
    }
}