travelagent 1.11.1

Agent-first TUI code review tool
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
use travelagent_core::error::{Result, TrvError};
use travelagent_core::model::build_tour_stops;
use travelagent_core::risk::{RiskScore, ScoredCommit, score_commit};
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};

use super::{App, DiffSource, DiffState, FileListState, GranularityHint, InputMode};
use travelagent_core::model::{
    CommentTriage, NewCommentLocation, TourAggressiveness, TourCommentMeta, TourState, TourStop,
    TourTriageVerdict,
};

/// Per-file risk detail returned by `tour_commit_risk_detail`.
#[derive(Debug, Clone)]
pub struct FileRiskDetail {
    pub file: String,
    pub risk: RiskScore,
}

/// Full risk picture for a commit: the overall score, the distinct change
/// types that fed into it, and per-file scores for inspection.
#[derive(Debug, Clone)]
pub struct CommitRiskDetail {
    pub sha: String,
    pub risk: RiskScore,
    pub change_types: Vec<travelagent_core::risk::ChangeType>,
    pub file_scores: Vec<FileRiskDetail>,
}

impl App {
    // --- Tour guide mode ---

    /// Resolve a revset (e.g. "HEAD~10..HEAD") to an ordered list of commit IDs
    /// using the current VCS backend. Returns oldest→newest.
    pub fn tour_resolve_revset(&self, revset: &str) -> Result<Vec<String>> {
        self.vcs.resolve_revisions(revset)
    }

    /// Begin a tour from the given plan. Resets to stop 0 and immediately
    /// loads that stop's diff. Returns an error string if the plan is empty
    /// or any commit ID fails to resolve into a diff.
    pub fn tour_start(&mut self, stops: Vec<TourStop>) -> Result<()> {
        if stops.is_empty() {
            return Err(TrvError::UnsupportedOperation(
                "Tour plan must contain at least one stop".into(),
            ));
        }
        self.tour.plan = Some(TourState::new(stops));
        self.tour_reload_current_stop()?;
        if let Some(tour) = self.tour.plan.as_ref()
            && let Some(stop) = tour.current()
        {
            let n = tour.stops.len();
            self.set_message(format!("Tour 1/{n}: {}", Self::tour_short_summary(stop)));
        }
        Ok(())
    }

    fn tour_short_summary(stop: &TourStop) -> String {
        // Target display width (columns). The status bar uses terminal columns,
        // so we truncate by Unicode display width rather than bytes or chars to
        // avoid both mid-codepoint panics and CJK/emoji overflow.
        const MAX_WIDTH: usize = 80;
        let s = stop.summary.trim();
        if s.width() <= MAX_WIDTH {
            return s.to_string();
        }
        // Reserve one column for the trailing ellipsis (U+2026, width 1).
        let budget = MAX_WIDTH.saturating_sub(1);
        let mut out = String::new();
        let mut used = 0usize;
        for ch in s.chars() {
            let w = UnicodeWidthChar::width(ch).unwrap_or(0);
            if used + w > budget {
                break;
            }
            out.push(ch);
            used += w;
        }
        out.push('\u{2026}');
        out
    }

    /// Jump to a specific stop index (0-based) and reload its diff.
    pub fn tour_goto(&mut self, index: usize) -> Result<()> {
        let Some(tour) = self.tour.plan.as_mut() else {
            return Err(TrvError::UnsupportedOperation(
                "No active tour — call trv_tour_set_plan first".into(),
            ));
        };
        let total = tour.stops.len();
        if index >= total {
            return Err(TrvError::UnsupportedOperation(format!(
                "Stop {index} out of range (tour has {total} stops)"
            )));
        }
        tour.index = index;
        self.tour_reload_current_stop()?;
        if let Some(stop) = self.tour.plan.as_ref().and_then(|t| t.current()) {
            self.set_message(format!(
                "Tour {}/{}: {}",
                index + 1,
                total,
                Self::tour_short_summary(stop)
            ));
        }
        Ok(())
    }

    /// Step to the next stop. No-op at the last stop (with a message).
    pub fn tour_next(&mut self) -> Result<()> {
        let Some(tour) = self.tour.plan.as_ref() else {
            return Ok(());
        };
        if tour.index + 1 >= tour.stops.len() {
            self.set_message("Tour complete — at last stop");
            return Ok(());
        }
        let next = tour.index + 1;
        self.tour_goto(next)
    }

    /// Step to the previous stop.
    pub fn tour_prev(&mut self) -> Result<()> {
        let Some(tour) = self.tour.plan.as_ref() else {
            return Ok(());
        };
        if tour.index == 0 {
            self.set_message("At first stop");
            return Ok(());
        }
        let prev = tour.index - 1;
        self.tour_goto(prev)
    }

    /// Rewind to the first stop (`:tour-rewind`). No-op (with a message) when
    /// no tour is active or already at stop 1.
    pub fn tour_rewind(&mut self) -> Result<()> {
        let Some(tour) = self.tour.plan.as_ref() else {
            self.set_message("No active tour");
            return Ok(());
        };
        if tour.index == 0 {
            self.set_message("Already at the first stop");
            return Ok(());
        }
        self.tour_goto(0)
    }

    /// End the tour and return state to the default commit-range view of all
    /// commits in the plan. Clears `self.tour.plan` but keeps comment metadata and
    /// triage so the agent can finish triaging after exiting tour mode.
    pub fn tour_end(&mut self) {
        self.tour.end_tour();
        self.set_message("Tour ended");
    }

    /// Record tour-stop provenance for a comment added during an active tour.
    /// Called by the MCP `add_comment` handler and any future TUI comment path.
    pub fn tour_record_comment(&mut self, comment_id: String, file: String, line: u32) {
        let Some(tour) = self.tour.plan.as_ref() else {
            return;
        };
        let Some(stop) = tour.current() else {
            return;
        };
        self.tour.record_comment_meta(
            comment_id,
            TourCommentMeta {
                stop_index: tour.index,
                stop_commit_shas: stop.commit_ids.clone(),
                file,
                line,
            },
        );
    }

    /// Set or overwrite a triage verdict for a tour comment.
    pub fn tour_set_triage(
        &mut self,
        comment_id: &str,
        verdict: TourTriageVerdict,
        reasoning: String,
        new_location: Option<NewCommentLocation>,
    ) -> Result<()> {
        if !self.tour.is_tour_comment(comment_id) {
            return Err(TrvError::UnsupportedOperation(format!(
                "Comment {comment_id} is not a tour comment (or was not added via MCP)"
            )));
        }
        if matches!(verdict, TourTriageVerdict::Moved) && new_location.is_none() {
            return Err(TrvError::UnsupportedOperation(
                "Moved verdict requires a new_location".into(),
            ));
        }
        self.tour.set_triage(
            comment_id.to_string(),
            CommentTriage {
                verdict,
                reasoning,
                new_location,
            },
        );
        Ok(())
    }

    /// Consume the pending granularity hint, if any. Called by the agent via
    /// `trv_tour_take_granularity_hint` so each hint is acted on exactly once.
    pub fn tour_take_granularity_hint(&mut self) -> Option<GranularityHint> {
        self.tour.take_granularity_hint()
    }

    /// Set a granularity hint from the human. The agent polls via MCP.
    pub fn tour_set_granularity_hint(&mut self, hint: GranularityHint) {
        self.tour.set_granularity_hint(hint);
        let label = match hint {
            GranularityHint::Coarser => "coarser (agent will batch more commits)",
            GranularityHint::Finer => "finer (agent will split batched stops)",
        };
        self.set_message(format!("Tour granularity hint: {label}"));
    }

    /// Copy tour state from the app into the session mirror so `save_session`
    /// persists it. Call this immediately before any
    /// `save_session(app.engine.session())`.
    pub fn sync_tour_to_session(&mut self) {
        let session = self.engine.session_mut();
        session.tour = self.tour.plan.clone();
        session.tour_comment_meta = self.tour.comment_meta.clone();
        session.tour_triage = self.tour.triage.clone();
    }

    /// Summary of triage counts (live, obsolete, moved) across all tour comments.
    pub fn tour_triage_counts(&self) -> (usize, usize, usize) {
        self.tour.triage_counts()
    }

    /// Get the current tour's threshold, or `None` if no tour is active.
    pub fn tour_get_threshold(&self) -> Option<RiskScore> {
        self.tour.plan.as_ref().map(|t| t.threshold)
    }

    /// Formatted date-range string for the current tour stop, e.g.
    /// `"2026-04-15 → 2026-05-02"` (or `"2026-04-15"` for a single-
    /// commit stop). Returns `None` when no tour is active or the VCS
    /// backend can't resolve the stop's commits.
    ///
    /// Cached on `TourSessionState.date_range_cache` keyed by
    /// `(first_sha, last_sha)`; a stop change invalidates by key
    /// mismatch, so callers don't need to flush explicitly.
    pub fn tour_date_range(&mut self) -> Option<String> {
        let stop = self.tour.plan.as_ref()?.current()?;
        let first = stop.first_sha().to_string();
        let last = stop.last_sha().to_string();
        if first.is_empty() {
            return None;
        }
        if let Some((f, l, cached)) = &self.tour.date_range_cache
            && f == &first
            && l == &last
        {
            return Some(cached.clone());
        }
        let ids = if first == last {
            vec![first.clone()]
        } else {
            vec![first.clone(), last.clone()]
        };
        let infos = self.vcs.get_commits_info(&ids).ok()?;
        if infos.is_empty() {
            return None;
        }
        let first_date = infos.first()?.time.format("%Y-%m-%d").to_string();
        let last_date = infos.last()?.time.format("%Y-%m-%d").to_string();
        let formatted = if first_date == last_date {
            first_date
        } else {
            format!("{first_date}{last_date}")
        };
        self.tour.date_range_cache = Some((first, last, formatted.clone()));
        Some(formatted)
    }

    /// Compute the full risk detail for a single commit using the VCS diff
    /// and the currently loaded [`RiskConfig`].
    pub fn tour_commit_risk_detail(&self, sha: &str) -> Result<CommitRiskDetail> {
        // Risk scoring doesn't need syntax highlighting, so skip decoration.
        let diff_files = self.vcs.get_commit_range_diff(&[sha.to_string()])?;

        let mut file_scores = Vec::with_capacity(diff_files.len());
        let mut type_set: std::collections::HashSet<travelagent_core::risk::ChangeType> =
            std::collections::HashSet::new();
        let mut files_for_commit: Vec<(
            std::path::PathBuf,
            Vec<travelagent_core::model::DiffHunk>,
        )> = Vec::with_capacity(diff_files.len());

        for df in &diff_files {
            let path = df.display_path_lossy().clone();
            let hunks = df.hunks.clone();
            for hunk in &hunks {
                for kind in
                    travelagent_core::risk::detect_change_types(&path, hunk, &self.risk_config)
                {
                    type_set.insert(kind);
                }
            }
            let risk = travelagent_core::risk::score_file(&path, &hunks, &self.risk_config);
            file_scores.push(FileRiskDetail {
                file: path.to_string_lossy().into_owned(),
                risk,
            });
            files_for_commit.push((path, hunks));
        }

        let risk = score_commit(&files_for_commit, &self.risk_config);
        let mut change_types: Vec<_> = type_set.into_iter().collect();
        change_types.sort_by_key(|c| c.id());

        Ok(CommitRiskDetail {
            sha: sha.to_string(),
            risk,
            change_types,
            file_scores,
        })
    }

    /// Compute a `ScoredCommit` for each SHA in order, scoring each commit's
    /// diff under the current [`RiskConfig`]. Results are memoized in
    /// `tour_score_cache` keyed by SHA, so repeat calls on the same commits
    /// (e.g. `:set tour=<preset>` retargets) skip the per-commit diff call.
    /// The cache is invalidated via [`App::invalidate_tour_score_cache`] when
    /// scorer inputs change.
    pub fn tour_score_commits(&mut self, shas: &[String]) -> Result<Vec<ScoredCommit>> {
        let mut out = Vec::with_capacity(shas.len());
        for sha in shas {
            if let Some(cached) = self.tour.cached_score(sha) {
                out.push(cached.clone());
                continue;
            }
            // Risk scoring doesn't need syntax highlighting, so skip decoration.
            let diff_files = self.vcs.get_commit_range_diff(std::slice::from_ref(sha))?;
            let files_for_commit: Vec<(std::path::PathBuf, Vec<_>)> = diff_files
                .iter()
                .map(|df| (df.display_path_lossy().clone(), df.hunks.clone()))
                .collect();
            let risk = score_commit(&files_for_commit, &self.risk_config);
            let scored = ScoredCommit {
                sha: sha.clone(),
                risk,
                summary: String::new(),
            };
            self.tour.cache_score(sha.clone(), scored.clone());
            out.push(scored);
        }
        Ok(out)
    }

    /// Drop all memoized tour commit scores. Call when scorer inputs change
    /// (risk config reload or session scope switch) so the next
    /// `tour_score_commits` call re-diffs and re-scores.
    pub fn invalidate_tour_score_cache(&mut self) {
        self.tour.invalidate_score_cache();
    }

    /// Rebuild the current tour's stops using the given aggressiveness. Uses
    /// the current plan's commit list as the input, re-scoring each commit.
    /// Returns the new stop count. Errors if no tour is active.
    pub fn tour_set_aggressiveness(&mut self, agg: TourAggressiveness) -> Result<usize> {
        let Some(tour) = self.tour.plan.as_ref() else {
            return Err(TrvError::UnsupportedOperation(
                "No active tour to retarget".into(),
            ));
        };
        // Flatten the stops back into their original ordered commit list.
        let mut shas: Vec<String> = Vec::new();
        for stop in &tour.stops {
            for sha in &stop.commit_ids {
                shas.push(sha.clone());
            }
        }

        let scored = self.tour_score_commits(&shas)?;
        let threshold = agg.threshold();
        let new_stops = build_tour_stops(&scored, threshold);

        self.tour.plan = Some(TourState::new_with_threshold(new_stops, threshold));
        let count = self
            .tour
            .plan
            .as_ref()
            .map(|t| t.stops.len())
            .unwrap_or_default();
        if count > 0 {
            self.tour_reload_current_stop()?;
        }
        Ok(count)
    }

    /// Set the threshold directly from a numeric level (0..=5). This is the
    /// MCP entry point (`trv_tour_set_threshold`).
    pub fn tour_set_threshold(&mut self, level: u8) -> Result<usize> {
        if level > 5 {
            return Err(TrvError::UnsupportedOperation(
                "threshold must be 0..=5".into(),
            ));
        }
        self.tour_set_aggressiveness(TourAggressiveness::Custom(RiskScore::new(level)))
    }

    /// Rebuild `diff_files` from the current stop's commit range. Keeps the
    /// same VCS/session; only the diff contents and layout reset.
    fn tour_reload_current_stop(&mut self) -> Result<()> {
        let stop = match self.tour.plan.as_ref().and_then(|t| t.current()) {
            Some(s) => s.clone(),
            None => return Ok(()),
        };
        let highlighter = self.theme.syntax_highlighter();
        // get_commit_range_diff expects commit IDs oldest→newest. We already
        // store them that way in TourStop.
        let mut diff_files = self.vcs.get_commit_range_diff(&stop.commit_ids)?;
        travelagent_core::syntax::decorate_diff_files(&mut diff_files, highlighter);

        // Preserve session comments across stops — tour comments are tagged
        // with stop_idx so we keep accumulating rather than resetting.
        self.engine.apply_diff_files(&diff_files);

        self.diff_files = diff_files;
        self.diff_source = DiffSource::CommitRange(stop.commit_ids.clone());
        self.nav.input_mode = InputMode::Normal;
        self.diff_state = DiffState::default();
        self.file_list_state = FileListState::default();
        self.clear_expanded_gaps();
        self.sort_files_by_directory(true);
        self.expand_all_dirs();
        self.rebuild_annotations();
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use travelagent_core::risk::RiskScore;
    use unicode_width::UnicodeWidthStr;

    fn stop_with(summary: &str) -> TourStop {
        TourStop {
            commit_ids: vec!["deadbeef".into()],
            summary: summary.into(),
            risk: RiskScore::MIN,
        }
    }

    #[test]
    fn tour_short_summary_ascii_under_limit_is_unchanged() {
        let stop = stop_with("fix off-by-one in paginator");
        let got = App::tour_short_summary(&stop);
        assert_eq!(got, "fix off-by-one in paginator");
        assert!(!got.contains('\u{2026}'));
    }

    #[test]
    fn tour_short_summary_ascii_over_limit_is_truncated_with_ellipsis() {
        // 120 'a's → exceeds the 80-column budget.
        let long = "a".repeat(120);
        let stop = stop_with(&long);
        let got = App::tour_short_summary(&stop);
        assert!(
            got.ends_with('\u{2026}'),
            "expected trailing ellipsis, got: {got:?}"
        );
        // Display width must fit in 80 cols (79 'a's + 1-col ellipsis = 80).
        assert!(
            got.width() <= 80,
            "truncated summary wider than 80 cols: width={}",
            got.width()
        );
        // Dropping the ellipsis should leave only ASCII 'a's.
        let body: String = got.chars().filter(|c| *c != '\u{2026}').collect();
        assert!(body.chars().all(|c| c == 'a'));
    }

    #[test]
    fn tour_short_summary_emoji_does_not_split_codepoint() {
        // Mix of emoji + ASCII, short enough to stay whole but exercises the
        // multi-byte path. Then a long variant that must truncate safely.
        let short = stop_with("🎉 ship v1 🚀");
        let got = App::tour_short_summary(&short);
        // Sanity: round-trips unchanged when under budget.
        assert_eq!(got, "🎉 ship v1 🚀");

        // Force truncation with a long emoji-heavy string; the key requirement
        // is that we do not panic and we emit valid UTF-8 that fits the budget.
        let long_emoji: String = "🎉".repeat(100); // each emoji is width 2
        let stop = stop_with(&long_emoji);
        let got = App::tour_short_summary(&stop);
        assert!(got.ends_with('\u{2026}'));
        assert!(
            got.width() <= 80,
            "emoji truncation exceeded 80 cols: width={}",
            got.width()
        );
        // Every non-ellipsis char must be the full 🎉 (no byte-split corruption).
        for ch in got.chars().filter(|c| *c != '\u{2026}') {
            assert_eq!(ch, '🎉');
        }
    }

    #[test]
    fn tour_short_summary_cjk_does_not_panic() {
        let stop = stop_with("修复了一个错误的bug");
        let got = App::tour_short_summary(&stop);
        // Under the 80-col budget → unchanged.
        assert_eq!(got, "修复了一个错误的bug");

        // Long CJK string must truncate without panicking and stay within budget.
        let long_cjk: String = "".repeat(100);
        let stop = stop_with(&long_cjk);
        let got = App::tour_short_summary(&stop);
        assert!(got.ends_with('\u{2026}'));
        assert!(
            got.width() <= 80,
            "CJK truncation exceeded 80 cols: width={}",
            got.width()
        );
        for ch in got.chars().filter(|c| *c != '\u{2026}') {
            assert_eq!(ch, '');
        }
    }
}

#[cfg(test)]
mod tour_score_cache_tests {
    use super::*;
    use crate::app::{DiffSource, InputMode};
    use crate::theme::Theme;
    use std::path::{Path, PathBuf};
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use travelagent_core::model::{
        DiffFile, DiffLine, FileStatus, ReviewSession, SessionDiffSource,
    };
    use travelagent_core::vcs::{VcsBackend, VcsInfo, VcsType};

    /// Stub VCS that counts how many times `get_commit_range_diff` is invoked.
    /// Used to prove the per-SHA cache suppresses redundant diff calls.
    struct CountingVcs {
        info: VcsInfo,
        calls: Arc<AtomicUsize>,
    }

    impl VcsBackend for CountingVcs {
        fn info(&self) -> &VcsInfo {
            &self.info
        }

        fn get_working_tree_diff(&self) -> Result<Vec<DiffFile>> {
            Err(TrvError::NoChanges)
        }

        fn get_commit_range_diff(&self, _commit_ids: &[String]) -> Result<Vec<DiffFile>> {
            self.calls.fetch_add(1, Ordering::SeqCst);
            Ok(Vec::new())
        }

        fn fetch_context_lines(
            &self,
            _file_path: &Path,
            _file_status: FileStatus,
            _start_line: u32,
            _end_line: u32,
        ) -> Result<Vec<DiffLine>> {
            Ok(Vec::new())
        }
    }

    fn build_app_with_counter() -> (App, Arc<AtomicUsize>) {
        let calls = Arc::new(AtomicUsize::new(0));
        let vcs_info = VcsInfo {
            root_path: PathBuf::from("/tmp"),
            head_commit: "head".to_string(),
            branch_name: Some("main".to_string()),
            vcs_type: VcsType::Git,
        };
        let session = ReviewSession::new(
            vcs_info.root_path.clone(),
            vcs_info.head_commit.clone(),
            vcs_info.branch_name.clone(),
            SessionDiffSource::WorkingTree,
        );
        let app = App::build(
            Box::new(CountingVcs {
                info: vcs_info.clone(),
                calls: calls.clone(),
            }),
            vcs_info,
            Theme::dark(),
            None,
            false,
            Vec::new(),
            session,
            DiffSource::WorkingTree,
            InputMode::Normal,
            Vec::new(),
            None,
            crate::test_support::runtime_handle(),
            crate::app::AppMode::Local(crate::app::LocalState::default()),
        )
        .expect("failed to build test app");
        (app, calls)
    }

    #[test]
    fn tour_score_commits_hits_cache_on_repeat_sha() {
        // Regression: before the cache, `:set tour=<preset>` re-diffed every
        // SHA on each retarget. Now the second call for the same SHA must not
        // invoke `get_commit_range_diff` again.
        let (mut app, calls) = build_app_with_counter();
        let shas = vec!["aaa".to_string()];

        let first = app.tour_score_commits(&shas).unwrap();
        assert_eq!(first.len(), 1);
        assert_eq!(calls.load(Ordering::SeqCst), 1);

        let second = app.tour_score_commits(&shas).unwrap();
        assert_eq!(second.len(), 1);
        assert_eq!(
            calls.load(Ordering::SeqCst),
            1,
            "cached SHA must not trigger a second diff call"
        );
        assert_eq!(first[0].sha, second[0].sha);
    }

    #[test]
    fn tour_score_commits_caches_each_unique_sha() {
        let (mut app, calls) = build_app_with_counter();
        let shas = vec!["aaa".to_string(), "bbb".to_string()];

        app.tour_score_commits(&shas).unwrap();
        assert_eq!(calls.load(Ordering::SeqCst), 2);

        // Both cached — second pass makes zero new diff calls.
        app.tour_score_commits(&shas).unwrap();
        assert_eq!(calls.load(Ordering::SeqCst), 2);
        assert_eq!(app.tour.score_cache.len(), 2);
    }

    #[test]
    fn invalidate_tour_score_cache_forces_rescore() {
        // Risk config reload must clear the cache so the next scoring pass
        // re-runs under the new config.
        let (mut app, calls) = build_app_with_counter();
        let shas = vec!["aaa".to_string()];

        app.tour_score_commits(&shas).unwrap();
        assert_eq!(calls.load(Ordering::SeqCst), 1);

        // Simulate a risk config reload.
        app.risk_config = travelagent_core::risk::RiskConfig::default();
        app.invalidate_tour_score_cache();
        assert!(app.tour.score_cache.is_empty());

        app.tour_score_commits(&shas).unwrap();
        assert_eq!(
            calls.load(Ordering::SeqCst),
            2,
            "invalidation must force a re-diff"
        );
    }

    fn three_stop_plan() -> Vec<TourStop> {
        vec![
            TourStop {
                commit_ids: vec!["aaa".into()],
                summary: "stop one".into(),
                risk: travelagent_core::risk::RiskScore::MIN,
            },
            TourStop {
                commit_ids: vec!["bbb".into()],
                summary: "stop two".into(),
                risk: travelagent_core::risk::RiskScore::MIN,
            },
            TourStop {
                commit_ids: vec!["ccc".into()],
                summary: "stop three".into(),
                risk: travelagent_core::risk::RiskScore::MIN,
            },
        ]
    }

    #[test]
    fn tour_rewind_jumps_to_first_stop() {
        let (mut app, _) = build_app_with_counter();
        app.tour_start(three_stop_plan()).unwrap();
        app.tour_next().unwrap();
        app.tour_next().unwrap();
        assert_eq!(app.tour.plan.as_ref().unwrap().index, 2, "at last stop");

        app.tour_rewind().unwrap();
        assert_eq!(
            app.tour.plan.as_ref().unwrap().index,
            0,
            "rewind returns to the first stop"
        );
    }

    #[test]
    fn tour_rewind_noop_without_active_tour() {
        let (mut app, _) = build_app_with_counter();
        // No tour started → graceful no-op, no panic.
        app.tour_rewind().unwrap();
        assert!(app.tour.plan.is_none());
    }

    #[test]
    fn tour_goto_is_zero_based_internally() {
        let (mut app, _) = build_app_with_counter();
        app.tour_start(three_stop_plan()).unwrap();
        // `:tour-goto 2` (1-based) maps to index 1.
        app.tour_goto(1).unwrap();
        assert_eq!(app.tour.plan.as_ref().unwrap().index, 1);
        // Out-of-range index is rejected.
        assert!(app.tour_goto(99).is_err());
    }
}