agentty 0.12.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
//! 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};
use crate::domain::session::{SessionId, Status};
use crate::domain::session_message::SessionTranscript;
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 this diff.
    ///
    /// Manual focused review can still replace this entry with `Loading`.
    Suppressed {
        /// Hash of the diff text that should not auto-start review assist.
        diff_hash: u64,
    },
}

impl ReviewCacheEntry {
    /// Returns the diff content hash stored in any variant.
    pub(crate) fn diff_hash(&self) -> u64 {
        match self {
            Self::Loading { diff_hash }
            | Self::Ready { diff_hash, .. }
            | Self::Failed { diff_hash, .. }
            | Self::Suppressed { diff_hash } => *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,
    /// Focused-review markdown to persist, or `None` when clearing it.
    pub(crate) text: Option<String>,
}

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

/// Returns whether one status line represents an in-flight focused review.
pub(crate) fn is_review_loading_status_message(status_message: &str) -> bool {
    status_message.starts_with(REVIEW_LOADING_MESSAGE_PREFIX)
}

/// 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())
}

/// Returns the focused-review render state that should be restored for one
/// session when reopening session view.
pub(crate) fn review_view_state<'a>(
    review_cache: &'a HashMap<SessionId, ReviewCacheEntry>,
    session_id: &str,
    review_model: AgentModel,
) -> (Option<String>, Option<&'a str>) {
    let Some(cache_entry) = review_cache.get(session_id) else {
        return (None, None);
    };

    match cache_entry {
        ReviewCacheEntry::Loading { .. } => (Some(review_loading_message(review_model)), None),
        ReviewCacheEntry::Ready { text, .. } => (None, Some(text.as_str())),
        ReviewCacheEntry::Failed { error, .. } => (
            Some(format!("Review assist unavailable: {}", error.trim())),
            None,
        ),
        ReviewCacheEntry::Suppressed { .. } => (None, None),
    }
}

/// 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()
}

/// Cancels an in-flight focused review for a session so a later stale
/// review-assist result is ignored.
///
/// Returns `true` when a loading review was removed, letting callers clear any
/// matching persisted review state from durable storage.
pub(crate) fn cancel_pending_review(
    review_cache: &mut HashMap<SessionId, ReviewCacheEntry>,
    session_id: &str,
) -> bool {
    let Some(ReviewCacheEntry::Loading { .. }) = review_cache.get(session_id) else {
        return false;
    };

    review_cache.remove(session_id);

    true
}

/// Spawns one focused review-assist task for the provided session diff.
pub(crate) fn start_review_assist(
    app_event_tx: mpsc::UnboundedSender<AppEvent>,
    review_selection: AgentSelection,
    session_id: &str,
    session_folder: &Path,
    diff_hash: u64,
    review_diff: &str,
    session_chat_history: Option<&str>,
) {
    task::TaskService::spawn_review_assist_task(task::ReviewAssistTaskInput {
        app_event_tx,
        diff_hash,
        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);
        }
    }

    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.
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>,
    review_selection: AgentSelection,
) {
    for session_id in session_ids {
        let Some(session) = session_state
            .sessions()
            .iter()
            .find(|session| session.id == *session_id)
        else {
            continue;
        };
        let current_status = session.status;

        if current_status == Status::InProgress {
            review_cache.remove(session_id);

            continue;
        }

        if current_status != Status::Review {
            continue;
        }

        if matches!(
            review_cache.get(session_id),
            Some(ReviewCacheEntry::Suppressed { .. })
        ) {
            continue;
        }

        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 = git_client
            .diff(session_folder.clone(), base_branch)
            .await
            .unwrap_or_default();

        if diff.trim().is_empty() || diff.starts_with("Failed to run git diff:") {
            continue;
        }

        let new_hash = diff_content_hash(&diff);

        if review_cache
            .get(session_id)
            .is_some_and(|entry| entry.diff_hash() == new_hash)
        {
            continue;
        }

        review_cache.insert(
            session_id.clone(),
            ReviewCacheEntry::Loading {
                diff_hash: new_hash,
            },
        );
        mark_session_agent_review(session_state, session_id);
        start_review_assist(
            app_event_tx.clone(),
            review_selection,
            session_id,
            &session_folder,
            new_hash,
            &diff,
            session_chat_history.as_deref(),
        );
    }
}

/// 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() != diff_hash
    {
        return None;
    }

    let persistence_update = FocusedReviewPersistence {
        diff_hash: result.as_ref().ok().map(|_| diff_hash),
        session_id: SessionId::from(session_id),
        text: result.as_ref().ok().cloned(),
    };
    review_cache.insert(
        SessionId::from(session_id),
        ReviewCacheEntry::from_result(diff_hash, &result),
    );
    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,
) {
    if let Some(session) = session_state
        .sessions_mut()
        .iter_mut()
        .find(|session| session.id == session_id)
        && session.status == current_status
    {
        session.status = next_status;
    }

    if let Some(handles) = session_state.handles().get(session_id)
        && let Ok(mut handle_status) = handles.status.lock()
        && *handle_status == current_status
    {
        *handle_status = next_status;
    }
}

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

    use ratatui::widgets::TableState;

    use super::*;
    use crate::app::session_state::SessionState;
    use crate::infra::clock::RealClock;

    /// 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(),
            TableState::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()),
            },
        )])
    }

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

        // Act
        let message = review_loading_message(review_model);

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

    #[test]
    fn is_review_loading_status_message_matches_model_aware_copy() {
        // Arrange
        let status_message = review_loading_message(AgentModel::ClaudeOpus48);

        // Act
        let is_loading = is_review_loading_status_message(&status_message);

        // Assert
        assert!(is_loading);
    }

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

        // Act
        let (review_status_message, review_text) =
            review_view_state(&review_cache, "session-id", AgentModel::ClaudeSonnet5);

        // Assert
        assert_eq!(
            review_status_message.as_deref(),
            Some("Reviewing changes with claude-sonnet-5")
        );
        assert_eq!(review_text, None);
    }

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

        // Act
        let (review_status_message, review_text) =
            review_view_state(&review_cache, "session-id", AgentModel::ClaudeSonnet5);

        // Assert
        assert_eq!(review_status_message, None);
        assert_eq!(review_text, 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 apply_review_updates_returns_success_for_persistence() {
        // 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,
                text: Some(review_text.to_string()),
            }]
        );
    }

    #[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: None,
                session_id,
                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 = empty_session_state();
        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_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 { diff_hash },
        )]);
        let mut session_state = empty_session_state();
        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 { diff_hash: cached_hash })
                if *cached_hash == diff_hash
        ));
    }
}