travelagent-core 1.10.2

Core library for travelagent code review tool
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
//! Tour Guide Mode types. A tour is an agent-curated sequence of commit-range
//! "stops" that the human walks through. Types live in core so they can be
//! persisted as part of `ReviewSession` and later consumed by both the TUI and
//! agents via MCP.
//!
//! ## Tour schema versioning
//!
//! [`TourState`] carries its own [`TOUR_SCHEMA_VERSION`] independent of
//! `SESSION_VERSION`. This lets semantic changes to tour shape (renaming a
//! field, adding a new cursor-position type, …) migrate cleanly without
//! rejecting every older session file — which would be the failure mode of
//! bumping `SESSION_VERSION` for a tour-only change and then running the
//! newer binary against a file whose non-tour parts are still compatible.
//!
//! See [`migrate_tour`] for the single switch branch every version change
//! must go through. `#[serde(default)]` on `tour_schema_version` means a
//! legacy tour JSON missing the field loads as version 0, which
//! [`migrate_tour`] then bumps to [`TOUR_SCHEMA_VERSION`] with any required
//! transformation applied.

use serde::{Deserialize, Deserializer, Serialize};

use crate::risk::{RiskScore, ScoredCommit};

/// Current tour schema version. Bump when a semantic change to [`TourState`]
/// or [`TourStop`] requires a transformation on load (e.g. a field rename,
/// a semantic reinterpretation of an existing field, or the addition of a
/// field whose default on legacy data is not simply `Default::default()`).
/// Purely-additive `#[serde(default)]` fields do NOT require a bump.
///
/// Every bump must add a matching arm to [`migrate_tour`].
pub const TOUR_SCHEMA_VERSION: u8 = 1;

/// A single stop in a tour — one or more commits grouped together, with a
/// human-readable summary from the agent.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TourStop {
    /// Ordered oldest→newest commit SHAs in this stop. Length ≥ 1. When the
    /// length is > 1 the stop represents a batched run and the diff shown is
    /// `parent(first)..last` so the human sees the net effect.
    pub commit_ids: Vec<String>,
    /// Agent-written summary of what changed in this stop. Shown in the status
    /// bar and persisted in end-of-tour triage.
    pub summary: String,
    /// Max risk across the stop's commits. Omitted in legacy session JSON
    /// (defaults to 0) so older sessions keep loading.
    #[serde(default = "RiskScore::min")]
    pub risk: RiskScore,
}

impl TourStop {
    /// SHA at the end of this stop (newest commit). Returns "" for the
    /// impossible empty-stop case so callers can still format it safely.
    pub fn last_sha(&self) -> &str {
        self.commit_ids.last().map_or("", String::as_str)
    }
    /// SHA at the start of this stop (oldest commit).
    pub fn first_sha(&self) -> &str {
        self.commit_ids.first().map_or("", String::as_str)
    }
    pub fn is_batched(&self) -> bool {
        self.commit_ids.len() > 1
    }
}

/// Active tour — the agent has laid out a sequence of stops and the human is
/// currently viewing one of them.
///
/// `index` is read-accessible but must only be mutated through [`TourState::set_index`]
/// (or via [`TourState::new`] at construction) to preserve the invariant
/// `index < stops.len()` whenever `stops` is non-empty. On deserialization an
/// out-of-bounds `index` is clamped to `stops.len() - 1` (or `0` if empty) so a
/// corrupt session file cannot produce a panic in [`TourState::current`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct TourState {
    pub stops: Vec<TourStop>,
    pub index: usize,
    /// Risk threshold used to construct this tour's stops. Stops at or below
    /// the threshold may be batched with neighbors; stops above stand alone.
    /// Defaults to 0 on legacy session JSON.
    #[serde(default)]
    pub threshold: RiskScore,
    /// On-disk schema version for this tour. See [`TOUR_SCHEMA_VERSION`] and
    /// [`migrate_tour`]. Tours written before H11 deserialize with `0`, which
    /// the migration path rolls forward to the current version.
    #[serde(default)]
    pub tour_schema_version: u8,
}

impl<'de> Deserialize<'de> for TourState {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct Raw {
            stops: Vec<TourStop>,
            #[serde(default)]
            index: usize,
            #[serde(default)]
            threshold: RiskScore,
            #[serde(default)]
            tour_schema_version: u8,
        }
        let raw = Raw::deserialize(deserializer)?;
        let max_index = raw.stops.len().saturating_sub(1);
        let clamped = if raw.stops.is_empty() {
            0
        } else {
            raw.index.min(max_index)
        };
        Ok(TourState {
            stops: raw.stops,
            index: clamped,
            threshold: raw.threshold,
            tour_schema_version: raw.tour_schema_version,
        })
    }
}

/// Roll `state` forward from its on-disk `tour_schema_version` to
/// [`TOUR_SCHEMA_VERSION`]. Every version bump adds an arm to the match;
/// each arm is responsible for transforming the data from its version to
/// the next, not jumping to current. Idempotent: calling `migrate_tour`
/// on an already-current tour is a no-op.
///
/// **Current migration landscape.**
/// - v0 → v1: purely a version stamp. Every pre-H11 tour JSON loads as v0
///   (missing field → `#[serde(default)]` = 0); the migration simply
///   records the current shape as v1. No field transformation is needed
///   because the v1 shape is identical to the serializable fields of every
///   prior writer.
///
/// Returns `Ok(true)` if any migration was applied, `Ok(false)` if already
/// current, and `Err(MigrateTourError)` when the recorded
/// `tour_schema_version` is *newer* than this binary knows how to handle
/// (downgrade scenario) or when a migration arm produces an
/// intermediate version with no downstream arm (programmer error).
pub fn migrate_tour(state: &mut TourState) -> Result<bool, MigrateTourError> {
    // Snapshot the starting version so any error path can roll the
    // in-memory state back. The migration contract (pinned by
    // `migrate_tour_preserves_version_on_error`) is: on `Err` the
    // caller sees the *same* tour_schema_version they passed in.
    // Without this, a chain like v0 → v1 (arm present) → v2 (arm
    // missing) would bump from 0 to 1 before returning MissingArm{1},
    // and a subsequent save would rewrite the on-disk file at v1
    // even though the user saw a load error.
    let entry_version = state.tour_schema_version;

    if state.tour_schema_version > TOUR_SCHEMA_VERSION {
        return Err(MigrateTourError::FromTheFuture {
            recorded: state.tour_schema_version,
            supported: TOUR_SCHEMA_VERSION,
        });
    }

    let mut changed = false;
    while state.tour_schema_version < TOUR_SCHEMA_VERSION {
        let before = state.tour_schema_version;
        match state.tour_schema_version {
            0 => {
                // v0 → v1: no semantic transform; every pre-H11 writer
                // produced the same shape that v1 names. Stamp and move on.
                state.tour_schema_version = 1;
            }
            // Add future arms here. Each arm MUST bump
            // `state.tour_schema_version` by exactly 1 before the loop
            // re-enters, or the loop will spin.
            other => {
                // Between a known-low version (0) and `TOUR_SCHEMA_VERSION`
                // but with no migration arm. Means someone added a
                // version bump without the matching transformation —
                // surface loudly instead of silently leaving the tour
                // stuck mid-chain.
                state.tour_schema_version = entry_version;
                return Err(MigrateTourError::MissingArm { version: other });
            }
        }
        debug_assert!(
            state.tour_schema_version > before,
            "migrate_tour arm must bump tour_schema_version"
        );
        changed = true;
    }
    Ok(changed)
}

/// Errors [`migrate_tour`] can return.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MigrateTourError {
    /// The on-disk tour records a `tour_schema_version` newer than this
    /// binary's [`TOUR_SCHEMA_VERSION`]. Typically a downgrade after a
    /// schema bump. Caller should surface to the user rather than load.
    FromTheFuture { recorded: u8, supported: u8 },
    /// A migration arm is missing for an intermediate version. Programmer
    /// error — a version bump without the corresponding transformation.
    MissingArm { version: u8 },
}

impl std::fmt::Display for MigrateTourError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::FromTheFuture {
                recorded,
                supported,
            } => write!(
                f,
                "tour schema version {recorded} is newer than supported {supported}",
            ),
            Self::MissingArm { version } => {
                write!(f, "migrate_tour has no arm for v{version}")
            }
        }
    }
}

impl std::error::Error for MigrateTourError {}

impl TourState {
    /// Construct a new tour at stop 0. Tagged with the current
    /// [`TOUR_SCHEMA_VERSION`] so it round-trips without a migration.
    pub fn new(stops: Vec<TourStop>) -> Self {
        Self {
            stops,
            index: 0,
            threshold: RiskScore::MIN,
            tour_schema_version: TOUR_SCHEMA_VERSION,
        }
    }

    /// Construct a new tour with an explicit aggressiveness threshold.
    pub fn new_with_threshold(stops: Vec<TourStop>, threshold: RiskScore) -> Self {
        Self {
            stops,
            index: 0,
            threshold,
            tour_schema_version: TOUR_SCHEMA_VERSION,
        }
    }

    /// Currently-selected stop index, or `None` if there are no stops.
    pub fn current_index(&self) -> Option<usize> {
        if self.stops.is_empty() {
            None
        } else {
            Some(self.index)
        }
    }

    /// Attempt to move the cursor to `idx`. Returns `true` on success; returns
    /// `false` (leaving `index` unchanged) if `idx` is out of bounds.
    pub fn set_index(&mut self, idx: usize) -> bool {
        if idx < self.stops.len() {
            self.index = idx;
            true
        } else {
            false
        }
    }

    pub fn current(&self) -> Option<&TourStop> {
        self.stops.get(self.index)
    }
}

/// Agent's triage verdict for a tour comment, applied at the end of the tour
/// once the full commit range is visible.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TourTriageVerdict {
    /// Still applicable at the final state — the human should address it.
    Live,
    /// The issue was fixed or rendered moot by a later commit in the tour.
    LikelyObsolete,
    /// Still applicable, but at a new file/line (see `new_location`).
    Moved,
}

impl TourTriageVerdict {
    pub fn id(&self) -> &'static str {
        match self {
            Self::Live => "live",
            Self::LikelyObsolete => "likely_obsolete",
            Self::Moved => "moved",
        }
    }

    pub fn from_id(s: &str) -> Option<Self> {
        match s {
            "live" => Some(Self::Live),
            "likely_obsolete" | "obsolete" => Some(Self::LikelyObsolete),
            "moved" => Some(Self::Moved),
            _ => None,
        }
    }
}

/// Location info for a Moved triage — where the agent thinks the comment now belongs.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewCommentLocation {
    pub file: String,
    pub line: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommentTriage {
    pub verdict: TourTriageVerdict,
    pub reasoning: String,
    #[serde(default)]
    pub new_location: Option<NewCommentLocation>,
}

/// Provenance metadata for a comment added while a tour was active. Keeps the
/// stop context out of the serialized Comment body so lookups stay structured.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TourCommentMeta {
    pub stop_index: usize,
    pub stop_commit_shas: Vec<String>,
    pub file: String,
    pub line: u32,
}

/// User-facing aggressiveness control for building tour stops. Presets map to
/// a concrete [`RiskScore`] threshold; `Custom` is the "5-point slider"
/// escape hatch for agents or advanced configs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TourAggressiveness {
    /// Only batch 0-risk commits (safest; splits most commits into own stop).
    Cautious,
    /// Batch 0..=3-risk commits together (default).
    Balanced,
    /// Batch everything up to 5-risk (most batching).
    Aggressive,
    /// Custom threshold, 0..=5.
    Custom(RiskScore),
}

impl TourAggressiveness {
    pub fn threshold(self) -> RiskScore {
        match self {
            Self::Cautious => RiskScore::new(1),
            Self::Balanced => RiskScore::new(3),
            Self::Aggressive => RiskScore::new(5),
            Self::Custom(s) => s,
        }
    }

    /// Stable identifier matching the `:set tour=<preset>` names.
    pub fn preset_id(self) -> &'static str {
        match self {
            Self::Cautious => "cautious",
            Self::Balanced => "balanced",
            Self::Aggressive => "aggressive",
            Self::Custom(_) => "custom",
        }
    }

    /// Parse `"cautious" | "balanced" | "aggressive" | "0".."5"` into an
    /// aggressiveness value. Returns `None` on any other input.
    pub fn parse(s: &str) -> Option<Self> {
        match s.trim() {
            "cautious" => Some(Self::Cautious),
            "balanced" => Some(Self::Balanced),
            "aggressive" => Some(Self::Aggressive),
            other => other.parse::<u8>().ok().and_then(|n| {
                if n <= 5 {
                    Some(Self::Custom(RiskScore::new(n)))
                } else {
                    None
                }
            }),
        }
    }

    /// Recover the nearest preset from a raw threshold (for status bar /
    /// MCP display). Values outside the preset set yield `Custom(s)`.
    pub fn from_threshold(s: RiskScore) -> Self {
        match s.as_u8() {
            1 => Self::Cautious,
            3 => Self::Balanced,
            5 => Self::Aggressive,
            _ => Self::Custom(s),
        }
    }
}

/// Walk `commits` in order and group them into [`TourStop`]s according to the
/// threshold:
///
/// - A commit whose risk is `> threshold` always starts a new single-commit
///   stop.
/// - A commit whose risk is `<= threshold` joins the previous stop *only* if
///   (a) that stop's existing commits also had risk `<= threshold` and (b) the
///   merged stop's risk would remain `<= threshold`. Otherwise it starts a
///   fresh stop.
///
/// The resulting stops are either a single high-risk commit or a run of
/// low-risk commits. The stop's `summary` is the joined summaries of its
/// members (first summary only for singleton stops to preserve the
/// agent-written text; batched stops get a "N commits" summary).
pub fn build_tour_stops(commits: &[ScoredCommit], threshold: RiskScore) -> Vec<TourStop> {
    let mut stops: Vec<TourStop> = Vec::with_capacity(commits.len());
    for c in commits {
        let above = c.risk > threshold;
        if !above
            && let Some(last) = stops.last_mut()
            && last.risk <= threshold
        {
            let merged = last.risk.max(c.risk);
            if merged <= threshold {
                last.commit_ids.push(c.sha.clone());
                last.risk = merged;
                last.summary = format!("{} commits batched", last.commit_ids.len());
                continue;
            }
        }
        stops.push(TourStop {
            commit_ids: vec![c.sha.clone()],
            summary: c.summary.clone(),
            risk: c.risk,
        });
    }
    stops
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn single_commit_stop_is_not_batched() {
        let stop = TourStop {
            commit_ids: vec!["abc".into()],
            summary: "one".into(),
            risk: crate::risk::RiskScore::MIN,
        };
        assert!(!stop.is_batched());
        assert_eq!(stop.first_sha(), "abc");
        assert_eq!(stop.last_sha(), "abc");
    }

    #[test]
    fn multi_commit_stop_reports_edge_shas() {
        let stop = TourStop {
            commit_ids: vec!["aaa".into(), "bbb".into(), "ccc".into()],
            summary: "batched".into(),
            risk: crate::risk::RiskScore::MIN,
        };
        assert!(stop.is_batched());
        assert_eq!(stop.first_sha(), "aaa");
        assert_eq!(stop.last_sha(), "ccc");
    }

    #[test]
    fn tour_state_current_returns_indexed_stop() {
        let t = TourState {
            stops: vec![
                TourStop {
                    commit_ids: vec!["a".into()],
                    summary: "first".into(),
                    risk: crate::risk::RiskScore::MIN,
                },
                TourStop {
                    commit_ids: vec!["b".into()],
                    summary: "second".into(),
                    risk: crate::risk::RiskScore::MIN,
                },
            ],
            index: 1,
            threshold: crate::risk::RiskScore::MIN,
            tour_schema_version: TOUR_SCHEMA_VERSION,
        };
        assert_eq!(t.current().unwrap().summary, "second");
    }

    #[test]
    fn tour_state_current_is_none_when_empty() {
        let t = TourState {
            stops: vec![],
            index: 0,
            threshold: crate::risk::RiskScore::MIN,
            tour_schema_version: TOUR_SCHEMA_VERSION,
        };
        assert!(t.current().is_none());
    }

    #[test]
    fn tour_triage_verdict_roundtrips_via_id() {
        for v in [
            TourTriageVerdict::Live,
            TourTriageVerdict::LikelyObsolete,
            TourTriageVerdict::Moved,
        ] {
            assert_eq!(TourTriageVerdict::from_id(v.id()), Some(v));
        }
        assert_eq!(TourTriageVerdict::from_id("bogus"), None);
        assert_eq!(
            TourTriageVerdict::from_id("obsolete"),
            Some(TourTriageVerdict::LikelyObsolete)
        );
    }

    #[test]
    fn tour_state_roundtrips_via_serde() {
        let t = TourState {
            stops: vec![
                TourStop {
                    commit_ids: vec!["a".into(), "b".into()],
                    summary: "one".into(),
                    risk: crate::risk::RiskScore::MIN,
                },
                TourStop {
                    commit_ids: vec!["c".into()],
                    summary: "two".into(),
                    risk: crate::risk::RiskScore::MIN,
                },
            ],
            index: 1,
            threshold: crate::risk::RiskScore::MIN,
            tour_schema_version: TOUR_SCHEMA_VERSION,
        };
        let json = serde_json::to_string(&t).unwrap();
        let back: TourState = serde_json::from_str(&json).unwrap();
        assert_eq!(back.index, 1);
        assert_eq!(back.stops.len(), 2);
        assert_eq!(back.stops[0].commit_ids, vec!["a", "b"]);
        assert_eq!(back.stops[1].summary, "two");
    }

    #[test]
    fn tour_state_new_sets_index_to_zero() {
        let t = TourState::new(vec![
            TourStop {
                commit_ids: vec!["a".into()],
                summary: "first".into(),
                risk: crate::risk::RiskScore::MIN,
            },
            TourStop {
                commit_ids: vec!["b".into()],
                summary: "second".into(),
                risk: crate::risk::RiskScore::MIN,
            },
        ]);
        assert_eq!(t.index, 0);
        assert_eq!(t.current_index(), Some(0));
    }

    #[test]
    fn tour_state_current_index_is_none_when_empty() {
        let t = TourState::new(vec![]);
        assert_eq!(t.current_index(), None);
        assert!(t.current().is_none());
    }

    #[test]
    fn tour_state_set_index_accepts_in_bounds() {
        let mut t = TourState::new(vec![
            TourStop {
                commit_ids: vec!["a".into()],
                summary: "a".into(),
                risk: crate::risk::RiskScore::MIN,
            },
            TourStop {
                commit_ids: vec!["b".into()],
                summary: "b".into(),
                risk: crate::risk::RiskScore::MIN,
            },
        ]);
        assert!(t.set_index(1));
        assert_eq!(t.index, 1);
        assert_eq!(t.current().unwrap().summary, "b");
    }

    #[test]
    fn tour_state_set_index_rejects_oob() {
        let mut t = TourState::new(vec![TourStop {
            commit_ids: vec!["a".into()],
            summary: "only".into(),
            risk: crate::risk::RiskScore::MIN,
        }]);
        assert!(!t.set_index(5));
        assert_eq!(t.index, 0, "index unchanged after OOB set_index");
    }

    #[test]
    fn tour_state_set_index_rejects_when_empty() {
        let mut t = TourState::new(vec![]);
        assert!(!t.set_index(0));
        assert_eq!(t.index, 0);
    }

    #[test]
    fn tour_state_deserialize_clamps_oob_index() {
        // Simulate a corrupt session: index points past stops.
        let json = r#"{"stops":[{"commit_ids":["a"],"summary":"s"}],"index":99}"#;
        let t: TourState = serde_json::from_str(json).expect("deserialize should succeed");
        assert_eq!(t.index, 0, "OOB index must be clamped to last valid index");
        assert!(t.current().is_some());
    }

    #[test]
    fn tour_state_deserialize_clamps_empty_stops_index() {
        let json = r#"{"stops":[],"index":7}"#;
        let t: TourState = serde_json::from_str(json).expect("deserialize should succeed");
        assert_eq!(t.index, 0);
        assert!(t.current().is_none());
    }

    #[test]
    fn tour_state_deserialize_preserves_valid_index() {
        let json = r#"{"stops":[{"commit_ids":["a"],"summary":"1"},{"commit_ids":["b"],"summary":"2"}],"index":1}"#;
        let t: TourState = serde_json::from_str(json).expect("deserialize should succeed");
        assert_eq!(t.index, 1);
        assert_eq!(t.current().unwrap().summary, "2");
    }

    #[test]
    fn triage_serializes_verdict_as_snake_case() {
        let t = CommentTriage {
            verdict: TourTriageVerdict::LikelyObsolete,
            reasoning: "fixed in later commit".into(),
            new_location: None,
        };
        let json = serde_json::to_string(&t).unwrap();
        assert!(
            json.contains("\"likely_obsolete\""),
            "expected snake_case verdict in: {json}"
        );
    }

    // --- risk + batching ---

    fn sc(sha: &str, risk: u8, summary: &str) -> ScoredCommit {
        ScoredCommit {
            sha: sha.into(),
            risk: RiskScore::new(risk),
            summary: summary.into(),
        }
    }

    #[test]
    fn build_stops_batches_below_threshold() {
        let commits = vec![
            sc("a", 0, "fmt only"),
            sc("b", 1, "typo fix"),
            sc("c", 0, "whitespace"),
        ];
        let stops = build_tour_stops(&commits, RiskScore::new(1));
        assert_eq!(stops.len(), 1, "all three should batch into one stop");
        assert_eq!(stops[0].commit_ids.len(), 3);
        assert_eq!(stops[0].risk.as_u8(), 1);
    }

    #[test]
    fn build_stops_isolates_above_threshold() {
        let commits = vec![sc("a", 0, "docs"), sc("b", 5, "crypto"), sc("c", 0, "fmt")];
        let stops = build_tour_stops(&commits, RiskScore::new(1));
        assert_eq!(stops.len(), 3);
        assert_eq!(stops[1].commit_ids, vec!["b".to_string()]);
        assert_eq!(stops[1].risk.as_u8(), 5);
    }

    #[test]
    fn build_stops_respects_merged_risk_cap() {
        // threshold=1: 1-risk | 2-risk (above) | 1-risk → 3 stops, not 1.
        let commits = vec![sc("a", 1, "doc"), sc("b", 2, "config"), sc("c", 1, "doc")];
        let stops = build_tour_stops(&commits, RiskScore::new(1));
        assert_eq!(stops.len(), 3, "2-risk commit breaks the batch");
        assert_eq!(stops[0].commit_ids, vec!["a".to_string()]);
        assert_eq!(stops[1].commit_ids, vec!["b".to_string()]);
        assert_eq!(stops[2].commit_ids, vec!["c".to_string()]);
    }

    #[test]
    fn tour_state_serde_preserves_threshold() {
        let t = TourState::new_with_threshold(
            vec![TourStop {
                commit_ids: vec!["a".into()],
                summary: "only".into(),
                risk: RiskScore::new(2),
            }],
            RiskScore::new(3),
        );
        let json = serde_json::to_string(&t).unwrap();
        let back: TourState = serde_json::from_str(&json).unwrap();
        assert_eq!(back.threshold.as_u8(), 3);
        assert_eq!(back.stops[0].risk.as_u8(), 2);
    }

    #[test]
    fn tour_stop_serde_preserves_risk() {
        let s = TourStop {
            commit_ids: vec!["a".into()],
            summary: "summary".into(),
            risk: RiskScore::new(4),
        };
        let json = serde_json::to_string(&s).unwrap();
        let back: TourStop = serde_json::from_str(&json).unwrap();
        assert_eq!(back.risk.as_u8(), 4);
    }

    #[test]
    fn legacy_tour_json_without_risk_field_defaults_to_zero() {
        let json = r#"{"stops":[{"commit_ids":["a"],"summary":"s"}],"index":0}"#;
        let t: TourState = serde_json::from_str(json).expect("legacy JSON must load");
        assert_eq!(t.stops[0].risk.as_u8(), 0);
        assert_eq!(t.threshold.as_u8(), 0);
    }

    // ── H11: tour schema migration ──

    #[test]
    fn legacy_tour_json_deserializes_as_schema_version_zero() {
        // A tour written before H11 has no `tour_schema_version` field.
        // Serde defaults it to 0; migrate_tour rolls it forward.
        let json = r#"{"stops":[{"commit_ids":["a"],"summary":"s"}],"index":0}"#;
        let t: TourState = serde_json::from_str(json).expect("legacy JSON must load");
        assert_eq!(t.tour_schema_version, 0, "missing field defaults to 0");
    }

    #[test]
    fn migrate_tour_rolls_legacy_v0_up_to_current() {
        let mut t: TourState =
            serde_json::from_str(r#"{"stops":[{"commit_ids":["a"],"summary":"s"}],"index":0}"#)
                .expect("legacy JSON must load");
        assert_eq!(t.tour_schema_version, 0);
        let changed = migrate_tour(&mut t).expect("v0 migration succeeds");
        assert!(changed, "migration must report work done on v0 input");
        assert_eq!(
            t.tour_schema_version, TOUR_SCHEMA_VERSION,
            "migrated tour is at current schema version"
        );
    }

    #[test]
    fn migrate_tour_is_idempotent_on_current_version() {
        let mut t = TourState::new(vec![TourStop {
            commit_ids: vec!["a".into()],
            summary: "s".into(),
            risk: RiskScore::MIN,
        }]);
        assert_eq!(t.tour_schema_version, TOUR_SCHEMA_VERSION);
        let changed = migrate_tour(&mut t).expect("idempotent migration");
        assert!(!changed, "no migration needed on current tour");
        assert_eq!(t.tour_schema_version, TOUR_SCHEMA_VERSION);
    }

    #[test]
    fn migrate_tour_rejects_future_schema_version() {
        // Regression (post-H11 crew review): a tour recorded with a
        // future schema version (e.g. user downgraded their binary after
        // a prior session bumped `tour_schema_version`) must fail the
        // migration rather than silently returning `changed = false` and
        // letting the caller interpret unknown shape as the known one.
        let mut t = TourState::new(vec![]);
        t.tour_schema_version = TOUR_SCHEMA_VERSION + 1;
        let err = migrate_tour(&mut t).expect_err("future-versioned tour must fail");
        assert!(matches!(
            err,
            MigrateTourError::FromTheFuture {
                recorded,
                supported
            } if recorded == TOUR_SCHEMA_VERSION + 1 && supported == TOUR_SCHEMA_VERSION
        ));
        assert_eq!(
            t.tour_schema_version,
            TOUR_SCHEMA_VERSION + 1,
            "version stamp must not be modified on rejection"
        );
    }

    #[test]
    fn new_tour_is_tagged_with_current_schema_version() {
        let t = TourState::new(vec![]);
        assert_eq!(t.tour_schema_version, TOUR_SCHEMA_VERSION);
        let t = TourState::new_with_threshold(vec![], RiskScore::new(3));
        assert_eq!(t.tour_schema_version, TOUR_SCHEMA_VERSION);
    }

    #[test]
    fn fresh_tour_roundtrips_with_schema_version() {
        let t = TourState::new(vec![TourStop {
            commit_ids: vec!["a".into()],
            summary: "s".into(),
            risk: RiskScore::MIN,
        }]);
        let json = serde_json::to_string(&t).expect("serialize");
        let back: TourState = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(back.tour_schema_version, TOUR_SCHEMA_VERSION);
    }

    #[test]
    fn aggressiveness_parses_presets_and_numbers() {
        assert_eq!(
            TourAggressiveness::parse("cautious"),
            Some(TourAggressiveness::Cautious)
        );
        assert_eq!(
            TourAggressiveness::parse("balanced"),
            Some(TourAggressiveness::Balanced)
        );
        assert_eq!(
            TourAggressiveness::parse("aggressive"),
            Some(TourAggressiveness::Aggressive)
        );
        assert_eq!(
            TourAggressiveness::parse("0"),
            Some(TourAggressiveness::Custom(RiskScore::new(0)))
        );
        assert_eq!(
            TourAggressiveness::parse("5"),
            Some(TourAggressiveness::Custom(RiskScore::new(5)))
        );
        assert_eq!(TourAggressiveness::parse("6"), None);
        assert_eq!(TourAggressiveness::parse("foo"), None);
    }

    #[test]
    fn aggressiveness_preset_thresholds_match_spec() {
        assert_eq!(TourAggressiveness::Cautious.threshold().as_u8(), 1);
        assert_eq!(TourAggressiveness::Balanced.threshold().as_u8(), 3);
        assert_eq!(TourAggressiveness::Aggressive.threshold().as_u8(), 5);
        assert_eq!(
            TourAggressiveness::Custom(RiskScore::new(2))
                .threshold()
                .as_u8(),
            2
        );
    }
}