atproto-devtool 0.1.1

A multitool for the atproto developer ecosystem
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
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
//! `report` stage: exercises the labeler's authenticated
//! `com.atproto.moderation.createReport` path.
//!
//! The `sentinel` submodule builds the pollution-avoidance reason string
//! that every committed report body carries.

use std::borrow::Cow;
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use url::Url;

use async_trait::async_trait;
use miette::{Diagnostic, NamedSource, SourceSpan};
use reqwest::StatusCode;
use thiserror::Error;

use crate::commands::test::labeler::identity::IdentityFacts;
use crate::commands::test::labeler::report::{CheckResult, CheckStatus, Stage};
use crate::common::diagnostics::pretty_json_for_display;
use crate::common::identity::{Did, is_local_labeler_hostname};

pub mod did_doc_server;
pub mod pollution;
pub mod self_mint;
pub mod sentinel;

/// Raw HTTP response from POSTing `com.atproto.moderation.createReport`.
///
/// Mirrors `RawXrpcResponse` from the HTTP stage but specialized for the
/// createReport shape: no typed decode (positive and negative checks need
/// different decode strategies) and the raw body is kept for diagnostic
/// rendering via miette.
#[derive(Debug)]
pub struct RawCreateReportResponse {
    /// HTTP status code.
    pub status: StatusCode,
    /// Content-Type header value, if present. Lowercased for matching.
    pub content_type: Option<String>,
    /// Raw response body bytes.
    pub raw_body: Arc<[u8]>,
    /// The URL that was POSTed to (for diagnostics).
    pub source_url: String,
}

/// Error type for `CreateReportTee` operations.
///
/// Kept intentionally narrow: either a transport failure (TCP / TLS / DNS /
/// reqwest internal), or a well-formed HTTP response that we return as-is.
/// Callers — i.e., the stage — decide what each non-2xx status means per
/// check.
#[derive(Debug, Error, Diagnostic)]
pub enum CreateReportStageError {
    /// Transport-level failure: the request never reached a well-formed
    /// HTTP exchange.
    #[error("createReport transport error: {source}")]
    #[diagnostic(code = "labeler::report::transport_error")]
    Transport {
        /// Underlying error.
        #[source]
        source: Box<dyn std::error::Error + Send + Sync>,
    },
}

/// Trait for POSTing `com.atproto.moderation.createReport`. Production
/// impl (`RealCreateReportTee`) wraps a `reqwest::Client`; tests inject
/// `FakeCreateReportTee` from `tests/common/mod.rs`.
///
/// The body is serialized from a `serde_json::Value` so negative-shape
/// tests can POST intentionally invalid bodies without fighting the type
/// system.
#[async_trait]
pub trait CreateReportTee: Send + Sync {
    /// POST the given body to the labeler's `com.atproto.moderation.createReport`
    /// endpoint.
    ///
    /// # Arguments
    /// * `auth` — optional Bearer token. `None` ⇒ no `Authorization` header
    ///   (for the `unauthenticated_rejected` check). `Some(token)` is
    ///   included as `Authorization: Bearer {token}`.
    /// * `body` — JSON body to POST. The impl sends `Content-Type: application/json`.
    async fn post_create_report(
        &self,
        auth: Option<&str>,
        body: &serde_json::Value,
    ) -> Result<RawCreateReportResponse, CreateReportStageError>;
}

/// Raw HTTP response from XRPC calls to the PDS.
///
/// Similar to `RawCreateReportResponse` but used for PDS-specific calls
/// (createSession, getServiceAuth) where the response needs to be parsed
/// as JSON by the caller.
#[derive(Debug)]
pub struct RawPdsXrpcResponse {
    /// HTTP status code.
    pub status: StatusCode,
    /// Raw response body bytes.
    pub raw_body: Arc<[u8]>,
    /// Content-Type header value, if present. Lowercased for matching.
    pub content_type: Option<String>,
    /// The URL that was requested (for diagnostics).
    pub source_url: String,
}

/// Narrow seam for POSTing/GETting against the user's PDS.
///
/// The existing `HttpClient` in `src/common/identity.rs` is GET-only and
/// does not support bearer headers or request bodies. This trait exists
/// to keep those capabilities out of the identity-resolution seam.
#[async_trait]
pub trait PdsXrpcClient: Send + Sync {
    /// POST `body` (JSON-serialized) to the PDS endpoint at the given path
    /// (e.g., `"xrpc/com.atproto.server.createSession"`). Optional bearer
    /// and `atproto-proxy` headers.
    async fn post(
        &self,
        path: &str,
        bearer: Option<&str>,
        atproto_proxy: Option<&str>,
        body: &serde_json::Value,
    ) -> Result<RawPdsXrpcResponse, CreateReportStageError>;

    /// GET the PDS endpoint at the given path with optional bearer and
    /// URL-encoded query pairs.
    async fn get(
        &self,
        path: &str,
        bearer: Option<&str>,
        query: &[(&str, &str)],
    ) -> Result<RawPdsXrpcResponse, CreateReportStageError>;
}

/// Real `PdsXrpcClient` implementation using reqwest.
pub struct RealPdsXrpcClient {
    client: reqwest::Client,
    base: Url,
}

impl RealPdsXrpcClient {
    /// Create a new `RealPdsXrpcClient` using the given shared reqwest
    /// client and PDS base URL.
    pub fn new(client: reqwest::Client, base: Url) -> Self {
        Self { client, base }
    }
}

#[async_trait]
impl PdsXrpcClient for RealPdsXrpcClient {
    async fn post(
        &self,
        path: &str,
        bearer: Option<&str>,
        atproto_proxy: Option<&str>,
        body: &serde_json::Value,
    ) -> Result<RawPdsXrpcResponse, CreateReportStageError> {
        let mut url = self.base.clone();
        url.set_path(path);
        let source_url = url.to_string();
        let mut req = self
            .client
            .post(url.as_str())
            .header("Content-Type", "application/json")
            .body(serde_json::to_vec(body).expect("serde_json::Value always serializes"));
        if let Some(b) = bearer {
            req = req.header("Authorization", format!("Bearer {b}"));
        }
        if let Some(p) = atproto_proxy {
            req = req.header("atproto-proxy", p);
        }
        let resp = req
            .send()
            .await
            .map_err(|e| CreateReportStageError::Transport {
                source: Box::new(e),
            })?;
        let status = resp.status();
        let content_type = resp
            .headers()
            .get(reqwest::header::CONTENT_TYPE)
            .and_then(|h| h.to_str().ok())
            .map(|s| s.to_ascii_lowercase());
        let body = resp
            .bytes()
            .await
            .map_err(|e| CreateReportStageError::Transport {
                source: Box::new(e),
            })?;
        Ok(RawPdsXrpcResponse {
            status,
            raw_body: Arc::from(body.as_ref()),
            content_type,
            source_url,
        })
    }

    async fn get(
        &self,
        path: &str,
        bearer: Option<&str>,
        query: &[(&str, &str)],
    ) -> Result<RawPdsXrpcResponse, CreateReportStageError> {
        let mut url = self.base.clone();
        url.set_path(path);
        {
            let mut pairs = url.query_pairs_mut();
            for (k, v) in query {
                pairs.append_pair(k, v);
            }
        }
        let source_url = url.to_string();
        let mut req = self.client.get(url.as_str());
        if let Some(b) = bearer {
            req = req.header("Authorization", format!("Bearer {b}"));
        }
        let resp = req
            .send()
            .await
            .map_err(|e| CreateReportStageError::Transport {
                source: Box::new(e),
            })?;
        let status = resp.status();
        let content_type = resp
            .headers()
            .get(reqwest::header::CONTENT_TYPE)
            .and_then(|h| h.to_str().ok())
            .map(|s| s.to_ascii_lowercase());
        let body = resp
            .bytes()
            .await
            .map_err(|e| CreateReportStageError::Transport {
                source: Box::new(e),
            })?;
        Ok(RawPdsXrpcResponse {
            status,
            raw_body: Arc::from(body.as_ref()),
            content_type,
            source_url,
        })
    }
}

/// Real `CreateReportTee` implementation using reqwest.
pub struct RealCreateReportTee {
    client: reqwest::Client,
    endpoint: Url,
}

impl RealCreateReportTee {
    /// Create a new `RealCreateReportTee` using the given shared reqwest
    /// client and labeler endpoint. The endpoint is the labeler's service
    /// URL (e.g., `https://labeler.example.com`); the POST path
    /// `/xrpc/com.atproto.moderation.createReport` is appended.
    pub fn new(client: reqwest::Client, endpoint: Url) -> Self {
        Self { client, endpoint }
    }
}

#[async_trait]
impl CreateReportTee for RealCreateReportTee {
    async fn post_create_report(
        &self,
        auth: Option<&str>,
        body: &serde_json::Value,
    ) -> Result<RawCreateReportResponse, CreateReportStageError> {
        let mut url = self.endpoint.clone();
        url.set_path("xrpc/com.atproto.moderation.createReport");
        let source_url = url.to_string();

        tracing::debug!(
            url = %source_url,
            auth_kind = match auth {
                None => "none",
                Some(t) if !t.starts_with("ey") => "malformed",
                Some(_) => "jwt",
            },
            "report stage: issuing createReport POST"
        );

        let mut req = self
            .client
            .post(url.as_str())
            .header("Content-Type", "application/json")
            .body(serde_json::to_vec(body).expect("serde_json::Value always serializes"));
        if let Some(token) = auth {
            req = req.header("Authorization", format!("Bearer {token}"));
        }

        let response = req
            .send()
            .await
            .map_err(|e| CreateReportStageError::Transport {
                source: Box::new(e),
            })?;

        let status = response.status();
        let content_type = response
            .headers()
            .get(reqwest::header::CONTENT_TYPE)
            .and_then(|h| h.to_str().ok())
            .map(|s| s.to_ascii_lowercase());

        let body_bytes = response
            .bytes()
            .await
            .map_err(|e| CreateReportStageError::Transport {
                source: Box::new(e),
            })?;

        tracing::debug!(
            url = %source_url,
            status = %status,
            body_len = body_bytes.len(),
            "report stage: createReport response received"
        );

        Ok(RawCreateReportResponse {
            status,
            content_type,
            raw_body: Arc::from(body_bytes.as_ref()),
            source_url,
        })
    }
}

/// Error type for `PdsJwtFetcher` operations.
///
/// Carries a human-readable message; every PDS-side failure is treated as
/// a `NetworkError` by the report stage (per AC5.3 / AC6.3).
#[derive(Debug)]
pub enum PdsJwtFetchError {
    Transport(CreateReportStageError),
    Failed(RawPdsXrpcResponse),
    InvalidBody {
        resp: RawPdsXrpcResponse,
        error: serde_json::Error,
    },
    MissingToken(RawPdsXrpcResponse),
}

impl std::fmt::Display for PdsJwtFetchError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PdsJwtFetchError::Transport(e) => write!(f, "getServiceAuth transport: {e}"),
            PdsJwtFetchError::Failed(resp) => {
                write!(f, "getServiceAuth returned status {}", resp.status)
            }
            PdsJwtFetchError::InvalidBody { error, .. } => {
                write!(f, "getServiceAuth body not JSON: {error}")
            }
            PdsJwtFetchError::MissingToken(_) => write!(f, "getServiceAuth response missing token"),
        }
    }
}

impl PdsJwtFetchError {
    fn into_diagnostic(self) -> Option<Box<dyn miette::Diagnostic + Send + Sync>> {
        match self {
            Self::Transport(_) => None,
            Self::Failed(resp) | Self::InvalidBody { resp, .. } | Self::MissingToken(resp) => {
                let (source_code, span) = body_as_named_source_from_pds(&resp);
                let diag = CreateReportDiagnostic::PdsServiceAuthRejected {
                    origin: ResponseOrigin::Pds,
                    status: resp.status.as_u16(),
                    source_code,
                    span,
                };
                Some(Box::new(diag))
            }
        }
    }
}

/// Fetches a service-auth JWT from a PDS by first creating a session and
/// then calling `getServiceAuth`. Used in mode-2 (`pds_service_auth_accepted`).
pub struct PdsJwtFetcher<'a> {
    client: &'a dyn PdsXrpcClient,
}

impl<'a> PdsJwtFetcher<'a> {
    /// Create a new `PdsJwtFetcher` using the given PDS client.
    pub fn new(client: &'a dyn PdsXrpcClient) -> Self {
        Self { client }
    }

    /// Call `getServiceAuth` using the provided access JWT, returning the
    /// minted service-auth JWT. The access JWT should come from a prior
    /// `createSession` call.
    pub async fn fetch_with_jwt(
        &self,
        access_jwt: &str,
        aud: &str,
        lxm: &str,
        exp_absolute_unix: i64,
    ) -> Result<String, PdsJwtFetchError> {
        // getServiceAuth (GET with query params).
        let exp_s = exp_absolute_unix.to_string();
        let resp = self
            .client
            .get(
                "xrpc/com.atproto.server.getServiceAuth",
                Some(access_jwt),
                &[("aud", aud), ("lxm", lxm), ("exp", &exp_s)],
            )
            .await
            .map_err(PdsJwtFetchError::Transport)?;
        if !resp.status.is_success() {
            return Err(PdsJwtFetchError::Failed(resp));
        }
        let token = match serde_json::from_slice::<serde_json::Value>(&resp.raw_body) {
            Err(error) => Err(PdsJwtFetchError::InvalidBody { resp, error }),
            Ok(auth) => auth["token"]
                .as_str()
                .map(|s| s.to_string())
                .ok_or_else(|| PdsJwtFetchError::MissingToken(resp)),
        }?;

        Ok(token)
    }
}

/// Posts `com.atproto.moderation.createReport` to the PDS (not the
/// labeler) with the `atproto-proxy` header, letting the PDS mint and
/// forward the JWT itself.
pub struct PdsProxiedPoster<'a> {
    client: &'a dyn PdsXrpcClient,
}

impl<'a> PdsProxiedPoster<'a> {
    /// Create a new `PdsProxiedPoster` using the given PDS client.
    pub fn new(client: &'a dyn PdsXrpcClient) -> Self {
        Self { client }
    }

    /// Post the createReport body through the PDS with the given user
    /// access JWT. Returns the `RawPdsXrpcResponse` so the caller can
    /// classify success / labeler-side rejection / PDS-side rejection.
    pub async fn post(
        &self,
        labeler_did: &str,
        access_jwt: &str,
        body: &serde_json::Value,
    ) -> Result<RawPdsXrpcResponse, CreateReportStageError> {
        self.client
            .post(
                "xrpc/com.atproto.moderation.createReport",
                Some(access_jwt),
                Some(&format!("{labeler_did}#atproto_labeler")),
                body,
            )
            .await
    }
}

/// Minimal per-check outcome facts for possible future consumer stages.
/// All three `Option<bool>` fields are `None` unless the corresponding
/// positive check ran and produced a concrete outcome.
#[derive(Debug, Clone, Default)]
pub struct CreateReportFacts {
    /// `self_mint_accepted` outcome: `Some(true)` on Pass, `Some(false)` on
    /// SpecViolation, `None` on Skipped/NetworkError.
    pub self_mint_succeeded: Option<bool>,
    /// `pds_service_auth_accepted` outcome (see above).
    pub pds_service_auth_succeeded: Option<bool>,
    /// `pds_proxied_accepted` outcome (see above).
    pub pds_proxied_succeeded: Option<bool>,
}

/// Stage output: facts (populated only when the stage produced meaningful
/// outcome data) and the full 10-row results vector.
#[derive(Debug)]
pub struct CreateReportStageOutput {
    pub facts: Option<CreateReportFacts>,
    pub results: Vec<CheckResult>,
}

/// Stable check identifiers for the `report` stage.
///
/// Order MUST match the DoD ordering (AC7.2): contract, unauth, malformed,
/// wrong-aud, wrong-lxm, expired, rejected-shape, self-mint, pds-service-auth,
/// pds-proxied.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Check {
    ContractPublished,
    UnauthenticatedRejected,
    MalformedBearerRejected,
    WrongAudRejected,
    WrongLxmRejected,
    ExpiredRejected,
    RejectedShapeReturns400,
    SelfMintAccepted,
    PdsServiceAuthAccepted,
    PdsProxiedAccepted,
}

impl Check {
    /// Stable `CheckResult.id` string.
    pub fn id(self) -> &'static str {
        match self {
            Check::ContractPublished => "report::contract_published",
            Check::UnauthenticatedRejected => "report::unauthenticated_rejected",
            Check::MalformedBearerRejected => "report::malformed_bearer_rejected",
            Check::WrongAudRejected => "report::wrong_aud_rejected",
            Check::WrongLxmRejected => "report::wrong_lxm_rejected",
            Check::ExpiredRejected => "report::expired_rejected",
            Check::RejectedShapeReturns400 => "report::rejected_shape_returns_400",
            Check::SelfMintAccepted => "report::self_mint_accepted",
            Check::PdsServiceAuthAccepted => "report::pds_service_auth_accepted",
            Check::PdsProxiedAccepted => "report::pds_proxied_accepted",
        }
    }

    /// Canonical iteration order for the 10 checks, matching AC7.2.
    pub const ORDER: [Check; 10] = [
        Check::ContractPublished,
        Check::UnauthenticatedRejected,
        Check::MalformedBearerRejected,
        Check::WrongAudRejected,
        Check::WrongLxmRejected,
        Check::ExpiredRejected,
        Check::RejectedShapeReturns400,
        Check::SelfMintAccepted,
        Check::PdsServiceAuthAccepted,
        Check::PdsProxiedAccepted,
    ];

    /// Build a `Pass` result for this check with a default summary.
    pub fn pass(self) -> CheckResult {
        CheckResult {
            id: self.id(),
            stage: Stage::Report,
            status: CheckStatus::Pass,
            summary: Cow::Borrowed(self.default_summary_pass()),
            diagnostic: None,
            skipped_reason: None,
        }
    }

    /// Build a `SpecViolation` result for this check with an optional
    /// diagnostic.
    pub fn spec_violation(self, diagnostic: CreateReportDiagnostic) -> CheckResult {
        CheckResult {
            id: self.id(),
            stage: Stage::Report,
            status: CheckStatus::SpecViolation,
            summary: Cow::Borrowed(self.default_summary_fail()),
            diagnostic: Some(Box::new(diagnostic) as _),
            skipped_reason: None,
        }
    }

    /// Build an `Advisory` result (used by `rejected_shape_returns_400` AC3.6).
    pub fn advisory(self, diagnostic: CreateReportDiagnostic) -> CheckResult {
        CheckResult {
            id: self.id(),
            stage: Stage::Report,
            status: CheckStatus::Advisory,
            summary: Cow::Borrowed(self.default_summary_fail()),
            diagnostic: Some(Box::new(diagnostic) as _),
            skipped_reason: None,
        }
    }

    /// Build a `NetworkError` result (used by PDS-side failure modes).
    pub fn network_error(self, message: String) -> CheckResult {
        CheckResult {
            id: self.id(),
            stage: Stage::Report,
            status: CheckStatus::NetworkError,
            summary: Cow::Owned(format!("{}: {message}", self.default_summary_fail())),
            diagnostic: None,
            skipped_reason: None,
        }
    }

    /// Build a `Skipped` result with the supplied reason.
    pub fn skip(self, reason: &'static str) -> CheckResult {
        CheckResult {
            id: self.id(),
            stage: Stage::Report,
            status: CheckStatus::Skipped,
            summary: Cow::Borrowed(self.default_summary_pass()),
            diagnostic: None,
            skipped_reason: Some(Cow::Borrowed(reason)),
        }
    }

    fn default_summary_pass(self) -> &'static str {
        match self {
            Check::ContractPublished => "Labeler advertises reportable shape",
            Check::UnauthenticatedRejected => "Unauthenticated report rejected",
            Check::MalformedBearerRejected => "Malformed bearer rejected",
            Check::WrongAudRejected => "JWT with wrong `aud` rejected",
            Check::WrongLxmRejected => "JWT with wrong `lxm` rejected",
            Check::ExpiredRejected => "Expired JWT rejected",
            Check::RejectedShapeReturns400 => "Invalid shape returns 400 InvalidRequest",
            Check::SelfMintAccepted => "Self-mint report accepted",
            Check::PdsServiceAuthAccepted => "PDS-minted JWT accepted",
            Check::PdsProxiedAccepted => "PDS-proxied report accepted",
        }
    }

    fn default_summary_fail(self) -> &'static str {
        match self {
            Check::ContractPublished => "Labeler does not advertise a reportable shape",
            Check::UnauthenticatedRejected => {
                "Unauthenticated report accepted (should have been rejected)"
            }
            Check::MalformedBearerRejected => {
                "Malformed bearer accepted (should have been rejected)"
            }
            Check::WrongAudRejected => "JWT with wrong `aud` accepted",
            Check::WrongLxmRejected => "JWT with wrong `lxm` accepted",
            Check::ExpiredRejected => "Expired JWT accepted",
            Check::RejectedShapeReturns400 => "Rejection status was not 400 InvalidRequest",
            Check::SelfMintAccepted => "Self-mint report rejected",
            Check::PdsServiceAuthAccepted => "PDS-minted JWT rejected",
            Check::PdsProxiedAccepted => "PDS-proxied report rejected",
        }
    }
}

/// Aggregate of the stage-relevant options, extracted from `LabelerOptions`
/// by the pipeline and passed to `run`. Having a local, narrow shape
/// avoids forcing `run`'s signature to take everything in `LabelerOptions`.
pub struct CreateReportRunOptions<'a> {
    pub commit_report: bool,
    pub force_self_mint: bool,
    pub self_mint_curve: self_mint::SelfMintCurve,
    pub report_subject_override: Option<&'a crate::common::identity::Did>,
    pub self_mint_signer: Option<&'a self_mint::SelfMintSigner>,
    pub pds_credentials: Option<&'a crate::commands::test::labeler::pipeline::PdsCredentials>,
    pub pds_xrpc_client: Option<&'a dyn PdsXrpcClient>,
    /// Populated by the pipeline when `--handle` was supplied but resolving
    /// the handle to the reporter's PDS endpoint failed. Surfaced as a
    /// `NetworkError` on both PDS-mediated checks so the operator can tell
    /// a resolution failure apart from a missing-credentials skip.
    pub pds_resolution_error: Option<&'a str>,
    pub run_id: &'a str,
}

/// Run the report stage.
///
/// Stage inputs are passed via `LabelerOptions` (or directly as arguments
/// here, to keep the signature mirroring the other stages). The stage
/// always emits exactly 10 `report::*` CheckResults (AC7.1) in canonical
/// order (AC7.2), regardless of gating decisions.
pub async fn run(
    identity_facts: Option<&crate::commands::test::labeler::identity::IdentityFacts>,
    report_tee: &dyn CreateReportTee,
    opts: &CreateReportRunOptions<'_>,
) -> CreateReportStageOutput {
    let mut results = Vec::with_capacity(10);

    // If identity didn't land, every check is blocked by the identity
    // stage. Emit 10 Skipped rows and return.
    let Some(id_facts) = identity_facts else {
        for c in Check::ORDER {
            results.push(c.skip("blocked by identity stage"));
        }
        return CreateReportStageOutput {
            facts: None,
            results,
        };
    };

    // Examine the published contract (from Task 0's extended IdentityFacts).
    let reason_types = id_facts.reason_types.as_ref();
    let subject_types = id_facts.subject_types.as_ref();
    let has_reason_types = reason_types.map(|v| !v.is_empty()).unwrap_or(false);
    let has_subject_types = subject_types.map(|v| !v.is_empty()).unwrap_or(false);
    let contract_advertised = has_reason_types && has_subject_types;

    // AC1: compute the contract_published row and the blocking reason for
    // all downstream checks if the contract is missing.
    //
    // Control-flow contract: each branch below pushes EXACTLY 10 rows
    // (1 contract row + 9 downstream) and returns. No fallthrough — the
    // "contract advertised" branch is the one that invokes the
    // authenticated negative checks and the committing positive checks.
    if !contract_advertised {
        if opts.commit_report {
            // AC1.3: commit requested, contract missing ⇒ SpecViolation +
            // every other check blocked by this one.
            let diag = CreateReportDiagnostic::ContractMissing {
                has_reason_types,
                has_subject_types,
            };
            results.push(Check::ContractPublished.spec_violation(diag));
            for c in Check::ORDER.iter().skip(1).copied() {
                results.push(c.skip("blocked by `report::contract_published`"));
            }
        } else {
            // AC1.2: no commit, contract missing ⇒ whole stage skipped.
            results.push(
                Check::ContractPublished.skip("labeler does not advertise report acceptance"),
            );
            for c in Check::ORDER.iter().skip(1).copied() {
                results.push(c.skip("labeler does not advertise report acceptance"));
            }
        }
        return CreateReportStageOutput {
            facts: None,
            results,
        };
    }

    // Contract advertised. Emit the Pass row and fall through into the
    // per-check logic.
    results.push(Check::ContractPublished.pass());

    // Minimal body for negative checks. The labeler should reject at auth
    // before examining body shape; we nonetheless supply a plausible body so
    // a labeler that performs body validation first doesn't return 400
    // instead of 401, which would make the test ambiguous.
    let negative_body = build_minimal_report_body(id_facts);

    // AC2.1/AC2.2/AC2.5 — unauthenticated:
    match report_tee.post_create_report(None, &negative_body).await {
        Ok(resp) => match RejectionShape::classify(&resp) {
            RejectionShape::Conformant { .. } => {
                results.push(Check::UnauthenticatedRejected.pass());
            }
            RejectionShape::ConformantStatusNonConformantShape => {
                results.push(CheckResult {
                    summary: Cow::Borrowed(
                        "Unauthenticated report rejected (status 401, non-conformant envelope)",
                    ),
                    ..Check::UnauthenticatedRejected.pass()
                });
            }
            RejectionShape::WrongStatus { status } => {
                let status_u16 = status.as_u16();
                let (source_code, span) = body_as_named_source(&resp);
                let diag = CreateReportDiagnostic::UnauthenticatedAccepted {
                    status: status_u16,
                    source_code,
                    span,
                };
                results.push(Check::UnauthenticatedRejected.spec_violation(diag));
            }
        },
        Err(CreateReportStageError::Transport { source }) => {
            results.push(Check::UnauthenticatedRejected.network_error(source.to_string()));
        }
    }

    // AC2.3/AC2.4 — malformed bearer:
    match report_tee
        .post_create_report(Some("not-a-jwt"), &negative_body)
        .await
    {
        Ok(resp) => match RejectionShape::classify(&resp) {
            RejectionShape::Conformant { .. } => {
                results.push(Check::MalformedBearerRejected.pass());
            }
            RejectionShape::ConformantStatusNonConformantShape => {
                results.push(CheckResult {
                    summary: Cow::Borrowed(
                        "Malformed bearer rejected (status 401, non-conformant envelope)",
                    ),
                    ..Check::MalformedBearerRejected.pass()
                });
            }
            RejectionShape::WrongStatus { status } => {
                let status_u16 = status.as_u16();
                let (source_code, span) = body_as_named_source(&resp);
                let diag = CreateReportDiagnostic::MalformedBearerAccepted {
                    status: status_u16,
                    source_code,
                    span,
                };
                results.push(Check::MalformedBearerRejected.spec_violation(diag));
            }
        },
        Err(CreateReportStageError::Transport { source }) => {
            results.push(Check::MalformedBearerRejected.network_error(source.to_string()));
        }
    }

    // Recompute self_mint_viable using the *actual* labeler endpoint now
    // that identity has run.
    let is_local_labeler = is_local_labeler_hostname(&id_facts.labeler_endpoint);
    let self_mint_viable = opts.force_self_mint || is_local_labeler;

    let signer_for_negative = if self_mint_viable {
        opts.self_mint_signer
    } else {
        None
    };

    // Compute `now` once for all JWT-based checks.
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0);

    // CRITICAL: this block either emits 4 Skipped rows OR emits 4 real-check
    // rows, then falls through to the committing checks for SelfMintAccepted,
    // PdsServiceAuthAccepted, PdsProxiedAccepted. Do NOT `return` here — the
    // stage always emits 10 rows total, and the later checks need to run
    // regardless of self-mint viability.
    if let Some(signer) = signer_for_negative {
        // Mint per-check tokens from the valid-claims template. All four
        // checks share the same `now`, `lxm`, and `template`. Each check
        // inlines its own `match` rather than using a shared helper —
        // nested `async fn` is unsupported in stable Rust, and a closure
        // returning `Box<dyn Diagnostic>` across `await` would force `Send`
        // bounds that complicate the call site.
        let lxm = "com.atproto.moderation.createReport";
        let template =
            signer.valid_claims_template(&id_facts.did, lxm, now, Duration::from_secs(60));

        let negative_body = build_minimal_report_body(id_facts);

        // AC3.1/AC3.2 — wrong aud:
        {
            let mut claims = template.clone();
            claims.aud = "did:plc:0000000000000000000000000".to_string();
            let token = signer.sign_jwt(claims);
            match report_tee
                .post_create_report(Some(&token), &negative_body)
                .await
            {
                Ok(resp) => match RejectionShape::classify(&resp) {
                    RejectionShape::Conformant { .. } => {
                        results.push(Check::WrongAudRejected.pass())
                    }
                    RejectionShape::ConformantStatusNonConformantShape => {
                        results.push(CheckResult {
                            summary: Cow::Borrowed(
                                "Rejected with 401 but envelope is non-conformant",
                            ),
                            ..Check::WrongAudRejected.pass()
                        })
                    }
                    RejectionShape::WrongStatus { .. } => {
                        let (source_code, span) = body_as_named_source(&resp);
                        let diag = CreateReportDiagnostic::WrongAudAccepted {
                            status: resp.status.as_u16(),
                            source_code,
                            span,
                        };
                        results.push(Check::WrongAudRejected.spec_violation(diag));
                    }
                },
                Err(CreateReportStageError::Transport { source }) => {
                    results.push(Check::WrongAudRejected.network_error(source.to_string()));
                }
            }
        }

        // AC3.3 — wrong lxm:
        {
            let mut claims = template.clone();
            claims.lxm = "com.atproto.server.getSession".to_string();
            let token = signer.sign_jwt(claims);
            match report_tee
                .post_create_report(Some(&token), &negative_body)
                .await
            {
                Ok(resp) => match RejectionShape::classify(&resp) {
                    RejectionShape::Conformant { .. } => {
                        results.push(Check::WrongLxmRejected.pass())
                    }
                    RejectionShape::ConformantStatusNonConformantShape => {
                        results.push(CheckResult {
                            summary: Cow::Borrowed(
                                "Rejected with 401 but envelope is non-conformant",
                            ),
                            ..Check::WrongLxmRejected.pass()
                        })
                    }
                    RejectionShape::WrongStatus { .. } => {
                        let (source_code, span) = body_as_named_source(&resp);
                        let diag = CreateReportDiagnostic::WrongLxmAccepted {
                            status: resp.status.as_u16(),
                            source_code,
                            span,
                        };
                        results.push(Check::WrongLxmRejected.spec_violation(diag));
                    }
                },
                Err(CreateReportStageError::Transport { source }) => {
                    results.push(Check::WrongLxmRejected.network_error(source.to_string()));
                }
            }
        }

        // AC3.4 — expired:
        {
            let mut claims = template.clone();
            claims.exp = now - 300;
            claims.iat = now - 360;
            let token = signer.sign_jwt(claims);
            match report_tee
                .post_create_report(Some(&token), &negative_body)
                .await
            {
                Ok(resp) => match RejectionShape::classify(&resp) {
                    RejectionShape::Conformant { .. } => {
                        results.push(Check::ExpiredRejected.pass())
                    }
                    RejectionShape::ConformantStatusNonConformantShape => {
                        results.push(CheckResult {
                            summary: Cow::Borrowed(
                                "Rejected with 401 but envelope is non-conformant",
                            ),
                            ..Check::ExpiredRejected.pass()
                        })
                    }
                    RejectionShape::WrongStatus { .. } => {
                        let (source_code, span) = body_as_named_source(&resp);
                        let diag = CreateReportDiagnostic::ExpiredAccepted {
                            status: resp.status.as_u16(),
                            source_code,
                            span,
                        };
                        results.push(Check::ExpiredRejected.spec_violation(diag));
                    }
                },
                Err(CreateReportStageError::Transport { source }) => {
                    results.push(Check::ExpiredRejected.network_error(source.to_string()));
                }
            }
        }

        // AC3.5/AC3.6 — rejected shape:
        {
            let claims = template.clone();
            let token = signer.sign_jwt(claims);
            // Invalid body: a reasonType that is NOT in id_facts.reason_types.
            let bogus_reason_type = synth_unadvertised_reason_type(id_facts);
            let invalid_body = {
                let mut body = negative_body.clone();
                if let Some(obj) = body.as_object_mut() {
                    obj.insert(
                        "reasonType".to_string(),
                        serde_json::Value::String(bogus_reason_type),
                    );
                }
                body
            };
            match report_tee
                .post_create_report(Some(&token), &invalid_body)
                .await
            {
                Ok(resp) => {
                    let envelope = XrpcErrorEnvelope::parse(&resp.raw_body);
                    let error_name = envelope.as_ref().and_then(|e| e.error.clone());
                    if resp.status == reqwest::StatusCode::BAD_REQUEST
                        && error_name.as_deref() == Some("InvalidRequest")
                    {
                        // AC3.5: 400 InvalidRequest → Pass.
                        results.push(Check::RejectedShapeReturns400.pass());
                    } else if resp.status == reqwest::StatusCode::UNAUTHORIZED
                        || resp.status.is_server_error()
                    {
                        // AC3.6: 401 or 5xx → Advisory with shape_not_400.
                        let (source_code, span) = body_as_named_source(&resp);
                        let diag = CreateReportDiagnostic::ShapeNot400 {
                            status: resp.status.as_u16(),
                            error_name: error_name.clone(),
                            source_code,
                            span,
                        };
                        results.push(Check::RejectedShapeReturns400.advisory(diag));
                    } else if resp.status == reqwest::StatusCode::BAD_REQUEST {
                        // 400 but not `InvalidRequest` name → Advisory.
                        let (source_code, span) = body_as_named_source(&resp);
                        let diag = CreateReportDiagnostic::ShapeNot400 {
                            status: 400,
                            error_name: error_name.clone(),
                            source_code,
                            span,
                        };
                        results.push(Check::RejectedShapeReturns400.advisory(diag));
                    } else {
                        // Catch-all: 200 accepted → Advisory. A 200 for an invalid
                        // shape is a labeler looseness issue, not the same category
                        // as the `self_mint_accepted` SpecViolation (which expects
                        // a *valid* shape to be accepted).
                        let (source_code, span) = body_as_named_source(&resp);
                        let diag = CreateReportDiagnostic::ShapeNot400 {
                            status: resp.status.as_u16(),
                            error_name,
                            source_code,
                            span,
                        };
                        results.push(Check::RejectedShapeReturns400.advisory(diag));
                    }
                }
                Err(CreateReportStageError::Transport { source }) => {
                    results.push(Check::RejectedShapeReturns400.network_error(source.to_string()));
                }
            }
        }
    } else {
        let reason = "self-mint required; labeler endpoint appears non-local (override with --force-self-mint)";
        for c in [
            Check::WrongAudRejected,
            Check::WrongLxmRejected,
            Check::ExpiredRejected,
            Check::RejectedShapeReturns400,
        ] {
            results.push(c.skip(reason));
        }
    }

    // Fallthrough to the committing check logic below. Keeping this block
    // fallthrough-safe is why the `if let Some(signer)` above does NOT
    // `return`.

    // AC4.4 — gate on commit_report.
    if !opts.commit_report {
        results.push(Check::SelfMintAccepted.skip("commit gated behind --commit-report"));
    } else if let Some(signer) = signer_for_negative {
        // AC4.1/AC4.2 — construct a positive POST with pollution-avoidance.
        // Reads the contract from the `reason_types` / `subject_types` fields
        // on `IdentityFacts`.
        let reason_type = pollution::choose_reason_type(
            id_facts.reason_types.as_deref().unwrap_or(&[]),
            is_local_labeler,
        );
        let subject = pollution::choose_subject(
            id_facts.subject_types.as_deref().unwrap_or(&[]),
            signer.issuer_did(),
            opts.report_subject_override,
            is_local_labeler,
        );
        let sentinel = sentinel::build(opts.run_id, SystemTime::now());
        let positive_body = serde_json::json!({
            "reasonType": reason_type,
            "subject": subject,
            "reason": sentinel,
        });

        // AC4.6 — the built body carries the sentinel; the integration test
        // in Task 4 asserts it via FakeCreateReportTee::last_request().

        let claims = signer.valid_claims_template(
            &id_facts.did,
            "com.atproto.moderation.createReport",
            now,
            Duration::from_secs(60),
        );
        let token = signer.sign_jwt(claims);

        match report_tee
            .post_create_report(Some(&token), &positive_body)
            .await
        {
            Ok(resp) if resp.status.is_success() => {
                // AC4.1/AC4.2: Pass. Optionally inspect body for createReport#output
                // shape — loose check: `id` is a number.
                let body_ok = serde_json::from_slice::<serde_json::Value>(&resp.raw_body)
                    .ok()
                    .and_then(|v| v.get("id").and_then(|id| id.as_i64()))
                    .is_some();
                if body_ok {
                    results.push(Check::SelfMintAccepted.pass());
                } else {
                    // 2xx but body doesn't look like createReport#output. Accept as
                    // Pass per design (status alone suffices), but note the
                    // non-conformant body in the summary.
                    results.push(CheckResult {
                        summary: Cow::Borrowed(
                            "Self-mint report accepted (2xx), body did not match createReport#output shape",
                        ),
                        ..Check::SelfMintAccepted.pass()
                    });
                }
            }
            Ok(resp) => {
                // AC4.3: non-2xx ⇒ SpecViolation.
                let (source_code, span) = body_as_named_source(&resp);
                let diag = CreateReportDiagnostic::SelfMintRejected {
                    status: resp.status.as_u16(),
                    source_code,
                    span,
                };
                results.push(Check::SelfMintAccepted.spec_violation(diag));
            }
            Err(CreateReportStageError::Transport { source }) => {
                results.push(Check::SelfMintAccepted.network_error(source.to_string()));
            }
        }
    } else {
        // AC4.5: commit requested but no signer available (non-viable or not provided).
        // Skip with the same viability reason as the AC3 checks.
        let reason = "self-mint required; labeler endpoint appears non-local (override with --force-self-mint)";
        results.push(Check::SelfMintAccepted.skip(reason));
    }

    // AC5/AC6 — PDS-mediated modes (modes 2 and 3).
    // Compute the gating precondition common to both PDS checks.
    let pds_gate_reason: &'static str = "requires --handle, --app-password, and --commit-report";
    let pds_ready =
        opts.commit_report && opts.pds_credentials.is_some() && opts.pds_xrpc_client.is_some();
    // Distinguish "no credentials" (skip) from "credentials supplied but the
    // reporter's PDS could not be resolved" (network error) so the operator
    // sees a useful failure mode rather than a silent skip.
    let pds_resolution_failed = opts.commit_report
        && opts.pds_credentials.is_some()
        && opts.pds_xrpc_client.is_none()
        && opts.pds_resolution_error.is_some();

    if pds_resolution_failed {
        let msg = opts
            .pds_resolution_error
            .expect("pds_resolution_failed implies Some")
            .to_string();
        results.push(Check::PdsServiceAuthAccepted.network_error(msg.clone()));
        results.push(Check::PdsProxiedAccepted.network_error(msg));
    } else if !pds_ready {
        results.push(Check::PdsServiceAuthAccepted.skip(pds_gate_reason));
        results.push(Check::PdsProxiedAccepted.skip(pds_gate_reason));
    } else {
        // Safe to unwrap thanks to pds_ready.
        let creds = opts.pds_credentials.expect("pds_ready implies creds");
        let pds_client = opts.pds_xrpc_client.expect("pds_ready implies client");

        // Reuse locality computed earlier.
        let is_local = is_local_labeler;
        let reason_type = pollution::choose_reason_type(
            id_facts.reason_types.as_deref().unwrap_or(&[]),
            is_local,
        );

        // Fetch the user session (DID and access JWT). Both PDS modes need
        // these upfront.
        match fetch_session_and_did(pds_client, &creds.handle, &creds.app_password).await {
            Err(message) => {
                results.push(Check::PdsServiceAuthAccepted.network_error(message.clone()));
                // AC6.3: if session fetch fails, proxied mode also fails at PDS.
                results.push(Check::PdsProxiedAccepted.network_error(message));
            }
            Ok(session) => {
                let user_did = Did(session.did);
                let access_jwt = session.access_jwt;
                let subject = pollution::choose_subject(
                    id_facts.subject_types.as_deref().unwrap_or(&[]),
                    &user_did,
                    opts.report_subject_override,
                    is_local,
                );
                let sentinel = sentinel::build(opts.run_id, SystemTime::now());
                let pds_body = serde_json::json!({
                    "reasonType": reason_type,
                    "subject": subject,
                    "reason": sentinel,
                });

                // Mode 2: getServiceAuth direct-POST.
                let exp_abs = now + 60;
                let fetcher = PdsJwtFetcher::new(pds_client);
                match fetcher
                    .fetch_with_jwt(
                        &access_jwt,
                        &id_facts.did.0,
                        "com.atproto.moderation.createReport",
                        exp_abs,
                    )
                    .await
                {
                    Err(e) => {
                        let message = e.to_string();
                        let diagnostic = e.into_diagnostic();
                        results.push(CheckResult {
                            diagnostic,
                            ..Check::PdsServiceAuthAccepted.network_error(message)
                        });
                    }
                    Ok(service_jwt) => {
                        match report_tee
                            .post_create_report(Some(&service_jwt), &pds_body)
                            .await
                        {
                            Ok(resp) if resp.status.is_success() => {
                                results.push(Check::PdsServiceAuthAccepted.pass());
                            }
                            Ok(resp) => {
                                let (source_code, span) = body_as_named_source(&resp);
                                let diag = CreateReportDiagnostic::PdsServiceAuthRejected {
                                    origin: ResponseOrigin::Labeler,
                                    status: resp.status.as_u16(),
                                    source_code,
                                    span,
                                };
                                results.push(Check::PdsServiceAuthAccepted.spec_violation(diag));
                            }
                            Err(CreateReportStageError::Transport { source }) => {
                                // Labeler-side transport failure during direct POST.
                                results.push(
                                    Check::PdsServiceAuthAccepted.network_error(source.to_string()),
                                );
                            }
                        }
                    }
                }

                // Mode 3: PDS-proxied.
                let proxier = PdsProxiedPoster::new(pds_client);
                match proxier.post(&id_facts.did.0, &access_jwt, &pds_body).await {
                    Err(CreateReportStageError::Transport { source }) => {
                        // Transport to the PDS itself; classify PDS-side.
                        results.push(Check::PdsProxiedAccepted.network_error(source.to_string()));
                    }
                    Ok(resp) if resp.status.is_success() => {
                        results.push(Check::PdsProxiedAccepted.pass());
                    }
                    Ok(resp) => {
                        // PDS surfaced a non-2xx. Interpret per envelope to
                        // distinguish PDS-side vs labeler-side:
                        let (source_code, span) = body_as_named_source_from_pds(&resp);
                        let envelope = XrpcErrorEnvelope::parse(&resp.raw_body);
                        let err_name = envelope.as_ref().and_then(|e| e.error.clone());
                        let is_upstream_label_error = matches!(
                            err_name.as_deref(),
                            Some("UpstreamError") | Some("UpstreamFailure")
                        ) || resp.status.as_u16() == 502
                            || resp.status.as_u16() == 504;
                        if is_upstream_label_error {
                            // AC6.2: labeler-side rejection surfaced by PDS.
                            let diag = CreateReportDiagnostic::PdsProxiedRejected {
                                origin: ResponseOrigin::Labeler,
                                status: resp.status.as_u16(),
                                source_code,
                                span,
                            };
                            results.push(Check::PdsProxiedAccepted.spec_violation(diag));
                        } else {
                            // AC6.3: PDS-side rejection of the proxy attempt.
                            let diag = CreateReportDiagnostic::PdsProxiedRejected {
                                origin: ResponseOrigin::Pds,
                                status: resp.status.as_u16(),
                                source_code,
                                span,
                            };
                            results.push(CheckResult {
                                diagnostic: Some(Box::new(diag)),
                                ..Check::PdsProxiedAccepted.network_error(format!(
                                    "PDS rejected proxy attempt with status {}",
                                    resp.status
                                ))
                            });
                        }
                    }
                }
            }
        }
    }

    CreateReportStageOutput {
        facts: None,
        results,
    }
}

/// Convenience wrapper that does createSession and returns both the DID
/// and the accessJwt. Needed by both PDS check modes to populate the body
/// with the correct subject DID.
struct SessionResult {
    did: String,
    access_jwt: String,
}

async fn fetch_session_and_did(
    client: &dyn PdsXrpcClient,
    handle: &str,
    app_password: &str,
) -> Result<SessionResult, String> {
    let body = serde_json::json!({ "identifier": handle, "password": app_password });
    let resp = client
        .post("xrpc/com.atproto.server.createSession", None, None, &body)
        .await
        .map_err(|e| format!("createSession transport: {e}"))?;
    if !resp.status.is_success() {
        return Err(format!("createSession returned {}", resp.status));
    }
    let session: serde_json::Value =
        serde_json::from_slice(&resp.raw_body).map_err(|e| format!("createSession body: {e}"))?;
    let did = session["did"]
        .as_str()
        .ok_or("createSession missing did")?
        .to_string();
    let access_jwt = session["accessJwt"]
        .as_str()
        .ok_or("createSession missing accessJwt")?
        .to_string();
    Ok(SessionResult { did, access_jwt })
}

/// Synthesize a `reasonType` string that is definitely NOT in the
/// labeler's advertised `reason_types`. NSID syntax (segments alphanumeric +
/// period only, fragment after `#`) is strictly valid so the labeler does
/// not reject for wrong reason (malformed NSID) before checking membership.
fn synth_unadvertised_reason_type(facts: &IdentityFacts) -> String {
    let empty = Vec::new();
    let advertised: &[String] = facts.reason_types.as_ref().unwrap_or(&empty);
    for i in 0..1000 {
        let candidate = format!("xyz.atprotodevtool.conformance.defs#unadvertised{i:03}");
        if !advertised.iter().any(|r| r == &candidate) {
            return candidate;
        }
    }
    // Unreachable in practice.
    "xyz.atprotodevtool.conformance.defs#unadvertisedFallback".to_string()
}

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

    #[test]
    fn check_ids_are_unique_and_report_namespaced() {
        let mut seen = std::collections::HashSet::new();
        for c in Check::ORDER {
            let id = c.id();
            assert!(id.starts_with("report::"), "{id} not in report:: namespace");
            assert!(seen.insert(id), "duplicate check id: {id}");
        }
        assert_eq!(Check::ORDER.len(), 10, "DoD requires exactly 10 checks");
    }
}

/// A loosely-parsed atproto XRPC error envelope. Missing fields are
/// rendered as `None` rather than failing the parse — the "loose
/// assertion" philosophy in the design (see "Error envelope assertion
/// is deliberately loose").
#[derive(Debug, Clone)]
pub struct XrpcErrorEnvelope {
    /// The `error` field (PascalCase error name). `None` if absent or
    /// not a string.
    pub error: Option<String>,
    /// The `message` field. `None` if absent or not a string.
    pub message: Option<String>,
}

impl XrpcErrorEnvelope {
    /// Try to parse an atproto error envelope from the response body.
    /// Returns `None` only when the body is not valid JSON at all.
    /// Otherwise returns an envelope with whatever fields we could find.
    pub fn parse(body: &[u8]) -> Option<Self> {
        let v: serde_json::Value = serde_json::from_slice(body).ok()?;
        let obj = v.as_object()?;
        Some(Self {
            error: obj.get("error").and_then(|x| x.as_str()).map(String::from),
            message: obj
                .get("message")
                .and_then(|x| x.as_str())
                .map(String::from),
        })
    }

    /// `true` when the envelope has a non-empty `error` string.
    pub fn has_nonempty_error(&self) -> bool {
        self.error
            .as_deref()
            .map(|s| !s.is_empty())
            .unwrap_or(false)
    }
}

/// Outcome of the 401-envelope assertion.
pub enum RejectionShape {
    /// 401 with a non-empty `error` field — full-conformant.
    Conformant {
        /// The envelope for diagnostic rendering.
        envelope: XrpcErrorEnvelope,
    },
    /// 401 but the envelope is missing or has an empty `error` field.
    /// Treated as Pass on status alone per AC2.5 but the summary
    /// notes the non-conformant response shape.
    ConformantStatusNonConformantShape,
    /// Any non-401 status.
    WrongStatus {
        /// The observed status code.
        status: reqwest::StatusCode,
    },
}

impl RejectionShape {
    /// Classify a createReport response against the 401-envelope rubric.
    pub fn classify(resp: &RawCreateReportResponse) -> Self {
        if resp.status != reqwest::StatusCode::UNAUTHORIZED {
            return Self::WrongStatus {
                status: resp.status,
            };
        }
        match XrpcErrorEnvelope::parse(&resp.raw_body) {
            Some(env) if env.has_nonempty_error() => Self::Conformant { envelope: env },
            _ => Self::ConformantStatusNonConformantShape,
        }
    }
}

#[derive(Debug, Error, Diagnostic)]
pub enum CreateReportDiagnostic {
    /// Diagnostic for the `contract_missing` spec violation (AC1.3).
    ///
    /// Emitted when `--commit-report` is set and the identity-stage
    /// `labeler_policies` does not advertise a non-empty `reasonTypes` and
    /// `subjectTypes`. The body of the labeler record is attached as source
    /// so users can see what _was_ published.
    #[error("Labeler does not advertise a reportable `LabelerPolicies` shape")]
    #[diagnostic(
        code = "labeler::report::contract_missing",
        help = "`reasonTypes` and `subjectTypes` must both be present and non-empty on the labeler's published policies; the tool cannot verify reporting conformance without them."
    )]
    ContractMissing {
        /// `reasonTypes` present and non-empty?
        has_reason_types: bool,
        /// `subjectTypes` present and non-empty?
        has_subject_types: bool,
    },

    /// Diagnostic for AC2.2: labeler accepted an unauthenticated createReport POST.
    #[error("Labeler accepted unauthenticated createReport (status {status})")]
    #[diagnostic(
        code = "labeler::report::unauthenticated_accepted",
        help = "A labeler must reject createReport with 401 when no Authorization header is supplied."
    )]
    UnauthenticatedAccepted {
        /// Observed status code, e.g., 200.
        status: u16,
        /// Response body for context.
        #[source_code]
        source_code: NamedSource<Arc<[u8]>>,
        /// Span covering the response body so miette renders `source_code`.
        #[label("accepted here")]
        span: SourceSpan,
    },

    /// Diagnostic for AC2.4: labeler accepted a malformed bearer token.
    #[error("Labeler accepted malformed Bearer token (status {status})")]
    #[diagnostic(
        code = "labeler::report::malformed_bearer_accepted",
        help = "A labeler must reject createReport with 401 when the Authorization header carries a non-JWT string."
    )]
    MalformedBearerAccepted {
        /// Observed status code, e.g., 200.
        status: u16,
        /// Response body for context.
        #[source_code]
        source_code: NamedSource<Arc<[u8]>>,
        /// Span covering the response body so miette renders `source_code`.
        #[label("accepted here")]
        span: SourceSpan,
    },

    /// Diagnostic for AC3.2: labeler accepted JWT with wrong `aud` claim.
    #[error("Labeler accepted JWT with wrong `aud` (status {status})")]
    #[diagnostic(
        code = "labeler::report::wrong_aud_accepted",
        help = "A labeler must reject JWTs whose `aud` claim does not match its own DID."
    )]
    WrongAudAccepted {
        /// Observed status code, e.g., 200.
        status: u16,
        /// Response body for context.
        #[source_code]
        source_code: NamedSource<Arc<[u8]>>,
        /// Span covering the response body so miette renders `source_code`.
        #[label("accepted here")]
        span: SourceSpan,
    },

    /// Diagnostic for AC3.3: labeler accepted JWT with wrong `lxm` claim.
    #[error("Labeler accepted JWT with wrong `lxm` (status {status})")]
    #[diagnostic(
        code = "labeler::report::wrong_lxm_accepted",
        help = "A labeler must reject JWTs whose `lxm` claim does not match the invoked Lexicon method."
    )]
    WrongLxmAccepted {
        /// Observed status code, e.g., 200.
        status: u16,
        /// Response body for context.
        #[source_code]
        source_code: NamedSource<Arc<[u8]>>,
        /// Span covering the response body so miette renders `source_code`.
        #[label("accepted here")]
        span: SourceSpan,
    },

    /// Diagnostic for AC3.4: labeler accepted expired JWT.
    #[error("Labeler accepted expired JWT (status {status})")]
    #[diagnostic(
        code = "labeler::report::expired_accepted",
        help = "A labeler must reject JWTs whose `exp` claim is in the past."
    )]
    ExpiredAccepted {
        /// Observed status code, e.g., 200.
        status: u16,
        /// Response body for context.
        #[source_code]
        source_code: NamedSource<Arc<[u8]>>,
        /// Span covering the response body so miette renders `source_code`.
        #[label("accepted here")]
        span: SourceSpan,
    },

    /// Diagnostic for AC3.6: labeler rejected invalid shape with wrong status.
    #[error(
        "Unadvertised `reasonType` was rejected with status {status}, expected 400 InvalidRequest"
    )]
    #[diagnostic(
        code = "labeler::report::shape_not_400",
        help = "A labeler should return 400 InvalidRequest (not 401 or 500) for a `reasonType` not listed in its published LabelerPolicies.reasonTypes."
    )]
    ShapeNot400 {
        /// Observed status code.
        status: u16,
        /// Error name from the response envelope, if present.
        error_name: Option<String>,
        /// Response body for context.
        #[source_code]
        source_code: NamedSource<Arc<[u8]>>,
        /// Span covering the response body so miette renders `source_code`.
        #[label("rejected with wrong status here")]
        span: SourceSpan,
    },

    /// Diagnostic for AC4.3: self-mint report rejected by the labeler.
    #[error("Self-mint report rejected (status {status})")]
    #[diagnostic(
        code = "labeler::report::self_mint_rejected",
        help = "A labeler that advertises reportable shape should accept a well-formed, authenticated createReport. Check the labeler's service-auth validation and its acceptance of the advertised reasonType/subject shape."
    )]
    SelfMintRejected {
        /// Observed HTTP status code.
        status: u16,
        /// Response body for context.
        #[source_code]
        source_code: NamedSource<Arc<[u8]>>,
        /// Span covering the response body so miette renders `source_code`.
        #[label("rejected here")]
        span: SourceSpan,
    },

    /// Diagnostic for AC5.2 / AC5.3: the PDS-mediated service-auth flow
    /// produced a non-2xx response. `origin` identifies whether the
    /// rejection came from the labeler (AC5.2 spec violation) or the
    /// user's PDS during `getServiceAuth` (AC5.3 network error).
    #[error("{origin} rejected PDS-minted service-auth createReport (status {status})")]
    #[diagnostic(
        code = "labeler::report::pds_service_auth_rejected",
        help = "When `origin` is `Labeler`, the PDS issued a service-auth JWT bound to the labeler's DID and the createReport NSID; the labeler should have accepted it. When `origin` is `PDS`, the user's PDS refused to mint the service-auth JWT — verify the handle and app password, and confirm `--handle` resolves to a PDS that can mint service-auth tokens for this user."
    )]
    PdsServiceAuthRejected {
        /// Which party produced the non-2xx response.
        origin: ResponseOrigin,
        /// Observed HTTP status code.
        status: u16,
        /// Response body for context.
        #[source_code]
        source_code: NamedSource<Arc<[u8]>>,
        /// Span covering the response body so miette renders `source_code`.
        #[label("rejected here")]
        span: SourceSpan,
    },

    /// Diagnostic for AC6.2 / AC6.3: the PDS-proxied `createReport` flow
    /// produced a non-2xx response. `origin` identifies whether the
    /// rejection came from the labeler via upstream envelope (AC6.2 spec
    /// violation) or the user's PDS refusing the proxy attempt before
    /// forwarding (AC6.3 network error).
    #[error("{origin} rejected PDS-proxied createReport (status {status})")]
    #[diagnostic(
        code = "labeler::report::pds_proxied_rejected",
        help = "When `origin` is `Labeler`, the PDS forwarded the createReport call on the user's behalf; the downstream labeler reached it but rejected the submission. When `origin` is `PDS`, the user's PDS rejected the proxied call before it could reach the labeler — verify the handle, app password, and that the PDS is configured to proxy moderation calls to the target labeler."
    )]
    PdsProxiedRejected {
        /// Which party produced the non-2xx response.
        origin: ResponseOrigin,
        /// Observed HTTP status code.
        status: u16,
        /// Response body for context.
        #[source_code]
        source_code: NamedSource<Arc<[u8]>>,
        /// Span covering the response body so miette renders `source_code`.
        #[label("rejected here")]
        span: SourceSpan,
    },
}

/// Identifies which party in the PDS-mediated flow produced a non-2xx
/// response. Used to discriminate labeler-side spec violations from
/// PDS-side network errors within a single diagnostic variant, keeping
/// the one-diagnostic-per-check shape the report stage documents.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResponseOrigin {
    /// The labeler itself produced the response (either directly, or via
    /// the PDS surfacing an upstream-labeler error envelope).
    Labeler,
    /// The user's PDS produced the response without the labeler being
    /// reached (e.g., `getServiceAuth` refused, or proxy rejected before
    /// forwarding).
    Pds,
}

impl std::fmt::Display for ResponseOrigin {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ResponseOrigin::Labeler => f.write_str("Labeler"),
            ResponseOrigin::Pds => f.write_str("PDS"),
        }
    }
}

/// Construct a `NamedSource` and a span covering the whole body.
///
/// The span must be non-empty (and present on a `#[label]` field) for miette's
/// `GraphicalReportHandler` to actually render the `source_code` block; a
/// `None` span causes the source to be silently dropped from the rendered
/// diagnostic. We therefore return the span alongside the source and expect
/// every `accepted_*` / `rejected_*` diagnostic to wire both through.
pub(crate) fn body_as_named_source(
    resp: &RawCreateReportResponse,
) -> (NamedSource<Arc<[u8]>>, SourceSpan) {
    let pretty = pretty_json_for_display(&resp.raw_body);
    let span = SourceSpan::new(0.into(), pretty.len());
    (NamedSource::new(resp.source_url.clone(), pretty), span)
}

/// Construct a `NamedSource` and whole-body span from the PDS. Used for
/// PDS-mediated mode diagnostics where the response comes from the PDS not
/// the labeler.
pub(crate) fn body_as_named_source_from_pds(
    resp: &RawPdsXrpcResponse,
) -> (NamedSource<Arc<[u8]>>, SourceSpan) {
    let pretty = pretty_json_for_display(&resp.raw_body);
    let span = SourceSpan::new(0.into(), pretty.len());
    (NamedSource::new(resp.source_url.clone(), pretty), span)
}

/// Build a minimal, plausible createReport body for negative tests.
///
/// Chooses the lex-first advertised `reasonType` and the first advertised
/// `subjectType`, pointing at a safe subject (the labeler's own DID —
/// labelers never take action on themselves). The body is well-formed so
/// any validation short-circuit returns auth-layer rejection rather than
/// shape-layer rejection.
pub(crate) fn build_minimal_report_body(facts: &IdentityFacts) -> serde_json::Value {
    // Unwrap the contract — run() has already guaranteed it's present
    // and non-empty before this function is reachable.
    let reason_type = facts
        .reason_types
        .as_ref()
        .and_then(|v| v.first())
        .cloned()
        .unwrap_or_else(|| "com.atproto.moderation.defs#reasonOther".to_string());

    let subject_types: &[String] = facts.subject_types.as_deref().unwrap_or(&[]);
    let subject = if subject_types.iter().any(|t| t == "account") {
        serde_json::json!({
            "$type": "com.atproto.admin.defs#repoRef",
            "did": facts.did.0,
        })
    } else if subject_types.iter().any(|t| t == "record") {
        serde_json::json!({
            "$type": "com.atproto.repo.strongRef",
            // Ghost AT-URI targeting the labeler's own DID. Negative-path
            // only; positive paths use the real pollution-avoidance logic
            // in `self_mint_accepted`.
            "uri": format!("at://{}/app.bsky.feed.post/not-real", facts.did.0),
            "cid": "bafyreiaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
        })
    } else {
        // Fallback: account shape against the labeler itself.
        serde_json::json!({
            "$type": "com.atproto.admin.defs#repoRef",
            "did": facts.did.0,
        })
    };

    serde_json::json!({
        "reasonType": reason_type,
        "subject": subject,
    })
}

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

    #[test]
    fn parse_well_formed_envelope() {
        let body = br#"{"error":"BadJwt","message":"invalid token"}"#;
        let env = XrpcErrorEnvelope::parse(body).expect("parses");
        assert_eq!(env.error.as_deref(), Some("BadJwt"));
        assert_eq!(env.message.as_deref(), Some("invalid token"));
        assert!(env.has_nonempty_error());
    }

    #[test]
    fn parse_empty_envelope() {
        let body = br#"{}"#;
        let env = XrpcErrorEnvelope::parse(body).expect("parses empty object");
        assert_eq!(env.error, None);
        assert!(!env.has_nonempty_error());
    }

    #[test]
    fn parse_non_json_returns_none() {
        assert!(XrpcErrorEnvelope::parse(b"<html>").is_none());
    }

    #[test]
    fn parse_empty_error_field_treated_as_missing() {
        let body = br#"{"error":""}"#;
        let env = XrpcErrorEnvelope::parse(body).unwrap();
        assert!(!env.has_nonempty_error());
    }
}