vgi-forge-github 0.16.0

GitHub adapter for VGI git namespaces: per-community GitHub App auth, repo creation and bootstrap, role projection, device-flow account linking and verified webhooks.
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
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
//! [`GitHubForge`]: the `Forge` implementation.

use std::collections::{BTreeMap, BTreeSet};
use std::sync::{Arc, Mutex, RwLock};

use base64::Engine;
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
use http::HeaderMap;
use reqwest::Method;
use serde::Deserialize;
use serde_json::{Value, json};
use vgi_forge::{
    AccessSource, ApplyReport, BindCallback, BindRequest, BindStep, BootstrapStep, Capabilities,
    Collaborator, Drift, Forge, ForgeAccount, ForgeError, ForgeEvent, ForgeHooks, ForgeKind,
    ForgeRole, HookDecision, IndirectAccess, LinkCallback, LinkMethod, LinkStep, Namespace,
    NamespaceBinding, NamespaceKind, Projection, ProtectionSpec, ProtectionState, RepoSpec,
    RepoState, RequiredCheckKind, Resource, Result, RoleAssignment, RoleChange, RoleOutcome,
    StepAction, StepOutcome, Unlisted, VgiConfig, Visibility, async_trait, collapse_to_ladder,
    default_diff, validate_repo_path,
};

use crate::api::{Api, Auth};
use crate::config::{GitHubConfig, JwtIssuer};
use crate::jwt::{AppKeySigner, app_jwt};
use crate::manifest::missing_permissions;
use crate::plan::{
    CENTRAL_REPO, CODEOWNERS_PATH, CheckGuard, GUARDED_PATH, ORG_RULESET_NAME, RULESET_NAME,
    WORKFLOW_PATH, github_plan, render_codeowners,
};
use crate::secret::Secret;
use crate::webhook;

mod guard;

/// The role ladder of an organisation repository.
const ORG_LADDER: [ForgeRole; 5] = [
    ForgeRole::Read,
    ForgeRole::Triage,
    ForgeRole::Write,
    ForgeRole::Maintain,
    ForgeRole::Admin,
];

/// A personal account's repositories have collaborators, and collaborators
/// are always `write` (§3, §8).
const USER_LADDER: [ForgeRole; 1] = [ForgeRole::Write];

/// Installation-token permissions per kind of job. Each token also names
/// the one repository it is for wherever a repository exists yet.
///
/// `inspect` asks for administration *write* although it only reads: GitHub
/// shows a ruleset's bypass actors only to a caller who could edit it, and
/// an inspect that could not see them would report "no bypass" for a ruleset
/// that has one.
const PERMS_ADMIN: &[(&str, &str)] = &[("administration", "write"), ("metadata", "read")];
const PERMS_CONTENTS: &[(&str, &str)] = &[("contents", "write"), ("metadata", "read")];
const PERMS_VARIABLES: &[(&str, &str)] = &[("actions_variables", "write"), ("metadata", "read")];
const PERMS_READ_CONTENTS: &[(&str, &str)] = &[("contents", "read"), ("metadata", "read")];
const PERMS_METADATA: &[(&str, &str)] = &[("metadata", "read")];
/// Reading someone's access to a repository and — in an organisation —
/// the teams and membership it comes from.
const PERMS_ACCESS: &[(&str, &str)] = &[("administration", "read"), ("metadata", "read")];
const PERMS_ACCESS_ORG: &[(&str, &str)] = &[
    ("administration", "read"),
    ("members", "read"),
    ("metadata", "read"),
];
/// Org rulesets. *Write* even to read them: GitHub lists every
/// `/orgs/{org}/rulesets` endpoint under organization Administration
/// (write), and shows bypass actors only to a caller who could edit them.
/// Minted with no repositories: it grants nothing on any repository.
const PERMS_ORG_RULESETS: &[(&str, &str)] = &[("organization_administration", "write")];

/// The namespace workflow an org ruleset pins (§9): which `.vgi` commit it
/// runs, and the check name its job reports.
///
/// The bridge records one per namespace when the `required-workflow` step
/// runs, and `inspect` compares the org ruleset against it: a pin the bridge
/// did not make is drift. Persist it (it is small and not secret) and hand it
/// back with [`GitHubForge::set_required_workflow_pin`] after a restart;
/// without it, `inspect` reports the pin as unverified until the step runs
/// again.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct RequiredWorkflowPin {
    /// Numeric id of `<org>/.vgi`.
    pub repository_id: u64,
    /// The pinned commit.
    pub sha: String,
    /// The check (job) name the workflow reports.
    pub check: String,
}

impl RequiredWorkflowPin {
    /// A pin.
    pub fn new(repository_id: u64, sha: impl Into<String>, check: impl Into<String>) -> Self {
        RequiredWorkflowPin {
            repository_id,
            sha: sha.into(),
            check: check.into(),
        }
    }
}

/// How long GitHub lets a device code live (15 minutes). Polling never runs
/// longer, whatever the caller says.
const DEVICE_CODE_MAX_LIFETIME_SECS: u64 = 900;

/// Shortest bind `state` accepted: 128 bits of base64url.
const MIN_STATE_LEN: usize = 22;

/// The GitHub adapter: one community's App on one GitHub (github.com or a
/// GHES instance).
///
/// Holds the App's key (behind [`AppKeySigner`]), its webhook secret, and
/// the namespaces the core has bound. It holds no forge token between calls:
/// each operation mints an installation token scoped to the one repository
/// and the permissions that operation needs, and drops it on return.
pub struct GitHubForge {
    config: GitHubConfig,
    api: Api,
    signer: Arc<dyn AppKeySigner>,
    webhook_secret: Secret,
    namespaces: RwLock<BTreeMap<Resource, Namespace>>,
    actions_app_id: Mutex<Option<u64>>,
    client_secret: Option<Secret>,
    /// Per organisation: whether org rulesets (and so a required workflow)
    /// are available. Absent means not known, which plans the owner-review
    /// fallback — safe everywhere.
    required_workflow: RwLock<BTreeMap<Resource, bool>>,
    /// Per namespace: whether its installation grants what the
    /// bridge-posted check needs (permissions and event subscriptions).
    /// Absent means not known, which keeps the in-repo workflow.
    check_ready: RwLock<BTreeMap<Resource, bool>>,
    pins: RwLock<BTreeMap<Resource, RequiredWorkflowPin>>,
    /// Per organisation: the forge ids of the repositories the bridge
    /// manages — what the org ruleset lists. From the bridge's store.
    managed: RwLock<BTreeMap<Resource, BTreeSet<u64>>>,
    /// One org-ruleset read-modify-write at a time per namespace.
    org_locks: Mutex<BTreeMap<Resource, Arc<tokio::sync::Mutex<()>>>>,
    /// The verify-trust action the last plan used, for the Actions-policy
    /// check in `inspect`.
    verify_trust_action: Mutex<Option<String>>,
}

impl std::fmt::Debug for GitHubForge {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GitHubForge")
            .field("host", &self.config.host)
            .field("app_id", &self.config.app_id)
            .field("signer", &"<redacted>")
            .field("webhook_secret", &self.webhook_secret)
            .finish_non_exhaustive()
    }
}

impl GitHubForge {
    /// An adapter for `config`'s App, signing with `signer` and verifying
    /// webhooks with `webhook_secret`.
    pub fn new(
        config: GitHubConfig,
        signer: Arc<dyn AppKeySigner>,
        webhook_secret: Secret,
    ) -> Result<Self> {
        if webhook_secret.expose().is_empty() {
            return Err(ForgeError::Config("empty webhook secret".into()));
        }
        let slug_ok = !config.app_slug.is_empty()
            && config
                .app_slug
                .bytes()
                .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-');
        if !slug_ok {
            return Err(ForgeError::Config(format!(
                "App slug `{}` must be lowercase letters, digits and `-`",
                config.app_slug
            )));
        }
        let api = Api::new(
            config.api_base.clone(),
            config.web_base.clone(),
            config.request_timeout,
        )?;
        let actions_app_id = Mutex::new(config.actions_integration_id);
        Ok(GitHubForge {
            config,
            api,
            signer,
            webhook_secret,
            namespaces: RwLock::new(BTreeMap::new()),
            actions_app_id,
            client_secret: None,
            required_workflow: RwLock::new(BTreeMap::new()),
            check_ready: RwLock::new(BTreeMap::new()),
            pins: RwLock::new(BTreeMap::new()),
            managed: RwLock::new(BTreeMap::new()),
            org_locks: Mutex::new(BTreeMap::new()),
            verify_trust_action: Mutex::new(None),
        })
    }

    /// Give the adapter the App's OAuth client secret (from the manifest
    /// exchange). With it, the member's user token from an account link is
    /// revoked as soon as their id is read; without it the token is only
    /// dropped and lapses on its own (eight hours for an expiring App user
    /// token), because revocation is authenticated with the client secret.
    pub fn with_client_secret(mut self, secret: Secret) -> Self {
        self.client_secret = Some(secret);
        self
    }

    /// The configuration.
    pub fn config(&self) -> &GitHubConfig {
        &self.config
    }

    pub(crate) fn api(&self) -> &Api {
        &self.api
    }

    pub(crate) fn webhook_secret(&self) -> &Secret {
        &self.webhook_secret
    }

    /// An installation token for `repo` alone, with `perms`, plus its owner
    /// and name — for the crate's other modules.
    pub(crate) async fn repo_token_for(
        &self,
        repo: &Resource,
        perms: &[(&str, &str)],
    ) -> Result<(Secret, String, String)> {
        self.repo_token(repo, perms).await
    }

    /// Tell the adapter about a bound namespace (from the VTC's store, after
    /// the admin confirmed the bind). Operations on repositories in a
    /// namespace that was never registered are refused with
    /// [`ForgeError::NotBound`]: the binding, not whatever the App happens
    /// to be installed on, is what authorises the bridge to act.
    pub fn register_namespace(&self, ns: Namespace) -> Result<()> {
        if ns.resource.host() != self.config.host || !ns.resource.is_namespace() {
            return Err(ForgeError::WrongResource {
                resource: ns.resource.to_string(),
                expected: format!("a namespace on `{}`", self.config.host),
            });
        }
        self.namespaces
            .write()
            .expect("namespace lock poisoned")
            .insert(ns.resource.clone(), ns);
        Ok(())
    }

    /// Forget a namespace (unbind).
    pub fn unregister_namespace(&self, ns: &Resource) {
        self.namespaces
            .write()
            .expect("namespace lock poisoned")
            .remove(ns);
        self.required_workflow
            .write()
            .expect("lock poisoned")
            .remove(ns);
        self.pins.write().expect("lock poisoned").remove(ns);
        self.managed.write().expect("lock poisoned").remove(ns);
        self.check_ready.write().expect("lock poisoned").remove(ns);
    }

    /// Tell the adapter which repositories (by forge id) it manages in
    /// organisation `ns`, from the bridge's store: at start-up and whenever
    /// the set changes. The org ruleset lists exactly these (plus a
    /// repository being bootstrapped); ids GitHub lists that are not here —
    /// archived, deleted or never managed — are dropped from it. Until it
    /// is set, the `required-workflow` step refuses to run rather than
    /// guess the set from GitHub.
    pub fn set_managed_repositories(&self, ns: &Resource, ids: impl IntoIterator<Item = u64>) {
        self.managed
            .write()
            .expect("lock poisoned")
            .insert(ns.clone(), ids.into_iter().collect());
    }

    /// The managed set as the adapter holds it (it adds each repository it
    /// bootstraps under a required workflow, and drops each it archives).
    pub fn managed_repositories(&self, ns: &Resource) -> Option<BTreeSet<u64>> {
        self.managed.read().expect("lock poisoned").get(ns).cloned()
    }

    fn org_lock(&self, ns: &Resource) -> Arc<tokio::sync::Mutex<()>> {
        self.org_locks
            .lock()
            .expect("lock poisoned")
            .entry(ns.clone())
            .or_default()
            .clone()
    }

    /// Record whether `ns`'s installation carries the bridge-posted check
    /// (from [`GitHubForge::detect_bridge_checks`], or the bridge's store
    /// after a restart). Until it is known, a namespace without a required
    /// workflow keeps the in-repo Actions workflow.
    pub fn set_bridge_checks_ready(&self, ns: &Resource, ready: bool) {
        self.check_ready
            .write()
            .expect("lock poisoned")
            .insert(ns.clone(), ready);
    }

    /// Whether `ns`'s installation is known to carry the bridge-posted
    /// check (`None`: not known yet).
    pub fn bridge_checks_ready(&self, ns: &Resource) -> Option<bool> {
        self.check_ready
            .read()
            .expect("lock poisoned")
            .get(ns)
            .copied()
    }

    /// Read `ns`'s installation and record whether it grants what the
    /// bridge-posted check needs: `checks: write`, `pull_requests: read`,
    /// `merge_queues: read` and the `pull_request` and `merge_group`
    /// subscriptions ([`crate::manifest::check_ready`]). An App registered
    /// before these were in the manifest lacks them until its owner updates
    /// the App's settings and each installation approves the change; the
    /// bridge probes again when an installation accepts new permissions.
    pub async fn detect_bridge_checks(&self, ns: &Resource) -> Result<bool> {
        Ok(self.detect_installation(ns).await?.0)
    }

    /// [`GitHubForge::detect_bridge_checks`], and what the installation
    /// lacks of what the App asks for (as `name:level`, and `event:<name>`
    /// for a missing subscription) — the same list a bind reports in
    /// [`NamespaceBinding::missing_permissions`], read again now (after an
    /// owner approved an upgrade, say).
    pub async fn detect_installation(&self, ns: &Resource) -> Result<(bool, Vec<String>)> {
        let namespace = self.namespace(ns)?;
        let Some(installation) = namespace.installation_id else {
            self.set_bridge_checks_ready(ns, false);
            return Ok((false, Vec::new()));
        };
        let jwt = self.jwt().await?;
        let inst: InstallationJson = self
            .api
            .json(
                Method::GET,
                self.api
                    .url(&["app", "installations", &installation.to_string()]),
                Auth::Bearer(&jwt),
                None,
                "installation",
            )
            .await?;
        let ready = crate::manifest::check_ready(&inst.permissions, &inst.events);
        self.set_bridge_checks_ready(ns, ready);
        Ok((ready, installation_missing(&inst)))
    }

    /// Record whether org rulesets — and so a required workflow — are
    /// available in organisation `ns` (from [`GitHubForge::detect_required_workflow`],
    /// or from the bridge's store after a restart). Until it is known the
    /// namespace plans the owner-review fallback.
    pub fn set_required_workflow(&self, ns: &Resource, available: bool) {
        self.required_workflow
            .write()
            .expect("lock poisoned")
            .insert(ns.clone(), available);
    }

    /// Restore the pin the `required-workflow` step last made in `ns`.
    pub fn set_required_workflow_pin(&self, ns: &Resource, pin: RequiredWorkflowPin) {
        self.pins
            .write()
            .expect("lock poisoned")
            .insert(ns.clone(), pin);
    }

    /// The pin the `required-workflow` step last made in `ns`, to persist.
    pub fn required_workflow_pin(&self, ns: &Resource) -> Option<RequiredWorkflowPin> {
        self.pins.read().expect("lock poisoned").get(ns).cloned()
    }

    /// Find out whether organisation `ns` can have a required workflow, and
    /// record the answer.
    ///
    /// The probe is `GET /orgs/{org}/rulesets` with an organization
    /// Administration token. Org rulesets exist on GitHub Team and
    /// Enterprise plans only; on a Free organisation, or where the owner has
    /// not granted the App organization Administration, GitHub refuses
    /// (403/404, or 422 when minting the token) and the answer is `false`.
    /// A personal account, or manual mode, is always `false`. Network and
    /// rate-limit failures are returned, not guessed at.
    ///
    /// A `true` here is necessary, not sufficient: GitHub documents the
    /// workflows rule for Enterprise Cloud. If the org ruleset is then
    /// refused, the `required-workflow` step records `false` and asks for a
    /// re-plan.
    pub async fn detect_required_workflow(&self, ns: &Resource) -> Result<bool> {
        let namespace = self.namespace(ns)?;
        let available = self.probe_org_rulesets(&namespace).await?;
        self.set_required_workflow(ns, available);
        Ok(available)
    }

    async fn probe_org_rulesets(&self, ns: &Namespace) -> Result<bool> {
        if ns.kind != NamespaceKind::Organization || ns.installation_id.is_none() {
            return Ok(false);
        }
        let token = match self.installation_token(ns, None, PERMS_ORG_RULESETS).await {
            Ok(t) => t,
            Err(ForgeError::Rejected { status: 422, .. } | ForgeError::Forbidden(_)) => {
                return Ok(false);
            }
            Err(e) => return Err(e),
        };
        let url = self.api.url(&["orgs", ns.resource.owner(), "rulesets"]);
        match self
            .api
            .get_all::<Value>(url, Auth::Bearer(&token), "org rulesets")
            .await
        {
            Ok(_) => Ok(true),
            Err(ForgeError::Forbidden(_) | ForgeError::NotFound { .. }) => Ok(false),
            Err(e) => Err(e),
        }
    }

    fn required_workflow_known(&self, ns: &Resource) -> bool {
        self.required_workflow
            .read()
            .expect("lock poisoned")
            .get(ns)
            .copied()
            .unwrap_or(false)
    }

    /// A fresh bind `state` nonce: 256 bits from the system CSPRNG,
    /// base64url. The caller stores it with its expiry and hands it back to
    /// [`Forge::complete_bind`].
    pub fn new_state() -> Result<String> {
        let mut bytes = [0u8; 32];
        aws_lc_rs::rand::fill(&mut bytes)
            .map_err(|_| ForgeError::Config("system RNG unavailable".into()))?;
        Ok(URL_SAFE_NO_PAD.encode(bytes))
    }

    /// Download GitHub's `web-flow` public key (`<web>/web-flow.gpg`) for the
    /// platform keyring. Never called implicitly: the keyring is
    /// configuration, and fetching it is a choice the operator makes and
    /// can review.
    pub async fn fetch_web_flow_key(&self) -> Result<Vec<u8>> {
        let url = self.api.web_url(&["web-flow.gpg"]);
        let resp = self
            .api
            .send(Method::GET, url, Auth::None, None, "web-flow key")
            .await?;
        resp.bytes()
            .await
            .map(|b| b.to_vec())
            .map_err(|e| ForgeError::Unavailable(e.without_url().to_string()))
    }

    // ── credentials ──────────────────────────────────────────────────────

    async fn jwt(&self) -> Result<Secret> {
        let issuer = match self.config.jwt_issuer {
            JwtIssuer::AppId => self.config.app_id.to_string(),
            _ => self.config.client_id.clone(),
        };
        app_jwt(self.signer.as_ref(), &issuer).await
    }

    /// Mint an installation token for `ns`, limited to `repo` (when given)
    /// and `perms`. Dropped by the caller when the operation returns.
    async fn installation_token(
        &self,
        ns: &Namespace,
        repo: Option<&str>,
        perms: &[(&str, &str)],
    ) -> Result<Secret> {
        let installation = ns.installation_id.ok_or_else(|| ForgeError::Unsupported {
            operation: "forge automation".into(),
            hint: format!(
                "namespace `{}` is in manual mode (no App installation); run the steps by hand \
                 with `vgi repo init`",
                ns.resource
            ),
        })?;
        let jwt = self.jwt().await?;
        let permissions: BTreeMap<_, _> = perms.iter().copied().collect();
        let mut body = json!({ "permissions": permissions });
        if let Some(repo) = repo {
            body["repositories"] = json!([repo]);
        }
        let url = self.api.url(&[
            "app",
            "installations",
            &installation.to_string(),
            "access_tokens",
        ]);
        #[derive(Deserialize)]
        struct Token {
            token: String,
        }
        let t: Token = self
            .api
            .json(
                Method::POST,
                url,
                Auth::Bearer(&jwt),
                Some(&body),
                "installation token",
            )
            .await
            .map_err(|e| match e {
                // GitHub answers 422 too when the installation has not
                // granted a permission the token asks for (an App whose
                // owner has not approved an upgrade): that is "forbidden",
                // and the namespace's `missingPermissions` says which.
                ForgeError::Rejected {
                    status: 422,
                    ref message,
                } if message.contains("permissions requested are not granted") => {
                    ForgeError::Forbidden(format!(
                        "the App installation on `{}` does not grant {}: {message}",
                        ns.resource,
                        perms
                            .iter()
                            .map(|(n, l)| format!("{n}:{l}"))
                            .collect::<Vec<_>>()
                            .join(", ")
                    ))
                }
                // GitHub answers 422 when a named repository is not in the
                // installation — for the caller that is "not found".
                ForgeError::Rejected { status: 422, .. } if repo.is_some() => {
                    ForgeError::NotFound {
                        what: format!(
                            "{}/{} (not visible to the App installation)",
                            ns.resource,
                            repo.unwrap_or_default()
                        ),
                    }
                }
                e => e,
            })?;
        Ok(Secret::new(t.token))
    }

    fn namespace(&self, ns: &Resource) -> Result<Namespace> {
        self.namespaces
            .read()
            .expect("namespace lock poisoned")
            .get(ns)
            .cloned()
            .ok_or_else(|| ForgeError::NotBound {
                namespace: ns.to_string(),
            })
    }

    /// Check `repo` is a repository on this forge and return its namespace,
    /// owner and name.
    fn locate<'r>(&self, repo: &'r Resource) -> Result<(Namespace, &'r str, &'r str)> {
        if repo.host() != self.config.host {
            return Err(ForgeError::WrongResource {
                resource: repo.to_string(),
                expected: format!("a repository on `{}`", self.config.host),
            });
        }
        // A `Resource` from a bridge job was validated against the general
        // grammar (any depth). Splitting `github.com/acme/evil/widgets` into
        // first and last segment would act on `acme/widgets`.
        repo.require_owner_repo()?;
        let name = repo.repo_name().ok_or_else(|| ForgeError::WrongResource {
            resource: repo.to_string(),
            expected: "a repository (`<host>/<owner>/<repo>`), not a namespace".into(),
        })?;
        Ok((self.namespace(&repo.namespace())?, repo.owner(), name))
    }

    async fn repo_token(
        &self,
        repo: &Resource,
        perms: &[(&str, &str)],
    ) -> Result<(Secret, String, String)> {
        let (ns, owner, name) = self.locate(repo)?;
        let token = self.installation_token(&ns, Some(name), perms).await?;
        Ok((token, owner.to_string(), name.to_string()))
    }

    /// The GitHub Actions App's id — what the required check is pinned to.
    async fn actions_app_id(&self, token: &Secret) -> Result<u64> {
        if let Some(id) = *self.actions_app_id.lock().expect("lock poisoned") {
            return Ok(id);
        }
        #[derive(Deserialize)]
        struct App {
            id: u64,
        }
        let app: App = self
            .api
            .json(
                Method::GET,
                self.api.url(&["apps", "github-actions"]),
                Auth::Bearer(token),
                None,
                "GitHub Actions app",
            )
            .await?;
        *self.actions_app_id.lock().expect("lock poisoned") = Some(app.id);
        Ok(app.id)
    }

    /// `DELETE /applications/{client_id}/token`, authenticated with the
    /// client id and secret. Best effort: the link already succeeded, and a
    /// token that could not be revoked still lapses on its own — so a
    /// failure is logged, not returned.
    async fn revoke_user_token(&self, token: &Secret) {
        let Some(secret) = &self.client_secret else {
            return;
        };
        let url = self
            .api
            .url(&["applications", &self.config.client_id, "token"]);
        let body = json!({ "access_token": token.expose() });
        if let Err(e) = self
            .api
            .basic_delete(url, &self.config.client_id, secret, &body)
            .await
        {
            tracing::warn!(error = %e, "could not revoke a member's user token after linking");
        }
    }

    // ── reads ────────────────────────────────────────────────────────────

    /// Where repository `id` is now, as namespace `ns`'s installation sees it
    /// (`GET /repositories/{id}` with that installation's token): `None` if
    /// it cannot see it. What a transfer into `ns` is confirmed by — GitHub's
    /// word, not a webhook's.
    pub async fn repository_by_id(&self, ns: &Resource, id: u64) -> Result<Option<Resource>> {
        let namespace = self.namespace(ns)?;
        let token = self
            .installation_token(&namespace, None, PERMS_METADATA)
            .await?;
        let url = self.api.url(&["repositories", &id.to_string()]);
        let r: Option<RepoJson> = self
            .api
            .get_opt(url, Auth::Bearer(&token), "repository")
            .await?;
        match r {
            Some(r) if r.id == id => Ok(Some(Resource::parse_owner_repo(&format!(
                "{}/{}",
                self.config.host, r.full_name
            ))?)),
            _ => Ok(None),
        }
    }

    fn repo_state(&self, r: &RepoJson) -> Result<RepoState> {
        let resource =
            Resource::parse_owner_repo(&format!("{}/{}", self.config.host, r.full_name))?;
        let mut state = RepoState::new(resource, r.id);
        state.visibility = match r.visibility.as_deref() {
            Some("public") => Visibility::Public,
            Some("internal") => Visibility::Internal,
            Some("private") => Visibility::Private,
            _ if r.private => Visibility::Private,
            _ => Visibility::Public,
        };
        state.archived = r.archived;
        state.default_branch = r.default_branch.clone();
        Ok(state)
    }

    async fn collaborators(
        &self,
        token: &Secret,
        owner: &str,
        name: &str,
    ) -> Result<Vec<CollaboratorJson>> {
        let mut url = self.api.url(&["repos", owner, name, "collaborators"]);
        url.query_pairs_mut().append_pair("affiliation", "direct");
        self.api
            .get_all(url, Auth::Bearer(token), "collaborators")
            .await
    }

    async fn invitations(
        &self,
        token: &Secret,
        owner: &str,
        name: &str,
    ) -> Result<Vec<InvitationJson>> {
        let url = self.api.url(&["repos", owner, name, "invitations"]);
        self.api
            .get_all(url, Auth::Bearer(token), "invitations")
            .await
    }

    async fn managed_ruleset(
        &self,
        token: &Secret,
        owner: &str,
        name: &str,
    ) -> Result<Option<RulesetJson>> {
        let mut url = self.api.url(&["repos", owner, name, "rulesets"]);
        url.query_pairs_mut()
            .append_pair("includes_parents", "false");
        let list: Vec<RulesetSummary> = self
            .api
            .get_all(url, Auth::Bearer(token), "rulesets")
            .await?;
        let Some(summary) = list.into_iter().find(|r| r.name == RULESET_NAME) else {
            return Ok(None);
        };
        let url = self
            .api
            .url(&["repos", owner, name, "rulesets", &summary.id.to_string()]);
        self.api.get_opt(url, Auth::Bearer(token), "ruleset").await
    }

    fn protection(
        &self,
        rs: &RulesetJson,
        default_branch: Option<&str>,
        actions_id: Option<u64>,
    ) -> ProtectionState {
        protection_of(rs, default_branch, actions_id)
    }

    // ── bootstrap steps ──────────────────────────────────────────────────

    async fn write_file(
        &self,
        repo: &Resource,
        path: &str,
        contents: &[u8],
        message: &str,
    ) -> Result<StepOutcome> {
        validate_repo_path(path)?;
        let (token, owner, name) = self.repo_token(repo, PERMS_CONTENTS).await?;
        self.write_file_with(&token, &owner, &name, path, contents, message)
            .await
    }

    /// [`GitHubForge::write_file`] with a contents token already in hand.
    async fn write_file_with(
        &self,
        token: &Secret,
        owner: &str,
        name: &str,
        path: &str,
        contents: &[u8],
        message: &str,
    ) -> Result<StepOutcome> {
        validate_repo_path(path)?;
        let mut segments = vec!["repos", owner, name, "contents"];
        segments.extend(path.split('/'));
        let url = self.api.url(&segments);

        // A directory at `path` answers with a JSON array, a file with an
        // object: read it untyped first so the conflict is reported as one.
        let existing: Option<Value> = self
            .api
            .get_opt(url.clone(), Auth::Bearer(token), path)
            .await?;
        let existing = match existing {
            Some(Value::Array(_)) => {
                return Err(ForgeError::Rejected {
                    status: 409,
                    message: format!("`{path}` exists and is a directory, not a file"),
                });
            }
            Some(v) => Some(
                serde_json::from_value::<ContentJson>(v)
                    .map_err(|e| ForgeError::Protocol(format!("{path}: {e}")))?,
            ),
            None => None,
        };
        let sha = match existing {
            Some(c) if c.kind != "file" => {
                return Err(ForgeError::Rejected {
                    status: 409,
                    message: format!("`{path}` exists and is a {}, not a file", c.kind),
                });
            }
            Some(c) => {
                if decode_content(&c)? == contents {
                    return Ok(StepOutcome::Unchanged);
                }
                Some(c.sha)
            }
            None => None,
        };

        let mut body = json!({ "message": message, "content": STANDARD.encode(contents) });
        if let Some(sha) = &sha {
            body["sha"] = json!(sha);
        }
        self.api
            .send(Method::PUT, url, Auth::Bearer(token), Some(&body), path)
            .await
            .map_err(|e| match e {
                ForgeError::Rejected { status, message } => ForgeError::Rejected {
                    status,
                    message: format!(
                        "{message} — if the default branch is already protected, this file can \
                         only change through a pull request (the ruleset has no bypass actors, \
                         by design)"
                    ),
                },
                e => e,
            })?;
        Ok(if sha.is_some() {
            StepOutcome::Updated
        } else {
            StepOutcome::Created
        })
    }

    async fn set_variable(&self, repo: &Resource, var: &str, value: &str) -> Result<StepOutcome> {
        check_variable_name(var)?;
        let (token, owner, name) = self.repo_token(repo, PERMS_VARIABLES).await?;
        let url = self
            .api
            .url(&["repos", &owner, &name, "actions", "variables", var]);
        #[derive(Deserialize)]
        struct Variable {
            value: String,
        }
        let body = json!({ "name": var, "value": value });
        match self
            .api
            .get_opt::<Variable>(url.clone(), Auth::Bearer(&token), var)
            .await?
        {
            Some(v) if v.value == value => Ok(StepOutcome::Unchanged),
            Some(_) => {
                self.api
                    .send(Method::PATCH, url, Auth::Bearer(&token), Some(&body), var)
                    .await?;
                Ok(StepOutcome::Updated)
            }
            None => {
                let url = self
                    .api
                    .url(&["repos", &owner, &name, "actions", "variables"]);
                self.api
                    .send(Method::POST, url, Auth::Bearer(&token), Some(&body), var)
                    .await?;
                Ok(StepOutcome::Created)
            }
        }
    }

    async fn protect(&self, repo: &Resource, spec: &ProtectionSpec) -> Result<StepOutcome> {
        let (ns, _, _) = self.locate(repo)?;
        let (token, owner, name) = self.repo_token(repo, PERMS_ADMIN).await?;
        let bridge_posted = self.capabilities(&ns).bridge_posted_check;
        self.protect_with(&token, &owner, &name, spec, bridge_posted)
            .await
    }

    /// The App a required check is pinned to: this App where the bridge
    /// posts the check itself, the GitHub Actions App otherwise.
    async fn check_integration_id(&self, token: &Secret, bridge_posted: bool) -> Result<u64> {
        if bridge_posted {
            Ok(self.config.app_id)
        } else {
            self.actions_app_id(token).await
        }
    }

    /// Converge the managed ruleset on `owner/name` to `spec`, with a token
    /// holding administration on it. `bridge_posted` pins the required check
    /// to this App instead of GitHub Actions.
    async fn protect_with(
        &self,
        token: &Secret,
        owner: &str,
        name: &str,
        spec: &ProtectionSpec,
        bridge_posted: bool,
    ) -> Result<StepOutcome> {
        // Looked up only when this rule carries the check: under a required
        // workflow the org ruleset does.
        let actions_id = if spec.require_status_check {
            Some(self.check_integration_id(token, bridge_posted).await?)
        } else {
            None
        };
        let repo_json: RepoJson = self
            .api
            .json(
                Method::GET,
                self.api.url(&["repos", owner, name]),
                Auth::Bearer(token),
                None,
                name,
            )
            .await?;
        let body = ruleset_body(spec, actions_id);

        match self.managed_ruleset(token, owner, name).await? {
            Some(rs) => {
                let observed =
                    self.protection(&rs, repo_json.default_branch.as_deref(), actions_id);
                if satisfies(&observed, spec) && rules_match(&rs, spec) {
                    return Ok(StepOutcome::Unchanged);
                }
                let url = self
                    .api
                    .url(&["repos", owner, name, "rulesets", &rs.id.to_string()]);
                self.api
                    .send(
                        Method::PUT,
                        url,
                        Auth::Bearer(token),
                        Some(&body),
                        "ruleset",
                    )
                    .await?;
                Ok(StepOutcome::Updated)
            }
            None => {
                let url = self.api.url(&["repos", owner, name, "rulesets"]);
                self.api
                    .send(
                        Method::POST,
                        url,
                        Auth::Bearer(token),
                        Some(&body),
                        "ruleset",
                    )
                    .await?;
                Ok(StepOutcome::Created)
            }
        }
    }

    /// Make sure `path` is absent from the default branch.
    async fn remove_file(&self, repo: &Resource, path: &str, message: &str) -> Result<StepOutcome> {
        validate_repo_path(path)?;
        let (token, owner, name) = self.repo_token(repo, PERMS_CONTENTS).await?;
        let Some((_, sha)) = self.file_at(&token, &owner, &name, path, None).await? else {
            return Ok(StepOutcome::Unchanged);
        };
        let mut segments = vec!["repos", owner.as_str(), name.as_str(), "contents"];
        segments.extend(path.split('/'));
        let body = json!({ "message": message, "sha": sha });
        self.api
            .send(
                Method::DELETE,
                self.api.url(&segments),
                Auth::Bearer(&token),
                Some(&body),
                path,
            )
            .await
            .map_err(|e| match e {
                ForgeError::Rejected { status, message } => ForgeError::Rejected {
                    status,
                    message: format!(
                        "{message} — the default branch is protected, so this clean-up has to \
                         land through a pull request"
                    ),
                },
                e => e,
            })?;
        Ok(StepOutcome::Updated)
    }

    /// Make sure CI variable `var` is absent.
    async fn remove_variable(&self, repo: &Resource, var: &str) -> Result<StepOutcome> {
        check_variable_name(var)?;
        let (token, owner, name) = self.repo_token(repo, PERMS_VARIABLES).await?;
        let url = self
            .api
            .url(&["repos", &owner, &name, "actions", "variables", var]);
        if self
            .api
            .get_opt::<Value>(url.clone(), Auth::Bearer(&token), var)
            .await?
            .is_none()
        {
            return Ok(StepOutcome::Unchanged);
        }
        self.api
            .send(Method::DELETE, url, Auth::Bearer(&token), None, var)
            .await?;
        Ok(StepOutcome::Updated)
    }

    // ── roles ────────────────────────────────────────────────────────────

    /// Whether `id` is the account holder of a personal-account namespace:
    /// the repository's implicit admin, never a collaborator to add, report
    /// or remove.
    fn is_personal_owner(ns: &Namespace, id: u64) -> bool {
        ns.kind == NamespaceKind::User && Some(id) == ns.owner_id
    }

    /// Drop assignments GitHub cannot express: the owner of a personal
    /// account is its implicit admin and cannot be added as a collaborator.
    fn expressible(&self, ns: &Namespace, desired: &[RoleAssignment]) -> Vec<RoleAssignment> {
        desired
            .iter()
            .filter(|a| !Self::is_personal_owner(ns, a.account.id))
            .cloned()
            .collect()
    }

    async fn login_for(&self, token: &Secret, id: u64) -> Result<String> {
        // The numeric id is the binding; the login is looked up fresh so a
        // renamed-and-re-registered login never receives the role.
        let user: UserJson = self
            .api
            .json(
                Method::GET,
                self.api.url(&["user", &id.to_string()]),
                Auth::Bearer(token),
                None,
                "user",
            )
            .await?;
        if user.id != id {
            return Err(ForgeError::Protocol(format!(
                "asked for user {id}, GitHub answered with {}",
                user.id
            )));
        }
        Ok(user.login)
    }

    #[allow(clippy::too_many_arguments)]
    async fn change_role(
        &self,
        token: &Secret,
        ns: &Namespace,
        owner: &str,
        name: &str,
        account: &ForgeAccount,
        to: ForgeRole,
        current: Option<&Current>,
    ) -> Result<RoleOutcome> {
        let auth = Auth::Bearer(token);
        match (current, to) {
            (Some(Current::Invited { id, .. }), ForgeRole::None) => {
                let url = self
                    .api
                    .url(&["repos", owner, name, "invitations", &id.to_string()]);
                self.api
                    .send(Method::DELETE, url, auth, None, "invitation")
                    .await?;
                Ok(RoleOutcome::Applied)
            }
            (Some(Current::Member { login, .. }), ForgeRole::None) => {
                let url = self
                    .api
                    .url(&["repos", owner, name, "collaborators", login]);
                self.api
                    .send(Method::DELETE, url, auth, None, "collaborator")
                    .await?;
                Ok(RoleOutcome::Applied)
            }
            (None, ForgeRole::None) => Ok(RoleOutcome::Applied),
            (Some(Current::Invited { id, .. }), role) => {
                let url = self
                    .api
                    .url(&["repos", owner, name, "invitations", &id.to_string()]);
                let body = json!({ "permissions": invitation_permission(role) });
                self.api
                    .send(Method::PATCH, url, auth, Some(&body), "invitation")
                    .await?;
                Ok(RoleOutcome::Invited)
            }
            (_, role) => {
                let login = self.login_for(token, account.id).await?;
                let url = self
                    .api
                    .url(&["repos", owner, name, "collaborators", &login]);
                // Personal-account repos take no permission: collaborators
                // there are always `write`.
                let body = (ns.kind == NamespaceKind::Organization)
                    .then(|| json!({ "permission": put_permission(role) }));
                let resp = self
                    .api
                    .send(Method::PUT, url, auth, body.as_ref(), "collaborator")
                    .await?;
                Ok(if resp.status() == reqwest::StatusCode::CREATED {
                    RoleOutcome::Invited
                } else {
                    RoleOutcome::Applied
                })
            }
        }
    }

    /// Where `login`'s access to an organisation's repository comes from,
    /// other than a direct role: owning the organisation, the teams with
    /// access to the repository that they are in, or — failing both — the
    /// organisation's base permission for members. Best effort: a lookup
    /// GitHub refuses leaves that source out, and the access is still
    /// reported.
    async fn access_sources(
        &self,
        token: &Secret,
        owner: &str,
        name: &str,
        login: &str,
    ) -> Vec<AccessSource> {
        let auth = Auth::Bearer(token);
        let membership = |url| async move {
            self.api
                .get_opt::<MembershipJson>(url, auth, "membership")
                .await
                .ok()
                .flatten()
                .filter(|m| m.state == "active")
        };
        let mut via = Vec::new();
        let org = membership(self.api.url(&["orgs", owner, "memberships", login])).await;
        if org.as_ref().is_some_and(|m| m.role == "admin") {
            via.push(AccessSource::OrgOwner(owner.to_string()));
        }
        let teams: Vec<TeamJson> = self
            .api
            .get_all(
                self.api.url(&["repos", owner, name, "teams"]),
                auth,
                "repository teams",
            )
            .await
            .unwrap_or_default();
        for t in teams {
            let url = self
                .api
                .url(&["orgs", owner, "teams", &t.slug, "memberships", login]);
            if membership(url).await.is_some() {
                via.push(AccessSource::Team(t.name));
            }
        }
        if via.is_empty() && org.is_some() {
            via.push(AccessSource::OrgMember(owner.to_string()));
        }
        via
    }
}

/// Where someone stands on a repository before a change.
enum Current {
    Member { login: String, role: ForgeRole },
    Invited { id: u64, role: ForgeRole },
}

impl Current {
    fn role(&self) -> ForgeRole {
        match self {
            Current::Member { role, .. } | Current::Invited { role, .. } => *role,
        }
    }
}

#[async_trait]
impl Forge for GitHubForge {
    fn kind(&self) -> ForgeKind {
        ForgeKind::GitHub
    }

    fn host(&self) -> &str {
        &self.config.host
    }

    fn capabilities(&self, ns: &Namespace) -> Capabilities {
        let automated = ns.installation_id.is_some();
        let mut c = Capabilities::default();
        c.automation = automated;
        c.required_checks = RequiredCheckKind::Ruleset;
        c.account_link = LinkMethod::DeviceFlow;
        c.webhooks = automated;
        c.per_repo_tokens = automated;
        c.required_workflow = automated
            && ns.kind == NamespaceKind::Organization
            && self.required_workflow_known(&ns.resource);
        // Without a namespace workflow the bridge posts the check itself
        // when configured to (§9, forged check runs): then nothing in the
        // repository is on the check's path at all.
        c.bridge_posted_check = automated
            && !c.required_workflow
            && self.config.bridge_checks
            && self.bridge_checks_ready(&ns.resource) == Some(true);
        // Otherwise a single-owner repository gets no review requirement on
        // its workflow (the user's decision: there is nobody else to review,
        // and its owner controls the repository anyway).
        c.single_owner_repos_unreviewed = !c.required_workflow && !c.bridge_posted_check;
        match ns.kind {
            NamespaceKind::User => {
                // §8: only the account holder can create repositories, and
                // every collaborator is `write`.
                c.bot_can_create_repos = false;
                c.role_levels = USER_LADDER.to_vec();
            }
            _ => {
                c.bot_can_create_repos = automated;
                c.role_levels = ORG_LADDER.to_vec();
            }
        }
        c
    }

    async fn begin_bind(&self, req: BindRequest) -> Result<BindStep> {
        if req.namespace.host() != self.config.host || !req.namespace.is_namespace() {
            return Err(ForgeError::WrongResource {
                resource: req.namespace.to_string(),
                expected: format!("a namespace on `{}`", self.config.host),
            });
        }
        if req.state.len() < MIN_STATE_LEN
            || !req
                .state
                .bytes()
                .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
        {
            return Err(ForgeError::Config(format!(
                "bind state must be at least {MIN_STATE_LEN} base64url characters from a CSPRNG \
                 (see GitHubForge::new_state)"
            )));
        }
        let mut url = self
            .api
            .web_url(&["apps", &self.config.app_slug, "installations", "new"]);
        url.query_pairs_mut().append_pair("state", &req.state);
        Ok(BindStep::Redirect {
            url: url.to_string(),
        })
    }

    async fn complete_bind(&self, cb: BindCallback) -> Result<NamespaceBinding> {
        let reject = |m: String| Err(ForgeError::BindRejected(m));
        let state = cb.params.get("state").map(String::as_str).unwrap_or("");
        if cb.expected_state.len() < MIN_STATE_LEN
            || aws_lc_rs::constant_time::verify_slices_are_equal(
                state.as_bytes(),
                cb.expected_state.as_bytes(),
            )
            .is_err()
        {
            return reject("the `state` does not match a bind this VTC started".into());
        }
        match cb.params.get("setup_action").map(String::as_str) {
            Some("install") | Some("update") | None => {}
            Some("request") => {
                return reject(
                    "the installation was requested but an owner has not approved it yet".into(),
                );
            }
            Some(other) => return reject(format!("unexpected setup_action `{other}`")),
        }
        if cb.expected_namespace.host() != self.config.host || !cb.expected_namespace.is_namespace()
        {
            return reject(format!(
                "`{}` is not a namespace on `{}`",
                cb.expected_namespace, self.config.host
            ));
        }
        let installation_id: u64 = match cb.params.get("installation_id").map(|s| s.parse()) {
            Some(Ok(id)) => id,
            _ => return reject("missing or malformed `installation_id`".into()),
        };

        // Authenticated as the App, this only finds installations of *this*
        // App — another App's id is a 404.
        let jwt = self.jwt().await?;
        let url = self
            .api
            .url(&["app", "installations", &installation_id.to_string()]);
        let inst: InstallationJson = match self
            .api
            .json(Method::GET, url, Auth::Bearer(&jwt), None, "installation")
            .await
        {
            Ok(i) => i,
            Err(ForgeError::NotFound { .. }) => {
                return reject(format!(
                    "installation {installation_id} is not an installation of this App"
                ));
            }
            Err(e) => return Err(e),
        };
        if inst.id != installation_id {
            return reject("GitHub returned a different installation".into());
        }
        if !inst
            .account
            .login
            .eq_ignore_ascii_case(cb.expected_namespace.owner())
        {
            return reject(format!(
                "the App was installed on `{}`, but the bind was for `{}`",
                inst.account.login, cb.expected_namespace
            ));
        }
        if inst.suspended_at.is_some() {
            return reject("the installation is suspended".into());
        }
        let kind = match inst.account.kind.as_str() {
            "Organization" => NamespaceKind::Organization,
            "User" => NamespaceKind::User,
            other => return reject(format!("unsupported account type `{other}`")),
        };
        let namespace = Namespace::new(cb.expected_namespace.clone(), kind)
            .with_owner_id(inst.account.id)
            .with_installation(installation_id);
        // Whether this org can have a required workflow (§9). Best effort:
        // a failure leaves it unknown, which plans the owner-review fallback
        // until `detect_required_workflow` is run again.
        let probed = match self.probe_org_rulesets(&namespace).await {
            Ok(available) => {
                self.set_required_workflow(&namespace.resource, available);
                true
            }
            Err(e) => {
                tracing::warn!(error = %e, "could not tell whether org rulesets are available");
                false
            }
        };
        // Whether the installation carries the bridge-posted check: its
        // permissions *and* its event subscriptions (an App registered before
        // they were in the manifest lacks both until its owner approves).
        self.set_bridge_checks_ready(
            &namespace.resource,
            crate::manifest::check_ready(&inst.permissions, &inst.events),
        );
        let binding = NamespaceBinding::new(namespace, installation_missing(&inst));
        // Handed back as data for the bridge to persist; the adapter's copy
        // is in memory only.
        Ok(if probed {
            let caps = self.capabilities(&binding.namespace);
            binding.with_capabilities(caps)
        } else {
            binding
        })
    }

    async fn begin_account_link(&self, member: &str) -> Result<LinkStep> {
        tracing::debug!(member, "starting GitHub device flow");
        let url = self.api.web_url(&["login", "device", "code"]);
        let resp: DeviceCodeJson = self
            .api
            .oauth(url, &json!({ "client_id": self.config.client_id }))
            .await?;
        if let Some(err) = resp.error {
            return Err(ForgeError::LinkFailed(format!(
                "{err}: {}",
                resp.error_description.unwrap_or_default()
            )));
        }
        let missing = || ForgeError::Protocol("device code response is incomplete".into());
        Ok(LinkStep::DeviceCode {
            device_code: resp.device_code.ok_or_else(missing)?,
            user_code: resp.user_code.ok_or_else(missing)?,
            verification_uri: resp.verification_uri.ok_or_else(missing)?,
            expires_in: resp.expires_in.ok_or_else(missing)?,
            interval: resp.interval.unwrap_or(5),
        })
    }

    async fn complete_account_link(&self, cb: LinkCallback) -> Result<ForgeAccount> {
        let LinkCallback::DeviceCode {
            device_code,
            mut interval,
            expires_in,
        } = cb
        else {
            return Err(ForgeError::Unsupported {
                operation: "redirect account link".into(),
                hint: "GitHub links accounts through the device flow".into(),
            });
        };
        let url = self.api.web_url(&["login", "oauth", "access_token"]);
        let body = json!({
            "client_id": self.config.client_id,
            "device_code": device_code,
            "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
        });
        // `expires_in` comes back from the caller, not from GitHub; never
        // poll longer than GitHub lets a device code live.
        let expires_in = expires_in.min(DEVICE_CODE_MAX_LIFETIME_SECS);
        let mut waited = 0u64;
        let token = loop {
            if waited >= expires_in {
                return Err(ForgeError::LinkFailed(
                    "the device code expired before the member approved; start again".into(),
                ));
            }
            tokio::time::sleep(self.config.device_poll_unit * interval.max(1) as u32).await;
            waited += interval.max(1);
            let poll: TokenPollJson = self.api.oauth(url.clone(), &body).await?;
            if let Some(token) = poll.access_token {
                break Secret::new(token);
            }
            match next_poll(interval, &poll)? {
                Some(next) => interval = next,
                None => unreachable!("next_poll returns Some or Err when there is no token"),
            }
        };

        let user: UserJson = self
            .api
            .json(
                Method::GET,
                self.api.url(&["user"]),
                Auth::Bearer(&token),
                None,
                "authenticated user",
            )
            .await?;
        // The bridge needs the id, not a standing credential for the
        // member's account: revoke the token when we can, and drop (wipe) it
        // either way.
        self.revoke_user_token(&token).await;
        Ok(ForgeAccount::new(user.id, user.login))
    }

    async fn inspect(&self, repo: &Resource) -> Result<RepoState> {
        let (ns, _, _) = self.locate(repo)?;
        let (token, owner, name) = self.repo_token(repo, PERMS_ADMIN).await?;
        let auth = Auth::Bearer(&token);
        let r: RepoJson = self
            .api
            .json(
                Method::GET,
                self.api.url(&["repos", &owner, &name]),
                auth,
                None,
                repo.as_str(),
            )
            .await?;
        let mut state = self.repo_state(&r)?;

        for c in self.collaborators(&token, &owner, &name).await? {
            if Self::is_personal_owner(&ns, c.id) {
                continue;
            }
            let role = c.role();
            state
                .collaborators
                .push(Collaborator::new(ForgeAccount::new(c.id, c.login), role));
        }
        for i in self.invitations(&token, &owner, &name).await? {
            if let Some(user) = i.invitee {
                state.collaborators.push(Collaborator::invited(
                    ForgeAccount::new(user.id, user.login),
                    role_from_name(&i.permissions).unwrap_or(ForgeRole::Read),
                ));
            }
        }
        let caps = self.capabilities(&ns);
        let rs = self.managed_ruleset(&token, &owner, &name).await?;
        if let Some(rs) = &rs {
            // Only a check pinned to the App that should post it counts.
            let check_app = self
                .check_integration_id(&token, caps.bridge_posted_check)
                .await?;
            state.protection = self.protection(rs, r.default_branch.as_deref(), Some(check_app));
        }
        if !caps.bridge_posted_check {
            // Actions runs the check only where the bridge does not.
            self.inspect_actions_policy(&token, &owner, &name, &mut state.protection)
                .await?;
        }
        drop(token);
        if caps.bridge_posted_check {
            // Nothing in the repository is on the check's path: the bridge
            // runs verify-trust from its own build and posts as its App.
            state.protection.check_source_guard = vgi_forge::CheckSourceGuard::BridgePosted;
        } else if caps.required_workflow {
            self.inspect_required_workflow(&ns, r.id, &mut state.protection)
                .await?;
        } else if caps.automation {
            self.inspect_owner_review(
                repo,
                &owner,
                &name,
                rs.as_ref(),
                r.default_branch.as_deref(),
                &mut state.protection,
            )
            .await?;
        }
        Ok(state)
    }

    async fn create_repo(&self, spec: &RepoSpec) -> Result<RepoState> {
        let (ns, owner, name) = self.locate(&spec.resource)?;
        if !self.capabilities(&ns).bot_can_create_repos {
            return Err(ForgeError::Unsupported {
                operation: "repository creation".into(),
                hint: format!(
                    "the bridge cannot create repositories in `{}`; the account holder runs \
                     `gh repo create {owner}/{name}` and `vgi repo init`, then the repo is adopted",
                    ns.resource
                ),
            });
        }
        // No repository to scope to yet: this token is org-wide, but only
        // for administration. Accepted residual (review F6): for the life of
        // this one call the token could administer every repository the
        // installation covers. GitHub offers no narrower grant for
        // `POST /orgs/{org}/repos`; the token is not reused and is dropped on
        // return.
        let token = self.installation_token(&ns, None, PERMS_ADMIN).await?;
        let auth = Auth::Bearer(&token);
        if let Some(existing) = self
            .api
            .get_opt::<RepoJson>(
                self.api.url(&["repos", owner, name]),
                auth,
                spec.resource.as_str(),
            )
            .await?
        {
            return Err(ForgeError::AlreadyExists {
                resource: spec.resource.to_string(),
                forge_id: Some(existing.id),
            });
        }
        let mut body = json!({
            "name": name,
            "visibility": match spec.visibility {
                Visibility::Private => "private",
                Visibility::Internal => "internal",
                _ => "public",
            },
            // A first commit gives the repo a default branch for the
            // bootstrap to commit to and the ruleset to cover.
            "auto_init": true,
        });
        if let Some(d) = &spec.description {
            body["description"] = json!(d);
        }
        let created: RepoJson = self
            .api
            .json(
                Method::POST,
                self.api.url(&["orgs", owner, "repos"]),
                auth,
                Some(&body),
                spec.resource.as_str(),
            )
            .await
            .map_err(|e| match e {
                ForgeError::Rejected {
                    status: 422,
                    message,
                } if message.contains("already exists") => ForgeError::AlreadyExists {
                    resource: spec.resource.to_string(),
                    forge_id: None,
                },
                e => e,
            })?;
        self.repo_state(&created)
    }

    async fn archive_repo(&self, repo: &Resource) -> Result<()> {
        let (token, owner, name) = self.repo_token(repo, PERMS_ADMIN).await?;
        let url = self.api.url(&["repos", &owner, &name]);
        let r: RepoJson = self
            .api
            .json(
                Method::GET,
                url.clone(),
                Auth::Bearer(&token),
                None,
                repo.as_str(),
            )
            .await?;
        if let Some(set) = self
            .managed
            .write()
            .expect("lock poisoned")
            .get_mut(&repo.namespace())
        {
            // An archived repository takes no pull requests: the org ruleset
            // drops it on its next convergence.
            set.remove(&r.id);
        }
        if r.archived {
            return Ok(());
        }
        self.api
            .send(
                Method::PATCH,
                url,
                Auth::Bearer(&token),
                Some(&json!({ "archived": true })),
                repo.as_str(),
            )
            .await?;
        Ok(())
    }

    async fn apply_roles(
        &self,
        repo: &Resource,
        desired: &[RoleAssignment],
        unlisted: Unlisted,
    ) -> Result<ApplyReport> {
        let (ns, owner, name) = self.locate(repo)?;
        let ladder = self.capabilities(&ns).role_levels;
        let desired = self.expressible(&ns, desired);
        let mut wanted: BTreeMap<u64, (ForgeAccount, ForgeRole)> = BTreeMap::new();
        for a in &desired {
            // Round down onto the ladder again: never trust the caller to
            // have done it, and never ask GitHub for more than it offers.
            let role = collapse_to_ladder(a.role, &ladder);
            if let Some((_, prev)) = wanted.insert(a.account.id, (a.account.clone(), role))
                && prev != role
            {
                return Err(ForgeError::Config(format!(
                    "account {} is assigned two different roles",
                    a.account.id
                )));
            }
        }

        let token = self
            .installation_token(&ns, Some(name), PERMS_ADMIN)
            .await?;
        let mut current: BTreeMap<u64, (ForgeAccount, Current)> = BTreeMap::new();
        for c in self.collaborators(&token, owner, name).await? {
            if Self::is_personal_owner(&ns, c.id) {
                continue;
            }
            let role = c.role();
            current.insert(
                c.id,
                (
                    ForgeAccount::new(c.id, c.login.clone()),
                    Current::Member {
                        login: c.login,
                        role,
                    },
                ),
            );
        }
        for i in self.invitations(&token, owner, name).await? {
            if let Some(user) = i.invitee {
                let role = role_from_name(&i.permissions).unwrap_or(ForgeRole::Read);
                current.entry(user.id).or_insert((
                    ForgeAccount::new(user.id, user.login),
                    Current::Invited { id: i.id, role },
                ));
            }
        }

        let mut report = ApplyReport::default();
        let mut todo: Vec<(ForgeAccount, ForgeRole)> = Vec::new();
        for (id, (account, role)) in &wanted {
            let have = current.get(id).map_or(ForgeRole::None, |(_, c)| c.role());
            if have == *role {
                if *role != ForgeRole::None {
                    report.unchanged.push(account.clone());
                }
            } else {
                todo.push((account.clone(), *role));
            }
        }
        for (id, (account, c)) in &current {
            if wanted.contains_key(id) {
                continue;
            }
            match unlisted {
                Unlisted::Remove => todo.push((account.clone(), ForgeRole::None)),
                _ => {
                    let mut collab = Collaborator::new(account.clone(), c.role());
                    collab.pending = matches!(c, Current::Invited { .. });
                    report.kept_unlisted.push(collab);
                }
            }
        }

        // The App's own bot user, by the login GitHub reports for it now: a
        // `[bot]` login cannot be registered by a person.
        let own_bot = format!("{}[bot]", self.config.app_slug);
        for (account, to) in todo {
            let cur = current.get(&account.id).map(|(_, c)| c);
            let from = cur.map_or(ForgeRole::None, Current::role);
            if to == ForgeRole::None
                && let Some(Current::Member { login, .. }) = cur
                && login.eq_ignore_ascii_case(&own_bot)
            {
                report.changes.push(RoleChange::new(
                    account,
                    from,
                    to,
                    RoleOutcome::Failed("the bridge's own App is never removed".into()),
                ));
                continue;
            }
            let outcome = match self
                .change_role(&token, &ns, owner, name, &account, to, cur)
                .await
            {
                Ok(o) => o,
                // Credentials and rate limits fail the whole job; anything
                // else is this one person's problem.
                Err(e @ (ForgeError::Unauthorized(_) | ForgeError::RateLimited { .. })) => {
                    return Err(e);
                }
                Err(e) => RoleOutcome::Failed(e.to_string()),
            };
            report
                .changes
                .push(RoleChange::new(account, from, to, outcome));
        }
        Ok(report)
    }

    /// GitHub's effective permission for the account
    /// (`/collaborators/{username}/permission` counts teams, organisation
    /// ownership and the base permission), then where it comes from.
    async fn indirect_access(
        &self,
        repo: &Resource,
        account: &ForgeAccount,
    ) -> Result<Option<IndirectAccess>> {
        let (ns, owner, name) = self.locate(repo)?;
        let org = ns.kind == NamespaceKind::Organization;
        let perms = if org { PERMS_ACCESS_ORG } else { PERMS_ACCESS };
        let token = self.installation_token(&ns, Some(name), perms).await?;
        let login = match self.login_for(&token, account.id).await {
            Ok(l) => l,
            // No such account any more: it has no access.
            Err(ForgeError::NotFound { .. }) => return Ok(None),
            Err(e) => return Err(e),
        };
        let url = self
            .api
            .url(&["repos", owner, name, "collaborators", &login, "permission"]);
        let Some(p) = self
            .api
            .get_opt::<PermissionJson>(url, Auth::Bearer(&token), "collaborator permission")
            .await?
        else {
            return Ok(None);
        };
        let role = p
            .role_name
            .as_deref()
            .and_then(role_from_name)
            .or_else(|| role_from_name(&p.permission))
            .unwrap_or(ForgeRole::None);
        if role == ForgeRole::None {
            return Ok(None);
        }
        if role == ForgeRole::Read {
            // Everyone reads a public repository (and every enterprise
            // member an internal one): that is no access to report.
            let r: RepoJson = self
                .api
                .json(
                    Method::GET,
                    self.api.url(&["repos", owner, name]),
                    Auth::Bearer(&token),
                    None,
                    repo.as_str(),
                )
                .await?;
            if self.repo_state(&r)?.visibility != Visibility::Private {
                return Ok(None);
            }
        }
        let via = if org {
            self.access_sources(&token, owner, name, &login).await
        } else {
            Vec::new()
        };
        Ok(Some(IndirectAccess::new(role, via)))
    }

    fn bootstrap_plan(&self, repo: &RepoSpec, cfg: &VgiConfig) -> Result<Vec<BootstrapStep>> {
        if repo.resource.host() != self.config.host {
            return Err(ForgeError::WrongResource {
                resource: repo.resource.to_string(),
                expected: format!("a repository on `{}`", self.config.host),
            });
        }
        repo.resource.require_owner_repo()?;
        let ns = self.namespace(&repo.resource.namespace())?;
        let guard = self.check_guard(&ns, repo);
        *self.verify_trust_action.lock().expect("lock poisoned") =
            Some(cfg.verify_trust_action.clone());
        github_plan(repo, cfg, &self.config.checkout_action, &guard)
    }

    async fn run_step(&self, repo: &Resource, step: &BootstrapStep) -> Result<StepOutcome> {
        match &step.action {
            StepAction::WriteFile {
                path,
                contents,
                message,
            } => self.write_file(repo, path, contents, message).await,
            StepAction::SetVariable { name, value } => self.set_variable(repo, name, value).await,
            StepAction::ProtectDefaultBranch(spec) => self.protect(repo, spec).await,
            StepAction::RequireNamespaceWorkflow {
                contents,
                check,
                message,
            } => {
                self.require_namespace_workflow(repo, contents, check, message)
                    .await
            }
            StepAction::RequireOwnerReview {
                paths,
                owners,
                community_rules,
                message,
            } => {
                self.require_owner_review(repo, paths, owners, community_rules, message)
                    .await
            }
            StepAction::RemoveFile { path, message } => self.remove_file(repo, path, message).await,
            StepAction::RemoveVariable { name } => self.remove_variable(repo, name).await,
            other => Err(ForgeError::Unsupported {
                operation: format!("bootstrap step {other:?}"),
                hint: "this GitHub adapter does not know that step".into(),
            }),
        }
    }

    async fn pull_request(&self, repo: &Resource, number: u64) -> Result<vgi_forge::PullRequest> {
        self.read_pull_request(repo, number).await
    }

    async fn has_own_comment(&self, repo: &Resource, number: u64, marker: &str) -> Result<bool> {
        self.find_own_comment(repo, number, marker).await
    }

    async fn comment_on_pull_request(
        &self,
        repo: &Resource,
        number: u64,
        body: &str,
    ) -> Result<()> {
        self.post_pull_request_comment(repo, number, body).await
    }

    async fn close_pull_request(&self, repo: &Resource, number: u64) -> Result<()> {
        self.patch_pull_request_closed(repo, number).await
    }

    fn parse_event(&self, headers: &HeaderMap, body: &[u8]) -> Result<Option<ForgeEvent>> {
        webhook::parse(&self.webhook_secret, &self.config.host, headers, body)
    }

    /// The default comparison, plus the owner-review guard against the
    /// projection's owners (§9, the user's decision on solo repositories):
    /// two or more owners must all be reviewers of a healthy guard; one
    /// owner needs no guard, and a guard left over from when there were
    /// more is a re-plan (it would lock the solo owner out).
    fn diff(&self, observed: &RepoState, desired: &Projection) -> Vec<Drift> {
        let mut drift = default_diff(observed, desired);
        if desired.required_check.is_some() {
            let ns = self.namespace(&desired.resource.namespace()).ok();
            drift.extend(guard::owner_review_drift(ns.as_ref(), observed, desired));
        }
        guard::merge_protection_drift(drift)
    }
}

impl ForgeHooks for GitHubForge {
    /// In a personal-account namespace the owner is the repository's
    /// implicit admin and GitHub refuses to add them as a collaborator, so
    /// they are dropped from the desired set before it reaches GitHub (and
    /// before the core reports their "missing" role as drift).
    fn before_apply_roles(
        &self,
        repo: &Resource,
        desired: &[RoleAssignment],
    ) -> HookDecision<Vec<RoleAssignment>> {
        let Ok(ns) = self.namespace(&repo.namespace()) else {
            return HookDecision::Continue;
        };
        let kept = self.expressible(&ns, desired);
        if kept.len() == desired.len() {
            HookDecision::Continue
        } else {
            HookDecision::Modify(kept)
        }
    }
}

/// What a ruleset enforces, read from GitHub's own shape of it. A required
/// check counts only when pinned to `actions_id` (the App the check must
/// come from).
fn protection_of(
    rs: &RulesetJson,
    default_branch: Option<&str>,
    actions_id: Option<u64>,
) -> ProtectionState {
    let mut p = ProtectionState::default();
    p.present = true;
    p.enforced = rs.enforcement == "active";

    let refs = |key: &str| -> Vec<String> {
        rs.conditions
            .as_ref()
            .and_then(|c| c.get("ref_name"))
            .and_then(|r| r.get(key))
            .and_then(Value::as_array)
            .map(|a| {
                a.iter()
                    .filter_map(Value::as_str)
                    .map(str::to_string)
                    .collect()
            })
            .unwrap_or_default()
    };
    let mut default_names = vec!["~DEFAULT_BRANCH".to_string(), "~ALL".to_string()];
    if let Some(b) = default_branch {
        default_names.push(format!("refs/heads/{b}"));
    }
    let (include, exclude) = (refs("include"), refs("exclude"));
    // Any exclusion at all counts as not covering: `refs/heads/*` or a
    // pattern matching the default branch excludes it as surely as its
    // literal name, and the managed ruleset is created with none.
    p.covers_default_branch = rs.target.as_deref().unwrap_or("branch") == "branch"
        && include.iter().any(|r| default_names.contains(r))
        && exclude.is_empty();

    for rule in &rs.rules {
        match rule.kind.as_str() {
            "pull_request" => p.requires_pull_request = true,
            "non_fast_forward" => p.blocks_force_push = true,
            "deletion" => p.blocks_deletion = true,
            "required_status_checks" => {
                let checks = rule
                    .parameters
                    .as_ref()
                    .and_then(|v| v.get("required_status_checks"))
                    .and_then(Value::as_array)
                    .cloned()
                    .unwrap_or_default();
                // Only a check pinned to the Actions App counts: an
                // unpinned one is satisfied by any status of that name,
                // which anyone with write access can post.
                p.required_checks.extend(checks.iter().filter_map(|c| {
                    let pinned = actions_id.is_some()
                        && c.get("integration_id").and_then(Value::as_u64) == actions_id;
                    pinned
                        .then(|| c.get("context").and_then(Value::as_str))
                        .flatten()
                        .map(str::to_string)
                }));
            }
            _ => {}
        }
    }

    match &rs.bypass_actors {
        Some(actors) => {
            p.bypass_actors = actors
                .iter()
                .map(|a| {
                    format!(
                        "{}:{}:{}",
                        a.actor_type,
                        a.actor_id.map_or_else(|| "-".into(), |i| i.to_string()),
                        a.bypass_mode.as_deref().unwrap_or("always")
                    )
                })
                .collect()
        }
        // Not visible to us is not the same as none: fail closed.
        None => p.bypass_actors = vec!["<bypass actors not visible to the bridge>".into()],
    }
    if let Some(mode) = rs.current_user_can_bypass.as_deref()
        && mode != "never"
    {
        p.bypass_actors.push(format!("bridge-app:{mode}"));
    }
    p
}

/// The ruleset GitHub is asked for: default branch, PR required, the check
/// required and pinned to the Actions App, no force-push, no deletion, and
/// an empty bypass list.
///
/// Public so a client acting as the repository's own admin (`vgi repo
/// init`) asks GitHub for exactly the ruleset the bridge would.
pub fn ruleset_body(spec: &ProtectionSpec, actions_id: Option<u64>) -> Value {
    let mut rules = Vec::new();
    if spec.block_deletion {
        rules.push(json!({ "type": "deletion" }));
    }
    if spec.block_force_push {
        rules.push(json!({ "type": "non_fast_forward" }));
    }
    if spec.require_pull_request {
        rules.push(json!({
            "type": "pull_request",
            "parameters": {
                // Owner review (§9): one approval, a code owner's where one
                // is named, dismissed by any later push, and not the last
                // pusher's own — or a reviewed change could be swapped after
                // approval.
                "required_approving_review_count": u8::from(spec.require_code_owner_review),
                "dismiss_stale_reviews_on_push": spec.require_code_owner_review,
                "require_code_owner_review": spec.require_code_owner_review,
                "require_last_push_approval": spec.require_code_owner_review,
                "required_review_thread_resolution": false,
            }
        }));
    }
    if let (true, Some(actions_id)) = (spec.require_status_check, actions_id) {
        rules.push(json!({
            "type": "required_status_checks",
            "parameters": {
                "strict_required_status_checks_policy": false,
                "required_status_checks": [
                    { "context": spec.required_check, "integration_id": actions_id }
                ],
            }
        }));
    }
    json!({
        "name": RULESET_NAME,
        "target": "branch",
        "enforcement": "active",
        "bypass_actors": [],
        "conditions": { "ref_name": { "include": ["~DEFAULT_BRANCH"], "exclude": [] } },
        "rules": rules,
    })
}

/// Whether `ruleset` — GitHub's JSON for one repository ruleset, as `GET
/// /repos/{owner}/{repo}/rulesets/{id}` returns it — already enforces `spec`
/// on a repository whose default branch is `default_branch`, with the
/// required check pinned to `actions_id`. The same test the adapter runs
/// before it rewrites its managed ruleset, so a client that converges on it
/// leaves a ruleset alone exactly when the bridge would.
pub fn ruleset_satisfies(
    ruleset: &Value,
    default_branch: Option<&str>,
    actions_id: Option<u64>,
    spec: &ProtectionSpec,
) -> Result<bool> {
    let rs: RulesetJson = serde_json::from_value(ruleset.clone())
        .map_err(|e| ForgeError::Protocol(format!("ruleset: {e}")))?;
    let observed = protection_of(&rs, default_branch, actions_id);
    Ok(satisfies(&observed, spec) && rules_match(&rs, spec))
}

fn check_variable_name(var: &str) -> Result<()> {
    if var.is_empty()
        || !var
            .bytes()
            .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_')
    {
        return Err(ForgeError::Config(format!(
            "variable name `{var}` must be [A-Z0-9_]"
        )));
    }
    Ok(())
}

/// Whether the ruleset's pull-request parameters and status-check rule are
/// exactly what `spec` asks for — no stricter either: a leftover code-owner
/// requirement locks a solo owner out, and a leftover status check is the
/// old guard's (L4).
fn rules_match(rs: &RulesetJson, spec: &ProtectionSpec) -> bool {
    let has_status = rs.rules.iter().any(|r| r.kind == "required_status_checks");
    let review = spec.require_code_owner_review;
    let pr_ok = !spec.require_pull_request
        || rs.rules.iter().any(|r| {
            let param = |k: &str| r.parameters.as_ref().and_then(|p| p.get(k)).cloned();
            let flag = |k: &str| param(k).and_then(|v| v.as_bool()).unwrap_or(false);
            r.kind == "pull_request"
                && param("required_approving_review_count")
                    .and_then(|v| v.as_u64())
                    .unwrap_or(0)
                    == u64::from(review)
                && flag("require_code_owner_review") == review
                && flag("dismiss_stale_reviews_on_push") == review
                && flag("require_last_push_approval") == review
        });
    has_status == spec.require_status_check && pr_ok
}

fn satisfies(observed: &ProtectionState, spec: &ProtectionSpec) -> bool {
    observed.present
        && observed.enforced
        && observed.covers_default_branch
        && observed.bypass_actors.is_empty()
        && (!spec.require_status_check || observed.required_checks.contains(&spec.required_check))
        && (!spec.require_pull_request || observed.requires_pull_request)
        && (!spec.block_force_push || observed.blocks_force_push)
        && (!spec.block_deletion || observed.blocks_deletion)
}

/// The next poll interval after a device-flow poll that returned no token:
/// `Some(interval)` to keep polling, `Err` to stop.
///
/// `slow_down` adds five seconds (RFC 8628 §3.5) unless GitHub names the new
/// interval itself.
pub(crate) fn next_poll(interval: u64, poll: &TokenPollJson) -> Result<Option<u64>> {
    match poll.error.as_deref() {
        Some("authorization_pending") => Ok(Some(interval)),
        Some("slow_down") => Ok(Some(
            poll.interval.unwrap_or(interval + 5).max(interval + 5),
        )),
        Some("expired_token") => Err(ForgeError::LinkFailed(
            "the device code expired before the member approved; start again".into(),
        )),
        Some("access_denied") => Err(ForgeError::LinkFailed(
            "the member declined the authorisation".into(),
        )),
        Some(other) => Err(ForgeError::LinkFailed(format!(
            "{other}: {}",
            poll.error_description.as_deref().unwrap_or("")
        ))),
        None => Err(ForgeError::Protocol(
            "token response has neither a token nor an error".into(),
        )),
    }
}

fn decode_content(c: &ContentJson) -> Result<Vec<u8>> {
    match c.encoding.as_deref() {
        Some("base64") => {
            let compact: String = c
                .content
                .as_deref()
                .unwrap_or("")
                .chars()
                .filter(|ch| !ch.is_whitespace())
                .collect();
            STANDARD
                .decode(compact)
                .map_err(|e| ForgeError::Protocol(format!("file content: {e}")))
        }
        // Over 1 MB GitHub returns `encoding: "none"` and no content. Nothing
        // the bootstrap writes is that large, so a file that is must have
        // been put there by someone else: refuse rather than overwrite what
        // we cannot see.
        Some("none") => Err(ForgeError::Rejected {
            status: 409,
            message: "the existing file is too large for GitHub to return inline (over 1 MB); \
                      it was not written by the bootstrap — remove or rename it"
                .into(),
        }),
        other => Err(ForgeError::Protocol(format!(
            "file content in unknown encoding {other:?}"
        ))),
    }
}

fn role_from_name(name: &str) -> Option<ForgeRole> {
    Some(match name {
        "admin" => ForgeRole::Admin,
        "maintain" => ForgeRole::Maintain,
        "write" | "push" => ForgeRole::Write,
        "triage" => ForgeRole::Triage,
        "read" | "pull" => ForgeRole::Read,
        _ => return None,
    })
}

fn put_permission(role: ForgeRole) -> &'static str {
    match role {
        ForgeRole::Admin => "admin",
        ForgeRole::Maintain => "maintain",
        ForgeRole::Write => "push",
        ForgeRole::Triage => "triage",
        _ => "pull",
    }
}

fn invitation_permission(role: ForgeRole) -> &'static str {
    match role {
        ForgeRole::Admin => "admin",
        ForgeRole::Maintain => "maintain",
        ForgeRole::Write => "write",
        ForgeRole::Triage => "triage",
        _ => "read",
    }
}

// ── wire shapes ──────────────────────────────────────────────────────────

#[derive(Deserialize)]
struct RepoJson {
    id: u64,
    full_name: String,
    #[serde(default)]
    visibility: Option<String>,
    #[serde(default)]
    private: bool,
    #[serde(default)]
    archived: bool,
    #[serde(default)]
    default_branch: Option<String>,
}

#[derive(Deserialize)]
struct UserJson {
    id: u64,
    login: String,
}

/// `GET /repos/{owner}/{repo}/collaborators/{username}/permission`: the
/// account's effective permission, whatever it comes from.
#[derive(Deserialize)]
struct PermissionJson {
    #[serde(default)]
    permission: String,
    #[serde(default)]
    role_name: Option<String>,
}

/// An organisation or team membership.
#[derive(Deserialize)]
struct MembershipJson {
    #[serde(default)]
    state: String,
    #[serde(default)]
    role: String,
}

#[derive(Deserialize)]
struct TeamJson {
    name: String,
    slug: String,
}

#[derive(Deserialize)]
struct CollaboratorJson {
    id: u64,
    login: String,
    #[serde(default)]
    role_name: Option<String>,
    #[serde(default)]
    permissions: Option<PermsJson>,
}

impl CollaboratorJson {
    /// `role_name`, or — for a custom role — the highest base permission.
    fn role(&self) -> ForgeRole {
        if let Some(role) = self.role_name.as_deref().and_then(role_from_name) {
            return role;
        }
        let p = self.permissions.as_ref();
        let has = |f: fn(&PermsJson) -> bool| p.is_some_and(f);
        if has(|p| p.admin) {
            ForgeRole::Admin
        } else if has(|p| p.maintain) {
            ForgeRole::Maintain
        } else if has(|p| p.push) {
            ForgeRole::Write
        } else if has(|p| p.triage) {
            ForgeRole::Triage
        } else {
            ForgeRole::Read
        }
    }
}

#[derive(Deserialize, Default)]
#[serde(default)]
struct PermsJson {
    admin: bool,
    maintain: bool,
    push: bool,
    triage: bool,
}

#[derive(Deserialize)]
struct InvitationJson {
    id: u64,
    #[serde(default)]
    invitee: Option<UserJson>,
    permissions: String,
}

#[derive(Deserialize)]
struct RulesetSummary {
    id: u64,
    name: String,
}

#[derive(Deserialize)]
struct RulesetJson {
    id: u64,
    #[serde(default)]
    target: Option<String>,
    enforcement: String,
    /// Absent when the caller may not edit the ruleset — which is exactly
    /// when it must not be read as "none".
    #[serde(default)]
    bypass_actors: Option<Vec<BypassJson>>,
    #[serde(default)]
    current_user_can_bypass: Option<String>,
    #[serde(default)]
    conditions: Option<Value>,
    #[serde(default)]
    rules: Vec<RuleJson>,
}

#[derive(Deserialize)]
struct BypassJson {
    #[serde(default)]
    actor_id: Option<u64>,
    actor_type: String,
    #[serde(default)]
    bypass_mode: Option<String>,
}

#[derive(Deserialize)]
struct RuleJson {
    #[serde(rename = "type")]
    kind: String,
    #[serde(default)]
    parameters: Option<Value>,
}

#[derive(Deserialize)]
struct InstallationJson {
    id: u64,
    account: AccountJson,
    #[serde(default)]
    permissions: BTreeMap<String, String>,
    #[serde(default)]
    events: Vec<String>,
    #[serde(default)]
    suspended_at: Option<String>,
}

/// What an installation lacks of what the App asks for: permissions as
/// `name:level`, subscriptions as `event:<name>`.
fn installation_missing(inst: &InstallationJson) -> Vec<String> {
    let mut missing = missing_permissions(&inst.permissions);
    missing.extend(
        crate::manifest::CHECK_EVENTS
            .iter()
            .filter(|e| !inst.events.iter().any(|x| x == *e))
            .map(|e| format!("event:{e}")),
    );
    missing
}

#[derive(Deserialize)]
struct AccountJson {
    id: u64,
    login: String,
    #[serde(rename = "type")]
    kind: String,
}

#[derive(Deserialize)]
struct ContentJson {
    sha: String,
    #[serde(rename = "type")]
    kind: String,
    #[serde(default)]
    content: Option<String>,
    #[serde(default)]
    encoding: Option<String>,
}

#[derive(Deserialize)]
struct DeviceCodeJson {
    device_code: Option<String>,
    user_code: Option<String>,
    verification_uri: Option<String>,
    expires_in: Option<u64>,
    interval: Option<u64>,
    error: Option<String>,
    error_description: Option<String>,
}

#[derive(Deserialize, Default)]
pub(crate) struct TokenPollJson {
    pub(crate) access_token: Option<String>,
    pub(crate) error: Option<String>,
    pub(crate) error_description: Option<String>,
    pub(crate) interval: Option<u64>,
}

impl std::fmt::Debug for TokenPollJson {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TokenPollJson")
            .field(
                "access_token",
                &self.access_token.as_ref().map(|_| "<redacted>"),
            )
            .field("error", &self.error)
            .field("interval", &self.interval)
            .finish()
    }
}

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

    fn poll(error: &str, interval: Option<u64>) -> TokenPollJson {
        TokenPollJson {
            error: Some(error.into()),
            interval,
            ..TokenPollJson::default()
        }
    }

    #[test]
    fn device_polling_backs_off_on_slow_down() {
        assert_eq!(
            next_poll(5, &poll("authorization_pending", None)).unwrap(),
            Some(5)
        );
        assert_eq!(next_poll(5, &poll("slow_down", None)).unwrap(), Some(10));
        assert_eq!(
            next_poll(5, &poll("slow_down", Some(15))).unwrap(),
            Some(15)
        );
        // A smaller server-named interval never speeds us up past +5.
        assert_eq!(next_poll(5, &poll("slow_down", Some(1))).unwrap(), Some(10));
        assert!(matches!(
            next_poll(5, &poll("expired_token", None)),
            Err(ForgeError::LinkFailed(_))
        ));
        assert!(matches!(
            next_poll(5, &poll("access_denied", None)),
            Err(ForgeError::LinkFailed(_))
        ));
    }

    #[test]
    fn roles_map_both_ways() {
        for role in [
            ForgeRole::Read,
            ForgeRole::Triage,
            ForgeRole::Write,
            ForgeRole::Maintain,
            ForgeRole::Admin,
        ] {
            assert_eq!(role_from_name(invitation_permission(role)), Some(role));
            assert_eq!(role_from_name(put_permission(role)), Some(role));
        }
        let custom = CollaboratorJson {
            id: 1,
            login: "x".into(),
            role_name: Some("security-reviewer".into()),
            permissions: Some(PermsJson {
                triage: true,
                ..PermsJson::default()
            }),
        };
        assert_eq!(custom.role(), ForgeRole::Triage);
    }
}