agentty 0.14.7

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
//! Focused review-cache and review-assist orchestration helpers.

use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::sync::Arc;

use ag_git::GitClient;
use tokio::sync::mpsc;

use super::core::AppEvent;
use super::task;
use crate::app::session_state::SessionState;
use crate::domain::agent::{AgentModel, AgentSelection, ReasoningLevel};
use crate::domain::review::FocusedReviewStatus;
use crate::domain::session::{Session, SessionId, SessionRole, Status};
use crate::domain::session_message::SessionTranscript;
use crate::domain::transient_message::{
    TransientMessage, TransientMessageAnchor, TransientMessageBody, TransientMessageLifecycle,
    TransientMessageSlot,
};
use crate::infra::db::SessionFocusedReviewRow;

/// Cached focused review state for a session.
#[derive(Debug)]
pub(crate) enum ReviewCacheEntry {
    /// Review generation is in progress.
    Loading {
        /// Hash of the diff text that triggered this review generation.
        diff_hash: u64,
    },
    /// Review text was successfully generated.
    Ready {
        /// Hash of the diff text that was reviewed.
        diff_hash: u64,
        /// Generated review text.
        text: String,
    },
    /// Review generation failed with an error description.
    Failed {
        /// Hash of the diff text that triggered the failed review.
        diff_hash: u64,
        /// Human-readable error description.
        error: String,
    },
    /// Automatic focused review is intentionally suppressed for the current
    /// stopped turn.
    ///
    /// Manual focused review can still replace this entry with `Loading`.
    Suppressed,
}

impl ReviewCacheEntry {
    /// Returns the diff content hash stored by generated review states.
    pub(crate) fn diff_hash(&self) -> Option<u64> {
        match self {
            Self::Loading { diff_hash }
            | Self::Ready { diff_hash, .. }
            | Self::Failed { diff_hash, .. } => Some(*diff_hash),
            Self::Suppressed => None,
        }
    }

    /// Returns whether one persistence update still represents this cache
    /// generation and lifecycle state.
    pub(crate) fn matches_persistence(&self, update: &FocusedReviewPersistence) -> bool {
        let status = match self {
            Self::Loading { .. } => FocusedReviewStatus::Pending,
            Self::Ready { .. } => FocusedReviewStatus::Ready,
            Self::Failed { .. } => FocusedReviewStatus::Failed,
            Self::Suppressed => return false,
        };

        status == update.status && self.diff_hash() == update.diff_hash
    }

    /// Builds one cache entry from a completed focused-review result.
    pub(crate) fn from_result(diff_hash: u64, result: &Result<String, String>) -> Self {
        match result {
            Ok(review_text) => Self::Ready {
                diff_hash,
                text: review_text.clone(),
            },
            Err(error) => Self::Failed {
                diff_hash,
                error: error.clone(),
            },
        }
    }
}

/// Aggregated review assist output keyed by session.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct ReviewUpdate {
    /// Hash of the diff that triggered this review, carried from the task.
    pub(crate) diff_hash: u64,
    /// Completed review assist result for the matching session.
    pub(crate) result: Result<String, String>,
}

/// Persistable focused-review cache change produced by the reducer.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct FocusedReviewPersistence {
    /// Hash of the diff that the persisted text applies to, or `None` when
    /// clearing a stale persisted review.
    pub(crate) diff_hash: Option<u64>,
    /// Stable session identifier for the focused-review cache row.
    pub(crate) session_id: SessionId,
    /// Durable generation state consumed by managed-worker orchestration.
    pub(crate) status: FocusedReviewStatus,
    /// Focused-review markdown to persist, or `None` when clearing it.
    pub(crate) text: Option<String>,
}

/// Maximum number of delayed persistence attempts after the initial
/// focused-review write fails.
pub(crate) const MAX_FOCUSED_REVIEW_PERSISTENCE_RETRIES: u8 = 3;

/// One delayed focused-review persistence attempt carried by the app event
/// reducer.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct FocusedReviewPersistenceRetry {
    /// One-based delayed retry number.
    pub(crate) attempt: u8,
    /// Focused-review generation that still needs persistence.
    pub(crate) persistence_update: FocusedReviewPersistence,
}

impl FocusedReviewPersistenceRetry {
    /// Wraps one initial write before any delayed retries have run.
    pub(crate) fn initial(persistence_update: FocusedReviewPersistence) -> Self {
        Self {
            attempt: 0,
            persistence_update,
        }
    }

    /// Returns the next bounded retry, or `None` after the retry limit.
    pub(crate) fn next(self) -> Option<Self> {
        (self.attempt < MAX_FOCUSED_REVIEW_PERSISTENCE_RETRIES).then(|| Self {
            attempt: self.attempt.saturating_add(1),
            persistence_update: self.persistence_update,
        })
    }
}

/// Prefix for the focused-review loading status while assist output is being
/// prepared.
const REVIEW_LOADING_MESSAGE_PREFIX: &str = "Reviewing changes with";

/// Computes a deterministic `FNV-1a` hash of diff text for focused-review
/// cache invalidation.
pub(crate) fn diff_content_hash(diff: &str) -> u64 {
    const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
    const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;

    diff.as_bytes().iter().fold(FNV_OFFSET_BASIS, |hash, byte| {
        (hash ^ u64::from(*byte)).wrapping_mul(FNV_PRIME)
    })
}

/// Formats the focused-review loading status with the active model name.
pub(crate) fn review_loading_message(review_model: AgentModel) -> String {
    format!("{REVIEW_LOADING_MESSAGE_PREFIX} {}", review_model.as_str())
}

/// Formats a focused-review failure for the session output panel.
pub(crate) fn review_failure_message(error: &str) -> String {
    format!("Review assist unavailable: {}", error.trim())
}

/// Returns focused-review markdown available to prompt actions for one
/// session.
pub(crate) fn review_view_text<'a>(
    review_cache: &'a HashMap<SessionId, ReviewCacheEntry>,
    session_id: &str,
) -> Option<&'a str> {
    let cache_entry = review_cache.get(session_id)?;

    match cache_entry {
        ReviewCacheEntry::Ready { text, .. } => Some(text.as_str()),
        ReviewCacheEntry::Loading { .. }
        | ReviewCacheEntry::Failed { .. }
        | ReviewCacheEntry::Suppressed => None,
    }
}

/// Rehydrates cached focused-review states into explicit display slots.
pub(crate) fn hydrate_review_transients(
    review_cache: &HashMap<SessionId, ReviewCacheEntry>,
    session_state: &mut SessionState,
    review_model: AgentModel,
) {
    for session in session_state.sessions_mut() {
        hydrate_session_review_transient(review_cache, session, review_model);
    }
}

/// Rehydrates one session's focused-review cache entry into its stable display
/// slot, retracting stale display state when the cache no longer owns output.
pub(crate) fn hydrate_review_transient(
    review_cache: &HashMap<SessionId, ReviewCacheEntry>,
    session_state: &mut SessionState,
    session_id: &str,
    review_model: AgentModel,
) {
    let Some(session) = session_state.session_mut_for_id(session_id) else {
        return;
    };

    hydrate_session_review_transient(review_cache, session, review_model);
}

/// Evicts inactive completed review entries while retaining in-flight work.
///
/// A `Loading` entry must survive project switches so its eventual result can
/// still be validated and persisted. Once that result arrives,
/// [`apply_review_updates()`] replaces the entry and this pruning step removes
/// it unless the session belongs to the currently loaded project.
pub(crate) fn prune_review_cache(
    review_cache: &mut HashMap<SessionId, ReviewCacheEntry>,
    session_state: &SessionState,
) {
    let active_session_ids = session_state
        .sessions()
        .iter()
        .map(|session| session.id.as_str())
        .collect::<HashSet<_>>();

    review_cache.retain(|session_id, cache_entry| {
        active_session_ids.contains(session_id.as_str())
            || matches!(cache_entry, ReviewCacheEntry::Loading { .. })
    });
}

/// Keeps a completed focused review at the position established by its
/// loading row, falling back to completed-turn placement for restored output.
pub(crate) fn focused_review_result_anchor(session: &Session) -> TransientMessageAnchor {
    session
        .transient_messages
        .get(TransientMessageSlot::Review)
        .map_or(TransientMessageAnchor::AfterCompletedTurn, |message| {
            message.anchor
        })
}

/// Synchronizes one session's focused-review display slot from the canonical
/// cache state.
fn hydrate_session_review_transient(
    review_cache: &HashMap<SessionId, ReviewCacheEntry>,
    session: &mut Session,
    review_model: AgentModel,
) {
    if !matches!(
        session.status,
        Status::Review | Status::Question | Status::AgentReview
    ) {
        session
            .transient_messages
            .retract(TransientMessageSlot::Review);

        return;
    }
    let Some(cache_entry) = review_cache.get(&session.id) else {
        session
            .transient_messages
            .retract(TransientMessageSlot::Review);

        return;
    };
    let (anchor, body) = match cache_entry {
        ReviewCacheEntry::Loading { .. } => (
            TransientMessageAnchor::Tail,
            TransientMessageBody::Loading(review_loading_message(review_model)),
        ),
        ReviewCacheEntry::Ready { text, .. } => (
            focused_review_result_anchor(session),
            TransientMessageBody::Markdown(text.clone()),
        ),
        ReviewCacheEntry::Failed { error, .. } => (
            focused_review_result_anchor(session),
            TransientMessageBody::Plain(review_failure_message(error)),
        ),
        ReviewCacheEntry::Suppressed => {
            session
                .transient_messages
                .retract(TransientMessageSlot::Review);

            return;
        }
    };

    session.transient_messages.upsert(TransientMessage {
        anchor,
        body,
        lifecycle: TransientMessageLifecycle::ClearOnNewTurn,
        slot: TransientMessageSlot::Review,
        turn_position: session.latest_user_prompt_position(),
    });
}

/// Builds the startup focused-review cache from persisted rows.
pub(crate) fn review_cache_from_rows(
    focused_review_rows: Vec<SessionFocusedReviewRow>,
) -> HashMap<SessionId, ReviewCacheEntry> {
    focused_review_rows
        .into_iter()
        .filter_map(|row| {
            let diff_hash = row.diff_hash.parse::<u64>().ok()?;

            Some((
                SessionId::from(row.session_id),
                ReviewCacheEntry::Ready {
                    diff_hash,
                    text: row.text,
                },
            ))
        })
        .collect()
}

/// Spawns one focused review-assist task for the provided session diff.
pub(crate) fn start_review_assist(
    app_event_tx: mpsc::UnboundedSender<AppEvent>,
    review_agent: (AgentSelection, ReasoningLevel),
    session_id: &str,
    session_folder: &Path,
    diff_hash: u64,
    review_diff: &str,
    session_chat_history: Option<&str>,
) {
    let (review_selection, reasoning_level) = review_agent;

    task::TaskService::spawn_review_assist_task(task::ReviewAssistTaskInput {
        app_event_tx,
        diff_hash,
        reasoning_level,
        review_diff: review_diff.to_string(),
        review_selection,
        session_chat_history: session_chat_history.map(str::to_string),
        session_folder: session_folder.to_path_buf(),
        session_id: SessionId::from(session_id),
    });
}

/// Marks one review-ready session as transient `AgentReview` while focused
/// review generation is running.
pub(crate) fn mark_session_agent_review(session_state: &mut SessionState, session_id: &str) {
    update_transient_review_status(
        session_state,
        session_id,
        Status::Review,
        Status::AgentReview,
    );
}

/// Applies review assist updates for all sessions in one reducer batch.
pub(crate) fn apply_review_updates(
    review_cache: &mut HashMap<SessionId, ReviewCacheEntry>,
    session_state: &mut SessionState,
    review_updates: HashMap<SessionId, ReviewUpdate>,
) -> Vec<FocusedReviewPersistence> {
    let mut persistence_updates = Vec::new();

    for (session_id, review_update) in review_updates {
        if let Some(persistence_update) =
            apply_review_update(review_cache, session_state, &session_id, review_update)
        {
            persistence_updates.push(persistence_update);
        }
    }

    prune_review_cache(review_cache, session_state);

    persistence_updates
}

/// Starts focused review generation for sessions that just entered review.
///
/// Uses a status-based check instead of transition detection because pending
/// `SessionUpdated` events may synchronize handle-backed status before the
/// paired review-related reducer work runs, making transition detection
/// unreliable.
///
/// Sessions returning to `InProgress` clear their cached review immediately so
/// the next completed diff triggers a fresh assist run. Sessions with a
/// [`ReviewCacheEntry::Suppressed`] marker skip diff loading entirely; stopped
/// turns set that marker synchronously so cancellation does not block on `git
/// diff` just to prevent automatic review startup. Orchestrator controllers
/// also skip automatic review because they coordinate child work without
/// owning branch changes.
pub(crate) async fn auto_start_reviews(
    review_cache: &mut HashMap<SessionId, ReviewCacheEntry>,
    session_ids: &HashSet<SessionId>,
    session_state: &mut SessionState,
    git_client: Arc<dyn GitClient>,
    app_event_tx: mpsc::UnboundedSender<AppEvent>,
    reasoning_level: ReasoningLevel,
    review_selection: AgentSelection,
) -> Vec<FocusedReviewPersistence> {
    let mut persistence_updates = Vec::new();
    for session_id in session_ids {
        if let Some(persistence_update) = auto_start_review_for_session(
            review_cache,
            session_state,
            git_client.as_ref(),
            &app_event_tx,
            reasoning_level,
            review_selection,
            session_id,
        )
        .await
        {
            persistence_updates.push(persistence_update);
        }
    }

    persistence_updates
}

/// Starts focused review generation for one eligible session snapshot.
async fn auto_start_review_for_session(
    review_cache: &mut HashMap<SessionId, ReviewCacheEntry>,
    session_state: &mut SessionState,
    git_client: &dyn GitClient,
    app_event_tx: &mpsc::UnboundedSender<AppEvent>,
    reasoning_level: ReasoningLevel,
    review_selection: AgentSelection,
    session_id: &SessionId,
) -> Option<FocusedReviewPersistence> {
    let session = session_state.session_for_id(session_id)?;
    let current_status = session.status;

    if current_status == Status::InProgress {
        review_cache.remove(session_id);
        if let Some(session) = session_state.session_mut_for_id(session_id) {
            session
                .transient_messages
                .retract(TransientMessageSlot::Review);
        }

        return None;
    }

    if session.role == SessionRole::Orchestrator
        || !matches!(current_status, Status::Review | Status::AgentReview)
        || matches!(
            review_cache.get(session_id),
            Some(ReviewCacheEntry::Suppressed)
        )
    {
        return None;
    }

    let base_branch = session.base_branch.clone();
    let session_chat_history = session
        .transcript
        .as_ref()
        .and_then(SessionTranscript::conversation_replay_text);
    let session_folder = session.folder.clone();
    let diff = match git_client.diff(session_folder.clone(), base_branch).await {
        Ok(diff) => diff,
        Err(error) => {
            return Some(fail_review_preparation(
                review_cache,
                session_state,
                session_id,
                format!("Failed to run git diff: {error}"),
                review_selection.model(),
            ));
        }
    };

    if diff.starts_with("Failed to run git diff:") {
        return Some(fail_review_preparation(
            review_cache,
            session_state,
            session_id,
            diff,
            review_selection.model(),
        ));
    }
    if diff.trim().is_empty() {
        return None;
    }

    let new_hash = diff_content_hash(&diff);
    if review_cache
        .get(session_id)
        .is_some_and(|entry| entry.diff_hash() == Some(new_hash))
    {
        return None;
    }

    review_cache.insert(
        session_id.clone(),
        ReviewCacheEntry::Loading {
            diff_hash: new_hash,
        },
    );
    mark_session_agent_review(session_state, session_id);
    if let Some(session) = session_state.session_mut_for_id(session_id) {
        session.transient_messages.upsert(TransientMessage {
            anchor: TransientMessageAnchor::Tail,
            body: TransientMessageBody::Loading(review_loading_message(review_selection.model())),
            lifecycle: TransientMessageLifecycle::ClearOnNewTurn,
            slot: TransientMessageSlot::Review,
            turn_position: session.latest_user_prompt_position(),
        });
    }
    start_review_assist(
        app_event_tx.clone(),
        (review_selection, reasoning_level),
        session_id,
        &session_folder,
        new_hash,
        &diff,
        session_chat_history.as_deref(),
    );

    Some(FocusedReviewPersistence {
        diff_hash: Some(new_hash),
        session_id: session_id.clone(),
        status: FocusedReviewStatus::Pending,
        text: None,
    })
}

/// Records a terminal focused-review failure when preparation cannot load a
/// diff for review generation.
fn fail_review_preparation(
    review_cache: &mut HashMap<SessionId, ReviewCacheEntry>,
    session_state: &mut SessionState,
    session_id: &SessionId,
    error: String,
    review_model: AgentModel,
) -> FocusedReviewPersistence {
    let diff_hash = diff_content_hash("");
    review_cache.insert(
        session_id.clone(),
        ReviewCacheEntry::Failed { diff_hash, error },
    );
    hydrate_review_transient(review_cache, session_state, session_id, review_model);

    FocusedReviewPersistence {
        diff_hash: Some(diff_hash),
        session_id: session_id.clone(),
        status: FocusedReviewStatus::Failed,
        text: None,
    }
}

/// Applies one review assist update to cache and session review status.
fn apply_review_update(
    review_cache: &mut HashMap<SessionId, ReviewCacheEntry>,
    session_state: &mut SessionState,
    session_id: &str,
    review_update: ReviewUpdate,
) -> Option<FocusedReviewPersistence> {
    let ReviewUpdate { diff_hash, result } = review_update;
    let cache_entry = review_cache.get(session_id)?;

    if !matches!(cache_entry, ReviewCacheEntry::Loading { .. })
        || cache_entry.diff_hash() != Some(diff_hash)
    {
        return None;
    }

    let persistence_update = FocusedReviewPersistence {
        diff_hash: Some(diff_hash),
        session_id: SessionId::from(session_id),
        status: if result.is_ok() {
            FocusedReviewStatus::Ready
        } else {
            FocusedReviewStatus::Failed
        },
        text: result.as_ref().ok().cloned(),
    };
    review_cache.insert(
        SessionId::from(session_id),
        ReviewCacheEntry::from_result(diff_hash, &result),
    );
    if let Some(session) = session_state
        .sessions_mut()
        .iter_mut()
        .find(|session| session.id == session_id)
    {
        let anchor = focused_review_result_anchor(session);
        let body = match &result {
            Ok(review_text) => TransientMessageBody::Markdown(review_text.clone()),
            Err(error) => TransientMessageBody::Plain(review_failure_message(error)),
        };
        session.transient_messages.upsert(TransientMessage {
            anchor,
            body,
            lifecycle: TransientMessageLifecycle::ClearOnNewTurn,
            slot: TransientMessageSlot::Review,
            turn_position: session.latest_user_prompt_position(),
        });
    }
    restore_session_review_status(session_state, session_id);

    Some(persistence_update)
}

/// Restores one transient `AgentReview` session back to `Review` after the
/// focused-review task completes.
fn restore_session_review_status(session_state: &mut SessionState, session_id: &str) {
    update_transient_review_status(
        session_state,
        session_id,
        Status::AgentReview,
        Status::Review,
    );
}

/// Updates one session snapshot and live handle when a transient review status
/// transition still matches the expected current status.
fn update_transient_review_status(
    session_state: &mut SessionState,
    session_id: &str,
    current_status: Status,
    next_status: Status,
) {
    session_state.transition_status_if_current(session_id, current_status, next_status);
}

#[cfg(test)]
mod tests {
    use std::collections::{HashMap, HashSet};
    use std::sync::Arc;

    use super::*;
    use crate::app::session_state::SessionState;
    use crate::domain::selection::SelectionState;
    use crate::infra::clock::RealClock;
    use crate::test_support::SessionFixtureBuilder;

    /// Builds empty session state for review reducer tests that only need mode
    /// field updates.
    fn empty_session_state() -> SessionState {
        SessionState::new(
            HashMap::new(),
            Vec::new(),
            SelectionState::default(),
            Arc::new(RealClock),
            0,
            0,
        )
    }

    /// Builds a single loading review cache entry for one session.
    fn loading_review_cache(
        session_id: &SessionId,
        diff_hash: u64,
    ) -> HashMap<SessionId, ReviewCacheEntry> {
        HashMap::from([(session_id.clone(), ReviewCacheEntry::Loading { diff_hash })])
    }

    /// Builds a single successful review update for one session.
    fn successful_review_update(
        session_id: &SessionId,
        diff_hash: u64,
        review_text: &str,
    ) -> HashMap<SessionId, ReviewUpdate> {
        HashMap::from([(
            session_id.clone(),
            ReviewUpdate {
                diff_hash,
                result: Ok(review_text.to_string()),
            },
        )])
    }

    /// Builds one review-ready session with stale focused-review display text.
    fn session_state_with_stale_review(session_id: &SessionId) -> SessionState {
        let mut session = SessionFixtureBuilder::new()
            .id(session_id.as_str())
            .status(Status::Review)
            .build();
        session.transient_messages.upsert(TransientMessage {
            anchor: TransientMessageAnchor::AfterCompletedTurn,
            body: TransientMessageBody::Markdown("stale review".to_string()),
            lifecycle: TransientMessageLifecycle::ClearOnNewTurn,
            slot: TransientMessageSlot::Review,
            turn_position: None,
        });

        SessionState::new(
            HashMap::new(),
            vec![session],
            SelectionState::default(),
            Arc::new(RealClock),
            0,
            0,
        )
    }

    #[test]
    fn review_loading_message_uses_requested_model_name() {
        // Arrange
        let review_model = AgentModel::Gpt56Sol;

        // Act
        let message = review_loading_message(review_model);

        // Assert
        assert_eq!(message, "Reviewing changes with gpt-5.6-sol");
    }

    #[test]
    fn review_view_text_hides_cached_review_generation() {
        // Arrange
        let mut review_cache = HashMap::new();
        review_cache.insert(
            "session-id".into(),
            ReviewCacheEntry::Loading { diff_hash: 7 },
        );

        // Act
        let review_text = review_view_text(&review_cache, "session-id");

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

    #[test]
    fn review_view_text_hides_suppressed_auto_review() {
        // Arrange
        let mut review_cache = HashMap::new();
        review_cache.insert("session-id".into(), ReviewCacheEntry::Suppressed);

        // Act
        let review_text = review_view_text(&review_cache, "session-id");

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

    #[test]
    fn review_cache_matches_only_current_persistence_state() {
        // Arrange
        let update = |status| FocusedReviewPersistence {
            diff_hash: Some(42),
            session_id: "session-id".into(),
            status,
            text: None,
        };
        let loading = ReviewCacheEntry::Loading { diff_hash: 42 };
        let ready = ReviewCacheEntry::Ready {
            diff_hash: 42,
            text: "review".to_string(),
        };
        let failed = ReviewCacheEntry::Failed {
            diff_hash: 42,
            error: "failed".to_string(),
        };

        // Act / Assert
        assert!(loading.matches_persistence(&update(FocusedReviewStatus::Pending)));
        assert!(ready.matches_persistence(&update(FocusedReviewStatus::Ready)));
        assert!(failed.matches_persistence(&update(FocusedReviewStatus::Failed)));
        assert!(!ready.matches_persistence(&update(FocusedReviewStatus::Pending)));
        assert!(
            !ReviewCacheEntry::Suppressed.matches_persistence(&update(FocusedReviewStatus::Failed))
        );
        let mut stale = update(FocusedReviewStatus::Ready);
        stale.diff_hash = Some(41);
        assert!(!ready.matches_persistence(&stale));
    }

    #[tokio::test]
    async fn auto_start_reviews_persists_diff_preparation_failures() {
        let cases = [
            (
                Err(ag_git::GitError::OutputParse(
                    "diff unavailable".to_string(),
                )),
                "Failed to run git diff: diff unavailable",
            ),
            (
                Ok("Failed to run git diff: command failed".to_string()),
                "Failed to run git diff: command failed",
            ),
        ];

        for (diff_result, expected_error) in cases {
            // Arrange
            let session_id = SessionId::from("session-id");
            let mut review_cache = HashMap::new();
            let mut session_state = session_state_with_stale_review(&session_id);
            let review_selection = session_state.sessions()[0].agent;
            let session_ids = HashSet::from([session_id.clone()]);
            let mut git_client = ag_git::MockGitClient::new();
            git_client
                .expect_diff()
                .return_once(move |_, _| Box::pin(async move { diff_result }));
            let (app_event_tx, _app_event_rx) = mpsc::unbounded_channel();
            let expected_diff_hash = diff_content_hash("");

            // Act
            let persistence_updates = auto_start_reviews(
                &mut review_cache,
                &session_ids,
                &mut session_state,
                Arc::new(git_client),
                app_event_tx,
                ReasoningLevel::High,
                review_selection,
            )
            .await;

            // Assert
            assert_eq!(
                persistence_updates,
                [FocusedReviewPersistence {
                    diff_hash: Some(expected_diff_hash),
                    session_id: session_id.clone(),
                    status: FocusedReviewStatus::Failed,
                    text: None,
                }]
            );
            assert!(matches!(
                review_cache.get(&session_id),
                Some(ReviewCacheEntry::Failed { diff_hash, error })
                    if *diff_hash == expected_diff_hash && error == expected_error
            ));
            assert_eq!(session_state.sessions()[0].status, Status::Review);
        }
    }

    #[test]
    fn focused_review_persistence_retry_stops_after_limit() {
        // Arrange
        let persistence_update = FocusedReviewPersistence {
            diff_hash: Some(42),
            session_id: "session-id".into(),
            status: FocusedReviewStatus::Ready,
            text: Some("review".to_string()),
        };

        // Act
        let first = FocusedReviewPersistenceRetry::initial(persistence_update)
            .next()
            .expect("first retry should exist");
        let second = first.clone().next().expect("second retry should exist");
        let third = second.clone().next().expect("third retry should exist");
        let exhausted = third.clone().next();

        // Assert
        assert_eq!((first.attempt, second.attempt, third.attempt), (1, 2, 3));
        assert_eq!(exhausted, None);
    }

    #[test]
    fn review_cache_from_rows_restores_persisted_ready_review() {
        // Arrange
        let focused_review_rows = vec![SessionFocusedReviewRow {
            diff_hash: "42".to_string(),
            session_id: "session-id".to_string(),
            text: "## Review\nPersisted finding.".to_string(),
        }];

        // Act
        let review_cache = review_cache_from_rows(focused_review_rows);

        // Assert
        assert!(matches!(
            review_cache.get("session-id"),
            Some(ReviewCacheEntry::Ready { diff_hash: 42, text })
                if text == "## Review\nPersisted finding."
        ));
    }

    #[test]
    fn hydrate_review_transients_retracts_terminal_session_review() {
        // Arrange
        let session_id = SessionId::from("session-id");
        let mut session = SessionFixtureBuilder::new()
            .id(session_id.as_str())
            .status(Status::Done)
            .build();
        session.transient_messages.upsert(TransientMessage {
            anchor: TransientMessageAnchor::AfterCompletedTurn,
            body: TransientMessageBody::Markdown("stale review".to_string()),
            lifecycle: TransientMessageLifecycle::ClearOnNewTurn,
            slot: TransientMessageSlot::Review,
            turn_position: None,
        });
        let review_cache = HashMap::from([(
            session_id,
            ReviewCacheEntry::Ready {
                diff_hash: 42,
                text: "persisted review".to_string(),
            },
        )]);
        let mut session_state = SessionState::new(
            HashMap::new(),
            vec![session],
            SelectionState::default(),
            Arc::new(RealClock),
            0,
            0,
        );

        // Act
        hydrate_review_transients(&review_cache, &mut session_state, AgentModel::Gpt56Sol);

        // Assert
        assert!(
            session_state.sessions()[0]
                .transient_messages
                .get(TransientMessageSlot::Review)
                .is_none()
        );
    }

    #[test]
    fn hydrate_review_transient_retracts_review_without_cache_entry() {
        // Arrange
        let session_id = SessionId::from("session-id");
        let mut session_state = session_state_with_stale_review(&session_id);

        // Act
        hydrate_review_transient(
            &HashMap::new(),
            &mut session_state,
            &session_id,
            AgentModel::Gpt56Sol,
        );

        // Assert
        assert!(
            session_state.sessions()[0]
                .transient_messages
                .get(TransientMessageSlot::Review)
                .is_none()
        );
    }

    #[test]
    fn hydrate_review_transient_retracts_suppressed_review() {
        // Arrange
        let session_id = SessionId::from("session-id");
        let review_cache = HashMap::from([(session_id.clone(), ReviewCacheEntry::Suppressed)]);
        let mut session_state = session_state_with_stale_review(&session_id);

        // Act
        hydrate_review_transient(
            &review_cache,
            &mut session_state,
            &session_id,
            AgentModel::Gpt56Sol,
        );

        // Assert
        assert!(
            session_state.sessions()[0]
                .transient_messages
                .get(TransientMessageSlot::Review)
                .is_none()
        );
    }

    #[test]
    fn hydrate_review_transient_restores_failed_review() {
        // Arrange
        let session_id = SessionId::from("session-id");
        let review_cache = HashMap::from([(
            session_id.clone(),
            ReviewCacheEntry::Failed {
                diff_hash: 42,
                error: "provider unavailable".to_string(),
            },
        )]);
        let mut session_state = session_state_with_stale_review(&session_id);

        // Act
        hydrate_review_transient(
            &review_cache,
            &mut session_state,
            &session_id,
            AgentModel::Gpt56Sol,
        );

        // Assert
        assert_eq!(
            session_state.sessions()[0]
                .transient_messages
                .get(TransientMessageSlot::Review)
                .map(|message| &message.body),
            Some(&TransientMessageBody::Plain(
                "Review assist unavailable: provider unavailable".to_string()
            ))
        );
    }

    #[test]
    fn hydrate_review_transient_ignores_missing_session() {
        // Arrange
        let mut session_state = empty_session_state();

        // Act
        hydrate_review_transient(
            &HashMap::new(),
            &mut session_state,
            "missing-session",
            AgentModel::Gpt56Sol,
        );

        // Assert
        assert!(session_state.sessions().is_empty());
    }

    #[test]
    fn prune_review_cache_retains_active_and_loading_entries() {
        // Arrange
        let active_session_id = SessionId::from("active-session");
        let loading_session_id = SessionId::from("loading-session");
        let mut review_cache = HashMap::from([
            (
                active_session_id.clone(),
                ReviewCacheEntry::Ready {
                    diff_hash: 1,
                    text: "active review".to_string(),
                },
            ),
            (
                "inactive-ready".into(),
                ReviewCacheEntry::Ready {
                    diff_hash: 2,
                    text: "inactive review".to_string(),
                },
            ),
            (
                "inactive-failed".into(),
                ReviewCacheEntry::Failed {
                    diff_hash: 3,
                    error: "failed review".to_string(),
                },
            ),
            ("inactive-suppressed".into(), ReviewCacheEntry::Suppressed),
            (
                loading_session_id.clone(),
                ReviewCacheEntry::Loading { diff_hash: 4 },
            ),
        ]);
        let session_state = session_state_with_stale_review(&active_session_id);

        // Act
        prune_review_cache(&mut review_cache, &session_state);

        // Assert
        assert_eq!(review_cache.len(), 2);
        assert!(review_cache.contains_key(&active_session_id));
        assert!(matches!(
            review_cache.get(&loading_session_id),
            Some(ReviewCacheEntry::Loading { diff_hash: 4 })
        ));
    }

    #[test]
    fn apply_review_updates_persists_and_evicts_inactive_success() {
        // Arrange
        let session_id = SessionId::from("session-persist-review");
        let diff_hash = 19;
        let review_text = "## Review\nPersist this finding.";
        let mut review_cache = loading_review_cache(&session_id, diff_hash);
        let mut session_state = empty_session_state();
        let review_updates = successful_review_update(&session_id, diff_hash, review_text);

        // Act
        let persistence_updates =
            apply_review_updates(&mut review_cache, &mut session_state, review_updates);

        // Assert
        assert_eq!(
            persistence_updates,
            vec![FocusedReviewPersistence {
                diff_hash: Some(diff_hash),
                session_id: session_id.clone(),
                status: FocusedReviewStatus::Ready,
                text: Some(review_text.to_string()),
            }]
        );
        assert!(!review_cache.contains_key(&session_id));
    }

    #[test]
    fn apply_review_updates_returns_clear_for_failed_regeneration() {
        // Arrange
        let session_id = SessionId::from("session-failed-review");
        let diff_hash = 29;
        let mut review_cache = loading_review_cache(&session_id, diff_hash);
        let mut session_state = empty_session_state();
        let review_updates = HashMap::from([(
            session_id.clone(),
            ReviewUpdate {
                diff_hash,
                result: Err("provider failed".to_string()),
            },
        )]);

        // Act
        let persistence_updates =
            apply_review_updates(&mut review_cache, &mut session_state, review_updates);

        // Assert
        assert_eq!(
            persistence_updates,
            vec![FocusedReviewPersistence {
                diff_hash: Some(diff_hash),
                session_id,
                status: FocusedReviewStatus::Failed,
                text: None,
            }]
        );
    }

    #[test]
    fn apply_review_updates_writes_success_to_cache() {
        // Arrange
        let session_id = SessionId::from("session-cache-review");
        let diff_hash = 11;
        let review_text = "## Review\nCache-backed finding.";
        let mut review_cache = loading_review_cache(&session_id, diff_hash);
        let mut session_state = session_state_with_stale_review(&session_id);
        let review_updates = successful_review_update(&session_id, diff_hash, review_text);

        // Act
        apply_review_updates(&mut review_cache, &mut session_state, review_updates);

        // Assert
        assert!(matches!(
            review_cache.get(session_id.as_str()),
            Some(ReviewCacheEntry::Ready { text, .. }) if text == review_text
        ));
    }

    #[test]
    fn apply_review_updates_preserves_loading_row_tail_position() {
        // Arrange
        let session_id = SessionId::from("session-tail-review");
        let diff_hash = 17;
        let review_text = "## Review\nChronological finding.";
        let mut review_cache = loading_review_cache(&session_id, diff_hash);
        let mut session = SessionFixtureBuilder::new()
            .id(session_id.as_str())
            .status(Status::AgentReview)
            .build();
        session.transient_messages.upsert(TransientMessage {
            anchor: TransientMessageAnchor::Tail,
            body: TransientMessageBody::Loading("Reviewing changes".to_string()),
            lifecycle: TransientMessageLifecycle::ClearOnNewTurn,
            slot: TransientMessageSlot::Review,
            turn_position: None,
        });
        let mut session_state = SessionState::new(
            HashMap::new(),
            vec![session],
            SelectionState::default(),
            Arc::new(RealClock),
            0,
            0,
        );
        let review_updates = successful_review_update(&session_id, diff_hash, review_text);

        // Act
        apply_review_updates(&mut review_cache, &mut session_state, review_updates);

        // Assert
        let review_message = session_state.sessions()[0]
            .transient_messages
            .get(TransientMessageSlot::Review)
            .expect("completed review should remain visible");
        assert_eq!(review_message.anchor, TransientMessageAnchor::Tail);
        assert_eq!(
            review_message.body,
            TransientMessageBody::Markdown(review_text.to_string())
        );
    }

    #[test]
    fn apply_review_updates_ignores_suppressed_auto_review_entry() {
        // Arrange
        let session_id = SessionId::from("session-suppressed-review");
        let diff_hash = 23;
        let mut review_cache = HashMap::from([(session_id.clone(), ReviewCacheEntry::Suppressed)]);
        let mut session_state = session_state_with_stale_review(&session_id);
        let review_updates =
            successful_review_update(&session_id, diff_hash, "## Review\nShould not be rendered.");

        // Act
        apply_review_updates(&mut review_cache, &mut session_state, review_updates);

        // Assert
        assert!(matches!(
            review_cache.get(session_id.as_str()),
            Some(ReviewCacheEntry::Suppressed)
        ));
    }
}