terraphim_orchestrator 1.20.2

AI Dark Factory orchestrator wiring spawner, router, supervisor into a reconciliation loop
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
//! Polling helpers for ROC v1 Step F — turn open PRs + reviewer comments into
//! [`crate::dispatcher::DispatchTask::AutoMerge`] tasks.
//!
//! The orchestrator invokes [`crate::AgentOrchestrator::poll_pending_reviews`] once
//! per `reconcile_tick`. That method walks every project with a Gitea config,
//! lists open PRs, looks for the latest structural-pr-review comment, calls
//! [`crate::pr_review::parse_verdict`] + [`crate::pr_review::evaluate`], and
//! enqueues a [`crate::dispatcher::DispatchTask::AutoMerge`] when — and only when — every gate
//! in [`crate::pr_review::AutoMergeCriteria::default`] is satisfied.
//!
//! The module is split into:
//!
//! - [`PrSummary`] / [`PrComment`]: transport types decoupled from the Gitea
//!   client so integration tests can supply in-memory fixtures.
//! - [`PrTracker`]: async trait with one real implementation
//!   ([`GiteaPrTracker`]) wrapping [`terraphim_tracker::GiteaTracker`] and any
//!   number of in-memory test implementations.
//! - [`evaluate_pr_verdict`]: pure function that turns a [`PrSummary`] + the
//!   latest [`PrComment`] into an [`EvaluationOutcome`] (parse, evaluate,
//!   classify). Extracted so tests drive it without any dispatcher state.
//! - [`PrPollRateLimiter`] / [`AutoMergeDedupeSet`]: in-memory guards that
//!   keep the poller from hammering Gitea and from double-enqueuing the same
//!   (PR, head-SHA).
//!
//! See `cto-executive-system/plans/adf-rate-of-change-design.md` §Step F and
//! Gitea issue `terraphim/adf-fleet#34`.

use std::collections::{HashMap, HashSet};
use std::time::{Duration, Instant};

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

use crate::pr_review::{
    self, AutoMergeCriteria, AutoMergeDecision, PrMetadata, ReviewVerdict, VerdictParseError,
};

/// Login that identifies the structural-pr-review agent.
///
/// Reviewer comments not authored by this login are ignored even if they
/// contain a `Last reviewed commit:` footer, so a human comment with the
/// same shape cannot accidentally trigger auto-merge.
pub const PR_REVIEWER_LOGIN: &str = "pr-reviewer";

/// Minimum interval between polls of the same PR. Prevents the reconcile
/// loop from re-hitting Gitea for the same PR every tick when the tick
/// cadence is short (<60s).
pub const PR_POLL_MIN_INTERVAL: Duration = Duration::from_secs(60);

/// Summary of an open pull request, decoupled from [`terraphim_tracker`] so
/// that tests can construct it without a live Gitea server.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PrSummary {
    pub number: u64,
    pub author_login: String,
    pub head_sha: String,
    pub base_ref: String,
    pub diff_loc: u32,
}

/// Single comment on a pull request. Only the fields needed for verdict
/// parsing are captured; the full Gitea payload is deliberately not mirrored.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PrComment {
    pub id: u64,
    pub user_login: String,
    pub body: String,
    /// RFC3339-ish `updated_at` string from the Gitea API. Used only for
    /// ordering; comments without a timestamp sort as the earliest.
    pub updated_at: String,
}

/// Read-side abstraction over an issue-tracker capable of answering the two
/// questions the poller asks: "what PRs are open?" and "what comments does
/// PR N carry?". Kept minimal so the test impl stays trivial.
#[async_trait]
pub trait PrTracker: Send + Sync {
    async fn list_open_prs(&self) -> Result<Vec<PrSummary>, String>;
    async fn fetch_pr_comments(&self, pr_number: u64) -> Result<Vec<PrComment>, String>;

    /// Commit statuses posted on `head_sha` for `pr_number`. The default impl
    /// returns an empty list (no statuses) so existing in-memory trackers keep
    /// working unchanged and the status layer is a no-op for them. `pr_number`
    /// is passed for trackers that key on the PR rather than the SHA; the Gitea
    /// implementation keys on `head_sha`.
    async fn list_head_commit_statuses(
        &self,
        _pr_number: u64,
        _head_sha: &str,
    ) -> Result<Vec<crate::pr_gate::CommitStatusSummary>, String> {
        Ok(Vec::new())
    }
}

/// Outcome of a successful merge call, decoupled from
/// [`terraphim_tracker::GiteaMergeResult`] so the orchestrator handler can
/// be driven by in-memory test implementations without pulling the tracker
/// concrete types into test code.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MergeOutcome {
    pub pr_number: u64,
    pub merge_commit_sha: String,
    pub title: String,
}

/// Write-side abstraction used by the AutoMerge handler (ROC v1 Step G).
///
/// Re-uses [`PrTracker::list_open_prs`] for the defensive head-SHA re-check
/// and adds two writer methods: `merge_pr` (actually merge the PR) and
/// `open_failure_issue` (record an `[ADF]` tracking issue when the merge
/// call fails). Test impls are plain structs that record calls — no mock
/// frameworks involved.
#[async_trait]
pub trait AutoMergeExecutor: PrTracker {
    /// Merge `pr_number` on the project this executor is scoped to.
    ///
    /// The real Gitea implementation does a standard merge with branch
    /// deletion; the style/flag choice is intentionally not parameterised
    /// here — it is a per-project policy baked into the impl.
    async fn merge_pr(&self, pr_number: u64) -> Result<MergeOutcome, String>;

    /// Create an `[ADF]` tracking issue describing a merge failure so a
    /// human can follow up. Returns the newly created issue number.
    async fn open_failure_issue(
        &self,
        title: &str,
        body: &str,
        labels: &[&str],
    ) -> Result<u64, String>;
}

/// Real [`PrTracker`] backed by [`terraphim_tracker::GiteaTracker`].
pub struct GiteaPrTracker {
    inner: terraphim_tracker::GiteaTracker,
}

impl GiteaPrTracker {
    pub fn new(inner: terraphim_tracker::GiteaTracker) -> Self {
        Self { inner }
    }
}

#[async_trait]
impl PrTracker for GiteaPrTracker {
    async fn list_open_prs(&self) -> Result<Vec<PrSummary>, String> {
        self.inner
            .list_open_prs()
            .await
            .map(|v| {
                v.into_iter()
                    .map(|p| PrSummary {
                        number: p.number,
                        author_login: p.author_login,
                        head_sha: p.head_sha,
                        base_ref: p.base_ref,
                        diff_loc: p.diff_loc,
                    })
                    .collect()
            })
            .map_err(|e| e.to_string())
    }

    async fn fetch_pr_comments(&self, pr_number: u64) -> Result<Vec<PrComment>, String> {
        self.inner
            .fetch_comments(pr_number, None)
            .await
            .map(|v| {
                v.into_iter()
                    .map(|c| PrComment {
                        id: c.id,
                        user_login: c.user.login,
                        body: c.body,
                        updated_at: c.updated_at,
                    })
                    .collect()
            })
            .map_err(|e| e.to_string())
    }

    async fn list_head_commit_statuses(
        &self,
        _pr_number: u64,
        head_sha: &str,
    ) -> Result<Vec<crate::pr_gate::CommitStatusSummary>, String> {
        let owner = self.inner.owner().to_string();
        let repo = self.inner.repo().to_string();
        self.inner
            .list_commit_statuses(&owner, &repo, head_sha)
            .await
            .map(|v| {
                v.into_iter()
                    .map(|s| crate::pr_gate::CommitStatusSummary {
                        context: s.context,
                        state: crate::pr_gate::CommitStatusState::from_api_str(&s.state),
                        created_at_unix: parse_rfc3339_to_unix(s.created_at.as_deref()),
                    })
                    .collect()
            })
            .map_err(|e| e.to_string())
    }
}

#[async_trait]
impl AutoMergeExecutor for GiteaPrTracker {
    async fn merge_pr(&self, pr_number: u64) -> Result<MergeOutcome, String> {
        self.inner
            .merge_pull(pr_number, terraphim_tracker::MergeStyle::Merge, true)
            .await
            .map(|r| MergeOutcome {
                pr_number: r.pr_number,
                merge_commit_sha: r.merge_commit_sha,
                title: r.title,
            })
            .map_err(|e| e.to_string())
    }

    async fn open_failure_issue(
        &self,
        title: &str,
        body: &str,
        labels: &[&str],
    ) -> Result<u64, String> {
        self.inner
            .create_issue(title, body, labels)
            .await
            .map(|i| i.number)
            .map_err(|e| e.to_string())
    }
}

/// Outcome of applying the auto-merge policy to a single PR.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EvaluationOutcome {
    /// Every gate cleared; the caller should enqueue [`crate::dispatcher::DispatchTask::AutoMerge`].
    Merge { head_sha: String },
    /// At least one gate failed. The reason is a short human-readable string
    /// suitable for logging or posting back to the PR.
    HumanReviewNeeded { reason: String },
    /// Below-threshold confidence with no P0 findings and an otherwise clean
    /// gate (CONDITIONAL). Eligible for a bounded autonomous remediation loop
    /// (Gitea terraphim-ai#2264). `verdict_excerpt` is the verbatim reviewer
    /// Findings section so the fix-agent reads it as a read-only input
    /// contract; `confidence` is the coordinator confidence that gated the PR.
    Remediate {
        head_sha: String,
        reason: String,
        verdict_excerpt: String,
        confidence: u8,
    },
    /// No pr-reviewer comment found yet — nothing to evaluate this tick.
    NoReviewerComment,
    /// A reviewer comment exists but did not parse as a structural verdict.
    ParseError { reason: String },
    /// A reviewer verdict exists and parses, but its `Last reviewed commit:`
    /// footer does not match the PR head — the review is stale. The poller must
    /// NOT merge and must NOT remediate; it treats the head as un-reviewed
    /// (awaiting a fresh review). Distinct from [`Self::HumanReviewNeeded`] so
    /// the staleness reason is logged and gated separately (Gitea
    /// terraphim-ai#2275).
    StaleReview { reviewed: String, head: String },
}

/// Return `true` when `comment.user_login == PR_REVIEWER_LOGIN` **or** the
/// body carries the canonical `Last reviewed commit:` footer emitted by the
/// structural-pr-review skill. The footer fallback lets the poller pick up
/// comments posted by agents running under an alternative login during
/// migration.
pub fn is_pr_reviewer_comment(comment: &PrComment) -> bool {
    if comment.user_login == PR_REVIEWER_LOGIN {
        return true;
    }
    comment.body.contains("Last reviewed commit:") && !is_non_reviewer_agent_comment(&comment.body)
}

/// Known heading prefixes emitted by non-reviewer ADF agents (security,
/// audit, traceability). Used to exclude comments that contain the
/// `Last reviewed commit:` footer but are not structural-pr-review output.
const NON_REVIEWER_HEADING_PREFIXES: &[&str] = &[
    "security_checklist Summary",
    "Security Audit Summary",
    "Requirements Traceability Summary",
    "Quality Gate Report",
];

/// Return `true` when the comment body starts with a known non-reviewer
/// agent heading, indicating it was produced by a different ADF skill.
fn is_non_reviewer_agent_comment(body: &str) -> bool {
    let trimmed = body.trim();
    for prefix in NON_REVIEWER_HEADING_PREFIXES {
        if trimmed.starts_with(prefix) {
            return true;
        }
    }
    false
}

/// Return the latest [`PrComment`] authored by the pr-reviewer, or `None`
/// when there is no such comment. "Latest" is `updated_at` ordering with
/// comment id as a tie-break.
pub fn latest_reviewer_comment(comments: &[PrComment]) -> Option<&PrComment> {
    comments
        .iter()
        .filter(|c| is_pr_reviewer_comment(c))
        .max_by(|a, b| {
            a.updated_at
                .cmp(&b.updated_at)
                .then_with(|| a.id.cmp(&b.id))
        })
}

/// Pure evaluator: given a PR + its comments + the merge policy, decide
/// whether to enqueue an auto-merge, ask for human review, or report a
/// parsing issue.
pub fn evaluate_pr_verdict(
    pr: &PrSummary,
    comments: &[PrComment],
    head_statuses: &[crate::pr_gate::CommitStatusSummary],
    criteria: &AutoMergeCriteria,
    required_contexts: &[String],
) -> EvaluationOutcome {
    use crate::pr_gate::{self, PrGateDecision, PrGateSnapshot};

    // 1. Status layer (no-op when `required_contexts` is empty -- reconcile_pr_gate
    //    returns ReadyForPolicy for an empty required set). Checked FIRST so a
    //    missing required status blocks before any comment parsing.
    let snapshot = PrGateSnapshot {
        pr_number: pr.number,
        head_sha: pr.head_sha.clone(),
        base_branch: pr.base_ref.clone(),
        required_contexts: required_contexts.to_vec(),
        head_statuses: head_statuses.to_vec(),
        // Staleness in this path is handled by missing/pending -> not Ready, so
        // a `now_unix` of 0 deliberately never trips the stale-pending timeout.
        now_unix: 0,
    };
    match pr_gate::reconcile_pr_gate(&snapshot) {
        PrGateDecision::ReadyForPolicy => { /* fall through to the structural layer */ }
        PrGateDecision::EnqueueMissingChecks { missing } => {
            return EvaluationOutcome::HumanReviewNeeded {
                reason: format!(
                    "required status(es) not posted on head: {}",
                    missing.join(", ")
                ),
            };
        }
        PrGateDecision::AwaitingChecks { pending } => {
            return EvaluationOutcome::HumanReviewNeeded {
                reason: format!(
                    "required status(es) still pending on head: {}",
                    pending.join(", ")
                ),
            };
        }
        PrGateDecision::BlockedByFailedChecks { failed } => {
            return EvaluationOutcome::HumanReviewNeeded {
                reason: format!(
                    "required status(es) failed on head: {}",
                    failed
                        .iter()
                        .map(|(c, s)| format!("{c}={s}"))
                        .collect::<Vec<_>>()
                        .join(", ")
                ),
            };
        }
        PrGateDecision::FactoryFault { error } => {
            return EvaluationOutcome::HumanReviewNeeded {
                reason: format!("status-gate fault: {error}"),
            };
        }
    }

    // 2. Structural layer (existing).
    let Some(latest) = latest_reviewer_comment(comments) else {
        return EvaluationOutcome::NoReviewerComment;
    };

    let verdict: ReviewVerdict = match pr_review::parse_verdict(&latest.body, latest.id) {
        Ok(v) => v,
        Err(e) => {
            return EvaluationOutcome::ParseError {
                reason: describe_parse_error(e),
            };
        }
    };

    // 2b. Structural SHA-bind (Gitea terraphim-ai#2275): the verdict footer's
    //     `commit_short_hash` must be a prefix of the current head, else the
    //     review is stale. Returns the distinct `StaleReview` outcome so the
    //     caller logs it separately and it is gated out of BOTH the merge and
    //     remediation paths (a stale verdict must not falsely merge, and a
    //     stale below-threshold verdict must not be treated as remediable).
    if !head_matches_footer(&pr.head_sha, &verdict.commit_short_hash) {
        return EvaluationOutcome::StaleReview {
            reviewed: verdict.commit_short_hash.clone(),
            head: pr.head_sha.clone(),
        };
    }

    let metadata = PrMetadata {
        pr_number: pr.number,
        author_login: pr.author_login.clone(),
        diff_loc: pr.diff_loc,
        head_sha: pr.head_sha.clone(),
        base_branch: pr.base_ref.clone(),
    };

    match pr_review::evaluate(&verdict, &metadata, criteria) {
        AutoMergeDecision::Merge => EvaluationOutcome::Merge {
            head_sha: pr.head_sha.clone(),
        },
        AutoMergeDecision::HumanReviewNeeded(reason) => {
            // CONDITIONAL classification (Gitea terraphim-ai#2264): a
            // below-threshold confidence with NO P0 findings, where the
            // confidence gate was the failing one, is remediable. The
            // confidence check is FIRST in `pr_review::evaluate`, so when
            // `confidence < min_confidence` the returned reason is the
            // confidence reason and no earlier gate fired. We additionally
            // re-assert `p0_count == 0` defensively. Every other failure
            // (P0, P1-over-cap, unchecked criteria, diff-cap, non-agent
            // author, status failure, stale review) stays HumanReviewNeeded.
            let remediable = verdict.confidence < criteria.min_confidence && verdict.p0_count == 0;
            if remediable {
                EvaluationOutcome::Remediate {
                    head_sha: pr.head_sha.clone(),
                    reason,
                    verdict_excerpt: findings_excerpt(&latest.body),
                    confidence: verdict.confidence,
                }
            } else {
                EvaluationOutcome::HumanReviewNeeded { reason }
            }
        }
    }
}

/// Maximum size of a verdict excerpt carried on [`EvaluationOutcome::Remediate`]
/// so the remediation trigger comment stays bounded.
const VERDICT_EXCERPT_CAP: usize = 16 * 1024;

/// Slice the verbatim `Inline Findings` section out of a reviewer comment
/// body for delivery to the fix-agent (Gitea terraphim-ai#2264, research R4).
///
/// The P0/P1/P2 parser counts finding lines only and never extracts their
/// text, so the fix-agent must receive the raw reviewer body. This helper
/// returns everything from the `Inline Findings` (or `Findings`) heading to
/// the end of the body, tolerating HTML `<h3>` and markdown `###` headings.
/// When no heading is found it falls back to the whole body. The result is
/// capped at [`VERDICT_EXCERPT_CAP`] bytes (on a char boundary) to keep the
/// trigger comment bounded.
fn findings_excerpt(body: &str) -> String {
    const HEADINGS: &[&str] = &[
        "<h3>Inline Findings</h3>",
        "<h3>Findings</h3>",
        "### Inline Findings",
        "### Findings",
    ];
    let start = HEADINGS
        .iter()
        .filter_map(|h| body.find(h))
        .min()
        .unwrap_or(0);
    // Stop the excerpt before the `Last reviewed commit:` footer. Carrying
    // that footer verbatim into the trigger comment would make
    // `is_pr_reviewer_comment` misclassify the orchestrator's trigger as a
    // structural verdict (research R2). The findings text precedes the footer,
    // so trimming it loses no finding content.
    let mut slice = &body[start..];
    if let Some(footer_at) = slice.find("Last reviewed commit:") {
        // Trim back to just before the enclosing `<sub>` tag when present so
        // no dangling markup is left.
        let cut = slice[..footer_at].rfind("<sub>").unwrap_or(footer_at);
        slice = slice[..cut].trim_end();
    }
    if slice.len() <= VERDICT_EXCERPT_CAP {
        return slice.to_string();
    }
    // Truncate on a char boundary at or below the cap.
    let mut end = VERDICT_EXCERPT_CAP;
    while end > 0 && !slice.is_char_boundary(end) {
        end -= 1;
    }
    slice[..end].to_string()
}

/// True when either SHA string is a case-insensitive prefix of the other and
/// the shorter is at least 7 chars (git short-SHA floor). Empty or too-short
/// inputs return `false`.
///
/// Used to bind the structural verdict's `Last reviewed commit:` footer
/// (`commit_short_hash`, typically 7-8 chars) to the PR's current `head_sha`
/// (which may be a full 40-char SHA), closing the latent stale-review gap
/// (research §2.2).
/// True when `footer` (a short or full git hash) is a case-insensitive prefix
/// of the full `head` SHA. An empty (or whitespace-only) footer never matches.
///
/// Unlike [`sha_prefix_matches`] (bidirectional, with a 7-char floor), this is
/// the direct head-binds-footer test the verdict gate uses: `PrSummary::head_sha`
/// is the full 40-char SHA and the verdict footer is its short prefix, so a
/// one-directional `head.starts_with(footer)` is the correct, intent-revealing
/// check for the staleness gate (Gitea terraphim-ai#2275).
pub fn head_matches_footer(head: &str, footer: &str) -> bool {
    let f = footer.trim();
    !f.is_empty()
        && head
            .to_ascii_lowercase()
            .starts_with(&f.to_ascii_lowercase())
}

pub fn sha_prefix_matches(footer_short: &str, head: &str) -> bool {
    let a = footer_short.trim().to_lowercase();
    let b = head.trim().to_lowercase();
    if a.len() < 7 || b.len() < 7 {
        return false;
    }
    let (short, long) = if a.len() <= b.len() {
        (&a, &b)
    } else {
        (&b, &a)
    };
    long.starts_with(short.as_str())
}

/// Parse an RFC3339 timestamp string into a Unix timestamp (seconds), or
/// `None` when the input is absent or unparseable.
///
/// The decoupled `reconcile_pr_gates` path historically parsed the Gitea
/// `created_at` string as an i64 directly (always yielding `None`); this
/// helper parses it correctly so the new verdict-poll status layer carries a
/// real timestamp. The legacy reconcile line is left untouched (out of scope
/// for #2116).
pub fn parse_rfc3339_to_unix(created_at: Option<&str>) -> Option<i64> {
    let raw = created_at?;
    chrono::DateTime::parse_from_rfc3339(raw)
        .ok()
        .map(|dt| dt.timestamp())
}

fn describe_parse_error(err: VerdictParseError) -> String {
    match err {
        VerdictParseError::MissingConfidence => "missing confidence score header".to_string(),
        VerdictParseError::ConfidenceOutOfRange(n) => {
            format!("confidence {n}/5 out of range (expected 1..=5)")
        }
        VerdictParseError::MissingFindings => "missing Inline Findings section".to_string(),
        VerdictParseError::MalformedFooter => {
            "malformed `Last reviewed commit:` footer".to_string()
        }
    }
}

/// Per-(project, PR) rate limiter used to cap how often the poller hits
/// Gitea for the same pull request. In-memory only; restarts reset the
/// cadence, which is acceptable given the 60-second floor.
#[derive(Debug, Default)]
pub struct PrPollRateLimiter {
    last_poll: HashMap<(String, u64), Instant>,
    min_interval: Duration,
}

impl PrPollRateLimiter {
    pub fn new(min_interval: Duration) -> Self {
        Self {
            last_poll: HashMap::new(),
            min_interval,
        }
    }

    /// Return `true` when enough time has elapsed since the last poll for
    /// `(project, pr_number)` — and mark the slot as just-polled. Concurrent
    /// callers are serialised by `&mut self`.
    pub fn allow(&mut self, project: &str, pr_number: u64, now: Instant) -> bool {
        let key = (project.to_string(), pr_number);
        if let Some(prev) = self.last_poll.get(&key)
            && now.duration_since(*prev) < self.min_interval
        {
            return false;
        }
        self.last_poll.insert(key, now);
        true
    }
}

/// Per-project dedupe set over `(pr_number, head_sha)` so the same revision
/// of a PR never yields two auto-merge tasks across ticks.
#[derive(Debug, Default)]
pub struct AutoMergeDedupeSet {
    by_project: HashMap<String, HashSet<(u64, String)>>,
}

impl AutoMergeDedupeSet {
    pub fn new() -> Self {
        Self::default()
    }

    /// Record `(pr_number, head_sha)` for `project`. Returns `true` when
    /// this was a fresh entry (caller should enqueue), `false` when it had
    /// already been recorded (caller must skip).
    pub fn record_if_new(&mut self, project: &str, pr_number: u64, head_sha: &str) -> bool {
        self.by_project
            .entry(project.to_string())
            .or_default()
            .insert((pr_number, head_sha.to_string()))
    }

    /// Return `true` when `(project, pr_number, head_sha)` has already
    /// been recorded. Used for observability (integration tests) and for
    /// the AutoMerge handler's defensive dedupe write.
    pub fn contains(&self, project: &str, pr_number: u64, head_sha: &str) -> bool {
        self.by_project
            .get(project)
            .is_some_and(|s| s.contains(&(pr_number, head_sha.to_string())))
    }

    /// Snapshot the `(pr, head_sha)` set for ONE project (Gitea
    /// terraphim-ai#2285 persistence). Empty when the project is unknown.
    pub fn snapshot_for(&self, project: &str) -> HashSet<(u64, String)> {
        self.by_project.get(project).cloned().unwrap_or_default()
    }

    /// Merge a loaded `(pr, head_sha)` set into the in-memory state for ONE
    /// project (restore-on-startup). Existing entries are preserved.
    pub fn restore_for(&mut self, project: &str, set: HashSet<(u64, String)>) {
        if set.is_empty() {
            return;
        }
        self.by_project
            .entry(project.to_string())
            .or_default()
            .extend(set);
    }
}

/// Per-(project, PR) remediation accounting (Gitea terraphim-ai#2264).
///
/// Keyed WITHOUT the head SHA so attempts accumulate across fix revisions (a
/// successful fix changes the head SHA). In-memory; resets on restart, which
/// is acceptable because the confidence-not-improving guard is the primary
/// thrash defence and this counter is a coarse backstop. The recorded
/// `last_confidence` is the latest below-threshold coordinator confidence
/// captured at dispatch time.
#[derive(Debug, Default)]
pub struct RemediationAttempts {
    by_project: HashMap<String, HashMap<u64, AttemptState>>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
struct AttemptState {
    count: u32,
    last_confidence: u8,
}

/// Persisted per-PR remediation attempt state (Gitea terraphim-ai#2285).
/// Public mirror of the private [`AttemptState`] so it can be serialised in
/// [`RemediationState`] without exposing the internal field layout.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct PersistedAttempt {
    pub count: u32,
    pub last_confidence: u8,
}

impl RemediationAttempts {
    pub fn new() -> Self {
        Self::default()
    }

    /// Current attempt count for `(project, pr)`; 0 if never dispatched.
    pub fn count(&self, project: &str, pr: u64) -> u32 {
        self.by_project
            .get(project)
            .and_then(|m| m.get(&pr))
            .map_or(0, |s| s.count)
    }

    /// Last recorded below-threshold confidence for `(project, pr)`, if any.
    pub fn last_confidence(&self, project: &str, pr: u64) -> Option<u8> {
        self.by_project
            .get(project)
            .and_then(|m| m.get(&pr))
            .map(|s| s.last_confidence)
    }

    /// Bump the attempt count for `(project, pr)` and store the confidence
    /// recorded at this dispatch.
    pub fn record(&mut self, project: &str, pr: u64, confidence: u8) {
        let entry = self
            .by_project
            .entry(project.to_string())
            .or_default()
            .entry(pr)
            .or_insert(AttemptState {
                count: 0,
                last_confidence: confidence,
            });
        entry.count += 1;
        entry.last_confidence = confidence;
    }

    /// Snapshot the per-PR attempt map for ONE project (Gitea
    /// terraphim-ai#2285 persistence). Empty when the project is unknown.
    pub fn snapshot_for(&self, project: &str) -> HashMap<u64, PersistedAttempt> {
        self.by_project
            .get(project)
            .map(|m| {
                m.iter()
                    .map(|(pr, s)| {
                        (
                            *pr,
                            PersistedAttempt {
                                count: s.count,
                                last_confidence: s.last_confidence,
                            },
                        )
                    })
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Merge a loaded per-PR attempt map into the in-memory state for ONE
    /// project (restore-on-startup). Loaded entries overwrite any existing
    /// entry for the same PR so the attempt count is not reset to zero.
    pub fn restore_for(&mut self, project: &str, map: HashMap<u64, PersistedAttempt>) {
        if map.is_empty() {
            return;
        }
        let entry = self.by_project.entry(project.to_string()).or_default();
        for (pr, persisted) in map {
            entry.insert(
                pr,
                AttemptState {
                    count: persisted.count,
                    last_confidence: persisted.last_confidence,
                },
            );
        }
    }
}

/// Persisted remediation dispatch + attempt state for ONE project (Gitea
/// terraphim-ai#2285). Mirrors the [`crate::mention::MentionCursor`] SQLite
/// blueprint: one JSON blob per project under `adf/remediation_state/<id>`,
/// delete/start-fresh on deserialise failure, bounded set growth. Survives a
/// restart so already-attempted `(pr, head_sha)` revisions are NOT
/// re-dispatched (the cold-start replay hole).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RemediationState {
    /// `(pr_number, head_sha)` pairs already dispatched (idempotency across
    /// restarts). Bounded; capped like `MentionCursor::processed_comment_ids`.
    #[serde(default)]
    pub dispatched: HashSet<(u64, String)>,
    /// Per-PR attempt count + last below-threshold confidence, keyed WITHOUT
    /// the SHA so attempts accumulate across fix revisions.
    #[serde(default)]
    pub attempts: HashMap<u64, PersistedAttempt>,
}

impl RemediationState {
    /// Maximum number of `(pr, head_sha)` entries retained in `dispatched`
    /// before the set is halved (mirror of the MentionCursor 10_000 cap).
    const DISPATCHED_CAP: usize = 10_000;

    /// Get the SQLite operator for persistent storage (None if unavailable).
    async fn sqlite_op() -> Option<opendal::Operator> {
        let storage = terraphim_persistence::DeviceStorage::instance()
            .await
            .ok()?;
        let (op, _) = storage.ops.get("sqlite")?;
        Some(op.clone())
    }

    /// Persistence key for a project's remediation state.
    fn state_key(project_id: &str) -> String {
        format!("adf/remediation_state/{project_id}")
    }

    /// Load the persisted state for `project_id`, or a default empty state.
    /// On deserialise failure the corrupt blob is deleted and an empty state
    /// returned (never panics; exact MentionCursor precedent).
    pub async fn load(project_id: &str) -> Self {
        let key = Self::state_key(project_id);
        if let Some(op) = Self::sqlite_op().await {
            match op.read(&key).await {
                Ok(bs) => match serde_json::from_slice::<Self>(&bs.to_vec()) {
                    Ok(state) => {
                        tracing::info!(
                            project = project_id,
                            dispatched = state.dispatched.len(),
                            attempts = state.attempts.len(),
                            "loaded RemediationState from persistence"
                        );
                        return state;
                    }
                    Err(e) => {
                        tracing::warn!(
                            project = project_id,
                            ?e,
                            "failed to deserialise RemediationState; deleting and starting fresh"
                        );
                        let _ = op.delete(&key).await;
                    }
                },
                Err(_) => {
                    tracing::info!(
                        project = project_id,
                        "no persisted RemediationState found, starting fresh"
                    );
                }
            }
        } else {
            tracing::warn!(
                project = project_id,
                "DeviceStorage sqlite not available; remediation state not persisted"
            );
        }
        Self::default()
    }

    /// Save the state under the project key. Logged-but-non-fatal on error.
    pub async fn save(&self, project_id: &str) {
        let key = Self::state_key(project_id);
        if let Some(op) = Self::sqlite_op().await {
            match serde_json::to_string(self) {
                Ok(json) => {
                    if let Err(e) = op.write(&key, json).await {
                        tracing::warn!(project = project_id, ?e, "failed to save RemediationState");
                    } else {
                        tracing::debug!(
                            project = project_id,
                            dispatched = self.dispatched.len(),
                            attempts = self.attempts.len(),
                            "saved RemediationState"
                        );
                    }
                }
                Err(e) => {
                    tracing::warn!(
                        project = project_id,
                        ?e,
                        "failed to serialise RemediationState"
                    );
                }
            }
        } else {
            tracing::warn!(
                project = project_id,
                "DeviceStorage sqlite not available; remediation state not persisted"
            );
        }
    }

    /// Bound `dispatched` growth by dropping half the entries when it exceeds
    /// the cap (mirror of `MentionCursor::mark_processed`).
    pub fn cap(&mut self) {
        if self.dispatched.len() > Self::DISPATCHED_CAP {
            let to_remove: Vec<(u64, String)> = self
                .dispatched
                .iter()
                .take(Self::DISPATCHED_CAP / 2)
                .cloned()
                .collect();
            for k in to_remove {
                self.dispatched.remove(&k);
            }
        }
    }
}

/// TTL-based dedupe cache for auto-merge failure issues.
///
/// Prevents the creation of duplicate `[ADF] Auto-merge failed` issues when
/// the same PR fails multiple times within a short window (e.g. protected
/// branch blocking every tick). Each entry expires after `ttl` so that a
/// genuine new failure after a long gap can still be tracked.
#[derive(Debug)]
pub struct AutoMergeFailureDedupe {
    /// `(project, pr_number, head_sha)` -> `Instant` when the failure issue
    /// was created.
    entries: HashMap<(String, u64, String), Instant>,
    /// How long an entry stays valid.
    ttl: Duration,
}

impl AutoMergeFailureDedupe {
    /// Create a new cache with the given TTL.
    pub fn new(ttl: Duration) -> Self {
        Self {
            entries: HashMap::new(),
            ttl,
        }
    }

    /// Check whether a failure issue has already been created for this
    /// `(project, pr_number, head_sha)` within the TTL window.
    ///
    /// Also purges expired entries as a side effect.
    pub fn is_recent(&mut self, project: &str, pr_number: u64, head_sha: &str) -> bool {
        self.purge_expired();
        let key = (project.to_string(), pr_number, head_sha.to_string());
        self.entries.contains_key(&key)
    }

    /// Record that a failure issue was just created for this PR.
    pub fn record(&mut self, project: &str, pr_number: u64, head_sha: &str) {
        let key = (project.to_string(), pr_number, head_sha.to_string());
        self.entries.insert(key, Instant::now());
    }

    /// Remove entries older than `self.ttl`.
    fn purge_expired(&mut self) {
        let now = Instant::now();
        self.entries
            .retain(|_, created| now.duration_since(*created) < self.ttl);
    }
}

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

    fn comment(id: u64, user: &str, body: &str, updated_at: &str) -> PrComment {
        PrComment {
            id,
            user_login: user.to_string(),
            body: body.to_string(),
            updated_at: updated_at.to_string(),
        }
    }

    fn pr(number: u64, author: &str, head: &str, diff_loc: u32) -> PrSummary {
        PrSummary {
            number,
            author_login: author.to_string(),
            head_sha: head.to_string(),
            base_ref: "main".to_string(),
            diff_loc,
        }
    }

    #[test]
    fn is_pr_reviewer_comment_matches_login() {
        let c = comment(1, PR_REVIEWER_LOGIN, "hello", "2026-01-01T00:00:00Z");
        assert!(is_pr_reviewer_comment(&c));
    }

    #[test]
    fn is_pr_reviewer_comment_matches_footer_fallback() {
        let c = comment(
            1,
            "random-user",
            "body\n<sub>Last reviewed commit: abc123</sub>",
            "2026-01-01T00:00:00Z",
        );
        assert!(is_pr_reviewer_comment(&c));
    }

    #[test]
    fn is_pr_reviewer_comment_rejects_security_checklist() {
        let c = comment(
            1,
            "random-user",
            "security_checklist Summary\n<sub>Last reviewed commit: abc123</sub>",
            "2026-01-01T00:00:00Z",
        );
        assert!(!is_pr_reviewer_comment(&c));
    }

    #[test]
    fn is_pr_reviewer_comment_rejects_security_audit() {
        let c = comment(
            1,
            "random-user",
            "Security Audit Summary\n<sub>Last reviewed commit: abc123</sub>",
            "2026-01-01T00:00:00Z",
        );
        assert!(!is_pr_reviewer_comment(&c));
    }

    #[test]
    fn is_pr_reviewer_comment_rejects_requirements_traceability() {
        let c = comment(
            1,
            "random-user",
            "Requirements Traceability Summary\n<sub>Last reviewed commit: abc123</sub>",
            "2026-01-01T00:00:00Z",
        );
        assert!(!is_pr_reviewer_comment(&c));
    }

    #[test]
    fn is_pr_reviewer_comment_rejects_quality_gate_report() {
        let c = comment(
            1,
            "random-user",
            "Quality Gate Report\n<sub>Last reviewed commit: abc123</sub>",
            "2026-01-01T00:00:00Z",
        );
        assert!(!is_pr_reviewer_comment(&c));
    }

    #[test]
    fn pr_reviewer_login_overrides_non_reviewer_heading() {
        let c = comment(
            1,
            PR_REVIEWER_LOGIN,
            "security_checklist Summary\n<sub>Last reviewed commit: abc123</sub>",
            "2026-01-01T00:00:00Z",
        );
        assert!(is_pr_reviewer_comment(&c));
    }

    #[test]
    fn latest_reviewer_comment_picks_max_updated_at() {
        let comments = vec![
            comment(1, PR_REVIEWER_LOGIN, "first", "2026-01-01T00:00:00Z"),
            comment(2, PR_REVIEWER_LOGIN, "second", "2026-01-02T00:00:00Z"),
            comment(3, "human", "noise", "2026-01-03T00:00:00Z"),
        ];
        let latest = latest_reviewer_comment(&comments).unwrap();
        assert_eq!(latest.id, 2);
    }

    #[test]
    fn evaluate_verdict_returns_no_reviewer_comment_when_empty() {
        let p = pr(1, "claude-code", "abc", 10);
        let out = evaluate_pr_verdict(&p, &[], &[], &AutoMergeCriteria::default(), &[]);
        assert_eq!(out, EvaluationOutcome::NoReviewerComment);
    }

    #[test]
    fn evaluate_verdict_returns_parse_error_on_malformed_body() {
        let p = pr(1, "claude-code", "abc", 10);
        let c = comment(7, PR_REVIEWER_LOGIN, "garbage", "2026-01-01T00:00:00Z");
        let out = evaluate_pr_verdict(&p, &[c], &[], &AutoMergeCriteria::default(), &[]);
        assert!(matches!(out, EvaluationOutcome::ParseError { .. }));
    }

    #[test]
    fn evaluate_pr_verdict_status_layer_blocks_before_parse() {
        // A required context with no posted status must block (HumanReviewNeeded)
        // even when there are NO comments at all -- the status layer is checked
        // before the structural layer, so it pre-empts NoReviewerComment.
        let p = pr(1, "claude-code", "2ef451d8aabbcc", 10);
        let required = vec!["adf/test".to_string()];
        let out = evaluate_pr_verdict(&p, &[], &[], &AutoMergeCriteria::default(), &required);
        match out {
            EvaluationOutcome::HumanReviewNeeded { reason } => {
                assert!(reason.contains("adf/test"), "reason was: {reason}");
                assert!(reason.contains("not posted"), "reason was: {reason}");
            }
            other => panic!("expected HumanReviewNeeded, got {other:?}"),
        }
    }

    #[test]
    fn sha_prefix_matches_short_is_prefix_of_long() {
        assert!(sha_prefix_matches(
            "2ef451d8",
            "2ef451d8aabbccddeeff00112233445566778899"
        ));
    }

    #[test]
    fn sha_prefix_matches_long_is_anchor_for_short() {
        // Either argument order works: the shorter is matched against the longer.
        assert!(sha_prefix_matches(
            "2ef451d8aabbccddeeff00112233445566778899",
            "2ef451d8"
        ));
    }

    #[test]
    fn sha_prefix_matches_equal_short_shas() {
        assert!(sha_prefix_matches("2ef451d8", "2ef451d8"));
    }

    #[test]
    fn sha_prefix_matches_case_insensitive() {
        assert!(sha_prefix_matches("2EF451D8", "2ef451d8aabbcc"));
    }

    #[test]
    fn sha_prefix_matches_rejects_mismatch() {
        assert!(!sha_prefix_matches("2ef451d8", "62672e38aabbcc"));
    }

    #[test]
    fn sha_prefix_matches_rejects_too_short() {
        assert!(!sha_prefix_matches("2ef451", "2ef451d8aabbcc"));
        assert!(!sha_prefix_matches("2ef451d8", "2ef451"));
    }

    #[test]
    fn sha_prefix_matches_rejects_empty() {
        assert!(!sha_prefix_matches("", "2ef451d8aabbcc"));
        assert!(!sha_prefix_matches("2ef451d8", ""));
    }

    #[test]
    fn head_matches_footer_prefix_match() {
        assert!(head_matches_footer(
            "abc123def4567890aabbccddeeff00112233445566",
            "abc123"
        ));
    }

    #[test]
    fn head_matches_footer_case_insensitive() {
        assert!(head_matches_footer(
            "ABC123def4567890aabbccddeeff00112233445566",
            "abc123"
        ));
    }

    #[test]
    fn head_matches_footer_empty_footer_never_matches() {
        assert!(!head_matches_footer("abc123def4567890", ""));
        // whitespace-only footer is also treated as empty.
        assert!(!head_matches_footer("abc123def4567890", "   "));
    }

    #[test]
    fn head_matches_footer_rejects_mismatch() {
        assert!(!head_matches_footer("abc123def4567890", "def999"));
    }

    #[test]
    fn parse_rfc3339_to_unix_parses_valid() {
        // 2026-03-31T12:00:00Z
        assert_eq!(
            parse_rfc3339_to_unix(Some("2026-03-31T12:00:00Z")),
            Some(1_774_958_400)
        );
    }

    #[test]
    fn parse_rfc3339_to_unix_handles_offset() {
        // Same instant expressed with a +02:00 offset must equal 14:00 +02:00.
        assert_eq!(
            parse_rfc3339_to_unix(Some("2026-03-31T14:00:00+02:00")),
            Some(1_774_958_400)
        );
    }

    #[test]
    fn parse_rfc3339_to_unix_none_and_garbage() {
        assert_eq!(parse_rfc3339_to_unix(None), None);
        assert_eq!(parse_rfc3339_to_unix(Some("not-a-timestamp")), None);
    }

    #[test]
    fn rate_limiter_blocks_inside_window() {
        let mut rl = PrPollRateLimiter::new(Duration::from_secs(60));
        let now = Instant::now();
        assert!(rl.allow("p", 1, now));
        assert!(!rl.allow("p", 1, now + Duration::from_secs(30)));
        assert!(rl.allow("p", 1, now + Duration::from_secs(61)));
    }

    #[test]
    fn rate_limiter_scopes_by_project_and_pr() {
        let mut rl = PrPollRateLimiter::new(Duration::from_secs(60));
        let now = Instant::now();
        assert!(rl.allow("a", 1, now));
        assert!(rl.allow("a", 2, now));
        assert!(rl.allow("b", 1, now));
    }

    #[test]
    fn dedupe_records_new_and_rejects_duplicates() {
        let mut set = AutoMergeDedupeSet::new();
        assert!(set.record_if_new("p", 1, "sha"));
        assert!(!set.record_if_new("p", 1, "sha"));
        assert!(set.record_if_new("p", 1, "sha2"));
        assert!(set.record_if_new("q", 1, "sha"));
    }

    #[test]
    fn failure_dedupe_blocks_duplicate_within_ttl() {
        let mut cache = AutoMergeFailureDedupe::new(Duration::from_secs(300));
        assert!(!cache.is_recent("p", 1, "sha"));
        cache.record("p", 1, "sha");
        assert!(cache.is_recent("p", 1, "sha"));
        // Different SHA or PR is allowed.
        assert!(!cache.is_recent("p", 1, "sha2"));
        assert!(!cache.is_recent("p", 2, "sha"));
        assert!(!cache.is_recent("q", 1, "sha"));
    }

    #[test]
    fn failure_dedupe_allows_recreate_after_ttl() {
        let mut cache = AutoMergeFailureDedupe::new(Duration::from_millis(50));
        cache.record("p", 1, "sha");
        assert!(cache.is_recent("p", 1, "sha"));
        std::thread::sleep(Duration::from_millis(60));
        assert!(!cache.is_recent("p", 1, "sha"));
    }

    // ===================================================================
    // #2264: CONDITIONAL classification + RemediationAttempts
    // ===================================================================

    /// A structural verdict body whose confidence is `conf`/5 with the given
    /// number of P0/P1 findings and a footer SHA that prefix-matches
    /// `2ef451d8...`. Acceptance criteria are all checked so only confidence
    /// gates the outcome.
    fn verdict_body(conf: u8, p0: usize, p1: usize) -> String {
        let mut s = format!("<h3>Confidence Score: {conf}/5</h3>\n<h3>Inline Findings</h3>\n");
        for i in 0..p0 {
            s.push_str(&format!("**P0 finding {i} in src/x.rs, line 1**: detail\n"));
        }
        for i in 0..p1 {
            s.push_str(&format!("**P1 finding {i} in src/x.rs, line 2**: detail\n"));
        }
        s.push_str("<sub>Last reviewed commit: 2ef451d8 | Reviews (1)</sub>");
        s
    }

    #[test]
    fn evaluate_verdict_conditional_below_threshold_no_p0_remediates() {
        let p = pr(1, "claude-code", "2ef451d8aabbcc", 42);
        let body = verdict_body(3, 0, 1);
        let c = comment(1, PR_REVIEWER_LOGIN, &body, "2026-01-02T00:00:00Z");
        let out = evaluate_pr_verdict(&p, &[c], &[], &AutoMergeCriteria::default(), &[]);
        match out {
            EvaluationOutcome::Remediate {
                head_sha,
                confidence,
                verdict_excerpt,
                ..
            } => {
                assert_eq!(head_sha, "2ef451d8aabbcc");
                assert_eq!(confidence, 3);
                assert!(
                    verdict_excerpt.contains("Inline Findings"),
                    "excerpt must carry the verbatim findings section: {verdict_excerpt}"
                );
                assert!(verdict_excerpt.contains("**P1 finding 0"));
            }
            other => panic!("expected Remediate, got {other:?}"),
        }
    }

    #[test]
    fn evaluate_verdict_p0_present_below_threshold_is_human_review() {
        // P0 present must NEVER remediate, even below threshold.
        let p = pr(2, "claude-code", "2ef451d8aabbcc", 42);
        let body = verdict_body(2, 1, 0);
        let c = comment(2, PR_REVIEWER_LOGIN, &body, "2026-01-02T00:00:00Z");
        let out = evaluate_pr_verdict(&p, &[c], &[], &AutoMergeCriteria::default(), &[]);
        assert!(
            matches!(out, EvaluationOutcome::HumanReviewNeeded { .. }),
            "P0-bearing verdict must escalate, not remediate: {out:?}"
        );
    }

    #[test]
    fn evaluate_verdict_at_threshold_still_merges_when_clean() {
        // A 5/5 clean verdict (no findings, criteria met) at the default
        // threshold still merges -- the CONDITIONAL branch never fires.
        let p = pr(3, "claude-code", "2ef451d8aabbcc", 42);
        let body = verdict_body(5, 0, 0);
        let c = comment(3, PR_REVIEWER_LOGIN, &body, "2026-01-02T00:00:00Z");
        let out = evaluate_pr_verdict(&p, &[c], &[], &AutoMergeCriteria::default(), &[]);
        assert!(
            matches!(out, EvaluationOutcome::Merge { .. }),
            "got {out:?}"
        );
    }

    #[test]
    fn evaluate_verdict_diff_over_cap_below_threshold_is_human_review() {
        // Diff over cap is a separate gate; but because confidence is checked
        // FIRST and is below threshold here, the reason is the confidence
        // reason and p0_count == 0, so this DOES remediate. To isolate the
        // diff-cap regression we use a 5/5 verdict with an over-cap diff: the
        // confidence gate passes, the diff gate fails -> HumanReviewNeeded
        // (never Remediate, because confidence is not below threshold).
        let p = pr(4, "claude-code", "2ef451d8aabbcc", 999);
        let body = verdict_body(5, 0, 0);
        let c = comment(4, PR_REVIEWER_LOGIN, &body, "2026-01-02T00:00:00Z");
        let out = evaluate_pr_verdict(&p, &[c], &[], &AutoMergeCriteria::default(), &[]);
        match out {
            EvaluationOutcome::HumanReviewNeeded { reason } => {
                assert!(reason.contains("diff size"), "got {reason}");
            }
            other => panic!("expected HumanReviewNeeded (diff cap), got {other:?}"),
        }
    }

    #[test]
    fn evaluate_verdict_non_agent_author_below_threshold_remediates_only_on_confidence() {
        // A human-authored PR with a below-threshold confidence: confidence is
        // checked FIRST, so the failing reason is confidence and p0 == 0 -->
        // this remediates (the author gate is downstream of confidence). This
        // pins that the CONDITIONAL rule keys on confidence + p0, matching the
        // evaluate() gate ordering. The author gate still blocks any eventual
        // merge after remediation because confidence must first clear.
        let p = pr(5, "alice-human", "2ef451d8aabbcc", 42);
        let body = verdict_body(3, 0, 1);
        let c = comment(5, PR_REVIEWER_LOGIN, &body, "2026-01-02T00:00:00Z");
        let out = evaluate_pr_verdict(&p, &[c], &[], &AutoMergeCriteria::default(), &[]);
        assert!(
            matches!(out, EvaluationOutcome::Remediate { .. }),
            "got {out:?}"
        );

        // Same human author but a 5/5 clean verdict: confidence passes, the
        // author gate fails -> HumanReviewNeeded (never Remediate).
        let body_clean = verdict_body(5, 0, 0);
        let c2 = comment(6, PR_REVIEWER_LOGIN, &body_clean, "2026-01-02T00:00:00Z");
        let out2 = evaluate_pr_verdict(&p, &[c2], &[], &AutoMergeCriteria::default(), &[]);
        match out2 {
            EvaluationOutcome::HumanReviewNeeded { reason } => {
                assert!(reason.contains("not a recognised agent"), "got {reason}");
            }
            other => panic!("expected HumanReviewNeeded (author), got {other:?}"),
        }
    }

    #[test]
    fn evaluate_verdict_failed_status_below_threshold_is_human_review() {
        use crate::pr_gate::{CommitStatusState, CommitStatusSummary};
        // Status gate is FIRST in evaluate_pr_verdict; a failed required
        // status blocks before any structural classification, so even a
        // would-be-CONDITIONAL verdict stays HumanReviewNeeded.
        let p = pr(7, "claude-code", "2ef451d8aabbcc", 42);
        let body = verdict_body(3, 0, 1);
        let c = comment(7, PR_REVIEWER_LOGIN, &body, "2026-01-02T00:00:00Z");
        let statuses = vec![CommitStatusSummary {
            context: "adf/test".to_string(),
            state: CommitStatusState::Failure,
            created_at_unix: None,
        }];
        let required = vec!["adf/test".to_string()];
        let out = evaluate_pr_verdict(
            &p,
            &[c],
            &statuses,
            &AutoMergeCriteria::default(),
            &required,
        );
        match out {
            EvaluationOutcome::HumanReviewNeeded { reason } => {
                assert!(reason.contains("failed"), "got {reason}");
            }
            other => panic!("expected HumanReviewNeeded (status), got {other:?}"),
        }
    }

    #[test]
    fn evaluate_verdict_stale_sha_below_threshold_is_stale_review() {
        // The structural SHA-bind fires before the CONDITIONAL classification:
        // a verdict reviewed against a different head is stale -> StaleReview
        // (Gitea terraphim-ai#2275). Must NOT fall through to Remediate even
        // though confidence is below threshold and there are no P0 findings.
        let p = pr(8, "claude-code", "deadbeef99aa11", 42);
        let body = verdict_body(3, 0, 1); // footer SHA is 2ef451d8, head is deadbeef...
        let c = comment(8, PR_REVIEWER_LOGIN, &body, "2026-01-02T00:00:00Z");
        let out = evaluate_pr_verdict(&p, &[c], &[], &AutoMergeCriteria::default(), &[]);
        match out {
            EvaluationOutcome::StaleReview { reviewed, head } => {
                assert_eq!(reviewed, "2ef451d8");
                assert_eq!(head, "deadbeef99aa11");
            }
            other => panic!("expected StaleReview, got {other:?}"),
        }
    }

    #[test]
    fn findings_excerpt_slices_inline_findings_section() {
        let body = "<h3>Summary</h3>\nblah\n<h3>Inline Findings</h3>\n**P1 thing**: detail\n<sub>Last reviewed commit: abc</sub>";
        let ex = findings_excerpt(body);
        assert!(ex.starts_with("<h3>Inline Findings</h3>"), "got: {ex}");
        assert!(ex.contains("**P1 thing**"));
        assert!(!ex.contains("<h3>Summary</h3>"));
    }

    #[test]
    fn findings_excerpt_falls_back_to_whole_body_without_heading() {
        let body = "no headings here, just text";
        assert_eq!(findings_excerpt(body), body);
    }

    #[test]
    fn findings_excerpt_caps_long_body_on_char_boundary() {
        let body = "x".repeat(VERDICT_EXCERPT_CAP + 100);
        let ex = findings_excerpt(&body);
        assert_eq!(ex.len(), VERDICT_EXCERPT_CAP);
    }

    #[test]
    fn remediation_attempts_count_starts_zero() {
        let a = RemediationAttempts::new();
        assert_eq!(a.count("p", 1), 0);
        assert_eq!(a.last_confidence("p", 1), None);
    }

    #[test]
    fn remediation_attempts_record_bumps_and_stores_confidence() {
        let mut a = RemediationAttempts::new();
        a.record("p", 1, 3);
        assert_eq!(a.count("p", 1), 1);
        assert_eq!(a.last_confidence("p", 1), Some(3));
        a.record("p", 1, 4);
        assert_eq!(a.count("p", 1), 2);
        assert_eq!(a.last_confidence("p", 1), Some(4));
        // Scoping by project and pr.
        assert_eq!(a.count("p", 2), 0);
        assert_eq!(a.count("q", 1), 0);
    }
}