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
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use super::comment::{AnchorState, Comment, LineSide};
use super::diff_types::{DiffFile, FileStatus};
use super::tour::{CommentTriage, TourCommentMeta, TourState};
/// Current on-disk session schema version. Bump the minor component when adding
/// fields that older binaries should still be able to load (via `serde(default)`);
/// bump the major component for incompatible changes. `load_session` refuses to
/// load sessions whose recorded version is newer than this constant.
///
/// Version history:
/// - 1.6: Added `resolved: bool` on `Comment` for spec reconciliation (Phase I5-2b).
/// - 1.5: Added `mental_model: Option<MentalModel>` (Phase I2).
/// - 1.4: Structured `author_kind` on `Comment` (replaces body-suffix marker).
/// - 1.3 and earlier: see git history.
pub const SESSION_VERSION: &str = "1.6";
/// Reviewer's pre-diff mental model, captured via the `m` chord before
/// reading the author's code (Phase I2, "Sparring Review"). Surfaces
/// alongside any failing sparring test during reconciliation.
///
/// The four fields map to the four prompts from the
/// [Dialectical Review](https://rrwright.com/notes/dialectical-review/)
/// article: what the change *should* do, what it *shouldn't* do, what
/// could go wrong, and what assumptions underlie it. Leaving a field
/// empty is permitted — the goal is reflection, not a full questionnaire.
///
/// Per-field size is bounded at the TUI / MCP boundary via
/// `MentalModelConfig::byte_limit` (default 2 KiB). The cap is enforced
/// on ingress; the core model accepts any `String` so old sessions with
/// pre-cap content still round-trip.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct MentalModel {
#[serde(default)]
pub should_do: String,
#[serde(default)]
pub shouldnt_do: String,
#[serde(default)]
pub could_go_wrong: String,
#[serde(default)]
pub assumptions: String,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
impl Default for MentalModel {
/// Stamp both timestamps at construction time. The derive default
/// would produce epoch-0 values, which is unobservable today
/// because [`MentalModel::is_empty`] skips the timestamp fields —
/// but a future helper like `has_recent_activity` would silently
/// classify the epoch as "never updated" and mis-fire. Stamping
/// `Utc::now()` up front avoids the foot-gun.
fn default() -> Self {
let now = Utc::now();
Self {
should_do: String::new(),
shouldnt_do: String::new(),
could_go_wrong: String::new(),
assumptions: String::new(),
created_at: now,
updated_at: now,
}
}
}
impl MentalModel {
/// True when every field is empty. Used to skip serializing an
/// effectively-absent model and to decide when to show the
/// first-open hint.
#[must_use]
pub fn is_empty(&self) -> bool {
self.should_do.is_empty()
&& self.shouldnt_do.is_empty()
&& self.could_go_wrong.is_empty()
&& self.assumptions.is_empty()
}
/// Return the label of the first field whose byte length exceeds
/// `limit`, or `None` if every field fits. Callers use this at the
/// ingress boundary (TUI modal, MCP propose) to reject oversized
/// input with a field-specific error before it reaches the session
/// model. Byte length matches the TUI modal's per-char cap path.
#[must_use]
pub fn oversized_field(&self, limit: usize) -> Option<(&'static str, usize)> {
for (label, body) in [
("should_do", &self.should_do),
("shouldnt_do", &self.shouldnt_do),
("could_go_wrong", &self.could_go_wrong),
("assumptions", &self.assumptions),
] {
if body.len() > limit {
return Some((label, body.len()));
}
}
None
}
/// Canonical wire-shape for the MCP `trv_get_mental_model` tool and
/// the approval `result_json` of `trv_propose_set_mental_model`.
/// Timestamps serialize as RFC 3339. Kept on the model (not in the
/// MCP bridge) so any future surface — status-bar digest, export
/// section — renders the same fields in the same order.
#[must_use]
pub fn to_mcp_payload(&self) -> serde_json::Value {
serde_json::json!({
"should_do": self.should_do,
"shouldnt_do": self.shouldnt_do,
"could_go_wrong": self.could_go_wrong,
"assumptions": self.assumptions,
"created_at": self.created_at.to_rfc3339(),
"updated_at": self.updated_at.to_rfc3339(),
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileReview {
pub path: PathBuf,
pub reviewed: bool,
pub status: FileStatus,
pub file_comments: Vec<Comment>,
pub line_comments: HashMap<u32, Vec<Comment>>,
/// Explicit user override for auto-collapse behaviour. `None` means follow
/// the auto rule (path match or line threshold). `Some(true)` means
/// force-collapse; `Some(false)` means force-expand even on a file the
/// auto rule would hide.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub collapsed: Option<bool>,
/// Comments whose anchored line disappeared after a live rescan. They
/// remember the line number + side + content they were attached to so
/// the user can re-anchor them with `R` once the line reappears.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub orphaned_comments: Vec<Comment>,
}
impl FileReview {
pub fn new(path: PathBuf, status: FileStatus) -> Self {
Self {
path,
reviewed: false,
status,
file_comments: Vec::new(),
line_comments: HashMap::new(),
collapsed: None,
orphaned_comments: Vec::new(),
}
}
#[must_use]
pub fn comment_count(&self) -> usize {
self.file_comments.len()
+ self
.line_comments
.values()
.map(std::vec::Vec::len)
.sum::<usize>()
+ self.orphaned_comments.len()
}
/// Number of orphaned comments on this file (comments whose anchor line
/// disappeared in a live rescan).
#[must_use]
pub fn orphan_count(&self) -> usize {
self.orphaned_comments.len()
}
pub fn add_file_comment(&mut self, comment: Comment) {
self.file_comments.push(comment);
}
pub fn add_line_comment(&mut self, line: u32, comment: Comment) {
self.line_comments.entry(line).or_default().push(comment);
}
/// Mark `comment` as orphaned (the line it used to anchor to disappeared
/// in a rescan) and push it into `orphaned_comments`. `line` and `side`
/// describe where it used to live; `last_seen` captures the source text
/// of that line so the UI can show `[ORPHANED] was line N: "…"`.
pub fn orphan_comment(
&mut self,
line: u32,
side: LineSide,
last_seen: String,
mut comment: Comment,
) {
comment.anchor = Some(AnchorState::Orphaned {
was_line: line,
was_side: side,
last_seen_content: last_seen,
orphaned_at: Some(Utc::now()),
});
self.orphaned_comments.push(comment);
}
/// Absorb a renamed source `FileReview` into `self` when both represent
/// the same post-rescan path (destination-collision merge).
///
/// File-level comments and already-orphaned comments extend cleanly
/// because they don't depend on the file's content snapshot.
/// `reviewed` unions (either side marked reviewed → dst reviewed).
/// `collapsed` lets the destination's explicit override win, falling
/// back to the source's override when destination is `None`, so a
/// user's force-collapse/force-expand survives the rename.
///
/// `src.line_comments` are **orphaned**, not merged into
/// `dst.line_comments`. Why: line comments anchor against pre-rescan
/// content, and the post-fix [`remap_rename_keys`] preserves the
/// destination's snapshot on collision (see reanchor.rs). Merging
/// source lines into destination's line map would cause the next
/// `reanchor_comments` pass to re-map them against destination's old
/// content — producing wrong line numbers or silent drops. Orphaning
/// preserves them with their original `was_line` / `was_side` /
/// `last_seen_content` so the user can re-anchor via `R` once the
/// line reappears.
pub fn absorb_rename_source(&mut self, src: FileReview) {
self.file_comments.extend(src.file_comments);
self.orphaned_comments.extend(src.orphaned_comments);
for (line, comments) in src.line_comments {
// Read `side` per-comment, not from the vec's first entry: a
// single HashMap<u32, Vec<Comment>> bucket can legitimately mix
// LineSide::Old (deletion) and LineSide::New (addition) entries
// at the same line number, and orphaning them all with the
// first entry's side would lose the reviewer's ability to
// re-anchor to the correct base-commit line via `R`.
for comment in comments {
let side = comment.side.unwrap_or(LineSide::New);
self.orphan_comment(line, side, String::new(), comment);
}
}
if src.reviewed {
self.reviewed = true;
}
if self.collapsed.is_none() {
self.collapsed = src.collapsed;
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[derive(Default)]
pub enum SessionDiffSource {
#[default]
WorkingTree,
Staged,
Unstaged,
StagedAndUnstaged,
CommitRange,
WorkingTreeAndCommits,
StagedUnstagedAndCommits,
Remote,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReviewSession {
pub id: String,
pub version: String,
pub repo_path: PathBuf,
#[serde(default)]
pub branch_name: Option<String>,
pub base_commit: String,
#[serde(default)]
pub diff_source: SessionDiffSource,
#[serde(default)]
pub commit_range: Option<Vec<String>>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
#[serde(default)]
pub review_comments: Vec<Comment>,
pub files: HashMap<PathBuf, FileReview>,
pub session_notes: Option<String>,
/// Active tour (if any) so reopening the session resumes mid-tour.
#[serde(default)]
pub tour: Option<TourState>,
/// Provenance metadata for comments added during an active tour.
#[serde(default)]
pub tour_comment_meta: HashMap<String, TourCommentMeta>,
/// Agent's triage verdicts for tour comments.
#[serde(default)]
pub tour_triage: HashMap<String, CommentTriage>,
/// Timestamp of the last successful review submission (local export or
/// remote `submit_review`).
#[serde(default)]
pub last_review_submitted_at: Option<DateTime<Utc>>,
/// PR head SHA at the moment of the last remote review submission.
#[serde(default)]
pub last_review_sha: Option<String>,
/// Reviewer's pre-diff mental model (Phase I2). `None` on sessions
/// created by travelagent < 1.3.0 *and* on fresh sessions that
/// haven't yet hit the `m` chord. The TUI save path collapses an
/// all-empty draft to `None` so the serialized JSON stays identical
/// to pre-1.5 sessions. Reconciliation against sparring-test results
/// is deferred to Phase I3; today this field is capture-only.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mental_model: Option<MentalModel>,
}
impl ReviewSession {
pub fn new(
repo_path: PathBuf,
base_commit: String,
branch_name: Option<String>,
diff_source: SessionDiffSource,
) -> Self {
let now = Utc::now();
Self {
id: uuid::Uuid::new_v4().to_string(),
version: SESSION_VERSION.to_string(),
repo_path,
branch_name,
base_commit,
diff_source,
commit_range: None,
created_at: now,
updated_at: now,
review_comments: Vec::new(),
files: HashMap::new(),
session_notes: None,
tour: None,
tour_comment_meta: HashMap::new(),
tour_triage: HashMap::new(),
last_review_submitted_at: None,
last_review_sha: None,
mental_model: None,
}
}
#[must_use]
pub fn reviewed_count(&self) -> usize {
self.files.values().filter(|f| f.reviewed).count()
}
/// Commit a reviewer's mental model to this session, preserving
/// `created_at` from any prior model and stamping `updated_at`.
/// All-empty fields collapse to `None` so the `skip_serializing_if`
/// contract on `mental_model` keeps pre-1.5 sessions byte-identical
/// on disk. Also bumps `ReviewSession::updated_at`.
///
/// Shared by the TUI `Ctrl+S` save path and the MCP
/// `trv_propose_set_mental_model` approval path so both produce the
/// same on-disk shape.
pub fn commit_mental_model(&mut self, mental_model: MentalModel, now: DateTime<Utc>) {
if mental_model.is_empty() {
self.mental_model = None;
} else {
let created_at = self
.mental_model
.as_ref()
.map(|m| m.created_at)
.unwrap_or(mental_model.created_at);
self.mental_model = Some(MentalModel {
created_at,
updated_at: now,
..mental_model
});
}
self.updated_at = now;
}
pub fn add_file(&mut self, path: PathBuf, status: FileStatus) {
self.files
.entry(path)
.or_insert_with_key(|k| FileReview::new(k.clone(), status));
}
pub fn get_file_mut(&mut self, path: &Path) -> Option<&mut FileReview> {
self.files.get_mut(path)
}
/// Migrate a `FileReview` keyed at `old_path` to `new_path`. Used when the
/// VCS reports a rename between rescans so existing comments follow the
/// file. If `old_path` is absent nothing happens; if `new_path` already
/// has an entry, `src` is merged via [`FileReview::absorb_rename_source`]
/// — which orphans `src.line_comments` because the destination's own
/// content snapshot drives re-anchoring on collision. Returns `true` if
/// a migration happened.
pub fn rename_file(&mut self, old_path: &Path, new_path: PathBuf) -> bool {
if old_path == new_path {
return false;
}
let Some(mut src) = self.files.remove(old_path) else {
return false;
};
src.path = new_path.clone();
match self.files.entry(new_path) {
std::collections::hash_map::Entry::Vacant(slot) => {
slot.insert(src);
}
std::collections::hash_map::Entry::Occupied(mut slot) => {
slot.get_mut().absorb_rename_source(src);
}
}
true
}
/// Apply a rescan: migrate renamed files to their new keys, then register
/// every file in the diff (idempotent). Preserves existing comments,
/// anchor states, and collapse overrides — both `rename_file` and
/// `add_file` already have these invariants.
///
/// Rename migration must happen BEFORE registration so any pre-existing
/// entry at the new path gets merged by `rename_file` instead of being
/// clobbered by a fresh `add_file`.
///
/// Uses a **two-pass** migration so pair-wise rename cycles in a single
/// diff (e.g. swap `A↔B`) don't clobber each other:
///
/// 1. Extract every renamed source out of `self.files` into a staging map
/// keyed by the destination path. If multiple renames target the same
/// destination, merge their `FileReview`s in the staging map.
/// 2. For each staged destination, merge into the current occupant (if
/// any) via `rename_file`-equivalent semantics, then insert.
///
/// Without this, a naive sequential loop applying `A→B` first and `B→A`
/// second would move A's state to B, then move the {A+B} combined state
/// back to A, wiping out B's original identity.
///
/// Transitive chains (`A→B, B→C` emitted as two diff entries in the
/// same call) are resolved by walking each source through the diff's
/// rename map to its *terminal* destination before staging, so A's
/// state lands at C (not B) and B's state also lands at C — the
/// destinations merge via `absorb_rename_source`. Cycles (swaps
/// `A→B, B→A`) break on the first repeated hop, preserving the
/// existing swap semantics. All collision merges (both staging-map
/// and final) use [`FileReview::absorb_rename_source`], which orphans
/// source line comments so they don't re-anchor against the
/// destination's content.
///
/// **Collision policy — intentional divergence from `remap_rename_keys`.**
/// The sibling function [`crate::reanchor::remap_rename_keys`] operates
/// on the pre-rescan *content* snapshot map and, on destination
/// collision, preserves the existing destination snapshot via
/// `.or_insert` (drops the source's content). This function, which
/// operates on `FileReview` *state*, instead merges via
/// `absorb_rename_source` on collision. The policies are coupled:
/// because content is preserved on the destination, source line
/// comments re-anchored against it would land on the wrong lines —
/// so `absorb_rename_source` orphans them rather than merging. Keep
/// both policies aligned if either changes.
pub fn apply_diff_files(&mut self, diff_files: &[DiffFile]) {
let direct = crate::reanchor::direct_rename_map(diff_files);
// Pass 1: extract all rename sources out of `self.files` and stage
// them at their *terminal* destinations (walking the chain so
// `A→B, B→C` stages both A and B under C). Multiple sources
// landing at the same terminal merge via `absorb_rename_source`.
let mut staged: HashMap<PathBuf, FileReview> = HashMap::new();
for src_path in direct.keys() {
let Some(mut src) = self.files.remove(src_path) else {
continue;
};
let dst = crate::reanchor::resolve_terminal_dest(src_path, &direct);
src.path = dst.clone();
match staged.entry(dst) {
std::collections::hash_map::Entry::Vacant(slot) => {
slot.insert(src);
}
std::collections::hash_map::Entry::Occupied(mut slot) => {
slot.get_mut().absorb_rename_source(src);
}
}
}
// Pass 2: settle each staged source into its destination. If
// `self.files` already has an occupant at `new_path` (which it may,
// since pass 1 only removed sources, not destinations), merge.
for (new_path, src) in staged {
match self.files.entry(new_path) {
std::collections::hash_map::Entry::Vacant(slot) => {
slot.insert(src);
}
std::collections::hash_map::Entry::Occupied(mut slot) => {
slot.get_mut().absorb_rename_source(src);
}
}
}
// Register every file in the diff at its terminal post-rescan
// path. For a chain `A→B, B→C`, the A→B entry's display_path is
// `B` — an intermediate that's also a rename source. Walk the
// rename map so we only register the terminal (C), matching the
// actual post-rescan file set.
for file in diff_files {
let display = file.display_path_lossy();
let terminal = if direct.contains_key(display) {
crate::reanchor::resolve_terminal_dest(display, &direct)
} else {
display.clone()
};
self.add_file(terminal, file.status);
}
}
#[must_use]
pub fn has_comments(&self) -> bool {
!self.review_comments.is_empty() || self.files.values().any(|f| f.comment_count() > 0)
}
/// Phase I6: total count of *active* (non-resolved)
/// `CommentType::Spec` comments across review-, file-, line-, and
/// orphaned- scopes. Used by the status bar's `[spar: N]` indicator
/// and the sparring summary in markdown exports.
///
/// Resolved specs (I5-2b) are kept on the session so the reviewer's
/// decision survives restarts, but they don't pay rent in the live
/// counts — counting them would make the badge drift upward over
/// the course of a review and make "all specs addressed" invisible.
#[must_use]
pub fn spec_count(&self) -> usize {
use crate::model::CommentType;
let is_active_spec =
|c: &crate::model::Comment| matches!(c.comment_type, CommentType::Spec) && !c.resolved;
let mut n = self
.review_comments
.iter()
.filter(|c| is_active_spec(c))
.count();
for fr in self.files.values() {
n += fr
.file_comments
.iter()
.filter(|c| is_active_spec(c))
.count();
n += fr
.line_comments
.values()
.flat_map(|v| v.iter())
.filter(|c| is_active_spec(c))
.count();
n += fr
.orphaned_comments
.iter()
.filter(|c| is_active_spec(c))
.count();
}
n
}
pub fn clear_comments(&mut self) -> (usize, usize) {
let mut cleared = self.review_comments.len();
let mut unreviewed = 0;
self.review_comments.clear();
for file in self.files.values_mut() {
cleared += file.comment_count();
file.file_comments.clear();
file.line_comments.clear();
file.orphaned_comments.clear();
if file.reviewed {
file.reviewed = false;
unreviewed += 1;
}
}
(cleared, unreviewed)
}
pub fn is_file_reviewed(&self, path: &Path) -> bool {
self.files.get(path).is_some_and(|r| r.reviewed)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::comment::{Comment, CommentType};
fn test_session() -> ReviewSession {
ReviewSession::new(
PathBuf::from("/repo"),
"abc123".to_string(),
None,
SessionDiffSource::WorkingTree,
)
}
#[test]
fn should_return_zero_when_clearing_empty_session() {
let mut session = test_session();
let (cleared, unreviewed) = session.clear_comments();
assert_eq!(cleared, 0);
assert_eq!(unreviewed, 0);
}
#[test]
fn should_clear_review_level_comments() {
let mut session = test_session();
session
.review_comments
.push(Comment::new("note".to_string(), CommentType::Note, None));
session
.review_comments
.push(Comment::new("issue".to_string(), CommentType::Issue, None));
let (cleared, unreviewed) = session.clear_comments();
assert_eq!(cleared, 2);
assert_eq!(unreviewed, 0);
assert!(session.review_comments.is_empty());
}
#[test]
fn should_clear_file_and_line_comments() {
let mut session = test_session();
let path = PathBuf::from("src/main.rs");
session.add_file(path.clone(), FileStatus::Modified);
let file = session.get_file_mut(&path).unwrap();
file.add_file_comment(Comment::new("comment".to_string(), CommentType::Note, None));
file.add_line_comment(
10,
Comment::new("line".to_string(), CommentType::Note, None),
);
let (cleared, _) = session.clear_comments();
assert_eq!(cleared, 2);
let file = session.files.get(&path).unwrap();
assert!(file.file_comments.is_empty());
assert!(file.line_comments.is_empty());
}
#[test]
fn should_reset_reviewed_status_on_all_files() {
let mut session = test_session();
let path_a = PathBuf::from("a.rs");
let path_b = PathBuf::from("b.rs");
session.add_file(path_a.clone(), FileStatus::Modified);
session.add_file(path_b.clone(), FileStatus::Added);
session.get_file_mut(&path_a).unwrap().reviewed = true;
session.get_file_mut(&path_b).unwrap().reviewed = true;
let (cleared, unreviewed) = session.clear_comments();
assert_eq!(cleared, 0);
assert_eq!(unreviewed, 2);
assert!(!session.is_file_reviewed(&path_a));
assert!(!session.is_file_reviewed(&path_b));
}
#[test]
fn should_only_count_reviewed_files_as_unreviewed() {
let mut session = test_session();
let reviewed = PathBuf::from("reviewed.rs");
let pending = PathBuf::from("pending.rs");
session.add_file(reviewed.clone(), FileStatus::Modified);
session.add_file(pending.clone(), FileStatus::Modified);
session.get_file_mut(&reviewed).unwrap().reviewed = true;
let (_, unreviewed) = session.clear_comments();
assert_eq!(unreviewed, 1);
}
#[test]
fn should_clear_both_comments_and_reviewed_status() {
let mut session = test_session();
let path = PathBuf::from("src/lib.rs");
session.add_file(path.clone(), FileStatus::Modified);
let file = session.get_file_mut(&path).unwrap();
file.reviewed = true;
file.add_file_comment(Comment::new("comment".to_string(), CommentType::Note, None));
session
.review_comments
.push(Comment::new("review".to_string(), CommentType::Note, None));
let (cleared, unreviewed) = session.clear_comments();
assert_eq!(cleared, 2);
assert_eq!(unreviewed, 1);
assert!(!session.is_file_reviewed(&path));
}
#[test]
fn last_review_fields_round_trip_through_serde() {
let mut session = test_session();
let ts = Utc::now();
session.last_review_submitted_at = Some(ts);
session.last_review_sha = Some("deadbeef".to_string());
let json = serde_json::to_string(&session).expect("serialize");
let restored: ReviewSession = serde_json::from_str(&json).expect("deserialize");
assert_eq!(restored.last_review_submitted_at, Some(ts));
assert_eq!(restored.last_review_sha.as_deref(), Some("deadbeef"));
}
#[test]
fn file_review_collapsed_defaults_to_none_for_new_file() {
let fr = FileReview::new(PathBuf::from("a.rs"), FileStatus::Modified);
assert_eq!(fr.collapsed, None);
}
#[test]
fn file_review_collapsed_roundtrips_through_serde() {
let mut fr = FileReview::new(PathBuf::from("a.rs"), FileStatus::Modified);
fr.collapsed = Some(true);
let json = serde_json::to_string(&fr).expect("serialize");
let restored: FileReview = serde_json::from_str(&json).expect("deserialize");
assert_eq!(restored.collapsed, Some(true));
fr.collapsed = Some(false);
let json = serde_json::to_string(&fr).expect("serialize");
let restored: FileReview = serde_json::from_str(&json).expect("deserialize");
assert_eq!(restored.collapsed, Some(false));
}
#[test]
fn file_review_legacy_json_without_collapsed_deserialises_with_none() {
// Old sessions written before auto-collapse landed omit the field;
// `#[serde(default)]` should keep them loading.
let legacy = r#"{
"path": "src/foo.rs",
"reviewed": false,
"status": "modified",
"file_comments": [],
"line_comments": {}
}"#;
let fr: FileReview = serde_json::from_str(legacy).expect("legacy deserialize");
assert_eq!(fr.collapsed, None);
}
#[test]
fn file_review_orphaned_comments_defaults_to_empty() {
let fr = FileReview::new(PathBuf::from("a.rs"), FileStatus::Modified);
assert!(fr.orphaned_comments.is_empty());
assert_eq!(fr.orphan_count(), 0);
assert_eq!(fr.comment_count(), 0);
}
#[test]
fn file_review_legacy_json_without_orphaned_comments_deserialises() {
// 1.2-era JSON — no orphaned_comments, no anchor field on comments.
let legacy = r#"{
"path": "src/foo.rs",
"reviewed": false,
"status": "modified",
"file_comments": [],
"line_comments": {}
}"#;
let fr: FileReview = serde_json::from_str(legacy).expect("legacy deserialize");
assert!(fr.orphaned_comments.is_empty());
}
#[test]
fn orphan_comment_sets_anchor_and_pushes_to_orphaned_list() {
use crate::model::comment::{AnchorState, Comment, CommentType, LineSide};
let mut fr = FileReview::new(PathBuf::from("a.rs"), FileStatus::Modified);
let c = Comment::new(
"obsolete".to_string(),
CommentType::Note,
Some(LineSide::New),
);
let cid = c.id.clone();
let before = Utc::now();
fr.orphan_comment(42, LineSide::New, "let x = 1;".to_string(), c);
let after = Utc::now();
assert_eq!(fr.orphan_count(), 1);
assert_eq!(fr.comment_count(), 1);
let stored = &fr.orphaned_comments[0];
assert_eq!(stored.id, cid);
match stored.anchor.as_ref().unwrap() {
AnchorState::Orphaned {
was_line,
was_side,
last_seen_content,
orphaned_at,
} => {
assert_eq!(*was_line, 42);
assert_eq!(*was_side, LineSide::New);
assert_eq!(last_seen_content, "let x = 1;");
let ts = orphaned_at.expect("orphaned_at should be stamped");
assert!(
ts >= before && ts <= after,
"orphaned_at {ts} not within [{before}, {after}]"
);
}
_ => panic!("comment should be orphaned"),
}
}
#[test]
fn comment_count_includes_orphaned_comments() {
use crate::model::comment::{Comment, CommentType, LineSide};
let mut fr = FileReview::new(PathBuf::from("a.rs"), FileStatus::Modified);
fr.add_file_comment(Comment::new(
"f".into(),
CommentType::Note,
Some(LineSide::New),
));
fr.add_line_comment(
10,
Comment::new("l".into(), CommentType::Note, Some(LineSide::New)),
);
fr.orphan_comment(
5,
LineSide::New,
"old".into(),
Comment::new("o".into(), CommentType::Note, Some(LineSide::New)),
);
assert_eq!(fr.comment_count(), 3);
}
#[test]
fn spec_count_sums_all_scopes_and_ignores_other_kinds() {
use crate::model::comment::{Comment, CommentType, LineSide};
let mut session = ReviewSession::new(
PathBuf::from("/tmp/repo"),
"head".into(),
None,
SessionDiffSource::WorkingTree,
);
session
.review_comments
.push(Comment::new("rs".into(), CommentType::Spec, None));
session
.review_comments
.push(Comment::new("rn".into(), CommentType::Note, None));
let path = PathBuf::from("a.rs");
let mut fr = FileReview::new(path.clone(), FileStatus::Modified);
fr.add_file_comment(Comment::new("fs".into(), CommentType::Spec, None));
fr.add_line_comment(
3,
Comment::new("ls".into(), CommentType::Spec, Some(LineSide::New)),
);
fr.add_line_comment(
3,
Comment::new("ln".into(), CommentType::Note, Some(LineSide::New)),
);
fr.orphan_comment(
5,
LineSide::New,
"old".into(),
Comment::new("os".into(), CommentType::Spec, Some(LineSide::New)),
);
session.files.insert(path, fr);
// 1 review spec + 1 file spec + 1 line spec + 1 orphaned spec = 4.
assert_eq!(session.spec_count(), 4);
}
#[test]
fn spec_count_excludes_resolved_specs() {
use crate::model::comment::{Comment, CommentType};
let mut session = ReviewSession::new(
PathBuf::from("/tmp/repo"),
"head".into(),
None,
SessionDiffSource::WorkingTree,
);
let mut active = Comment::new("active".into(), CommentType::Spec, None);
active.resolved = false;
let mut done = Comment::new("done".into(), CommentType::Spec, None);
done.resolved = true;
session.review_comments.push(active);
session.review_comments.push(done);
assert_eq!(
session.spec_count(),
1,
"resolved specs must not appear in active count"
);
}
#[test]
fn session_version_is_1_6() {
// Trip-wire so future schema-impacting changes can't silently rebase
// onto the live-mode L2 fields without bumping SESSION_VERSION.
// Version history:
// 1.3 → 1.4: `AuthorKind` + legacy MCP-marker migration.
// 1.4 → 1.5: `mental_model: Option<MentalModel>` (Phase I2).
// 1.5 → 1.6: `resolved: bool` on `Comment` (Phase I5-2b).
assert_eq!(SESSION_VERSION, "1.6");
}
#[test]
fn legacy_1_2_session_json_round_trips_to_current() {
// A 1.2 session on disk has no `orphaned_comments` on files and no
// `anchor` field on comments. The loader should accept it verbatim
// (via `serde(default)`), and the in-memory representation should
// serialize out with no loss of user data.
let legacy = r#"{
"id": "abc",
"version": "1.2",
"repo_path": "/repo",
"base_commit": "deadbeef",
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-01T00:00:00Z",
"files": {
"src/foo.rs": {
"path": "src/foo.rs",
"reviewed": false,
"status": "modified",
"file_comments": [],
"line_comments": {
"10": [
{
"id": "c-1",
"content": "still anchored",
"comment_type": "note",
"created_at": "2024-01-01T00:00:00Z",
"line_context": null,
"side": "new"
}
]
}
}
}
}"#;
let mut session: ReviewSession =
serde_json::from_str(legacy).expect("legacy 1.2 session must deserialize");
// Legacy field preserved exactly.
assert_eq!(session.version, "1.2");
let file = session
.files
.get(&PathBuf::from("src/foo.rs"))
.expect("file present");
assert_eq!(file.line_comments.len(), 1);
assert!(file.orphaned_comments.is_empty());
assert!(
file.line_comments
.get(&10)
.and_then(|v| v.first())
.is_some_and(|c| c.anchor.is_none()),
"legacy comment has no explicit anchor (inferred from key)"
);
// After "saving" (bumping version), the schema version becomes the
// current `SESSION_VERSION`.
session.version = SESSION_VERSION.to_string();
let round = serde_json::to_string(&session).expect("serialize");
let restored: ReviewSession = serde_json::from_str(&round).expect("round-trip deserialize");
assert_eq!(restored.version, SESSION_VERSION);
assert_eq!(restored.files.len(), 1);
}
fn diff_file(
status: FileStatus,
old_path: Option<&str>,
new_path: Option<&str>,
) -> crate::model::diff_types::DiffFile {
crate::model::diff_types::DiffFile {
old_path: old_path.map(PathBuf::from),
new_path: new_path.map(PathBuf::from),
status,
hunks: Vec::new(),
is_binary: false,
is_too_large: false,
is_commit_message: false,
}
}
#[test]
fn apply_diff_files_registers_files() {
let mut session = test_session();
let added = diff_file(FileStatus::Added, None, Some("src/new.rs"));
let modified = diff_file(FileStatus::Modified, Some("src/old.rs"), Some("src/old.rs"));
session.apply_diff_files(&[added, modified]);
assert!(session.files.contains_key(&PathBuf::from("src/new.rs")));
assert!(session.files.contains_key(&PathBuf::from("src/old.rs")));
assert_eq!(session.files.len(), 2);
assert_eq!(
session
.files
.get(&PathBuf::from("src/new.rs"))
.unwrap()
.status,
FileStatus::Added
);
assert_eq!(
session
.files
.get(&PathBuf::from("src/old.rs"))
.unwrap()
.status,
FileStatus::Modified
);
}
#[test]
fn apply_diff_files_migrates_renamed_files_preserving_comments() {
let mut session = test_session();
let old_path = PathBuf::from("src/old.rs");
let new_path = PathBuf::from("src/new.rs");
// Pre-existing entry at the old path with a line comment.
session.add_file(old_path.clone(), FileStatus::Modified);
session
.get_file_mut(&old_path)
.unwrap()
.add_line_comment(2, Comment::new("hi".into(), CommentType::Note, None));
// Rescan reports a rename old -> new.
let renamed = diff_file(FileStatus::Renamed, Some("src/old.rs"), Some("src/new.rs"));
session.apply_diff_files(&[renamed]);
// Old key is gone; new key exists with the migrated comment on line 2.
assert!(!session.files.contains_key(&old_path));
let migrated = session
.files
.get(&new_path)
.expect("file should now live at new path");
assert_eq!(migrated.line_comments.get(&2).map(Vec::len), Some(1));
}
#[test]
fn apply_diff_files_handles_swap_without_losing_state() {
// Regression: a diff that simultaneously reports `A→B` and `B→A`
// (a file swap) must end with A holding B's original FileReview
// and B holding A's original FileReview. A naive single-pass loop
// would apply `A→B` first (merging A into B), then apply `B→A`
// (moving the combined {A+B} to A), wiping out B's identity.
let mut session = test_session();
let a = PathBuf::from("src/a.rs");
let b = PathBuf::from("src/b.rs");
session.add_file(a.clone(), FileStatus::Modified);
session
.get_file_mut(&a)
.unwrap()
.add_file_comment(Comment::new("from-a".into(), CommentType::Note, None));
session.add_file(b.clone(), FileStatus::Modified);
session
.get_file_mut(&b)
.unwrap()
.add_file_comment(Comment::new("from-b".into(), CommentType::Note, None));
let swap = [
diff_file(FileStatus::Renamed, Some("src/a.rs"), Some("src/b.rs")),
diff_file(FileStatus::Renamed, Some("src/b.rs"), Some("src/a.rs")),
];
session.apply_diff_files(&swap);
assert_eq!(session.files.len(), 2, "both files still tracked");
let at_a = session.files.get(&a).expect("a still present");
let at_b = session.files.get(&b).expect("b still present");
assert_eq!(at_a.file_comments.len(), 1, "a now holds one comment");
assert_eq!(
at_a.file_comments[0].content, "from-b",
"a now holds b's original comment (they swapped)"
);
assert_eq!(at_b.file_comments.len(), 1, "b now holds one comment");
assert_eq!(
at_b.file_comments[0].content, "from-a",
"b now holds a's original comment (they swapped)"
);
}
#[test]
fn apply_diff_files_orphans_source_line_comments_on_destination_collision() {
// Regression: when `A→B` collides with a pre-existing B, A's
// line comments must be orphaned on B (not merged into B's
// line_comments map), because they anchor against A's pre-rescan
// content which is no longer in the snapshot map — B's snapshot
// is preserved by `remap_rename_keys` on collision.
let mut session = test_session();
let a = PathBuf::from("src/a.rs");
let b = PathBuf::from("src/b.rs");
session.add_file(a.clone(), FileStatus::Modified);
session
.get_file_mut(&a)
.unwrap()
.add_line_comment(5, Comment::new("a-line-5".into(), CommentType::Note, None));
session.add_file(b.clone(), FileStatus::Modified);
session
.get_file_mut(&b)
.unwrap()
.add_line_comment(5, Comment::new("b-line-5".into(), CommentType::Note, None));
let renamed = diff_file(FileStatus::Renamed, Some("src/a.rs"), Some("src/b.rs"));
session.apply_diff_files(&[renamed]);
assert!(!session.files.contains_key(&a), "a is gone");
let at_b = session.files.get(&b).expect("b still present");
// B's own line 5 comment stays on line 5.
let line5 = at_b.line_comments.get(&5).expect("b line 5 still present");
assert_eq!(line5.len(), 1, "b's own line comment unchanged");
assert_eq!(line5[0].content, "b-line-5");
// A's line 5 comment was orphaned (can't re-anchor against B's content).
assert_eq!(at_b.orphaned_comments.len(), 1, "a's line comment orphaned");
assert_eq!(at_b.orphaned_comments[0].content, "a-line-5");
assert!(
matches!(
at_b.orphaned_comments[0].anchor,
Some(AnchorState::Orphaned { was_line: 5, .. })
),
"orphaned comment remembers was_line=5"
);
}
#[test]
fn absorb_rename_source_preserves_collapsed_override() {
// Regression: a user's explicit force-collapse/force-expand on the
// source file must survive a rename collision.
let a = PathBuf::from("src/a.rs");
let b = PathBuf::from("src/b.rs");
// Destination has no collapse override; source forced collapse.
let mut dst = FileReview::new(b.clone(), FileStatus::Modified);
let mut src = FileReview::new(a.clone(), FileStatus::Modified);
src.collapsed = Some(true);
dst.absorb_rename_source(src);
assert_eq!(
dst.collapsed,
Some(true),
"src's override wins when dst has none"
);
// Destination's explicit override wins when both set.
let mut dst2 = FileReview::new(b.clone(), FileStatus::Modified);
dst2.collapsed = Some(false);
let mut src2 = FileReview::new(a, FileStatus::Modified);
src2.collapsed = Some(true);
dst2.absorb_rename_source(src2);
assert_eq!(
dst2.collapsed,
Some(false),
"dst's override wins when both are set"
);
}
#[test]
fn absorb_rename_source_preserves_per_comment_side_on_mixed_vec() {
// Regression (post-H9 crew review): `line_comments: HashMap<u32, Vec<Comment>>`
// is keyed only on line number, so a single bucket can legitimately
// hold both LineSide::Old and LineSide::New entries at the same
// line. Previously `absorb_rename_source` read `side` from
// `comments.first()` and applied it to all comments in the vec,
// losing the side info on Old-side comments when the first
// comment happened to be New (or vice versa). The fix reads
// `comment.side` per comment.
let a = PathBuf::from("src/a.rs");
let mut src = FileReview::new(a, FileStatus::Modified);
let mut old_side = Comment::new("was-old-side".into(), CommentType::Note, None);
old_side.side = Some(LineSide::Old);
let mut new_side = Comment::new("was-new-side".into(), CommentType::Note, None);
new_side.side = Some(LineSide::New);
// Both live at line 5 in the same Vec<Comment> bucket.
src.line_comments.insert(5, vec![old_side, new_side]);
let mut dst = FileReview::new(PathBuf::from("src/b.rs"), FileStatus::Modified);
dst.absorb_rename_source(src);
assert_eq!(dst.orphaned_comments.len(), 2);
let mut by_body: std::collections::HashMap<&str, &Comment> =
std::collections::HashMap::new();
for c in &dst.orphaned_comments {
by_body.insert(c.content.as_str(), c);
}
let old = by_body.get("was-old-side").expect("old-side orphaned");
let new = by_body.get("was-new-side").expect("new-side orphaned");
assert!(
matches!(
old.anchor,
Some(AnchorState::Orphaned {
was_side: LineSide::Old,
..
})
),
"Old-side comment must orphan with was_side: Old"
);
assert!(
matches!(
new.anchor,
Some(AnchorState::Orphaned {
was_side: LineSide::New,
..
})
),
"New-side comment must orphan with was_side: New"
);
}
#[test]
fn apply_diff_files_merges_multiple_sources_targeting_one_destination() {
// Regression: two `Renamed` entries whose new_path is the same
// (unusual but possible with aggregated diffs) must merge both
// sources into the destination — file_comments extend, line
// comments orphan.
let mut session = test_session();
let a = PathBuf::from("src/a.rs");
let b = PathBuf::from("src/b.rs");
let c = PathBuf::from("src/c.rs");
session.add_file(a.clone(), FileStatus::Modified);
session
.get_file_mut(&a)
.unwrap()
.add_file_comment(Comment::new("from-a".into(), CommentType::Note, None));
session.add_file(b.clone(), FileStatus::Modified);
session
.get_file_mut(&b)
.unwrap()
.add_file_comment(Comment::new("from-b".into(), CommentType::Note, None));
// Both A and B rename to C (no pre-existing C entry).
let diffs = [
diff_file(FileStatus::Renamed, Some("src/a.rs"), Some("src/c.rs")),
diff_file(FileStatus::Renamed, Some("src/b.rs"), Some("src/c.rs")),
];
session.apply_diff_files(&diffs);
assert!(!session.files.contains_key(&a));
assert!(!session.files.contains_key(&b));
let at_c = session.files.get(&c).expect("c created");
assert_eq!(
at_c.file_comments.len(),
2,
"both source file_comments merged into c"
);
}
#[test]
fn apply_diff_files_registers_renamed_destination_when_source_absent() {
// Edge case: a `Renamed` entry whose old_path isn't in
// self.files (no prior review on the source) must still register
// the new_path via the final `add_file` pass.
let mut session = test_session();
let new_path = PathBuf::from("src/new.rs");
let renamed = diff_file(
FileStatus::Renamed,
Some("src/unknown.rs"),
Some("src/new.rs"),
);
session.apply_diff_files(&[renamed]);
assert!(session.files.contains_key(&new_path), "new path registered");
}
#[test]
fn apply_diff_files_preserves_add_file_idempotency() {
let mut session = test_session();
let path = PathBuf::from("src/foo.rs");
let df = diff_file(FileStatus::Modified, Some("src/foo.rs"), Some("src/foo.rs"));
// First apply registers the file; add a comment so we can detect
// clobbering on the second apply.
session.apply_diff_files(std::slice::from_ref(&df));
session
.get_file_mut(&path)
.unwrap()
.add_file_comment(Comment::new("keep me".into(), CommentType::Note, None));
session.get_file_mut(&path).unwrap().reviewed = true;
// Second apply with the same diff must not clobber the existing entry.
session.apply_diff_files(std::slice::from_ref(&df));
assert_eq!(session.files.len(), 1);
let fr = session.files.get(&path).unwrap();
assert_eq!(fr.file_comments.len(), 1);
assert!(fr.reviewed);
}
#[test]
fn apply_diff_files_resolves_transitive_rename_chain() {
// Regression (H6.19): a diff emitted as `A→B, B→C` in the same
// call must land A's review at the terminal destination C, not
// at the intermediate B. Previously A's state migrated to B
// (where a pass-1 B already existed from the `B→C` extraction
// — or, more subtly, the pass-1 loop extracted both A and B,
// staged A at B, then staged B at C, leaving A stranded at B
// which has no destination entry post-pass-2).
let mut session = test_session();
let a = PathBuf::from("src/a.rs");
let b = PathBuf::from("src/b.rs");
let c = PathBuf::from("src/c.rs");
session.add_file(a.clone(), FileStatus::Modified);
session
.get_file_mut(&a)
.unwrap()
.add_file_comment(Comment::new("from-a".into(), CommentType::Note, None));
session.add_file(b.clone(), FileStatus::Modified);
session
.get_file_mut(&b)
.unwrap()
.add_file_comment(Comment::new("from-b".into(), CommentType::Note, None));
// A→B, B→C as two diff entries in one call.
let chain = [
diff_file(FileStatus::Renamed, Some("src/a.rs"), Some("src/b.rs")),
diff_file(FileStatus::Renamed, Some("src/b.rs"), Some("src/c.rs")),
];
session.apply_diff_files(&chain);
assert!(
!session.files.contains_key(&a),
"a consumed by rename chain"
);
assert!(
!session.files.contains_key(&b),
"b consumed as intermediate hop"
);
let at_c = session
.files
.get(&c)
.expect("c is the terminal destination");
assert_eq!(
at_c.file_comments.len(),
2,
"both a's and b's file_comments merged at the terminal destination c"
);
let bodies: Vec<&str> = at_c
.file_comments
.iter()
.map(|c| c.content.as_str())
.collect();
assert!(
bodies.contains(&"from-a"),
"a's comment followed the chain to c"
);
assert!(
bodies.contains(&"from-b"),
"b's comment moved to c directly"
);
}
#[test]
fn last_review_fields_default_to_none_when_missing_from_json() {
// Synthesize a minimal legacy session JSON that omits the new fields
// and make sure it still loads with the defaults applied.
let legacy = r#"{
"id": "abc",
"version": "1.2",
"repo_path": "/repo",
"base_commit": "deadbeef",
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-01T00:00:00Z",
"files": {}
}"#;
let session: ReviewSession = serde_json::from_str(legacy).expect("legacy deserialize");
assert!(session.last_review_submitted_at.is_none());
assert!(session.last_review_sha.is_none());
}
#[test]
fn mental_model_defaults_to_none_on_pre_1_5_sessions() {
// 1.4-era sessions have no `mental_model` field. The loader must
// accept them with `mental_model: None` so re-opening an old
// session doesn't lose user data.
let legacy_1_4 = r#"{
"id": "abc",
"version": "1.4",
"repo_path": "/repo",
"base_commit": "deadbeef",
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-01T00:00:00Z",
"files": {}
}"#;
let session: ReviewSession =
serde_json::from_str(legacy_1_4).expect("1.4 session must deserialize");
assert!(
session.mental_model.is_none(),
"pre-1.5 sessions must surface `mental_model = None`"
);
}
#[test]
fn mental_model_round_trips_through_session_json() {
// Round-trip a session with a populated mental model through
// serde_json and assert every field survives.
let mut session = ReviewSession::new(
PathBuf::from("/repo"),
"deadbeef".to_string(),
None,
SessionDiffSource::WorkingTree,
);
session.mental_model = Some(MentalModel {
should_do: "validate user input before hitting the DB".to_string(),
shouldnt_do: "trust the frontend's claimed role".to_string(),
could_go_wrong: "SQL injection via the search box".to_string(),
assumptions: "the audit log catches the attacker eventually".to_string(),
created_at: Utc::now(),
updated_at: Utc::now(),
});
let json = serde_json::to_string(&session).expect("serialize");
let restored: ReviewSession = serde_json::from_str(&json).expect("deserialize");
let mm = restored.mental_model.expect("mental_model must round-trip");
assert_eq!(mm.should_do, "validate user input before hitting the DB");
assert_eq!(mm.shouldnt_do, "trust the frontend's claimed role");
assert_eq!(mm.could_go_wrong, "SQL injection via the search box");
assert_eq!(
mm.assumptions,
"the audit log catches the attacker eventually"
);
}
#[test]
fn mental_model_default_stamps_current_timestamps() {
let before = Utc::now();
let mm = MentalModel::default();
let after = Utc::now();
assert!(
mm.created_at >= before && mm.created_at <= after,
"Default created_at must be Utc::now() (got {}), not epoch-0",
mm.created_at
);
assert_eq!(
mm.created_at, mm.updated_at,
"Default timestamps must match so commit_mental_model preserves the stamp on all-fields-blank seeds"
);
// And the epoch-0 bug stays fixed: a freshly-constructed model
// is *not* equal to an epoch-0-valued one.
let year_2000 = DateTime::<Utc>::from_timestamp(946_684_800, 0).unwrap();
assert!(
mm.created_at > year_2000,
"Default created_at must be well past the epoch"
);
}
#[test]
fn mental_model_oversized_field_reports_first_overflow() {
let long = "x".repeat(10);
let mm = MentalModel {
should_do: String::new(),
shouldnt_do: long.clone(),
could_go_wrong: long.clone(),
assumptions: String::new(),
created_at: Utc::now(),
updated_at: Utc::now(),
};
// First field to exceed wins — `shouldnt_do` in this arrangement.
let hit = mm.oversized_field(5);
assert_eq!(hit, Some(("shouldnt_do", 10)));
// A generous cap passes.
assert!(mm.oversized_field(100).is_none());
}
#[test]
fn mental_model_to_mcp_payload_emits_rfc3339_timestamps() {
let t = Utc::now();
let mm = MentalModel {
should_do: "a".into(),
shouldnt_do: "b".into(),
could_go_wrong: "c".into(),
assumptions: "d".into(),
created_at: t,
updated_at: t,
};
let v = mm.to_mcp_payload();
assert_eq!(v["should_do"], "a");
assert_eq!(v["shouldnt_do"], "b");
assert_eq!(v["could_go_wrong"], "c");
assert_eq!(v["assumptions"], "d");
assert!(v["created_at"].as_str().unwrap().contains('T'));
assert_eq!(v["updated_at"], t.to_rfc3339());
}
#[test]
fn commit_mental_model_preserves_created_at_on_edit() {
let mut session = ReviewSession::new(
PathBuf::from("/repo"),
"deadbeef".to_string(),
None,
SessionDiffSource::WorkingTree,
);
let seeded_created = Utc::now() - chrono::Duration::hours(1);
session.mental_model = Some(MentalModel {
should_do: "first".into(),
shouldnt_do: String::new(),
could_go_wrong: String::new(),
assumptions: String::new(),
created_at: seeded_created,
updated_at: seeded_created,
});
let now = Utc::now();
session.commit_mental_model(
MentalModel {
should_do: "edited".into(),
shouldnt_do: String::new(),
could_go_wrong: String::new(),
assumptions: String::new(),
created_at: now,
updated_at: now,
},
now,
);
let mm = session
.mental_model
.as_ref()
.expect("must remain populated");
assert_eq!(mm.should_do, "edited");
assert_eq!(
mm.created_at, seeded_created,
"edits must preserve the original created_at"
);
assert_eq!(mm.updated_at, now);
assert_eq!(session.updated_at, now);
}
#[test]
fn commit_mental_model_collapses_empty_to_none() {
let mut session = ReviewSession::new(
PathBuf::from("/repo"),
"deadbeef".to_string(),
None,
SessionDiffSource::WorkingTree,
);
let now = Utc::now();
session.mental_model = Some(MentalModel {
should_do: "old".into(),
shouldnt_do: String::new(),
could_go_wrong: String::new(),
assumptions: String::new(),
created_at: now,
updated_at: now,
});
session.commit_mental_model(MentalModel::default(), now);
assert!(
session.mental_model.is_none(),
"all-empty commit must collapse to None to preserve the \
skip_serializing_if contract"
);
}
#[test]
fn mental_model_is_empty_detects_all_blank_fields() {
let blank = MentalModel::default();
assert!(blank.is_empty());
let partial = MentalModel {
should_do: "something".to_string(),
..MentalModel::default()
};
assert!(
!partial.is_empty(),
"a single non-empty field must mark the model as populated"
);
}
#[test]
fn empty_mental_model_is_skipped_by_default_serialization() {
// `skip_serializing_if = "Option::is_none"` on the ReviewSession
// field means a `None` mental model doesn't emit the key at all.
// This keeps the session JSON clean for sessions created before
// the user opens the `m` modal, and means 1.5 sessions with no
// model look identical to 1.4 sessions modulo `version`.
let session = ReviewSession::new(
PathBuf::from("/repo"),
"deadbeef".to_string(),
None,
SessionDiffSource::WorkingTree,
);
let json = serde_json::to_string(&session).expect("serialize");
assert!(
!json.contains("mental_model"),
"None mental_model must not appear in session JSON: {json}"
);
}
}