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
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
//! Headless review engine — the session-level workhorse shared by the TUI
//! and the standalone MCP server.
//!
//! [`ReviewEngine`] owns a [`ReviewSession`] and exposes the session-level
//! operations that every consumer needs: applying a rescan's diff files,
//! running the pure re-anchoring pipeline, comment CRUD, and handing off
//! the owned session when the consumer needs to serialize or shut down.
//! Later slices of Phase H6 will migrate cursor-independent anchor
//! helpers and tour state onto this type; for now the session is still
//! reachable via [`ReviewEngine::session`] / [`ReviewEngine::session_mut`]
//! for ops the engine does not yet cover.
//!
//! This type is UI-agnostic: it has no knowledge of ratatui, no cursor
//! position, no viewport state. Those concerns stay on the consumer
//! (`App` in the TUI, `ReviewState` in the MCP server).

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

use chrono::Utc;

use crate::model::review::FileReview;
use crate::model::{
    AnchorState, Comment, CommentType, DiffFile, FileStatus, LineSide, ReviewSession,
};

/// Headless review engine. Owns the [`ReviewSession`] and exposes the
/// session-level operations that both the TUI and the standalone MCP
/// server use. See the module-level docs for the current scope.
#[derive(Debug)]
pub struct ReviewEngine {
    session: ReviewSession,
}

impl ReviewEngine {
    /// Wrap an existing [`ReviewSession`] in a new engine.
    pub fn new(session: ReviewSession) -> Self {
        Self { session }
    }

    /// Borrow the owned session.
    pub fn session(&self) -> &ReviewSession {
        &self.session
    }

    /// Mutably borrow the owned session. Preferred by consumers that still
    /// drive the session directly pending later slices of the refactor.
    pub fn session_mut(&mut self) -> &mut ReviewSession {
        &mut self.session
    }

    /// Apply the output of a rescan to the session. Convenience
    /// delegation to [`ReviewSession::apply_diff_files`] so callers don't
    /// have to reach through `session_mut()` for this common operation.
    pub fn apply_diff_files(&mut self, diff_files: &[DiffFile]) {
        self.session.apply_diff_files(diff_files);
    }

    /// Replace the owned session wholesale. Used by call sites that
    /// rebuild a session from scratch (rescan, commit-range retarget,
    /// persisted-session reload). Does NOT touch `updated_at` — callers
    /// decide whether the new session represents a write or a reload.
    pub fn replace_session(&mut self, session: ReviewSession) {
        self.session = session;
    }

    /// Convenience: replace the session AND register all files from a
    /// rescan's diff in one call. Equivalent to `replace_session` followed
    /// by `apply_diff_files`. Most session-swap call sites want this pair.
    pub fn reset_with_diff(&mut self, session: ReviewSession, diff_files: &[DiffFile]) {
        self.session = session;
        self.session.apply_diff_files(diff_files);
    }

    /// Run the pure re-anchoring pipeline over the owned session.
    /// Convenience delegation to [`crate::reanchor::reanchor_comments`].
    pub fn reanchor_comments(
        &mut self,
        old_new_content: &HashMap<PathBuf, String>,
        new_content_map: &HashMap<PathBuf, String>,
        new_paths: &HashSet<PathBuf>,
        path_filter_active: bool,
    ) {
        crate::reanchor::reanchor_comments(
            &mut self.session,
            old_new_content,
            new_content_map,
            new_paths,
            path_filter_active,
        );
    }

    /// Consume the engine, returning the owned session. Useful for
    /// serialization / shutdown paths where the session needs to be
    /// handed off independently.
    pub fn into_session(self) -> ReviewSession {
        self.session
    }

    /// Register a file in the session if it isn't already tracked and stamp
    /// `updated_at`. Returns a mutable borrow of the resulting [`FileReview`]
    /// so callers that need extra per-file writes (reanchor, orphan pushes,
    /// etc.) can do so without re-fetching.
    ///
    /// # Footgun
    ///
    /// `status` is **only consulted when the file is absent from the session**
    /// (i.e., a brand-new `FileReview` is being seeded). If the file is
    /// already tracked, the existing `status` is kept and the argument is
    /// silently ignored — callers cannot use this method to *mutate* status.
    ///
    /// Because the new-file branch trusts `status` blindly, callers must
    /// supply one that matches the live diff. The convention is to look it
    /// up from the current `DiffFile`, as `mcp_bridge::handle_mark_reviewed`
    /// does. Passing a fabricated status registers a stub `FileReview` that
    /// rides through save/reanchor with the wrong metadata. Prefer
    /// [`Self::try_add_line_comment`] / [`Self::try_add_file_comment`] from
    /// any call site that doesn't need to *create* a file entry — they
    /// refuse to register an absent file rather than guessing.
    pub fn touch_file(&mut self, path: PathBuf, status: FileStatus) -> &mut FileReview {
        self.session.add_file(path.clone(), status);
        self.session.updated_at = Utc::now();
        self.session
            .get_file_mut(&path)
            .expect("file was just registered via add_file")
    }

    /// Add a line comment to `path` at `line`. Registers the file if absent,
    /// stamps `updated_at`, and returns the new comment's id.
    ///
    /// Prefer [`Self::try_add_line_comment`] when the caller cannot safely
    /// seed a new `FileReview` — see [`Self::touch_file`] for the footgun
    /// around `status`. This lenient variant exists for call sites that
    /// *must* create the file entry (e.g. MCP `trv_add_comment`, which
    /// derives `status` from the live `DiffFile` and falls back to seeding
    /// an entry so the comment is never silently dropped).
    pub fn add_line_comment(
        &mut self,
        path: PathBuf,
        status: FileStatus,
        line: u32,
        comment: Comment,
    ) -> String {
        let id = comment.id.clone();
        let review = self.touch_file(path, status);
        review.add_line_comment(line, comment);
        id
    }

    /// Add a file-level comment to `path`. Registers the file if absent,
    /// stamps `updated_at`, and returns the new comment's id.
    ///
    /// Prefer [`Self::try_add_file_comment`] unless the caller must create
    /// the file entry — see [`Self::touch_file`] for the `status` footgun.
    pub fn add_file_comment(
        &mut self,
        path: PathBuf,
        status: FileStatus,
        comment: Comment,
    ) -> String {
        let id = comment.id.clone();
        let review = self.touch_file(path, status);
        review.add_file_comment(comment);
        id
    }

    /// Strict variant of [`add_line_comment`]: add a line comment only if
    /// `path` is already tracked in the session. Does not register the file
    /// if absent. Stamps `updated_at` only on success. Returns the new
    /// comment's id, or `None` if the file wasn't found.
    ///
    /// Useful for call sites that treat an unregistered file as a
    /// precondition failure (e.g. a TUI action that should drop the
    /// comment rather than silently seed a `FileReview` with no diff).
    pub fn try_add_line_comment(
        &mut self,
        path: &Path,
        line: u32,
        comment: Comment,
    ) -> Option<String> {
        let id = comment.id.clone();
        let review = self.session.get_file_mut(path)?;
        review.add_line_comment(line, comment);
        self.session.updated_at = Utc::now();
        Some(id)
    }

    /// Strict variant of [`add_file_comment`]: add a file-level comment
    /// only if `path` is already tracked. See [`try_add_line_comment`] for
    /// the rationale.
    pub fn try_add_file_comment(&mut self, path: &Path, comment: Comment) -> Option<String> {
        let id = comment.id.clone();
        let review = self.session.get_file_mut(path)?;
        review.add_file_comment(comment);
        self.session.updated_at = Utc::now();
        Some(id)
    }

    /// Add a review-level (session-wide) comment. Stamps `updated_at` and
    /// returns the new comment's id.
    pub fn add_review_comment(&mut self, comment: Comment) -> String {
        let id = comment.id.clone();
        self.session.review_comments.push(comment);
        self.session.updated_at = Utc::now();
        id
    }

    /// Remove a comment by id from any scope (review-level, file-level,
    /// line-level, or orphaned). Bumps `updated_at` and returns `true` if a
    /// comment was removed.
    pub fn remove_comment(&mut self, id: &str) -> bool {
        let session = &mut self.session;
        if let Some(pos) = session.review_comments.iter().position(|c| c.id == id) {
            session.review_comments.remove(pos);
            session.updated_at = Utc::now();
            return true;
        }
        for file in session.files.values_mut() {
            if let Some(pos) = file.file_comments.iter().position(|c| c.id == id) {
                file.file_comments.remove(pos);
                session.updated_at = Utc::now();
                return true;
            }
            let mut target_line: Option<u32> = None;
            for (line, comments) in file.line_comments.iter_mut() {
                if let Some(pos) = comments.iter().position(|c| c.id == id) {
                    comments.remove(pos);
                    target_line = Some(*line);
                    break;
                }
            }
            if let Some(line) = target_line {
                if file.line_comments.get(&line).is_some_and(|v| v.is_empty()) {
                    file.line_comments.remove(&line);
                }
                session.updated_at = Utc::now();
                return true;
            }
            if let Some(pos) = file.orphaned_comments.iter().position(|c| c.id == id) {
                file.orphaned_comments.remove(pos);
                session.updated_at = Utc::now();
                return true;
            }
        }
        false
    }

    /// Replace both the body and `comment_type` of an existing comment by
    /// id across any scope. Bumps `updated_at` and returns `true` if the
    /// comment was found.
    pub fn edit_comment(&mut self, id: &str, new_body: String, new_type: CommentType) -> bool {
        let session = &mut self.session;
        let apply = |c: &mut Comment| {
            c.content = new_body.clone();
            c.comment_type = new_type.clone();
        };
        if let Some(c) = session.review_comments.iter_mut().find(|c| c.id == id) {
            apply(c);
            session.updated_at = Utc::now();
            return true;
        }
        for file in session.files.values_mut() {
            if let Some(c) = file.file_comments.iter_mut().find(|c| c.id == id) {
                apply(c);
                session.updated_at = Utc::now();
                return true;
            }
            for comments in file.line_comments.values_mut() {
                if let Some(c) = comments.iter_mut().find(|c| c.id == id) {
                    apply(c);
                    session.updated_at = Utc::now();
                    return true;
                }
            }
            if let Some(c) = file.orphaned_comments.iter_mut().find(|c| c.id == id) {
                apply(c);
                session.updated_at = Utc::now();
                return true;
            }
        }
        false
    }

    /// Clear all comments (review-, file-, line-, and orphan-level) and
    /// mark all files as un-reviewed. Returns `(comments_cleared,
    /// files_unreviewed)` — matches [`ReviewSession::clear_comments`].
    /// Bumps `updated_at` when anything actually changed.
    pub fn clear_comments(&mut self) -> (usize, usize) {
        let (cleared, unreviewed) = self.session.clear_comments();
        if cleared > 0 || unreviewed > 0 {
            self.session.updated_at = Utc::now();
        }
        (cleared, unreviewed)
    }

    /// Re-anchor the orphan at `(path, orphan_idx)` back onto
    /// `(dest_line, dest_side)`. Pops the comment off
    /// `review.orphaned_comments`, stamps a fresh
    /// [`AnchorState::Anchored`] with `reanchored_at = now`, and
    /// appends it to `review.line_comments[dest_line]`. Bumps
    /// `updated_at` and returns `true` on success; returns `false`
    /// (without touching `updated_at`) if the path is unknown or
    /// `orphan_idx` is out of range.
    ///
    /// Only the anchor state changes — the comment body, type,
    /// author, and id are preserved so threading (reactions,
    /// replies) is not broken.
    pub fn reanchor_orphan(
        &mut self,
        path: &Path,
        orphan_idx: usize,
        dest_line: u32,
        dest_side: LineSide,
    ) -> bool {
        let Some(review) = self.session.get_file_mut(path) else {
            return false;
        };
        if orphan_idx >= review.orphaned_comments.len() {
            return false;
        }
        let mut comment = review.orphaned_comments.remove(orphan_idx);
        comment.anchor = Some(AnchorState::Anchored {
            line: dest_line,
            side: dest_side,
            reanchored_at: Some(Utc::now()),
        });
        comment.side = Some(dest_side);
        review
            .line_comments
            .entry(dest_line)
            .or_default()
            .push(comment);
        self.session.updated_at = Utc::now();
        true
    }

    /// Read-only accessor for a file's line comments. Returns an empty vec
    /// if the file isn't tracked. Used by renderers that need a snapshot
    /// without mutably borrowing the session.
    pub fn line_comments_for(&self, path: &Path) -> std::collections::HashMap<u32, Vec<Comment>> {
        self.session
            .files
            .get(path)
            .map(|r| r.line_comments.clone())
            .unwrap_or_default()
    }
}

/// Test-only helpers for seeding pre-stamped session state. Gated so
/// they never leak into production builds. These bypass the
/// `updated_at` bump and let tests control every timestamp precisely.
#[cfg(any(test, feature = "test-support"))]
impl ReviewEngine {
    /// Seed a line comment whose [`crate::model::comment::AnchorState::Anchored`]
    /// has been stamped by the caller. Registers `path` on the session if absent.
    /// Unlike [`ReviewEngine::add_line_comment`], this does NOT touch
    /// `session.updated_at` and does NOT overwrite `comment.anchor`.
    /// `comment.created_at` is preserved as-is. Returns the comment's id.
    pub fn seed_anchored_line_comment(
        &mut self,
        path: PathBuf,
        status: FileStatus,
        line: u32,
        comment: Comment,
    ) -> String {
        let id = comment.id.clone();
        self.session.add_file(path.clone(), status);
        let review = self
            .session
            .get_file_mut(&path)
            .expect("file was just registered via add_file");
        review.add_line_comment(line, comment);
        id
    }

    /// Seed an orphaned comment whose [`crate::model::comment::AnchorState::Orphaned`]
    /// has been stamped by the caller. Registers `path` on the session if absent.
    /// Like `seed_anchored_line_comment`, this preserves all timestamps
    /// on `comment` and does not bump `session.updated_at`.
    pub fn seed_orphaned_comment(
        &mut self,
        path: PathBuf,
        status: FileStatus,
        comment: Comment,
    ) -> String {
        let id = comment.id.clone();
        self.session.add_file(path.clone(), status);
        let review = self
            .session
            .get_file_mut(&path)
            .expect("file was just registered via add_file");
        review.orphaned_comments.push(comment);
        id
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::FileStatus;
    use crate::model::comment::{AnchorState, Comment, CommentType, LineSide};
    use crate::model::review::SessionDiffSource;
    use chrono::Duration;

    fn make_session() -> ReviewSession {
        ReviewSession::new(
            PathBuf::from("/tmp/repo"),
            "abc123".to_string(),
            Some("main".to_string()),
            SessionDiffSource::WorkingTree,
        )
    }

    fn make_comment(body: &str) -> Comment {
        Comment::new(body.to_string(), CommentType::Note, Some(LineSide::New))
    }

    #[test]
    fn session_mut_exposes_owned_session() {
        let session = make_session();
        let original_base = session.base_commit.clone();
        let mut engine = ReviewEngine::new(session);

        // Mutating through `session_mut` must be visible through `session`.
        engine.session_mut().base_commit = "xyz999".to_string();
        assert_ne!(engine.session().base_commit, original_base);
        assert_eq!(engine.session().base_commit, "xyz999");
    }

    #[test]
    fn apply_diff_files_delegates_to_session() {
        let mut engine = ReviewEngine::new(make_session());
        let df = DiffFile {
            old_path: None,
            new_path: Some(PathBuf::from("src/lib.rs")),
            status: FileStatus::Added,
            hunks: vec![],
            is_binary: false,
            is_too_large: false,
            is_commit_message: false,
        };

        engine.apply_diff_files(std::slice::from_ref(&df));

        // Same post-condition as calling `ReviewSession::apply_diff_files`
        // directly: the file is registered in the session's files map.
        assert!(
            engine
                .session()
                .files
                .contains_key(&PathBuf::from("src/lib.rs"))
        );
    }

    #[test]
    fn reanchor_comments_delegates_to_core_reanchor() {
        // Empty maps — the pipeline should be a no-op and leave the
        // session in a valid state. Exercising the delegation is enough
        // here; the pipeline's behavior is covered by `core::reanchor`
        // tests.
        let mut engine = ReviewEngine::new(make_session());
        let old: HashMap<PathBuf, String> = HashMap::new();
        let new: HashMap<PathBuf, String> = HashMap::new();
        let paths: HashSet<PathBuf> = HashSet::new();

        engine.reanchor_comments(&old, &new, &paths, false);

        // No files were registered, so nothing should have changed.
        assert!(engine.session().files.is_empty());
    }

    #[test]
    fn into_session_returns_owned_session() {
        let mut session = make_session();
        session.base_commit = "marker".to_string();
        let engine = ReviewEngine::new(session);
        let unwrapped = engine.into_session();
        assert_eq!(unwrapped.base_commit, "marker");
    }

    #[test]
    fn touch_file_registers_and_bumps_updated_at() {
        let mut engine = ReviewEngine::new(make_session());
        let before = engine.session().updated_at;
        let path = PathBuf::from("src/lib.rs");
        let review = engine.touch_file(path.clone(), FileStatus::Added);
        assert_eq!(review.path, path);
        assert_eq!(review.status, FileStatus::Added);
        assert!(engine.session().files.contains_key(&path));
        assert!(engine.session().updated_at >= before);

        // Touching again is idempotent — file stays registered and status
        // on the existing entry is preserved (add_file is or_insert_with).
        engine.touch_file(path.clone(), FileStatus::Modified);
        assert_eq!(engine.session().files.len(), 1);
        assert_eq!(
            engine.session().files.get(&path).unwrap().status,
            FileStatus::Added
        );
    }

    #[test]
    fn add_line_comment_registers_file_and_returns_id() {
        let mut engine = ReviewEngine::new(make_session());
        let path = PathBuf::from("src/lib.rs");
        let comment = make_comment("line comment");
        let expected_id = comment.id.clone();

        let id = engine.add_line_comment(path.clone(), FileStatus::Modified, 42, comment);

        assert_eq!(id, expected_id);
        let file = engine.session().files.get(&path).expect("file registered");
        let comments = file.line_comments.get(&42).expect("line comment present");
        assert_eq!(comments.len(), 1);
        assert_eq!(comments[0].content, "line comment");
    }

    #[test]
    fn add_file_comment_registers_file_and_returns_id() {
        let mut engine = ReviewEngine::new(make_session());
        let path = PathBuf::from("src/lib.rs");
        let comment = make_comment("file comment");
        let expected_id = comment.id.clone();

        let id = engine.add_file_comment(path.clone(), FileStatus::Modified, comment);

        assert_eq!(id, expected_id);
        let file = engine.session().files.get(&path).expect("file registered");
        assert_eq!(file.file_comments.len(), 1);
        assert_eq!(file.file_comments[0].content, "file comment");
    }

    #[test]
    fn add_review_comment_pushes_and_returns_id() {
        let mut engine = ReviewEngine::new(make_session());
        let comment = make_comment("review-level");
        let expected_id = comment.id.clone();

        let id = engine.add_review_comment(comment);

        assert_eq!(id, expected_id);
        assert_eq!(engine.session().review_comments.len(), 1);
        assert_eq!(engine.session().review_comments[0].content, "review-level");
    }

    #[test]
    fn remove_comment_finds_across_scopes() {
        let mut engine = ReviewEngine::new(make_session());
        let path = PathBuf::from("src/lib.rs");

        let review_id = engine.add_review_comment(make_comment("r"));
        let file_id =
            engine.add_file_comment(path.clone(), FileStatus::Modified, make_comment("f"));
        let line_id =
            engine.add_line_comment(path.clone(), FileStatus::Modified, 10, make_comment("l"));

        assert!(engine.remove_comment(&review_id));
        assert!(engine.session().review_comments.is_empty());

        assert!(engine.remove_comment(&file_id));
        assert!(
            engine
                .session()
                .files
                .get(&path)
                .unwrap()
                .file_comments
                .is_empty()
        );

        assert!(engine.remove_comment(&line_id));
        // line 10 entry should be pruned because it became empty.
        assert!(
            !engine
                .session()
                .files
                .get(&path)
                .unwrap()
                .line_comments
                .contains_key(&10)
        );

        // Unknown id → false, no panic.
        assert!(!engine.remove_comment("does-not-exist"));
    }

    #[test]
    fn edit_comment_updates_both_body_and_type() {
        let mut engine = ReviewEngine::new(make_session());
        let review_id = engine.add_review_comment(make_comment("initial"));

        assert!(engine.edit_comment(&review_id, "updated".to_string(), CommentType::Praise,));
        let comment = &engine.session().review_comments[0];
        assert_eq!(comment.content, "updated");
        assert_eq!(comment.comment_type, CommentType::Praise);

        assert!(!engine.edit_comment("missing", "x".to_string(), CommentType::Note,));
    }

    #[test]
    fn clear_comments_returns_counts_and_unreviews() {
        let mut engine = ReviewEngine::new(make_session());
        let path = PathBuf::from("src/lib.rs");

        engine.add_review_comment(make_comment("r"));
        engine.add_file_comment(path.clone(), FileStatus::Modified, make_comment("f"));
        engine.add_line_comment(path.clone(), FileStatus::Modified, 1, make_comment("l"));
        engine.session_mut().get_file_mut(&path).unwrap().reviewed = true;

        let (cleared, unreviewed) = engine.clear_comments();
        assert_eq!(cleared, 3);
        assert_eq!(unreviewed, 1);
        assert!(engine.session().review_comments.is_empty());
        let fr = engine.session().files.get(&path).unwrap();
        assert!(fr.file_comments.is_empty());
        assert!(fr.line_comments.is_empty());
        assert!(!fr.reviewed);
    }

    #[test]
    fn line_comments_for_returns_snapshot_or_empty() {
        let mut engine = ReviewEngine::new(make_session());
        let path = PathBuf::from("src/lib.rs");

        // Unknown path → empty map (no panic, no allocation on the session).
        let empty = engine.line_comments_for(&path);
        assert!(empty.is_empty());

        engine.add_line_comment(path.clone(), FileStatus::Modified, 3, make_comment("hello"));
        let map = engine.line_comments_for(&path);
        assert_eq!(map.len(), 1);
        assert_eq!(map.get(&3).unwrap()[0].content, "hello");
    }

    #[test]
    fn try_add_line_comment_returns_none_for_unregistered_file() {
        let mut engine = ReviewEngine::new(make_session());
        let path = PathBuf::from("src/never.rs");
        let updated_before = engine.session().updated_at;

        // File not registered → None, no file created, no timestamp bump.
        let res = engine.try_add_line_comment(&path, 5, make_comment("nope"));
        assert!(res.is_none());
        assert!(engine.session().files.is_empty());
        assert_eq!(engine.session().updated_at, updated_before);

        // Register the file, then strict add should succeed and stamp.
        engine.touch_file(path.clone(), FileStatus::Modified);
        let after_touch = engine.session().updated_at;
        let id = engine.try_add_line_comment(&path, 5, make_comment("yes"));
        assert!(id.is_some());
        assert!(engine.session().updated_at >= after_touch);
        assert_eq!(
            engine
                .session()
                .files
                .get(&path)
                .unwrap()
                .line_comments
                .get(&5)
                .unwrap()[0]
                .content,
            "yes"
        );
    }

    #[test]
    fn replace_session_swaps_in_new_session() {
        let mut session_a = make_session();
        session_a.add_file(PathBuf::from("src/lib.rs"), FileStatus::Added);
        let mut engine = ReviewEngine::new(session_a);
        assert!(
            engine
                .session()
                .files
                .contains_key(&PathBuf::from("src/lib.rs"))
        );

        let mut session_b = make_session();
        session_b.base_commit = "different".to_string();
        engine.replace_session(session_b);

        assert_eq!(engine.session().base_commit, "different");
        assert!(
            !engine
                .session()
                .files
                .contains_key(&PathBuf::from("src/lib.rs"))
        );
    }

    #[test]
    fn reset_with_diff_replaces_and_registers() {
        let mut engine = ReviewEngine::new(make_session());
        engine
            .session_mut()
            .add_file(PathBuf::from("old/stale.rs"), FileStatus::Added);

        let fresh = make_session();
        let df = DiffFile {
            old_path: None,
            new_path: Some(PathBuf::from("src/new.rs")),
            status: FileStatus::Added,
            hunks: vec![],
            is_binary: false,
            is_too_large: false,
            is_commit_message: false,
        };
        engine.reset_with_diff(fresh, std::slice::from_ref(&df));

        assert!(
            engine
                .session()
                .files
                .contains_key(&PathBuf::from("src/new.rs"))
        );
        assert!(
            !engine
                .session()
                .files
                .contains_key(&PathBuf::from("old/stale.rs"))
        );
    }

    #[test]
    fn reset_with_diff_handles_renames() {
        let mut engine = ReviewEngine::new(make_session());
        let fresh = make_session();
        let new_path = PathBuf::from("src/new.rs");
        let renamed = DiffFile {
            old_path: Some(PathBuf::from("src/old.rs")),
            new_path: Some(new_path.clone()),
            status: FileStatus::Renamed,
            hunks: vec![],
            is_binary: false,
            is_too_large: false,
            is_commit_message: false,
        };

        engine.reset_with_diff(fresh, std::slice::from_ref(&renamed));

        assert!(engine.session().files.contains_key(&new_path));
    }

    #[test]
    fn try_add_file_comment_returns_none_for_unregistered_file() {
        let mut engine = ReviewEngine::new(make_session());
        let path = PathBuf::from("src/never.rs");
        let updated_before = engine.session().updated_at;

        let res = engine.try_add_file_comment(&path, make_comment("nope"));
        assert!(res.is_none());
        assert!(engine.session().files.is_empty());
        assert_eq!(engine.session().updated_at, updated_before);

        engine.touch_file(path.clone(), FileStatus::Modified);
        let id = engine.try_add_file_comment(&path, make_comment("yes"));
        assert!(id.is_some());
        assert_eq!(
            engine.session().files.get(&path).unwrap().file_comments[0].content,
            "yes"
        );
    }

    #[test]
    fn seed_anchored_line_comment_preserves_timestamps_and_anchor() {
        let mut engine = ReviewEngine::new(make_session());
        let path = PathBuf::from("src/lib.rs");

        let created_at = Utc::now() - Duration::days(365);
        let reanchored_at = Utc::now() - Duration::days(30);

        let mut comment = make_comment("seeded");
        comment.created_at = created_at;
        comment.anchor = Some(AnchorState::Anchored {
            line: 7,
            side: LineSide::New,
            reanchored_at: Some(reanchored_at),
        });
        let expected_id = comment.id.clone();

        let updated_before = engine.session().updated_at;

        let id = engine.seed_anchored_line_comment(path.clone(), FileStatus::Modified, 7, comment);

        assert_eq!(id, expected_id);
        let stored = &engine
            .session()
            .files
            .get(&path)
            .unwrap()
            .line_comments
            .get(&7)
            .unwrap()[0];
        assert_eq!(stored.created_at, created_at);
        match stored.anchor.as_ref().unwrap() {
            AnchorState::Anchored {
                line,
                side,
                reanchored_at: stamped,
            } => {
                assert_eq!(*line, 7);
                assert_eq!(*side, LineSide::New);
                assert_eq!(*stamped, Some(reanchored_at));
            }
            other => panic!("expected anchored state, got {other:?}"),
        }
        assert_eq!(
            engine.session().updated_at,
            updated_before,
            "seed must not bump updated_at"
        );
    }

    #[test]
    fn seed_orphaned_comment_preserves_timestamps_and_anchor() {
        let mut engine = ReviewEngine::new(make_session());
        let path = PathBuf::from("src/lib.rs");

        let created_at = Utc::now() - Duration::days(365);
        let orphaned_at = Utc::now() - Duration::days(30);

        let mut comment = make_comment("orphaned seed");
        comment.created_at = created_at;
        comment.anchor = Some(AnchorState::Orphaned {
            was_line: 5,
            was_side: LineSide::New,
            last_seen_content: "x".into(),
            orphaned_at: Some(orphaned_at),
        });
        let expected_id = comment.id.clone();

        let updated_before = engine.session().updated_at;

        let id = engine.seed_orphaned_comment(path.clone(), FileStatus::Modified, comment);

        assert_eq!(id, expected_id);
        let file = engine.session().files.get(&path).unwrap();
        assert_eq!(file.orphaned_comments.len(), 1);
        let stored = &file.orphaned_comments[0];
        assert_eq!(stored.created_at, created_at);
        match stored.anchor.as_ref().unwrap() {
            AnchorState::Orphaned {
                was_line,
                was_side,
                last_seen_content,
                orphaned_at: stamped,
            } => {
                assert_eq!(*was_line, 5);
                assert_eq!(*was_side, LineSide::New);
                assert_eq!(last_seen_content, "x");
                assert_eq!(*stamped, Some(orphaned_at));
            }
            other => panic!("expected orphaned state, got {other:?}"),
        }
        assert_eq!(
            engine.session().updated_at,
            updated_before,
            "seed must not bump updated_at"
        );
    }

    #[test]
    fn reanchor_orphan_moves_and_bumps_updated_at() {
        let mut engine = ReviewEngine::new(make_session());
        let path = PathBuf::from("a.rs");
        let mut comment = Comment::new("stale".into(), CommentType::Note, Some(LineSide::New));
        comment.anchor = Some(AnchorState::Orphaned {
            was_line: 5,
            was_side: LineSide::New,
            last_seen_content: "x".into(),
            orphaned_at: Some(Utc::now() - Duration::seconds(60)),
        });
        let cid = comment.id.clone();
        engine.seed_orphaned_comment(path.clone(), FileStatus::Modified, comment);

        let before = engine.session().updated_at;

        assert!(engine.reanchor_orphan(&path, 0, 2, LineSide::New));

        let review = engine.session().files.get(&path).unwrap();
        assert!(
            review.orphaned_comments.is_empty(),
            "orphan popped off orphaned_comments"
        );
        let line_comments = review
            .line_comments
            .get(&2)
            .expect("comment now lives at the new line");
        assert_eq!(line_comments.len(), 1);
        assert_eq!(line_comments[0].id, cid);
        match line_comments[0].anchor.as_ref().unwrap() {
            AnchorState::Anchored {
                line,
                side,
                reanchored_at,
            } => {
                assert_eq!(*line, 2);
                assert_eq!(*side, LineSide::New);
                assert!(
                    reanchored_at.is_some(),
                    "re-anchored comment must stamp reanchored_at"
                );
            }
            other => panic!("re-anchored comment must be Anchored, got {other:?}"),
        }
        assert!(
            engine.session().updated_at >= before,
            "successful reanchor must bump updated_at"
        );
    }

    #[test]
    fn reanchor_stamps_timestamp_when_transitioning_from_orphaned() {
        // The Orphaned→Anchored transition (via `R` re-bind or via a rescan
        // that brings back a line) is the one that ORIGINALLY stamps
        // `reanchored_at`. The shift-preserves test on the TUI side pins the
        // Anchored→Anchored case; this test pins the other direction so a
        // future refactor can't silently drop the initial stamp.
        let mut engine = ReviewEngine::new(make_session());
        let path = PathBuf::from("a.rs");

        // Seed an orphan that has never been re-anchored (no prior
        // `reanchored_at`). The orphaned_at stamp exists because
        // `orphan_comment` sets it — but that's the orphaning timestamp, not
        // a re-anchor one.
        let mut comment = Comment::new("was gone".into(), CommentType::Note, Some(LineSide::New));
        comment.anchor = Some(AnchorState::Orphaned {
            was_line: 7,
            was_side: LineSide::New,
            last_seen_content: "gone-line".into(),
            orphaned_at: Some(Utc::now() - Duration::minutes(10)),
        });
        engine.seed_orphaned_comment(path.clone(), FileStatus::Modified, comment);

        let before = Utc::now();

        assert!(engine.reanchor_orphan(&path, 0, 3, LineSide::New));

        let review = engine.session().files.get(&path).unwrap();
        assert!(review.orphaned_comments.is_empty());
        let at_3 = review
            .line_comments
            .get(&3)
            .expect("re-anchored comment lives at dest line");
        assert_eq!(at_3.len(), 1);
        match at_3[0].anchor.as_ref().unwrap() {
            AnchorState::Anchored {
                line,
                side,
                reanchored_at,
            } => {
                assert_eq!(*line, 3);
                assert_eq!(*side, LineSide::New);
                let stamped = reanchored_at.expect(
                    "Orphaned → Anchored transition MUST stamp reanchored_at \
                     so polling agents can observe the recovery",
                );
                assert!(
                    stamped >= before,
                    "reanchored_at should be a fresh timestamp, not reused"
                );
            }
            other => panic!("expected Anchored, got {other:?}"),
        }
    }

    #[test]
    fn reanchor_orphan_returns_false_and_preserves_updated_at_on_miss() {
        let mut engine = ReviewEngine::new(make_session());
        let path = PathBuf::from("a.rs");

        // Unknown file → false, no bump.
        let before_unknown = engine.session().updated_at;
        assert!(!engine.reanchor_orphan(&path, 0, 1, LineSide::New));
        assert_eq!(
            engine.session().updated_at,
            before_unknown,
            "miss must not bump updated_at"
        );

        // Known file, out-of-range orphan_idx → false, no bump.
        engine
            .session_mut()
            .add_file(path.clone(), FileStatus::Modified);
        let before_oob = engine.session().updated_at;
        assert!(!engine.reanchor_orphan(&path, 99, 1, LineSide::New));
        assert_eq!(
            engine.session().updated_at,
            before_oob,
            "out-of-range orphan_idx must not bump updated_at"
        );
    }
}