agentty 0.13.6

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
use std::fmt::Write as _;
use std::path::PathBuf;

use ag_agent as agent;
use ag_forge::{ReviewCommentSnapshot, ReviewCommentThread};
use tracing::warn;

use crate::app::{App, ReviewCacheEntry, diff_content_hash};
use crate::domain::agent::{AgentSelection, ReasoningLevel};
use crate::domain::composer::PromptAttachment;
use crate::domain::review;
use crate::domain::session::{Session, SessionId, Status};
use crate::domain::transcript_notice::TranscriptNotice;
use crate::domain::turn_prompt::{TurnPrompt, TurnPromptAttachment, TurnPromptTextSource};
use crate::infra::clipboard_image;
use crate::presentation::app_mode::{ReviewCommentAction, ReviewCommentActionSelection};

/// Checked-in prompt template submitted by the `/apply` slash command.
const APPLY_REVIEW_PROMPT_TEMPLATE: &str = include_str!("template/apply_review_prompt.md");
/// Checked-in prompt template submitted from the review-comments page.
const RESOLVE_REVIEW_COMMENT_PROMPT_TEMPLATE: &str =
    include_str!("template/resolve_review_comment_prompt.md");

/// Presentation navigation requested after a review-comment resolution attempt.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) enum ReviewCommentResolutionOutcome {
    /// Keep the review-comment page open because no reply was enqueued.
    KeepReviewComments,
    /// Show the session that accepted the review-comment reply.
    ShowSession { session_id: SessionId },
}

/// Typed prompt submission emitted by the presentation boundary.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct PromptSubmission {
    /// Structured user input drained from the prompt composer.
    pub(crate) prompt: TurnPrompt,
    /// Stable identifier for the active prompt session.
    pub(crate) session_id: SessionId,
    /// Session lifecycle shape used for app-layer submission routing.
    pub(crate) session_mode: PromptSessionMode,
}

/// Typed cancellation request emitted by the presentation boundary.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct PromptCancellation {
    /// Stable identifier for the active prompt session.
    pub(crate) session_id: SessionId,
    /// Session lifecycle shape used for app-layer cancellation routing.
    pub(crate) session_mode: PromptSessionMode,
}

/// Session lifecycle shape used by prompt submission and cancellation routing.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum PromptSessionMode {
    /// Existing session receiving a follow-up reply.
    Existing,
    /// New non-draft session that can be deleted when prompt composition is
    /// canceled.
    NewDeletable,
    /// Draft-mode session that stages prompt text instead of starting a turn.
    NewDraft,
    /// New non-draft session that should be preserved on cancel because it
    /// has staged drafts.
    NewRegular,
}

/// Presentation navigation requested after one app-layer prompt workflow.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) enum PromptWorkflowOutcome {
    /// Keep the prompt composer open because no submit action was performed.
    KeepPrompt,
    /// Return to the active session chat view.
    ShowSession { session_id: SessionId },
    /// Return to the top-level session list after deleting a blank draft.
    ShowSessionList,
}

/// Presentation action requested after executing `/apply`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) enum PromptApplyOutcome {
    /// Clear the accepted slash command and keep the composer open.
    ClearComposer,
    /// Preserve the slash command for correction or retry.
    KeepComposer,
    /// Clear the composer and show the session chat view.
    ShowSession { session_id: SessionId },
}

/// Clipboard-image capture request emitted from a prompt composer.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct PromptImagePaste {
    /// One-based image placeholder number allocated by presentation state.
    pub(crate) attachment_number: usize,
    /// Session that owns the prompt composer.
    pub(crate) session_id: SessionId,
}

impl App {
    /// Submits one agent turn for the selected forge review comments.
    ///
    /// Returns a navigation effect that shows the session only when at least
    /// one actionable comment was rendered and its worker accepted the reply.
    pub(crate) async fn resolve_session_review_comments(
        &mut self,
        session_id: &SessionId,
        snapshot: &ReviewCommentSnapshot,
        selections: &[ReviewCommentActionSelection],
    ) -> ReviewCommentResolutionOutcome {
        let can_reply = self
            .sessions
            .sessions()
            .iter()
            .find(|session| session.id == *session_id)
            .is_some_and(Session::allows_review_comment_reply);
        if !can_reply {
            return ReviewCommentResolutionOutcome::KeepReviewComments;
        }

        let Some((prompt, thread_ids)) = build_resolve_review_comment_prompt(snapshot, selections)
        else {
            return ReviewCommentResolutionOutcome::KeepReviewComments;
        };

        self.clear_review_output(session_id.as_str());
        let _ = self
            .services
            .db()
            .sessions()
            .update_session_focused_review(session_id, None, None)
            .await;
        let enqueued = self
            .sessions
            .reply_to_review_comments(&self.services, session_id, prompt, thread_ids)
            .await;
        if !enqueued {
            return ReviewCommentResolutionOutcome::KeepReviewComments;
        }

        ReviewCommentResolutionOutcome::ShowSession {
            session_id: session_id.clone(),
        }
    }

    /// Routes one presentation-owned prompt submission through the matching
    /// session workflow and returns the requested navigation effect.
    pub(crate) async fn submit_prompt(
        &mut self,
        submission: PromptSubmission,
    ) -> PromptWorkflowOutcome {
        let PromptSubmission {
            prompt,
            session_id,
            session_mode,
        } = submission;
        if prompt.is_empty() {
            return PromptWorkflowOutcome::KeepPrompt;
        }

        self.submit_turn_prompt(session_id.clone(), session_mode, prompt)
            .await;

        PromptWorkflowOutcome::ShowSession { session_id }
    }

    /// Persists one clipboard image and returns its local path for the
    /// presentation-owned composer to insert as a placeholder.
    pub(crate) async fn persist_prompt_image(&self, request: PromptImagePaste) -> Option<PathBuf> {
        match self
            .services
            .clipboard_image_client()
            .persist_clipboard_image(
                request.session_id.as_str().to_string(),
                request.attachment_number,
            )
            .await
        {
            Ok(persisted_image) => Some(persisted_image.local_image_path),
            Err(error) => {
                self.append_prompt_status_line(
                    request.session_id.as_str(),
                    TranscriptNotice::PasteImageError,
                    &clipboard_image::normalize_clipboard_image_error(&error),
                )
                .await;

                None
            }
        }
    }

    /// Removes image files whose attachment identities are no longer
    /// reachable through the presentation-owned prompt composer.
    pub(crate) async fn cleanup_prompt_attachments(&self, attachments: Vec<PromptAttachment>) {
        if attachments.is_empty() {
            return;
        }

        let attachments = attachments
            .into_iter()
            .map(|attachment| TurnPromptAttachment {
                local_image_path: attachment.local_image_path,
                placeholder: attachment.placeholder,
            })
            .collect();
        let prompt = TurnPrompt {
            attachments,
            text: String::new(),
            text_source: TurnPromptTextSource::UserPrompt,
        };

        self.cleanup_prompt_attachment_files(&prompt).await;
    }

    /// Cancels one presentation-owned prompt and returns the requested
    /// navigation effect.
    pub(crate) async fn cancel_prompt(
        &mut self,
        cancellation: PromptCancellation,
    ) -> PromptWorkflowOutcome {
        if cancellation.session_mode == PromptSessionMode::NewDeletable {
            self.delete_selected_session_deferred_cleanup().await;

            return PromptWorkflowOutcome::ShowSessionList;
        }

        PromptWorkflowOutcome::ShowSession {
            session_id: cancellation.session_id,
        }
    }

    /// Returns whether cached focused-review text contains actionable
    /// suggestions for one session.
    pub(crate) fn prompt_apply_command_is_available_for_session(&self, session_id: &str) -> bool {
        let Some(ReviewCacheEntry::Ready { text, .. }) = self.review_cache.get(session_id) else {
            return false;
        };

        review::has_actionable_review_suggestions(Some(text))
    }

    /// Persists one slash-selected model change and logs any failure with
    /// session context.
    pub(crate) async fn update_prompt_session_model(
        &mut self,
        session_id: &SessionId,
        selected_agent: AgentSelection,
    ) {
        if let Err(error) = self.set_session_model(session_id, selected_agent).await {
            warn!(
                session_id = %session_id,
                agent = %selected_agent.kind(),
                model = %selected_agent.model().as_str(),
                error = %error,
                "failed to switch session model from prompt slash command"
            );
        }
    }

    /// Persists one slash-selected reasoning level and logs any failure with
    /// session context.
    pub(crate) async fn update_prompt_session_reasoning_level(
        &mut self,
        session_id: &SessionId,
        reasoning_level: ReasoningLevel,
    ) {
        if let Err(error) = self
            .set_session_reasoning_level(session_id, reasoning_level)
            .await
        {
            warn!(
                session_id = %session_id,
                reasoning_level = ?reasoning_level,
                error = %error,
                "failed to update session reasoning level from prompt slash command"
            );
        }
    }

    /// Handles `/apply` by extracting suggestions from the focused review and
    /// submitting them as a verification-gated prompt to the agent.
    pub(crate) async fn apply_focused_review(
        &mut self,
        session_id: &SessionId,
        session_index: usize,
    ) -> PromptApplyOutcome {
        let Some((session_status, session_folder, base_branch)) =
            self.session_at(session_index).map(|session| {
                (
                    session.status,
                    session.folder.clone(),
                    session.base_branch.clone(),
                )
            })
        else {
            return PromptApplyOutcome::KeepComposer;
        };

        if session_status != Status::Review {
            self.append_prompt_status_line(
                session_id,
                TranscriptNotice::Apply,
                "Apply is only available after a focused review completes (session status must be \
                 Review).",
            )
            .await;

            return PromptApplyOutcome::ClearComposer;
        }

        let (cached_hash, cached_text) = if let Some(ReviewCacheEntry::Ready { diff_hash, text }) =
            self.review_cache.get(session_id.as_str())
        {
            (*diff_hash, text.clone())
        } else {
            self.append_prompt_status_line(
                session_id,
                TranscriptNotice::Apply,
                "No actionable suggestions available. Run a focused review first (f key).",
            )
            .await;

            return PromptApplyOutcome::ClearComposer;
        };

        let current_diff = match self
            .services
            .git_client()
            .diff(session_folder, base_branch)
            .await
        {
            Ok(diff) => diff,
            Err(error) => {
                self.append_prompt_status_line(
                    session_id,
                    TranscriptNotice::Apply,
                    &format!(
                        "Failed to read worktree diff: {error}. Review cache preserved; try \
                         /apply again."
                    ),
                )
                .await;

                return PromptApplyOutcome::ClearComposer;
            }
        };
        let current_hash = diff_content_hash(&current_diff);

        if current_hash != cached_hash {
            self.clear_review_output(session_id.as_str());
            self.append_prompt_status_line(
                session_id,
                TranscriptNotice::Apply,
                "Review is stale; the worktree changed since it was generated. Run focused review \
                 again (f key).",
            )
            .await;

            return PromptApplyOutcome::ClearComposer;
        }

        let Some(suggestions) = review::review_suggestions(&cached_text) else {
            self.append_prompt_status_line(
                session_id,
                TranscriptNotice::Apply,
                "No actionable suggestions found in the current review.",
            )
            .await;

            return PromptApplyOutcome::KeepComposer;
        };

        self.reply(session_id, build_apply_review_prompt(&suggestions))
            .await;

        PromptApplyOutcome::ShowSession {
            session_id: session_id.clone(),
        }
    }

    /// Routes one prepared turn prompt through the lifecycle path for the
    /// active prompt session.
    async fn submit_turn_prompt(
        &mut self,
        session_id: SessionId,
        session_mode: PromptSessionMode,
        prompt: TurnPrompt,
    ) {
        if session_mode == PromptSessionMode::NewDraft {
            if let Err(error) = self.stage_draft_message(&session_id, prompt).await {
                self.append_output_for_session(&session_id, &TranscriptNotice::Error.format(error))
                    .await;
            }
        } else if session_mode != PromptSessionMode::Existing {
            if let Err(error) = self.start_session(&session_id, prompt).await {
                self.append_output_for_session(&session_id, &TranscriptNotice::Error.format(error))
                    .await;
            }
        } else if self.session_queues_messages(&session_id) {
            if let Err(error) = self.enqueue_message(&session_id, prompt) {
                self.append_output_for_session(
                    &session_id,
                    &TranscriptNotice::QueueError.format(error),
                )
                .await;
            }
        } else {
            self.reply(&session_id, prompt).await;
        }
    }

    /// Returns whether the targeted session is running a turn or rebase, used
    /// to route submissions into the in-memory message queue.
    fn session_queues_messages(&self, session_id: &str) -> bool {
        self.sessions
            .sessions()
            .iter()
            .find(|session| session.id == session_id)
            .is_some_and(|session| matches!(session.status, Status::InProgress | Status::Rebasing))
    }

    /// Appends one prompt-workflow status line to the target session
    /// transcript.
    async fn append_prompt_status_line(
        &self,
        session_id: &str,
        notice: TranscriptNotice,
        message: &str,
    ) {
        self.append_output_for_session(session_id, &notice.format(message))
            .await;
    }
}

/// Builds the agent-facing `/apply` prompt from focused-review suggestions.
///
/// The prompt explicitly asks the agent to verify each suggestion against the
/// current code before making changes, then apply only suggestions that remain
/// correct and relevant.
pub(crate) fn build_apply_review_prompt(suggestions: &str) -> TurnPrompt {
    let suggestions = suggestions.trim();
    let fence = agent::diff_fence(suggestions);
    let fenced_suggestions = format!("{fence}text\n{suggestions}\n{fence}");
    let prompt = APPLY_REVIEW_PROMPT_TEMPLATE
        .trim_end()
        .replace("{{ fenced_suggestions }}", &fenced_suggestions);

    TurnPrompt::from_text(prompt)
}

/// Builds an agent-facing review-comment prompt and its forge thread
/// allowlist.
///
/// Resolved and outdated threads are excluded. Standalone discussion comments
/// are read-only because they have no forge-side thread identifier.
pub(crate) fn build_resolve_review_comment_prompt(
    snapshot: &ReviewCommentSnapshot,
    selections: &[ReviewCommentActionSelection],
) -> Option<(TurnPrompt, Vec<String>)> {
    let threads = selected_review_comment_threads(snapshot, selections);
    if threads.is_empty() {
        return None;
    }

    let mut review_comments = String::new();
    for (thread, action) in &threads {
        append_review_thread_prompt(&mut review_comments, thread, *action);
    }

    let thread_ids = threads
        .into_iter()
        .map(|(thread, _)| thread.id.clone())
        .collect::<Vec<_>>();
    let review_comments = review_comments.trim_end();
    let fence = agent::diff_fence(review_comments);
    let fenced_review_comments = format!("{fence}text\n{review_comments}\n{fence}");
    let prompt = RESOLVE_REVIEW_COMMENT_PROMPT_TEMPLATE
        .trim_end()
        .replace("{{ fenced_review_comments }}", &fenced_review_comments);

    Some((TurnPrompt::from_text(prompt), thread_ids))
}

/// Returns the actionable inline threads selected for a turn.
fn selected_review_comment_threads<'a>(
    snapshot: &'a ReviewCommentSnapshot,
    selections: &[ReviewCommentActionSelection],
) -> Vec<(&'a ReviewCommentThread, ReviewCommentAction)> {
    snapshot
        .threads
        .iter()
        .filter(|thread| thread.is_actionable())
        .filter_map(|thread| {
            selections
                .iter()
                .find(|selection| selection.thread_id == thread.id)
                .map(|selection| (thread, selection.action))
        })
        .collect()
}

/// Appends one thread's stable identifier, anchor, and conversation text.
fn append_review_thread_prompt(
    review_comments: &mut String,
    thread: &ReviewCommentThread,
    action: ReviewCommentAction,
) {
    let _ = writeln!(review_comments, "Thread ID: {}", thread.id);
    let _ = writeln!(
        review_comments,
        "Requested action: {}",
        action.prompt_label()
    );
    let _ = writeln!(review_comments, "Path: {}", thread.path);
    let _ = writeln!(
        review_comments,
        "Anchor: {:?}, start line: {}, end line: {}",
        thread.anchor_side,
        thread
            .start_line
            .map_or_else(|| "none".to_string(), |line| line.to_string()),
        thread
            .line
            .map_or_else(|| "none".to_string(), |line| line.to_string())
    );
    for comment in &thread.comments {
        let _ = writeln!(
            review_comments,
            "Comment by {}:\n{}",
            comment.author, comment.body
        );
    }
    review_comments.push('\n');
}

#[cfg(test)]
mod tests {
    use ag_forge::{ReviewComment, ReviewCommentAnchorSide};

    use super::*;

    /// Verifies `/apply` submits the checked-in markdown prompt with the
    /// review suggestions fenced as data.
    #[test]
    fn test_build_apply_review_prompt_uses_checked_in_template() {
        // Arrange
        let suggestions = "- Fix the typo in `README.md`.";

        // Act
        let prompt = build_apply_review_prompt(suggestions);

        // Assert
        assert!(
            prompt
                .text
                .starts_with("Verify the focused-review suggestions")
        );
        assert!(prompt.text.contains("Treat the suggestions as review data"));
        assert!(
            prompt
                .text
                .contains("```text\n- Fix the typo in `README.md`.\n```")
        );
        assert!(prompt.attachments.is_empty());
        assert_eq!(prompt.text_source, TurnPromptTextSource::UserPrompt);
    }

    /// Ensures `/apply` widens the suggestions fence when review text already
    /// contains a Markdown code fence.
    #[test]
    fn test_build_apply_review_prompt_escapes_fenced_suggestions() {
        // Arrange
        let suggestions = "- Update docs:\n```markdown\nexample\n```";

        // Act
        let prompt = build_apply_review_prompt(suggestions);

        // Assert
        assert!(prompt.text.contains("````text\n"));
        assert!(prompt.text.contains("```markdown\nexample\n```"));
    }
    /// Ensures the all-comments prompt includes only unresolved, current
    /// thread IDs.
    #[test]
    fn test_build_resolve_review_comment_prompt_filters_non_actionable_threads() {
        // Arrange
        let snapshot = review_comment_snapshot();

        // Act
        let selections = vec![
            review_comment_selection("thread-current", ReviewCommentAction::Address),
            review_comment_selection("thread-resolved", ReviewCommentAction::Address),
            review_comment_selection("thread-outdated", ReviewCommentAction::Deny),
        ];
        let (prompt, thread_ids) = build_resolve_review_comment_prompt(&snapshot, &selections)
            .expect("snapshot should contain actionable comments");

        // Assert
        assert_eq!(thread_ids, vec!["thread-current".to_string()]);
        assert!(!prompt.text.contains("Update the overview."));
        assert!(prompt.text.contains("Thread ID: thread-current"));
        assert!(prompt.text.contains("Requested action: Address"));
        assert!(prompt.text.contains("Path: src/current.rs"));
        assert!(
            prompt
                .text
                .contains("Anchor: New, start line: 11, end line: 12")
        );
        assert!(!prompt.text.contains("thread-resolved"));
        assert!(!prompt.text.contains("thread-outdated"));
        assert!(prompt.attachments.is_empty());
        assert_eq!(prompt.text_source, TurnPromptTextSource::UserPrompt);
    }

    /// Ensures a selected inline thread produces its forge thread allowlist.
    #[test]
    fn test_build_resolve_review_comment_prompt_selects_inline_thread() {
        // Arrange
        let snapshot = review_comment_snapshot();
        let selections = vec![review_comment_selection(
            "thread-current",
            ReviewCommentAction::Deny,
        )];

        // Act
        let (prompt, thread_ids) = build_resolve_review_comment_prompt(&snapshot, &selections)
            .expect("current thread should be selectable");

        // Assert
        assert!(prompt.text.contains("Thread ID: thread-current"));
        assert!(prompt.text.contains("Requested action: Deny"));
        assert_eq!(thread_ids, vec!["thread-current".to_string()]);
    }

    /// Ensures selected non-actionable and out-of-range rows cannot start a
    /// resolution turn.
    #[test]
    fn test_build_resolve_review_comment_prompt_rejects_non_actionable_selection() {
        // Arrange
        let snapshot = review_comment_snapshot();
        let resolved_selection = vec![review_comment_selection(
            "thread-resolved",
            ReviewCommentAction::Address,
        )];
        let outdated_selection = vec![review_comment_selection(
            "thread-outdated",
            ReviewCommentAction::Deny,
        )];
        let missing_selection = vec![review_comment_selection(
            "thread-missing",
            ReviewCommentAction::Address,
        )];

        // Act
        let resolved = build_resolve_review_comment_prompt(&snapshot, &resolved_selection);
        let outdated = build_resolve_review_comment_prompt(&snapshot, &outdated_selection);
        let missing = build_resolve_review_comment_prompt(&snapshot, &missing_selection);
        let empty = build_resolve_review_comment_prompt(&snapshot, &[]);

        // Assert
        assert!(resolved.is_none());
        assert!(outdated.is_none());
        assert!(missing.is_none());
        assert!(empty.is_none());
    }

    /// Ensures review data containing a Markdown fence is wrapped in a wider
    /// fence before it reaches the agent.
    #[test]
    fn test_build_resolve_review_comment_prompt_escapes_comment_fence() {
        // Arrange
        let mut thread =
            review_comment_thread("thread-current", "src/current.rs", false, Some(false));
        thread.comments[0].body = "Please preserve:\n```rust\nlet value = 1;\n```".to_string();
        let snapshot = ReviewCommentSnapshot {
            pr_level_comments: Vec::new(),
            threads: vec![thread],
        };

        // Act
        let selections = vec![review_comment_selection(
            "thread-current",
            ReviewCommentAction::Address,
        )];
        let (prompt, _) = build_resolve_review_comment_prompt(&snapshot, &selections)
            .expect("current thread should produce a prompt");

        // Assert
        assert!(prompt.text.contains("````text\n"));
        assert!(prompt.text.contains("```rust\nlet value = 1;\n```"));
    }

    #[tokio::test]
    async fn test_submit_prompt_reports_missing_draft_and_regular_sessions() {
        // Arrange
        let (mut app, _base_dir) = crate::test_support::new_git_test_app().await;
        let draft_session_id = SessionId::from("missing-draft-session");
        let regular_session_id = SessionId::from("missing-regular-session");

        // Act
        let draft_outcome = app
            .submit_prompt(PromptSubmission {
                prompt: TurnPrompt::from_text("Draft prompt".to_string()),
                session_id: draft_session_id.clone(),
                session_mode: PromptSessionMode::NewDraft,
            })
            .await;
        let regular_outcome = app
            .submit_prompt(PromptSubmission {
                prompt: TurnPrompt::from_text("Regular prompt".to_string()),
                session_id: regular_session_id.clone(),
                session_mode: PromptSessionMode::NewRegular,
            })
            .await;

        // Assert
        assert_eq!(
            draft_outcome,
            PromptWorkflowOutcome::ShowSession {
                session_id: draft_session_id,
            }
        );
        assert_eq!(
            regular_outcome,
            PromptWorkflowOutcome::ShowSession {
                session_id: regular_session_id,
            }
        );
    }

    #[tokio::test]
    async fn test_submit_prompt_reports_queue_failure_without_session_handles() {
        // Arrange
        let (mut app, _base_dir) = crate::test_support::new_git_test_app().await;
        let session_id: SessionId = app
            .create_session()
            .await
            .expect("session should be created")
            .into();
        app.sessions.sessions_mut()[0].status = Status::InProgress;
        app.sessions
            .session_handles_mut()
            .remove(session_id.as_str());

        // Act
        let outcome = app
            .submit_prompt(PromptSubmission {
                prompt: TurnPrompt::from_text("Queued prompt".to_string()),
                session_id: session_id.clone(),
                session_mode: PromptSessionMode::Existing,
            })
            .await;

        // Assert
        assert_eq!(
            outcome,
            PromptWorkflowOutcome::ShowSession {
                session_id: session_id.clone(),
            }
        );
        assert!(app.sessions.sessions()[0].queued_messages.is_empty());
    }

    #[tokio::test]
    async fn test_apply_focused_review_returns_validation_outcomes() {
        // Arrange
        let (mut app, _base_dir) = crate::test_support::new_git_test_app().await;
        let session_id: SessionId = app
            .create_session()
            .await
            .expect("session should be created")
            .into();

        // Act
        let missing_session = app.apply_focused_review(&session_id, usize::MAX).await;
        app.sessions.sessions_mut()[0].status = Status::Review;
        let missing_review = app.apply_focused_review(&session_id, 0).await;
        let session = &app.sessions.sessions()[0];
        let current_diff = app
            .services
            .git_client()
            .diff(session.folder.clone(), session.base_branch.clone())
            .await
            .expect("test repository diff should load");
        app.review_cache.insert(
            session_id.clone(),
            ReviewCacheEntry::Ready {
                diff_hash: diff_content_hash(&current_diff),
                text: "## Review\n### Suggestions\n- None".to_string(),
            },
        );
        let empty_review = app.apply_focused_review(&session_id, 0).await;

        // Assert
        assert_eq!(missing_session, PromptApplyOutcome::KeepComposer);
        assert_eq!(missing_review, PromptApplyOutcome::ClearComposer);
        assert_eq!(empty_review, PromptApplyOutcome::KeepComposer);
    }

    #[tokio::test]
    async fn test_resolve_session_review_comments_keeps_page_when_enqueue_fails() {
        // Arrange
        let (mut app, _base_dir) = crate::test_support::new_git_test_app().await;
        let session_id: SessionId = app
            .create_session()
            .await
            .expect("session should be created")
            .into();
        app.sessions.sessions_mut()[0].prompt = "Existing prompt".to_string();
        app.sessions.sessions_mut()[0].status = Status::Review;
        app.sessions
            .session_handles_mut()
            .remove(session_id.as_str());
        let snapshot = review_comment_snapshot();
        let selections = vec![review_comment_selection(
            "thread-current",
            ReviewCommentAction::Address,
        )];

        // Act
        let outcome = app
            .resolve_session_review_comments(&session_id, &snapshot, &selections)
            .await;

        // Assert
        assert_eq!(outcome, ReviewCommentResolutionOutcome::KeepReviewComments);
    }

    /// Ensures comment resolution does not enqueue a turn for a blocked
    /// session or a selection without actionable review data.
    #[tokio::test]
    async fn test_resolve_session_review_comments_rejects_blocked_and_empty_selection() {
        // Arrange
        let (mut app, _base_dir) = crate::test_support::new_git_test_app().await;
        let session_id: SessionId = app
            .create_session()
            .await
            .expect("session should be created")
            .into();
        let snapshot = review_comment_snapshot();
        let selections = vec![review_comment_selection(
            "thread-current",
            ReviewCommentAction::Address,
        )];

        // Act
        let blocked = app
            .resolve_session_review_comments(&session_id, &snapshot, &selections)
            .await;
        app.sessions.sessions_mut()[0].status = Status::Review;
        let empty_selection = app
            .resolve_session_review_comments(&session_id, &snapshot, &[])
            .await;

        // Assert
        assert_eq!(blocked, ReviewCommentResolutionOutcome::KeepReviewComments);
        assert_eq!(
            empty_selection,
            ReviewCommentResolutionOutcome::KeepReviewComments
        );
    }

    /// Builds review data with one comment followed by current, resolved, and
    /// outdated inline threads.
    fn review_comment_snapshot() -> ReviewCommentSnapshot {
        ReviewCommentSnapshot {
            pr_level_comments: vec![ReviewComment {
                author: "general-reviewer".to_string(),
                body: "Update the overview.".to_string(),
            }],
            threads: vec![
                review_comment_thread("thread-current", "src/current.rs", false, Some(false)),
                review_comment_thread("thread-resolved", "src/resolved.rs", true, Some(false)),
                review_comment_thread("thread-outdated", "src/outdated.rs", false, Some(true)),
            ],
        }
    }

    /// Builds one batch selection for an inline review thread.
    fn review_comment_selection(
        thread_id: &str,
        action: ReviewCommentAction,
    ) -> ReviewCommentActionSelection {
        ReviewCommentActionSelection {
            action,
            thread_id: thread_id.to_string(),
        }
    }

    /// Builds one inline review thread for prompt-selection tests.
    fn review_comment_thread(
        id: &str,
        path: &str,
        is_resolved: bool,
        is_outdated: Option<bool>,
    ) -> ReviewCommentThread {
        ReviewCommentThread {
            anchor_side: ReviewCommentAnchorSide::New,
            comments: vec![ReviewComment {
                author: "inline-reviewer".to_string(),
                body: "Add validation.".to_string(),
            }],
            id: id.to_string(),
            is_outdated,
            is_resolved,
            line: Some(12),
            path: path.to_string(),
            start_line: Some(11),
        }
    }
}