shadow-diff 3.2.5

Behavior contracts for AI agents — tested in your PR, enforced at runtime. Core engine: parser, writer, content-addressed store, replay, and nine-axis behavioral differ.
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
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
//! Prescriptive fix recommendations derived from a [`DiffReport`].
//!
//! Once Shadow has detected divergences and ranked them (see
//! [`crate::diff::alignment`]), this module turns that raw signal into
//! a **list of actionable next-steps a reviewer can act on in under
//! 30 seconds** — the "what do I do about this?" layer. It replaces
//! the generic "investigate turn 9" instinct with specific moves like
//! *"Restore `send_confirmation_email`"* or *"Revert refund amount
//! 9.99 → 99.99"*.
//!
//! ## Design decisions
//!
//! - **Deterministic, rule-based.** No LLM dependency in the core crate.
//!   The recommendation engine maps each divergence shape to one or
//!   more specific recommendations via pure pattern matching. An LLM-
//!   assisted "enriched" suggestion layer can live in the Python
//!   optional-extras path later, but the rule-based core must always
//!   work offline.
//! - **Actionable phrasing.** Every recommendation starts with a verb
//!   (Restore / Remove / Revert / Review / Verify). No "consider
//!   investigating" or "you might want to". If the rule can't decide
//!   whether action is safe, it uses `Review` + rationale; it doesn't
//!   recommend a specific action it can't justify.
//! - **Hedged for non-obvious cases.** Style drift → Info severity.
//!   Low-confidence signals are tagged with `Verify` action rather
//!   than directive `Restore` / `Revert`. The rule engine errs on the
//!   side of under-prescribing: false positives waste reviewer time
//!   more than false negatives waste engineer attention.
//! - **Rationale included.** Every recommendation has both a short
//!   action and a one-line rationale explaining the signal that
//!   triggered it. Reviewers should never have to re-read the raw
//!   trace to understand why a recommendation appeared.
//!
//! ## Severity scheme (mirrors ESLint / SonarQube / Rustc)
//!
//! - `Error` — structural regression with high confidence (dropped or
//!   reordered tool, refusal flip). Block-merge signal.
//! - `Warning` — decision drift (arg value change, semantic shift).
//!   Needs review before merge; may be intended.
//! - `Info` — style drift, below-noise variance, low-confidence
//!   signals. FYI, not action-required.

use serde::{Deserialize, Serialize};

use crate::diff::alignment::{DivergenceKind, FirstDivergence};
use crate::diff::axes::{Axis, Severity as AxisSeverity};
use crate::diff::report::DiffReport;

/// Severity of a recommendation. Uses the same three-tier scheme as
/// mainstream linters / static analyzers (ESLint, SonarQube, Rustc).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RecommendationSeverity {
    /// Likely a real regression that should block merge (or at least
    /// demand explicit review). Produced for high-confidence
    /// structural drift and stop_reason flips to `content_filter`.
    Error,
    /// Probably a behaviour change worth reviewing before merge. Decision
    /// drift with meaningful confidence, axis-level severity of
    /// `moderate`/`severe`.
    Warning,
    /// Informational — style drift, below-noise divergence, or
    /// low-confidence signals. Won't gate merge; callers may hide it
    /// in summary views.
    Info,
}

impl RecommendationSeverity {
    /// Short lowercase label for terminal / markdown / JSON rendering.
    pub fn label(&self) -> &'static str {
        match self {
            RecommendationSeverity::Error => "error",
            RecommendationSeverity::Warning => "warning",
            RecommendationSeverity::Info => "info",
        }
    }

    /// Numeric weight so callers can sort recommendations by severity
    /// without a case match. Higher = more urgent.
    pub fn rank(&self) -> u8 {
        match self {
            RecommendationSeverity::Error => 3,
            RecommendationSeverity::Warning => 2,
            RecommendationSeverity::Info => 1,
        }
    }
}

/// The action category. Informs rendering (icon/color) and tells the
/// reviewer what KIND of move is being suggested.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ActionKind {
    /// Bring back something the candidate dropped (tool call, required
    /// field, turn).
    Restore,
    /// Remove something the candidate added without justification
    /// (duplicate tool call, extra unneeded turn).
    Remove,
    /// Change a value back to the baseline (arg value, temperature).
    Revert,
    /// Human judgment needed — the candidate change may be intentional
    /// or context-dependent (prompt wording, refusal behaviour).
    Review,
    /// Low-signal event that might be noise; verify before acting.
    Verify,
    /// A higher-level root-cause recommendation inferred from a
    /// cross-axis correlation pattern (e.g. "looks like a model swap
    /// because cost + latency + semantic all moved together"). Subsumes
    /// the individual per-axis recommendations the same signature
    /// would have produced; the renderer should prefer the RootCause
    /// over the individual ones when both are present.
    RootCause,
}

impl ActionKind {
    /// Short lowercase label used in terminal / markdown / JSON rendering.
    pub fn label(&self) -> &'static str {
        match self {
            ActionKind::Restore => "restore",
            ActionKind::Remove => "remove",
            ActionKind::Revert => "revert",
            ActionKind::Review => "review",
            ActionKind::Verify => "verify",
            ActionKind::RootCause => "root_cause",
        }
    }
}

/// One prescriptive recommendation for a reviewer.
///
/// Wire format is verbose-but-diff-friendly (all fields named); the
/// renderers condense it into one-line "severity · action · target"
/// sentences for display.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Recommendation {
    /// Severity/priority; sort key for display.
    pub severity: RecommendationSeverity,
    /// What kind of move is being suggested.
    pub action: ActionKind,
    /// 0-based turn index the recommendation refers to, in the
    /// **baseline** chat-response sequence. 0 when the recommendation
    /// is trace-wide (not tied to a specific turn).
    ///
    /// Kept for backward compatibility: this is always equal to
    /// `baseline_turn`. New consumers should prefer `baseline_turn` /
    /// `candidate_turn`, since the former can exceed `report.pair_count`
    /// (which is `min(N_baseline, N_candidate)`) when the candidate
    /// dropped a turn.
    pub turn: usize,
    /// 0-based index in the baseline's chat-response sequence (mirror
    /// of `FirstDivergence::baseline_turn`). May exceed
    /// `report.pair_count` when the candidate dropped turns.
    #[serde(default)]
    pub baseline_turn: usize,
    /// 0-based index in the candidate's chat-response sequence (mirror
    /// of `FirstDivergence::candidate_turn`). May differ from
    /// `baseline_turn` when the alignment path contains gaps.
    #[serde(default)]
    pub candidate_turn: usize,
    /// One-line action statement, starts with an imperative verb.
    /// Example: "Restore `send_confirmation_email` tool call at turn 9."
    pub message: String,
    /// One-line explanation of the signal that triggered this
    /// recommendation. Sourced from the underlying `FirstDivergence`'s
    /// `explanation` field plus any rule-specific context.
    pub rationale: String,
    /// Which diff axis the signal came from. Lets callers filter
    /// recommendations by concern (e.g. only safety-related).
    pub axis: Axis,
    /// Confidence from the underlying divergence, 0..1. Low-confidence
    /// recommendations may be suppressed in compact views.
    pub confidence: f64,
}

/// Generate recommendations from a complete [`DiffReport`].
///
/// Rules:
///
/// 1. For every divergence in `report.divergences` (top-K ranked),
///    apply the rule that matches its `(kind, primary_axis, explanation)`
///    shape.
/// 2. If the overall worst-severity axis is `Severe` and no divergence
///    produced an Error-level recommendation, add a single trace-wide
///    recommendation pointing the reviewer at the strongest axis.
/// 3. Sort by (severity desc, confidence desc, turn asc). Cap at 8 to
///    avoid overwhelming PR comments (callers that want all can still
///    read the raw list — but the canonical ordering is stable here).
///
/// Output is stable and deterministic given the same input `DiffReport`.
pub fn generate(report: &DiffReport) -> Vec<Recommendation> {
    let mut out: Vec<Recommendation> = Vec::new();

    // Cross-axis pattern detection runs FIRST so root-cause
    // recommendations sort to the top and the per-divergence
    // recommendations land underneath as supporting evidence.
    out.extend(detect_cross_axis_patterns(report));

    for dv in &report.divergences {
        if let Some(rec) = rule_for_divergence(dv) {
            out.push(rec);
        }
    }

    // Trace-wide fallback: if the worst axis severity is Severe and we
    // haven't produced any Error-level recommendation, surface the
    // strongest axis as a top-level concern. Protects against the
    // edge case where axis severity is loud but first-divergence
    // couldn't attribute it to a specific turn.
    // The `Severity` enum derives `Ord` (declared in the None < Minor <
    // Moderate < Severe order). We filter to Severe rows and take any —
    // the axis itself tiebreaks naturally via the iteration order.
    let worst_axis_row = report
        .rows
        .iter()
        .filter(|r| r.severity == AxisSeverity::Severe)
        .max_by(|a, b| a.severity.cmp(&b.severity));
    if let Some(worst) = worst_axis_row {
        let has_error = out
            .iter()
            .any(|r| r.severity == RecommendationSeverity::Error);
        if !has_error {
            out.push(Recommendation {
                severity: RecommendationSeverity::Error,
                action: ActionKind::Review,
                turn: 0,
                baseline_turn: 0,
                candidate_turn: 0,
                message: format!(
                    "Review the candidate: {} axis shifted with severity {}.",
                    worst.axis.label(),
                    worst.severity.label(),
                ),
                rationale: format!(
                    "Aggregate signal crosses the `severe` threshold \
                    ({}: delta {:+.3}, CI [{:+.3}, {:+.3}]).",
                    worst.axis.label(),
                    worst.delta,
                    worst.ci95_low,
                    worst.ci95_high,
                ),
                axis: worst.axis,
                confidence: 0.8,
            });
        }
    }

    // Sort: severity desc, confidence desc, turn asc.
    out.sort_by(|a, b| {
        b.severity
            .rank()
            .cmp(&a.severity.rank())
            .then_with(|| {
                b.confidence
                    .partial_cmp(&a.confidence)
                    .unwrap_or(std::cmp::Ordering::Equal)
            })
            .then_with(|| a.turn.cmp(&b.turn))
    });
    out.truncate(8);
    out
}

/// Map a single divergence to a recommendation. Returns `None` if the
/// divergence is noise below an actionable threshold.
fn rule_for_divergence(dv: &FirstDivergence) -> Option<Recommendation> {
    let exp = dv.explanation.to_lowercase();
    match dv.kind {
        // ---------------------------------------------------------
        // Structural drift — Error severity, specific actions
        // ---------------------------------------------------------
        DivergenceKind::Structural => {
            // Pattern 1: candidate dropped tool call(s) → Restore
            if exp.contains("dropped tool")
                || exp.contains("dropped a response turn")
                || exp.contains("dropped a turn")
            {
                let tool_ref = extract_backticked(&dv.explanation).unwrap_or("missing element");
                Some(Recommendation {
                    severity: RecommendationSeverity::Error,
                    action: ActionKind::Restore,
                    turn: dv.baseline_turn,
                    baseline_turn: dv.baseline_turn,
                    candidate_turn: dv.candidate_turn,
                    message: format!("Restore {tool_ref} at turn {}.", dv.baseline_turn),
                    rationale: dv.explanation.clone(),
                    axis: dv.primary_axis,
                    confidence: dv.confidence,
                })
            }
            // Pattern 2: candidate added tool call(s) → Remove (if it
            // looks like a duplicate) OR Review (unclear intent).
            else if exp.contains("added tool") || exp.contains("inserted an extra") {
                let tool_ref = extract_backticked(&dv.explanation).unwrap_or("extra element");
                Some(Recommendation {
                    severity: RecommendationSeverity::Error,
                    action: ActionKind::Review,
                    turn: dv.baseline_turn,
                    baseline_turn: dv.baseline_turn,
                    candidate_turn: dv.candidate_turn,
                    message: format!(
                        "Review unexpected addition at turn {}: {tool_ref}.",
                        dv.baseline_turn
                    ),
                    rationale: dv.explanation.clone(),
                    axis: dv.primary_axis,
                    confidence: dv.confidence,
                })
            }
            // Pattern 3: duplicate tool invocation → Remove
            else if exp.contains("duplicate tool") {
                let tool_ref = extract_backticked(&dv.explanation).unwrap_or("the duplicated tool");
                Some(Recommendation {
                    severity: RecommendationSeverity::Error,
                    action: ActionKind::Remove,
                    turn: dv.baseline_turn,
                    baseline_turn: dv.baseline_turn,
                    candidate_turn: dv.candidate_turn,
                    message: format!(
                        "Remove duplicate invocation of {tool_ref} at turn {}.",
                        dv.baseline_turn
                    ),
                    rationale: dv.explanation.clone(),
                    axis: dv.primary_axis,
                    confidence: dv.confidence,
                })
            }
            // Pattern 4: tool set changed (renamed / swapped / reordered) → Review
            else if exp.contains("tool set changed") || exp.contains("tool ordering differs") {
                Some(Recommendation {
                    severity: RecommendationSeverity::Error,
                    action: ActionKind::Review,
                    turn: dv.baseline_turn,
                    baseline_turn: dv.baseline_turn,
                    candidate_turn: dv.candidate_turn,
                    message: format!(
                        "Review tool-schema change at turn {}: call shape diverged.",
                        dv.baseline_turn
                    ),
                    rationale: dv.explanation.clone(),
                    axis: dv.primary_axis,
                    confidence: dv.confidence,
                })
            }
            // Catch-all for unmatched Structural — still Error, generic Review.
            else {
                Some(Recommendation {
                    severity: RecommendationSeverity::Error,
                    action: ActionKind::Review,
                    turn: dv.baseline_turn,
                    baseline_turn: dv.baseline_turn,
                    candidate_turn: dv.candidate_turn,
                    message: format!("Review structural change at turn {}.", dv.baseline_turn),
                    rationale: dv.explanation.clone(),
                    axis: dv.primary_axis,
                    confidence: dv.confidence,
                })
            }
        }
        // ---------------------------------------------------------
        // Decision drift — Warning severity, rule picks action
        // ---------------------------------------------------------
        DivergenceKind::Decision => {
            // Safety-axis decision: refusal flip / stop_reason change.
            if dv.primary_axis == Axis::Safety && exp.contains("stop_reason") {
                // Upgrade to Error when candidate introduced a refusal.
                let is_new_refusal = exp.contains("content_filter");
                let severity = if is_new_refusal {
                    RecommendationSeverity::Error
                } else {
                    RecommendationSeverity::Warning
                };
                Some(Recommendation {
                    severity,
                    action: ActionKind::Review,
                    turn: dv.baseline_turn,
                    baseline_turn: dv.baseline_turn,
                    candidate_turn: dv.candidate_turn,
                    message: format!(
                        "Review refusal behaviour at turn {}: candidate may be over-refusing.",
                        dv.baseline_turn
                    ),
                    rationale: dv.explanation.clone(),
                    axis: dv.primary_axis,
                    confidence: dv.confidence,
                })
            }
            // Trajectory-axis decision: arg value changed → Revert.
            else if dv.primary_axis == Axis::Trajectory && exp.contains("arg value") {
                let arg_ref = extract_backticked(&dv.explanation).unwrap_or("arg value");
                Some(Recommendation {
                    severity: RecommendationSeverity::Warning,
                    action: ActionKind::Revert,
                    turn: dv.baseline_turn,
                    baseline_turn: dv.baseline_turn,
                    candidate_turn: dv.candidate_turn,
                    message: format!(
                        "Revert {arg_ref} at turn {} to the baseline value.",
                        dv.baseline_turn
                    ),
                    rationale: dv.explanation.clone(),
                    axis: dv.primary_axis,
                    confidence: dv.confidence,
                })
            }
            // Semantic decision drift: content meaning shifted → Review.
            else if dv.primary_axis == Axis::Semantic {
                Some(Recommendation {
                    severity: RecommendationSeverity::Warning,
                    action: ActionKind::Review,
                    turn: dv.baseline_turn,
                    baseline_turn: dv.baseline_turn,
                    candidate_turn: dv.candidate_turn,
                    message: format!(
                        "Review response text at turn {}: semantic content shifted.",
                        dv.baseline_turn
                    ),
                    rationale: dv.explanation.clone(),
                    axis: dv.primary_axis,
                    confidence: dv.confidence,
                })
            }
            // Catch-all for unmatched Decision.
            else {
                Some(Recommendation {
                    severity: RecommendationSeverity::Warning,
                    action: ActionKind::Review,
                    turn: dv.baseline_turn,
                    baseline_turn: dv.baseline_turn,
                    candidate_turn: dv.candidate_turn,
                    message: format!("Review decision change at turn {}.", dv.baseline_turn),
                    rationale: dv.explanation.clone(),
                    axis: dv.primary_axis,
                    confidence: dv.confidence,
                })
            }
        }
        // ---------------------------------------------------------
        // Style drift — Info severity, Verify (might not need action)
        // ---------------------------------------------------------
        DivergenceKind::Style => Some(Recommendation {
            severity: RecommendationSeverity::Info,
            action: ActionKind::Verify,
            turn: dv.baseline_turn,
            baseline_turn: dv.baseline_turn,
            candidate_turn: dv.candidate_turn,
            message: format!(
                "Cosmetic wording change at turn {} — verify intended.",
                dv.baseline_turn
            ),
            rationale: dv.explanation.clone(),
            axis: dv.primary_axis,
            confidence: dv.confidence,
        }),
    }
}

/// Extract the first backtick-delimited token from a string, e.g.
/// pull `"search(limit,query)"` out of
/// `"tool set changed: removed `search(query)`, added `search(limit,query)`"`.
/// Returns `None` when there is no backticked span.
fn extract_backticked(s: &str) -> Option<&str> {
    let first = s.find('`')?;
    let rest = &s[first + 1..];
    let end = rest.find('`')?;
    Some(&rest[..end])
}

// ---------------------------------------------------------------------------
// Cross-axis correlation pattern detection
// ---------------------------------------------------------------------------

/// Threshold above which an axis is considered "moved" for cross-axis
/// pattern detection. Severity must be Moderate or Severe.
fn axis_moved(report: &DiffReport, axis: Axis) -> bool {
    report
        .rows
        .iter()
        .find(|r| r.axis == axis)
        .map(|r| matches!(r.severity, AxisSeverity::Moderate | AxisSeverity::Severe))
        .unwrap_or(false)
}

/// True iff the axis severity is at least Severe (the strongest tier).
fn axis_severe(report: &DiffReport, axis: Axis) -> bool {
    report
        .rows
        .iter()
        .find(|r| r.axis == axis)
        .map(|r| r.severity == AxisSeverity::Severe)
        .unwrap_or(false)
}

/// Detect cross-axis correlation patterns and emit RootCause
/// recommendations naming the inferred underlying change.
///
/// Patterns encoded (each fires only when the per-axis severity
/// signals all clear the noise floor — Moderate or Severe — so
/// noise on one axis can't trigger a root-cause claim alone):
///
///   1. **Model swap** — cost + latency + semantic all moved together.
///      Frontier-vs-haiku swaps and provider switches show this exact
///      tri-axis signature; reverting the model_id usually neutralises
///      all three at once. Pattern reference: GPT-4 → GPT-4o, Sonnet
///      → Haiku, Anthropic → OpenAI provider migrations.
///
///   2. **Prompt drift** — semantic + verbosity moved together,
///      typically with safety joining when the prompt changed
///      refusal-style instructions. System-prompt edits classically
///      produce this two-or-three-axis signature.
///
///   3. **Refusal escalation** — safety axis severe + verbosity often
///      down. Stricter system instructions or tighter content
///      policies. Often paired with stop_reason flips to
///      content_filter (which the safety axis already encodes).
///
///   4. **Tool schema migration** — trajectory severe + reasoning
///      moves + sometimes cost slightly up. Adding/removing tool args
///      shows up as a same-set-of-tools-different-arg-keys divergence
///      that touches the trajectory axis directly and the reasoning
///      axis indirectly (the model thinks longer about the new schema).
///
///   5. **Hallucination cluster** — semantic moderate-or-severe +
///      judge moderate-or-severe + verbosity often up. The classic
///      "agent talks confidently and incorrectly" signature: the
///      semantic axis catches the divergence, the judge axis catches
///      the wrongness, and verbosity often spikes because the
///      hallucinated content is longer than the correct answer.
fn detect_cross_axis_patterns(report: &DiffReport) -> Vec<Recommendation> {
    let mut out = Vec::new();

    // 1. Model swap signature
    if axis_moved(report, Axis::Cost)
        && axis_moved(report, Axis::Latency)
        && axis_moved(report, Axis::Semantic)
    {
        let cost_delta = axis_delta(report, Axis::Cost);
        let lat_delta = axis_delta(report, Axis::Latency);
        let sem_delta = axis_delta(report, Axis::Semantic);
        out.push(Recommendation {
            severity: RecommendationSeverity::Error,
            action: ActionKind::RootCause,
            turn: 0,
            baseline_turn: 0,
            candidate_turn: 0,
            message:
                "Looks like a model change. Cost, latency, and semantic axes all shifted together."
                    .to_string(),
            rationale: format!(
                "Cross-axis signature: cost Δ {cost_delta:+.3}, latency Δ {lat_delta:+.3}, \
                 semantic Δ {sem_delta:+.3}. Three axes moving together is the canonical \
                 model-swap signature (provider change, frontier→haiku, etc.). Diff the \
                 `model` field across configs first."
            ),
            axis: Axis::Cost,
            confidence: 0.85,
        });
    }

    // 2. Prompt drift signature
    if axis_moved(report, Axis::Semantic) && axis_moved(report, Axis::Verbosity) {
        // Don't double-fire when we already attributed to model swap.
        let already_model_swap = out.iter().any(|r| {
            matches!(r.action, ActionKind::RootCause)
                && r.message.starts_with("Looks like a model change")
        });
        if !already_model_swap {
            let sem_delta = axis_delta(report, Axis::Semantic);
            let vrb_delta = axis_delta(report, Axis::Verbosity);
            let safety_part = if axis_moved(report, Axis::Safety) {
                " plus safety axis (refusal-style instruction change)"
            } else {
                ""
            };
            out.push(Recommendation {
                severity: RecommendationSeverity::Warning,
                action: ActionKind::RootCause,
                turn: 0,
                baseline_turn: 0,
                candidate_turn: 0,
                message: format!(
                    "Looks like a system-prompt edit. Semantic + verbosity moved together{safety_part}."
                ),
                rationale: format!(
                    "Cross-axis signature: semantic Δ {sem_delta:+.3}, verbosity Δ {vrb_delta:+.3}. \
                     Diff the `system` field of the request across configs."
                ),
                axis: Axis::Semantic,
                confidence: 0.70,
            });
        }
    }

    // 3. Refusal escalation signature
    if axis_severe(report, Axis::Safety) {
        let safety_delta = axis_delta(report, Axis::Safety);
        if safety_delta > 0.0 {
            out.push(Recommendation {
                severity: RecommendationSeverity::Error,
                action: ActionKind::RootCause,
                turn: 0,
                baseline_turn: 0,
                candidate_turn: 0,
                message: "Refusal rate is up severely. Check for stricter system instructions \
                          or tighter content policies."
                    .to_string(),
                rationale: format!(
                    "Safety axis severe with positive delta {safety_delta:+.3} — the candidate \
                     refused or was content-filtered more often than baseline. Common causes: \
                     added safety preamble in system prompt, model upgrade with stricter RLHF, \
                     provider-side content-filter tightening."
                ),
                axis: Axis::Safety,
                confidence: 0.80,
            });
        }
    }

    // 4. Tool schema migration signature
    if axis_severe(report, Axis::Trajectory) && axis_moved(report, Axis::Reasoning) {
        let traj_delta = axis_delta(report, Axis::Trajectory);
        let reason_delta = axis_delta(report, Axis::Reasoning);
        out.push(Recommendation {
            severity: RecommendationSeverity::Error,
            action: ActionKind::RootCause,
            turn: 0,
            baseline_turn: 0,
            candidate_turn: 0,
            message: "Looks like a tool-schema migration. Trajectory + reasoning both moved."
                .to_string(),
            rationale: format!(
                "Cross-axis signature: trajectory Δ {traj_delta:+.3} (tool sequence/args \
                 changed), reasoning Δ {reason_delta:+.3} (the model is thinking through a \
                 different schema). Diff the `tools` array across configs and check whether \
                 arg keys were added or removed."
            ),
            axis: Axis::Trajectory,
            confidence: 0.78,
        });
    }

    // 5. Hallucination cluster signature
    if axis_moved(report, Axis::Semantic) && axis_moved(report, Axis::Judge) {
        let sem_delta = axis_delta(report, Axis::Semantic);
        let judge_delta = axis_delta(report, Axis::Judge);
        let verbosity_part = if axis_moved(report, Axis::Verbosity) {
            ", with verbosity also up"
        } else {
            ""
        };
        out.push(Recommendation {
            severity: RecommendationSeverity::Error,
            action: ActionKind::RootCause,
            turn: 0,
            baseline_turn: 0,
            candidate_turn: 0,
            message: format!(
                "Possible hallucination regression. Semantic and judge axes both moved{verbosity_part}."
            ),
            rationale: format!(
                "Cross-axis signature: semantic Δ {sem_delta:+.3}, judge Δ {judge_delta:+.3}. \
                 The classic 'confident-and-wrong' signature — the response diverged \
                 semantically AND was scored lower by the rubric. Sample 3-5 candidate \
                 outputs and verify factual claims against ground truth before merging."
            ),
            axis: Axis::Judge,
            confidence: 0.82,
        });
    }

    // 6. Context-window-overflow signature: cost spike + reasoning collapse.
    // When prompts grow past the model's effective context, providers either
    // truncate (losing signal → reasoning axis drops) or charge for the full
    // overflow (cost axis spikes). Either path produces this two-axis
    // signature: cost up severely AND reasoning movement.
    if axis_severe(report, Axis::Cost) && axis_moved(report, Axis::Reasoning) {
        let cost_d = axis_delta(report, Axis::Cost);
        let reason_d = axis_delta(report, Axis::Reasoning);
        // Don't double-fire when model_swap already explains the cost shift.
        let model_swap_active = out
            .iter()
            .any(|r| r.action == ActionKind::RootCause && r.message.contains("model change"));
        if !model_swap_active && cost_d > 0.0 {
            out.push(Recommendation {
                severity: RecommendationSeverity::Error,
                action: ActionKind::RootCause,
                turn: 0,
                baseline_turn: 0,
                candidate_turn: 0,
                message: "Possible context-window overflow. Cost spiked severely without a model \
                     change, and reasoning shifted with it."
                    .to_string(),
                rationale: format!(
                    "Cross-axis signature: cost Δ {cost_d:+.3} (severe) with reasoning \
                     Δ {reason_d:+.3}, model unchanged. Common cause: prompt-length growth \
                     past the effective context window — providers either truncate (lossy \
                     reasoning) or charge for the full prompt every turn (cost balloons). \
                     Check prompt-token usage trend across the candidate's turns."
                ),
                axis: Axis::Cost,
                confidence: 0.72,
            });
        }
    }

    // 7. Retry-loop signature: same tool called repeatedly with high latency
    // variance. Trajectory severe AND latency moved suggests the candidate is
    // retrying a failing tool call (each retry adds latency variance, and the
    // duplicate-call penalty in the trajectory metric registers).
    if axis_severe(report, Axis::Trajectory) && axis_moved(report, Axis::Latency) {
        // Don't double-fire with tool-schema-migration which uses the same
        // axes — tool-schema is reasoning-driven, retry-loop is latency-driven.
        let schema_active = out
            .iter()
            .any(|r| r.action == ActionKind::RootCause && r.message.contains("tool-schema"));
        if !schema_active {
            let traj_d = axis_delta(report, Axis::Trajectory);
            let lat_d = axis_delta(report, Axis::Latency);
            if lat_d > 0.0 {
                out.push(Recommendation {
                    severity: RecommendationSeverity::Error,
                    action: ActionKind::RootCause,
                    turn: 0,
                    baseline_turn: 0,
                    candidate_turn: 0,
                    message: "Possible retry loop. Trajectory diverged severely with latency \
                              spike but no reasoning shift."
                        .to_string(),
                    rationale: format!(
                        "Cross-axis signature: trajectory Δ {traj_d:+.3}, latency Δ \
                         {lat_d:+.3}, reasoning stable. Suggests the agent is retrying a \
                         failing tool call (each retry inflates the tool-call count and \
                         adds latency, but doesn't change reasoning depth). Inspect tool \
                         results for transient errors that the agent is silently retrying."
                    ),
                    axis: Axis::Trajectory,
                    confidence: 0.70,
                });
            }
        }
    }

    // 8. Cost-explosion-cached-mismatch signature: cost severe with latency
    // STABLE. Caching layer is doing the work for latency but billing is
    // not following the cache hits — the typical signature when an SDK
    // upgrade silently drops the cache_control flag.
    if axis_severe(report, Axis::Cost)
        && !axis_moved(report, Axis::Latency)
        && !axis_moved(report, Axis::Semantic)
    {
        let cost_d = axis_delta(report, Axis::Cost);
        if cost_d > 0.0 {
            out.push(Recommendation {
                severity: RecommendationSeverity::Error,
                action: ActionKind::RootCause,
                turn: 0,
                baseline_turn: 0,
                candidate_turn: 0,
                message: "Cost up severely with latency stable. Suggests cache control \
                          stopped being honored."
                    .to_string(),
                rationale: format!(
                    "Cross-axis signature: cost Δ {cost_d:+.3}, latency stable, semantic \
                     stable. Cache-hit latency without cache-hit pricing means the request \
                     hit the cache for performance but billed at the uncached rate. Common \
                     causes: SDK upgrade dropped the `cache_control` flag, prompt-prefix \
                     drift broke cache reuse, or the provider changed cache pricing."
                ),
                axis: Axis::Cost,
                confidence: 0.68,
            });
        }
    }

    // 9. Prompt-injection-on-tool-args signature: trajectory severe driven
    // by arg-VALUE digest churn (not key churn) AND safety axis moves toward
    // the candidate becoming MORE permissive (negative safety delta — the
    // opposite of refusal escalation). The classic exfiltration pattern:
    // tool calls succeed at the same rate but with payloads the agent
    // wouldn't normally send.
    if axis_severe(report, Axis::Trajectory) && axis_moved(report, Axis::Safety) {
        let safety_d = axis_delta(report, Axis::Safety);
        // Negative safety delta = candidate refuses LESS, the suspicious
        // direction (positive delta is "stricter", which has its own pattern).
        if safety_d < 0.0 {
            let traj_d = axis_delta(report, Axis::Trajectory);
            out.push(Recommendation {
                severity: RecommendationSeverity::Error,
                action: ActionKind::RootCause,
                turn: 0,
                baseline_turn: 0,
                candidate_turn: 0,
                message: "Possible prompt-injection or tool-args exfiltration. Trajectory \
                          severe AND refusal rate dropped."
                    .to_string(),
                rationale: format!(
                    "Cross-axis signature: trajectory Δ {traj_d:+.3} with safety Δ \
                     {safety_d:+.3} (refusing less). Tool calls diverged AND the agent \
                     became more permissive — the canonical signature of a prompt-injected \
                     trace where tool args are being used to exfiltrate or escalate. \
                     Sample 3-5 candidate tool-call payloads against the baseline; look \
                     for unexpected URLs, IDs, or tokens in the input objects."
                ),
                axis: Axis::Safety,
                confidence: 0.75,
            });
        }
    }

    // 10. Latency-spike-without-cost signature: latency severe, cost stable,
    // semantic stable. The model is taking longer per response but neither
    // generating more tokens nor using a different model. Typical causes:
    // provider-side capacity issue, network path change, or a reasoning-token
    // ramp that's billed at the output rate (so cost moves with reasoning,
    // not with raw latency).
    if axis_severe(report, Axis::Latency)
        && !axis_moved(report, Axis::Cost)
        && !axis_moved(report, Axis::Semantic)
    {
        let lat_d = axis_delta(report, Axis::Latency);
        // Don't fire when model_swap or context-window-overflow already
        // explains the latency.
        let already_explained = out.iter().any(|r| {
            r.action == ActionKind::RootCause
                && (r.message.contains("model change") || r.message.contains("context-window"))
        });
        if !already_explained && lat_d > 0.0 {
            out.push(Recommendation {
                severity: RecommendationSeverity::Warning,
                action: ActionKind::RootCause,
                turn: 0,
                baseline_turn: 0,
                candidate_turn: 0,
                message: "Latency up severely with cost stable. Provider-side capacity or \
                          network change."
                    .to_string(),
                rationale: format!(
                    "Cross-axis signature: latency Δ {lat_d:+.3}, cost stable, semantic \
                     stable. Same model, same output length, slower response. Common \
                     causes: provider capacity event, network path change, regional \
                     fail-over. Check provider status pages for the candidate's run window \
                     before treating this as a code regression."
                ),
                axis: Axis::Latency,
                confidence: 0.65,
            });
        }
    }

    out
}

/// Look up the per-axis delta value for cross-axis pattern formatting.
/// Returns 0.0 when the axis is missing from the report.
fn axis_delta(report: &DiffReport, axis: Axis) -> f64 {
    report
        .rows
        .iter()
        .find(|r| r.axis == axis)
        .map(|r| r.delta)
        .unwrap_or(0.0)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::diff::axes::{Axis, AxisStat, Severity};

    fn empty_report() -> DiffReport {
        let rows = Axis::all().iter().map(|a| AxisStat::empty(*a)).collect();
        DiffReport {
            rows,
            baseline_trace_id: String::new(),
            candidate_trace_id: String::new(),
            pair_count: 0,
            first_divergence: None,
            divergences: Vec::new(),
            recommendations: Vec::new(),
            drill_down: Vec::new(),
        }
    }

    fn divergence(
        kind: DivergenceKind,
        axis: Axis,
        explanation: &str,
        confidence: f64,
    ) -> FirstDivergence {
        FirstDivergence {
            baseline_turn: 3,
            candidate_turn: 3,
            kind,
            primary_axis: axis,
            explanation: explanation.to_string(),
            confidence,
        }
    }

    #[test]
    fn no_divergences_produces_no_recommendations() {
        let out = generate(&empty_report());
        assert!(out.is_empty());
    }

    #[test]
    fn dropped_tool_becomes_restore_error() {
        let mut r = empty_report();
        r.divergences.push(divergence(
            DivergenceKind::Structural,
            Axis::Trajectory,
            "candidate dropped tool call(s): `send_confirmation_email(order_id,to)`",
            0.9,
        ));
        let recs = generate(&r);
        assert_eq!(recs.len(), 1);
        let rec = &recs[0];
        assert_eq!(rec.severity, RecommendationSeverity::Error);
        assert_eq!(rec.action, ActionKind::Restore);
        assert!(rec.message.contains("Restore"));
        assert!(rec.message.contains("send_confirmation_email"));
        assert_eq!(rec.turn, 3);
        // The mirror fields must agree with the legacy `turn` so existing
        // consumers stay valid, and `candidate_turn` must come from the
        // divergence (not be inferred from `turn`).
        assert_eq!(rec.baseline_turn, rec.turn);
        assert_eq!(rec.candidate_turn, 3);
    }

    #[test]
    fn baseline_turn_can_exceed_pair_count_when_candidate_dropped_turns() {
        // Repro for the schema gap: when the candidate has fewer
        // chat_responses than the baseline, the alignment surfaces a
        // divergence at a baseline index >= pair_count. The
        // recommendation's `turn` (== `baseline_turn`) follows the
        // baseline-side index — this is correct, but downstream tooling
        // that bounded turn-iteration by `pair_count` would miss the
        // dropped turn. The mirror fields make the semantics explicit.
        let mut r = empty_report();
        r.pair_count = 3; // candidate kept only 3 of 5 baseline turns
        r.divergences.push(FirstDivergence {
            baseline_turn: 4,
            candidate_turn: 2, // alignment insertion-point on the short side
            kind: DivergenceKind::Structural,
            primary_axis: Axis::Trajectory,
            explanation: "candidate dropped tool call(s): `send_email(to)`".to_string(),
            confidence: 0.9,
        });
        let recs = generate(&r);
        let rec = recs
            .iter()
            .find(|r| r.action == ActionKind::Restore)
            .unwrap();
        assert!(rec.baseline_turn >= r.pair_count);
        assert_eq!(rec.baseline_turn, 4);
        assert_eq!(rec.candidate_turn, 2);
        assert_eq!(rec.turn, rec.baseline_turn);
    }

    #[test]
    fn recommendation_serializes_with_both_turn_fields() {
        // Wire-format guard: both mirror fields must appear in the JSON
        // shape, and the legacy `turn` must remain present for
        // backward compatibility.
        let mut r = empty_report();
        r.divergences.push(divergence(
            DivergenceKind::Structural,
            Axis::Trajectory,
            "candidate dropped tool call(s): `x(y)`",
            0.9,
        ));
        let recs = generate(&r);
        let json = serde_json::to_value(&recs[0]).unwrap();
        assert!(json.get("turn").is_some());
        assert!(json.get("baseline_turn").is_some());
        assert!(json.get("candidate_turn").is_some());
    }

    #[test]
    fn duplicate_tool_becomes_remove_error() {
        let mut r = empty_report();
        r.divergences.push(divergence(
            DivergenceKind::Structural,
            Axis::Trajectory,
            "candidate called `lookup_order(order_id)` 2 time(s) vs baseline's 1 — duplicate tool invocation",
            0.5,
        ));
        let recs = generate(&r);
        assert_eq!(recs.len(), 1);
        let rec = &recs[0];
        assert_eq!(rec.severity, RecommendationSeverity::Error);
        assert_eq!(rec.action, ActionKind::Remove);
        assert!(rec.message.contains("Remove duplicate"));
        assert!(rec.message.contains("lookup_order"));
    }

    #[test]
    fn added_tool_becomes_review_error() {
        let mut r = empty_report();
        r.divergences.push(divergence(
            DivergenceKind::Structural,
            Axis::Trajectory,
            "candidate added tool call(s): `new_tool(arg)`",
            0.7,
        ));
        let recs = generate(&r);
        assert_eq!(recs.len(), 1);
        assert_eq!(recs[0].action, ActionKind::Review);
        assert_eq!(recs[0].severity, RecommendationSeverity::Error);
    }

    #[test]
    fn refusal_flip_to_content_filter_is_error() {
        let mut r = empty_report();
        r.divergences.push(divergence(
            DivergenceKind::Decision,
            Axis::Safety,
            "stop_reason changed: `end_turn` → `content_filter`",
            0.8,
        ));
        let recs = generate(&r);
        assert_eq!(recs.len(), 1);
        // content_filter → stricter treatment → Error, not Warning
        assert_eq!(recs[0].severity, RecommendationSeverity::Error);
        assert_eq!(recs[0].action, ActionKind::Review);
        assert!(recs[0].message.to_lowercase().contains("refusal"));
    }

    #[test]
    fn arg_value_change_becomes_revert_warning() {
        let mut r = empty_report();
        r.divergences.push(divergence(
            DivergenceKind::Decision,
            Axis::Trajectory,
            "tool arg value changed: `refund(amount)`: `99.99` → `9.99`",
            0.6,
        ));
        let recs = generate(&r);
        assert_eq!(recs.len(), 1);
        assert_eq!(recs[0].severity, RecommendationSeverity::Warning);
        assert_eq!(recs[0].action, ActionKind::Revert);
        assert!(recs[0].message.contains("Revert"));
        assert!(recs[0].message.contains("refund(amount)"));
    }

    #[test]
    fn semantic_decision_drift_becomes_review_warning() {
        let mut r = empty_report();
        r.divergences.push(divergence(
            DivergenceKind::Decision,
            Axis::Semantic,
            "response text diverged (text similarity 0.10); same tool sequence",
            0.6,
        ));
        let recs = generate(&r);
        assert_eq!(recs.len(), 1);
        assert_eq!(recs[0].severity, RecommendationSeverity::Warning);
        assert_eq!(recs[0].action, ActionKind::Review);
    }

    #[test]
    fn style_drift_becomes_verify_info() {
        let mut r = empty_report();
        r.divergences.push(divergence(
            DivergenceKind::Style,
            Axis::Semantic,
            "cosmetic wording change — tool sequence preserved",
            0.3,
        ));
        let recs = generate(&r);
        assert_eq!(recs.len(), 1);
        assert_eq!(recs[0].severity, RecommendationSeverity::Info);
        assert_eq!(recs[0].action, ActionKind::Verify);
    }

    #[test]
    fn sort_puts_errors_before_warnings_before_info() {
        let mut r = empty_report();
        r.divergences.push(divergence(
            DivergenceKind::Style,
            Axis::Semantic,
            "cosmetic wording change",
            0.9, // high confidence, but still Info
        ));
        r.divergences.push(divergence(
            DivergenceKind::Structural,
            Axis::Trajectory,
            "candidate dropped tool call(s): `x(y)`",
            0.2, // low confidence, but Error
        ));
        r.divergences.push(divergence(
            DivergenceKind::Decision,
            Axis::Trajectory,
            "tool arg value changed: `f(a)`: `1` → `2`",
            0.5,
        ));
        let recs = generate(&r);
        assert_eq!(recs.len(), 3);
        assert_eq!(recs[0].severity, RecommendationSeverity::Error);
        assert_eq!(recs[1].severity, RecommendationSeverity::Warning);
        assert_eq!(recs[2].severity, RecommendationSeverity::Info);
    }

    #[test]
    fn trace_wide_severe_axis_adds_fallback_recommendation() {
        // No divergences but one axis is severe — should produce a
        // trace-wide Review recommendation.
        let mut r = empty_report();
        let row = r
            .rows
            .iter_mut()
            .find(|a| a.axis == Axis::Semantic)
            .unwrap();
        row.delta = -0.6;
        row.baseline_median = 1.0;
        row.candidate_median = 0.4;
        row.ci95_low = -0.7;
        row.ci95_high = -0.5;
        row.severity = Severity::Severe;
        row.n = 20;
        let recs = generate(&r);
        assert_eq!(recs.len(), 1);
        assert_eq!(recs[0].severity, RecommendationSeverity::Error);
        assert_eq!(recs[0].action, ActionKind::Review);
        assert_eq!(recs[0].turn, 0);
        assert!(recs[0].message.contains("semantic"));
        assert!(recs[0].rationale.contains("severe"));
    }

    #[test]
    fn trace_wide_fallback_skipped_when_error_already_exists() {
        let mut r = empty_report();
        r.divergences.push(divergence(
            DivergenceKind::Structural,
            Axis::Trajectory,
            "candidate dropped tool call(s): `x(y)`",
            0.8,
        ));
        let row = r
            .rows
            .iter_mut()
            .find(|a| a.axis == Axis::Semantic)
            .unwrap();
        row.delta = -0.6;
        row.severity = Severity::Severe;
        row.n = 20;
        let recs = generate(&r);
        // Expect exactly ONE recommendation (from the Structural), not two.
        assert_eq!(recs.len(), 1);
        assert_eq!(recs[0].severity, RecommendationSeverity::Error);
    }

    #[test]
    fn output_capped_at_8() {
        let mut r = empty_report();
        for i in 0..15 {
            r.divergences.push(divergence(
                DivergenceKind::Decision,
                Axis::Trajectory,
                &format!("tool arg value changed: `f(a)`: `{i}` → `{}`", i + 1),
                0.5,
            ));
        }
        let recs = generate(&r);
        assert_eq!(recs.len(), 8);
    }

    #[test]
    fn extract_backticked_pulls_first_token() {
        assert_eq!(
            extract_backticked("before `first(token)` middle `second`"),
            Some("first(token)")
        );
        assert_eq!(extract_backticked("no backticks here"), None);
        assert_eq!(extract_backticked("`only-one`"), Some("only-one"));
    }

    #[test]
    fn severity_rank_ordering_is_error_above_warning_above_info() {
        assert!(RecommendationSeverity::Error.rank() > RecommendationSeverity::Warning.rank());
        assert!(RecommendationSeverity::Warning.rank() > RecommendationSeverity::Info.rank());
    }

    // ----------------------------------------------------------------
    // Cross-axis correlation pattern detection
    // ----------------------------------------------------------------

    fn force_axis_severe(report: &mut DiffReport, axis: Axis, delta: f64) {
        let row = report.rows.iter_mut().find(|a| a.axis == axis).unwrap();
        row.delta = delta;
        row.baseline_median = if delta < 0.0 { 1.0 } else { 0.0 };
        row.candidate_median = row.baseline_median + delta;
        row.ci95_low = delta - 0.05;
        row.ci95_high = delta + 0.05;
        row.severity = Severity::Severe;
        row.n = 20;
    }

    fn force_axis_moderate(report: &mut DiffReport, axis: Axis, delta: f64) {
        let row = report.rows.iter_mut().find(|a| a.axis == axis).unwrap();
        row.delta = delta;
        row.baseline_median = if delta < 0.0 { 1.0 } else { 0.0 };
        row.candidate_median = row.baseline_median + delta;
        row.ci95_low = delta - 0.05;
        row.ci95_high = delta + 0.05;
        row.severity = Severity::Moderate;
        row.n = 20;
    }

    #[test]
    fn model_swap_signature_emits_root_cause() {
        let mut r = empty_report();
        force_axis_moderate(&mut r, Axis::Cost, 0.6);
        force_axis_moderate(&mut r, Axis::Latency, 0.8);
        force_axis_moderate(&mut r, Axis::Semantic, -0.3);
        let recs = generate(&r);
        let model_swap_rec = recs
            .iter()
            .find(|r| r.action == ActionKind::RootCause && r.message.contains("model change"));
        assert!(
            model_swap_rec.is_some(),
            "model-swap signature should produce a root-cause recommendation; got {:#?}",
            recs
        );
        let rec = model_swap_rec.unwrap();
        assert_eq!(rec.severity, RecommendationSeverity::Error);
        assert!(rec.rationale.contains("cost"));
        assert!(rec.rationale.contains("latency"));
        assert!(rec.rationale.contains("semantic"));
    }

    #[test]
    fn prompt_drift_signature_fires_when_only_two_axes_move() {
        let mut r = empty_report();
        force_axis_moderate(&mut r, Axis::Semantic, -0.2);
        force_axis_moderate(&mut r, Axis::Verbosity, 0.4);
        // Cost and latency NOT moved — should NOT fire model_swap.
        let recs = generate(&r);
        let prompt_rec = recs
            .iter()
            .find(|r| r.action == ActionKind::RootCause && r.message.contains("prompt"));
        assert!(prompt_rec.is_some());
        let no_model = recs
            .iter()
            .all(|r| !(r.action == ActionKind::RootCause && r.message.contains("model change")));
        assert!(no_model, "prompt-drift should not also fire model_swap");
    }

    #[test]
    fn prompt_drift_suppressed_when_model_swap_already_fires() {
        let mut r = empty_report();
        force_axis_moderate(&mut r, Axis::Cost, 0.5);
        force_axis_moderate(&mut r, Axis::Latency, 0.7);
        force_axis_moderate(&mut r, Axis::Semantic, -0.3);
        force_axis_moderate(&mut r, Axis::Verbosity, 0.4);
        let recs = generate(&r);
        let n_root_cause = recs
            .iter()
            .filter(|r| r.action == ActionKind::RootCause)
            .count();
        // Exactly one root-cause should fire (model swap subsumes prompt
        // drift when both signatures match — the model swap is the
        // upstream explanation).
        let n_model = recs
            .iter()
            .filter(|r| r.action == ActionKind::RootCause && r.message.contains("model change"))
            .count();
        let n_prompt = recs
            .iter()
            .filter(|r| r.action == ActionKind::RootCause && r.message.contains("prompt"))
            .count();
        assert_eq!(n_model, 1);
        assert_eq!(
            n_prompt, 0,
            "prompt drift should be suppressed; got {n_root_cause} root-causes"
        );
    }

    #[test]
    fn refusal_escalation_fires_on_severe_safety_with_positive_delta() {
        let mut r = empty_report();
        force_axis_severe(&mut r, Axis::Safety, 0.4); // refusal rate up 40%
        let recs = generate(&r);
        let refusal_rec = recs
            .iter()
            .find(|r| r.action == ActionKind::RootCause && r.message.contains("Refusal rate"));
        assert!(refusal_rec.is_some(), "got {:#?}", recs);
        assert_eq!(refusal_rec.unwrap().severity, RecommendationSeverity::Error);
    }

    #[test]
    fn refusal_escalation_does_not_fire_on_negative_safety_delta() {
        // Refusal rate DROPPED — that's the candidate refusing less,
        // which isn't a "stricter instructions" signature.
        let mut r = empty_report();
        force_axis_severe(&mut r, Axis::Safety, -0.4);
        let recs = generate(&r);
        let refusal_rec = recs
            .iter()
            .find(|r| r.action == ActionKind::RootCause && r.message.contains("Refusal rate"));
        assert!(refusal_rec.is_none());
    }

    #[test]
    fn tool_schema_migration_fires_on_severe_trajectory_plus_reasoning() {
        let mut r = empty_report();
        force_axis_severe(&mut r, Axis::Trajectory, 0.5);
        force_axis_moderate(&mut r, Axis::Reasoning, 0.3);
        let recs = generate(&r);
        let tool_rec = recs
            .iter()
            .find(|r| r.action == ActionKind::RootCause && r.message.contains("tool-schema"));
        assert!(tool_rec.is_some(), "got {:#?}", recs);
    }

    #[test]
    fn hallucination_cluster_fires_on_semantic_plus_judge() {
        let mut r = empty_report();
        force_axis_moderate(&mut r, Axis::Semantic, -0.3);
        force_axis_moderate(&mut r, Axis::Judge, -0.4);
        let recs = generate(&r);
        let halluc_rec = recs
            .iter()
            .find(|r| r.action == ActionKind::RootCause && r.message.contains("hallucination"));
        assert!(halluc_rec.is_some(), "got {:#?}", recs);
        assert_eq!(halluc_rec.unwrap().severity, RecommendationSeverity::Error);
    }

    #[test]
    fn single_axis_movement_triggers_at_most_one_root_cause() {
        // v2.7+ semantics: pattern #10 (latency-spike-without-cost) is
        // explicitly a single-axis pattern. The invariant is no longer
        // "zero root-causes on single-axis" but "at most one." The
        // property test below covers this for every axis; this test
        // pins the latency-only path specifically.
        let mut r = empty_report();
        force_axis_severe(&mut r, Axis::Trajectory, 0.7);
        let recs = generate(&r);
        let n_root = recs
            .iter()
            .filter(|r| r.action == ActionKind::RootCause)
            .count();
        assert!(
            n_root <= 1,
            "single-axis trajectory fired {n_root} root-causes: {recs:#?}"
        );
    }

    #[test]
    fn root_cause_action_label_is_root_cause() {
        assert_eq!(ActionKind::RootCause.label(), "root_cause");
    }

    // ----------------------------------------------------------------
    // v2.7+ extended cross-axis patterns (6-10)
    // ----------------------------------------------------------------

    #[test]
    fn context_window_overflow_fires_on_severe_cost_plus_reasoning() {
        let mut r = empty_report();
        force_axis_severe(&mut r, Axis::Cost, 0.7);
        force_axis_moderate(&mut r, Axis::Reasoning, -0.4);
        let recs = generate(&r);
        let context_rec = recs
            .iter()
            .find(|r| r.action == ActionKind::RootCause && r.message.contains("context-window"));
        assert!(context_rec.is_some(), "got {:#?}", recs);
    }

    #[test]
    fn context_window_suppressed_when_model_swap_explains_cost() {
        let mut r = empty_report();
        // Trigger model swap: cost + latency + semantic.
        force_axis_severe(&mut r, Axis::Cost, 0.7);
        force_axis_moderate(&mut r, Axis::Latency, 0.5);
        force_axis_moderate(&mut r, Axis::Semantic, -0.3);
        force_axis_moderate(&mut r, Axis::Reasoning, -0.4);
        let recs = generate(&r);
        let n_model = recs
            .iter()
            .filter(|r| r.action == ActionKind::RootCause && r.message.contains("model change"))
            .count();
        let n_context = recs
            .iter()
            .filter(|r| r.action == ActionKind::RootCause && r.message.contains("context-window"))
            .count();
        assert_eq!(n_model, 1);
        assert_eq!(
            n_context, 0,
            "context-window should be suppressed; got {:#?}",
            recs
        );
    }

    #[test]
    fn retry_loop_fires_on_severe_trajectory_plus_latency_without_reasoning() {
        let mut r = empty_report();
        force_axis_severe(&mut r, Axis::Trajectory, 0.5);
        force_axis_moderate(&mut r, Axis::Latency, 0.4);
        // Reasoning explicitly NOT moved
        let recs = generate(&r);
        let retry_rec = recs
            .iter()
            .find(|r| r.action == ActionKind::RootCause && r.message.contains("retry loop"));
        assert!(retry_rec.is_some(), "got {:#?}", recs);
    }

    #[test]
    fn retry_loop_suppressed_when_tool_schema_explains_trajectory() {
        let mut r = empty_report();
        force_axis_severe(&mut r, Axis::Trajectory, 0.5);
        force_axis_moderate(&mut r, Axis::Reasoning, 0.3);
        force_axis_moderate(&mut r, Axis::Latency, 0.4);
        let recs = generate(&r);
        let n_schema = recs
            .iter()
            .filter(|r| r.action == ActionKind::RootCause && r.message.contains("tool-schema"))
            .count();
        let n_retry = recs
            .iter()
            .filter(|r| r.action == ActionKind::RootCause && r.message.contains("retry loop"))
            .count();
        assert_eq!(n_schema, 1);
        assert_eq!(n_retry, 0);
    }

    #[test]
    fn cost_explosion_cached_mismatch_fires_on_severe_cost_with_stable_latency_and_semantic() {
        let mut r = empty_report();
        force_axis_severe(&mut r, Axis::Cost, 0.6);
        // Latency + semantic explicitly NOT moved
        let recs = generate(&r);
        let cache_rec = recs
            .iter()
            .find(|r| r.action == ActionKind::RootCause && r.message.contains("cache control"));
        assert!(cache_rec.is_some(), "got {:#?}", recs);
    }

    #[test]
    fn prompt_injection_fires_on_severe_trajectory_plus_negative_safety() {
        let mut r = empty_report();
        force_axis_severe(&mut r, Axis::Trajectory, 0.5);
        force_axis_moderate(&mut r, Axis::Safety, -0.4); // refusing LESS
        let recs = generate(&r);
        let inj_rec = recs
            .iter()
            .find(|r| r.action == ActionKind::RootCause && r.message.contains("prompt-injection"));
        assert!(inj_rec.is_some(), "got {:#?}", recs);
    }

    #[test]
    fn prompt_injection_does_not_fire_on_positive_safety_delta() {
        // Positive safety delta = stricter, which is refusal-escalation, not injection.
        let mut r = empty_report();
        force_axis_severe(&mut r, Axis::Trajectory, 0.5);
        force_axis_moderate(&mut r, Axis::Safety, 0.4);
        let recs = generate(&r);
        let inj_rec = recs
            .iter()
            .find(|r| r.action == ActionKind::RootCause && r.message.contains("prompt-injection"));
        assert!(inj_rec.is_none());
    }

    #[test]
    fn latency_spike_without_cost_fires_on_severe_latency_alone() {
        let mut r = empty_report();
        force_axis_severe(&mut r, Axis::Latency, 0.6);
        // Cost + semantic explicitly NOT moved
        let recs = generate(&r);
        let lat_rec = recs.iter().find(|r| {
            r.action == ActionKind::RootCause && r.message.contains("Provider-side capacity")
        });
        assert!(lat_rec.is_some(), "got {:#?}", recs);
    }

    #[test]
    fn latency_spike_suppressed_when_model_swap_explains_it() {
        let mut r = empty_report();
        // Model swap pattern subsumes latency-only.
        force_axis_severe(&mut r, Axis::Cost, 0.5);
        force_axis_severe(&mut r, Axis::Latency, 0.6);
        force_axis_moderate(&mut r, Axis::Semantic, -0.3);
        let recs = generate(&r);
        let n_model = recs
            .iter()
            .filter(|r| r.action == ActionKind::RootCause && r.message.contains("model change"))
            .count();
        let n_lat_alone = recs
            .iter()
            .filter(|r| {
                r.action == ActionKind::RootCause && r.message.contains("Provider-side capacity")
            })
            .count();
        assert_eq!(n_model, 1);
        assert_eq!(n_lat_alone, 0);
    }

    /// Property test: across every fixture combination of single-axis
    /// movements at moderate-or-severe, no two ROOT-CAUSE patterns can
    /// claim the same single piece of evidence — ie when only one axis
    /// is moved, at most ONE root-cause should fire (or zero).
    #[test]
    fn no_two_root_causes_fire_on_single_axis_movement() {
        for axis in [
            Axis::Semantic,
            Axis::Trajectory,
            Axis::Safety,
            Axis::Verbosity,
            Axis::Latency,
            Axis::Cost,
            Axis::Reasoning,
            Axis::Judge,
            Axis::Conformance,
        ] {
            let mut r = empty_report();
            force_axis_severe(&mut r, axis, 0.5);
            let recs = generate(&r);
            let n_root = recs
                .iter()
                .filter(|r| r.action == ActionKind::RootCause)
                .count();
            assert!(
                n_root <= 1,
                "single-axis severe on {axis:?} fired {n_root} root-causes; \
                 patterns must be mutually exclusive on the same single-axis evidence: {recs:#?}"
            );
        }
    }
}