vtc-service 0.12.0

Service for Verifiable Trust Communities
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
//! Second-party consent for authority-conferring grants — **VTI-APV-018**, the
//! generalisation of **VTI-APV-014**.
//!
//! > Creating an entry with unrestricted act scope, or widening an entry to
//! > unrestricted act scope, MUST require consent from a party other than the
//! > requester. (VTI-APV-014)
//!
//! At a VTC, administration is role-based (`vtc-admin-roles.md`), so the trigger
//! is no longer "unrestricted act scope" but **an authority-conferring
//! capability** (§4): one whose holder can create authority — its own or someone
//! else's. Granting or widening one is an N-of-M action in every case. One stolen
//! credential must not be enough to make one. The requester's own passkey
//! gesture proves the requester is present; it says nothing about whether anyone
//! else agrees. This module is the anyone-else.
//!
//! Design: `docs/05-design-notes/vtc-action-list.md` §4 (the action list) over
//! `docs/05-design-notes/vtc-operation-bound-step-up.md` §4, with the approver
//! sets of `vtc-admin-roles.md` §7.
//!
//! ## One model, not a parallel one (VTI-VTC-020)
//!
//! It is the VTA's DTTE ceremony — `task-consent/{request,decision}` — with the
//! approver set fixed by the requirement rather than by a configured rule:
//!
//! - **Trigger** ([`newly_conferred`]): an `acl/grant`, `acl/update` or
//!   `acl/change-role` whose resulting entry holds an authority-conferring
//!   capability, at a covering qualifier, that the entry before it did not.
//! - **Stake**: the capabilities conferred. **Approvers**: every other live
//!   entry that holds *and may approve* each of them at a covering qualifier
//!   ([`approvers_for`]) — `excludeRequester` is always on (VTI-APV-007), and a
//!   qualifier-bound approver approves only inside its qualifier.
//! - **Threshold**: [`crate::config_store::UNRESTRICTED_ADMIN_CONSENT_THRESHOLD`],
//!   default and minimum 1. A value the community cannot meet is refused when it
//!   is written ([`check_threshold_meetable`], VTI-APV-009).
//!
//! ## The loop: park, then complete on the N-th approval
//!
//! 1. The operation arrives and every other check passes. The requester's
//!    passkey gesture, bound to the operation, is asked for and spent
//!    (VTI-APV-015). The operation is then **parked** as an action
//!    ([`crate::admin_actions`]) — the requester's signed document verbatim,
//!    the approver set, the threshold, one challenge per approver and a pin on
//!    the state the approvers are shown — and the requester is answered with a
//!    `trust-task-next-step/0.1` naming `vtc/admin/actions/show` (continuation
//!    `proceed`). Nothing is asked of the requester again.
//! 2. Approvers answer `task-consent/decision`, each signed by the approver's
//!    own DID. One deny closes the action for everyone.
//! 3. The approval that reaches the threshold **executes** the parked document
//!    through the same handler it was submitted to, with every check re-run
//!    against the community as it is then (VTI-APV-017). Reaching this gate
//!    again during that execution, [`gesture_then_consent_for`] re-checks the
//!    approvals — still eligible, still enough, state pin unmoved — instead of
//!    parking, and a failed re-check fails the action closed.
//!
//! The approval binds the payload digest (VTI-APV-004) and is spent by one
//! execution. It elevates nothing (VTI-APV-005): the operation runs as the
//! requester, with the requester's authority read again at execution.
//!
//! There is no re-send: a client that answers `consent_required` by sending
//! the operation again is not supported (design §8a).
//!
//! ## Single-administrator mode (VTI-APV-022)
//!
//! On a node configured on the host for it ([`crate::acl::single_admin`]), no
//! operation is parked for consent: once the requester's gesture bound to the
//! operation is spent, it stands in for the consent, and
//! [`ReadyGrant::spend`] audits the waiver at `Critical` — whether or not
//! other administrators' entries exist. The mode states that every
//! administrator is the same person, under as many identifiers as they hold,
//! and the node cannot tell one person's identifiers from two people's
//! (VTI-APV-022). Reductions ([`gate_reduction`]) take the unopposed
//! VTI-APV-019 path — the gesture, a notice to the subject, a `Critical` row —
//! and keep its cooling-off by default, a delay rather than a consent; the
//! requester may land one now, on a typed confirmation and a gesture bound to
//! the immediate variant (`immediate_reduction`, `vtc-action-list.md` §8.5).
//!
//! ## Suspension during a cooling-off
//!
//! The subject of an open cooling-off is suspended (`vtc-action-list.md`
//! §8.2): its entry authorizes nothing ([`VtcAclEntry::can`] answers `false`),
//! approves nothing ([`may_approve`]), and is no role assigner for the
//! attrition guard ([`role_assigners`]).
//!
//! ## The other acts it gates
//!
//! The same machinery also gates the acts that could otherwise undo APV-018
//! one step at a time (`vtc-action-list.md` §7b, §8.1). Each is an [`Act`];
//! what differs between them is only who may consent and what they are shown:
//!
//! - [`Act::ReduceUnrestricted`] — **VTI-APV-019**: removing, demoting or
//!   narrowing *another* subject's authority-conferring capabilities. The
//!   approvers hold what is being taken away, and exclude the subject as well as
//!   the requester, so neither party to the dispute can decide it. Where nobody
//!   is left, [`gate_reduction`] lets the requester's step-up suffice and the
//!   caller records it at `Critical` ([`record_unopposed_reduction`]).
//! - [`Act::LowerThreshold`] — **VTI-APV-020**: lowering
//!   `acl.unrestricted_admin_consent_threshold` needs consent at the threshold as
//!   it stands, which is what [`threshold`] reads, from the holders of
//!   `vtc.roles.assign`.
//! - [`Act::ChangeAuthorityPolicy`] — **VTI-VTC-022**: replacing or activating
//!   the policy that decides authority (role change, removal, join,
//!   cross-community roles, git namespaces), approved by the holders of
//!   `vtc.policy.admin @ policy:<purpose>`.
//! - [`Act::ChangeTrustedWitnesses`] — **VTI-CMP-090**: any change to the
//!   witnesses whose Verifiable Witness Credentials count in this community
//!   (`witnesses.trusted`) — adding, removing or relabelling one — approved by
//!   the other holders of `vtc.config.admin`. Whose attestation counts as
//!   evidence is a major trust change, and the "same review" CMP-090 asks of
//!   it is a second administrator's (`credentials::trusted_witnesses`).
//! - [`Act::ChangeJoinCriteria`] — **VTI-APV-023**: registering, replacing or
//!   deleting a join criterion (`vtc/schemas/accepts/*`), approved by the other
//!   holders of `vtc.surface.admin`. Who may become a member is decided by the
//!   criteria; one administrator should not change what admission means alone.
//! - [`Act::ChangeHiddenVetting`] — **VTI-APV-023**: publishing or withdrawing
//!   hidden vetting on a join criterion (`vtc/vetting/hidden/{publish,withdraw}`),
//!   approved by the other holders of `vtc.vetting.manage` — the capability
//!   those tasks take. A further way to meet a criterion is a change to it.
//! - [`Act::ChangeDirectoryPrivacy`] — **VTI-DIR-024**: widening a member
//!   directory field (`vtc/directory/fields/update`) — a wider ceiling or
//!   default visibility, a field made searchable or a facet, re-enabled or no
//!   longer required — approved by the other holders of `vtc.directory.admin`.
//!   It changes what membership exposes, for every member at once.
//! - [`Act::ChangeRecognitionPolicy`] — **VTI-APV-023**: replacing or
//!   activating the personhood policy, approved by the other holders of
//!   `vtc.policy.admin @ policy:personhood`. Not authority — the capability is
//!   not conferring — but who is recognised as a person is a trust change.

use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use tracing::warn;
use trust_tasks_rs::specs::task_consent::decision::v0_1 as decision;
use trust_tasks_rs::specs::task_consent::decision::v0_2 as decision_v0_2;
use trust_tasks_rs::specs::task_consent::request::v0_1 as request;
use vti_common::audit::AuditEvent;
use vti_common::error::AppError;
use vti_common::task_consent::{self, effects::StatePin};

use super::{CapRef, Capability, ResourceQualifier, VtcAclEntry, get_acl_entry, list_acl_entries};
use crate::auth::session::now_epoch;
use crate::config_store::{ConfigStore, UNRESTRICTED_ADMIN_CONSENT_THRESHOLD};
use crate::server::AppState;

/// The approver set a request names: the holders of what is conferred. Not
/// configurable: VTI-APV-018 fixes who may consent, so there is no rule to look
/// it up in.
pub const APPROVER_SET: &str = "capability-holders";

/// `task-consent/request/0.1` — what this service signs and pushes to each
/// approver, best-effort, when an action is raised.
pub(crate) const REQUEST_TYPE: &str = <request::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `task-consent/decision/0.1` — what an approver answers with.
pub(crate) const DECISION_TYPE: &str = <decision::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// `task-consent/decision/0.2` — 0.1 plus an optional `evidence` factor and
/// an optional `actionId` locator.
pub(crate) const DECISION_V0_2_TYPE: &str =
    <decision_v0_2::Payload as trust_tasks_rs::Payload>::TYPE_URI;

/// The approver set a request to take authority-conferring capabilities away
/// from another subject names (VTI-APV-019): their holders other than the
/// requester **and the subject**.
pub const APPROVER_SET_EXCEPT_SUBJECT: &str = "capability-holders-except-subject";

/// Domain tag for the [`StatePin`] version over a subject's ACL entry.
const STATE_DOMAIN: &[u8] = b"vtc/acl-entry-state/v1\0";

/// Domain tag for the [`StatePin`] version over a piece of community state that
/// is not an ACL entry — the consent threshold, the active policy of a purpose.
const SETTING_STATE_DOMAIN: &[u8] = b"vtc/consent-setting-state/v1\0";

/// Which act a consent is asked for. The machinery is one; what differs is who
/// may consent, what they are shown, and what state the consent is pinned to.
///
/// The variant names predate role-based administration and are kept for the
/// stored action records: "unrestricted" now reads "authority-conferring".
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Act {
    /// **VTI-APV-018** (generalising **VTI-APV-014**) — creating or widening an
    /// entry to hold an authority-conferring capability it did not hold. The
    /// subject is the DID that would hold it; the stake is what is conferred.
    GrantUnrestricted,
    /// **VTI-APV-019** — removing, demoting or narrowing another subject's
    /// authority-conferring capabilities. The subject is the DID that holds
    /// them, and never counts as an approver; the stake is what it loses.
    ReduceUnrestricted,
    /// **VTI-APV-020** — lowering the consent threshold. The subject is the
    /// threshold's config key; the consent is pinned to its current value.
    LowerThreshold,
    /// **VTI-VTC-022** — replacing or activating a policy that decides
    /// authority. The subject names the purpose; the consent is pinned to the
    /// revision active for it now.
    ChangeAuthorityPolicy(crate::policy::PolicyPurpose),
    /// **VTI-VTC-023** — an operator's offline write, surfaced to every
    /// remaining administrator to acknowledge. Nothing is consented to: it
    /// already happened. Never gated, never executed.
    OperatorWrite,
    /// **VTI-APV-018** applied to the authority vocabulary
    /// (`vtc-admin-roles.md` §6.2, §7) — defining, replacing or deleting a
    /// custom role. The subject is the role's name; the consent is pinned to
    /// its stored definition (or its absence).
    ChangeRoles,
    /// **VTI-APV-018** — restoring a backup (`vtc.backup.restore`), which
    /// replaces the whole ACL (`vtc-admin-roles.md` §4, §7). The subject is
    /// the bundle being restored.
    RestoreBackup,
    /// **VTI-ACL-071** — a departed granter's grants, raised for review
    /// (`vtc-admin-roles.md` §6.3). Approving re-affirms them under the
    /// approver's own authority; declining, or letting it lapse, withdraws
    /// them. Raised by the community itself, never by a requester's document.
    GrantsReview,
    /// A **queue** item (`vtc-action-list.md` §8.2, *Existing queues*): an
    /// unratified git-ns break-glass, for another administrator of the
    /// namespace to ratify or revoke (`git-ns/right/ratify/0.1`,
    /// `git-ns/right/revoke/0.3`). The subject is the record's subject, who
    /// never decides it. A decision, not a consent: it never expires into
    /// acceptance and is never gated (`crate::admin_actions::queues`).
    BreakGlassReview,
    /// A **queue** item: a join request referred for review
    /// (`admission: review`), decided by a holder of `vtc.join.decide` through
    /// the same `vtc/join-requests/decide` operation the Join requests page
    /// sends. The subject is the applicant.
    JoinReview,
    /// A **queue** item: a withdrawn vetting statement a current membership
    /// rests on (`vtc/vetting/revocations/list`, `needsReview`), for a holder
    /// of `vtc.vetting.manage` to keep the member or start their removal. The
    /// subject is the member.
    VettingReview,
    /// A **direct admission** the community's `admission` policy referred for
    /// approval: adding a member without a join request
    /// (`vtc/members/admit/0.1`), or making an existing ACL entry a
    /// membership (`vtc/members/make-membership/0.1`). It bypasses the join
    /// criteria, so the approvers are the other holders of
    /// `vtc.members.manage` — never the requester, never the subject. The
    /// subject is the DID being admitted; the consent is pinned to its ACL
    /// entry and member record.
    DirectAdmission,
    /// A change to where the community keeps its rooms' files
    /// (`vtc/storage/configs/{create,update,retire}`,
    /// `vtc/rooms/storage/assign`): parked for the other holders of
    /// `vtc.rooms.admin` by those tasks' own definitions. Not conferring — it
    /// grants nobody anything — but it decides where members' files go and
    /// what reaches them. The subject is the config or the room; the consent is
    /// pinned to its stored config and assignment.
    ChangeStorage,
    /// **VTI-CMP-090** — changing the trusted-witness list
    /// (`witnesses.trusted`): adding, removing or relabelling a witness whose
    /// VWCs count here. Not conferring, but it decides whose attestations are
    /// evidence in this community, so a second administrator reviews it. The
    /// subject is the config key; the consent is pinned to the list in force.
    ChangeTrustedWitnesses,
    /// **VTI-APV-023** — registering, replacing or deleting a join criterion
    /// (`vtc/schemas/accepts/register` / `delete`). Not conferring, but the
    /// criteria decide who may become a member. The subject is the criterion's
    /// id; the consent is pinned to the criterion as stored (or its absence).
    ChangeJoinCriteria,
    /// **VTI-APV-023** — publishing, changing or withdrawing hidden vetting on
    /// a join criterion (`vtc/vetting/hidden/publish` / `withdraw`): another
    /// way of meeting the criterion, so a change to the criteria. A sibling of
    /// [`Self::ChangeJoinCriteria`] rather than the same act because those
    /// tasks are `vtc.vetting.manage`'s, not `vtc.surface.admin`'s: the
    /// approvers, and what the requester must still hold at execution, follow
    /// the capability that makes the change. The subject is the criterion's
    /// id; the consent is pinned to the criterion as stored.
    ChangeHiddenVetting,
    /// **VTI-DIR-024** — widening a member-directory field
    /// (`vtc/directory/fields/update`): after it, some viewer could see or find
    /// what they could not before. Never changes a choice a member made, but it
    /// changes the community's privacy semantics (VTI-VTC-032, VTI-CMP-090). The
    /// subject is the field's key; the consent is pinned to its definition.
    ChangeDirectoryPrivacy,
    /// **VTI-APV-023** — replacing or activating a policy that decides who this
    /// community recognises as a person
    /// ([`crate::policy::PolicyPurpose::decides_recognition`]). Kept apart from
    /// [`Self::ChangeAuthorityPolicy`] because it decides no authority: what
    /// approvers are told differs, and so does the requirement it implements.
    /// The subject names the purpose; the consent is pinned to the revision
    /// active for it now.
    ChangeRecognitionPolicy(crate::policy::PolicyPurpose),
}

impl Act {
    /// The requirement this act's consent implements, for refusals.
    pub(crate) fn requirement(self) -> &'static str {
        match self {
            Self::GrantUnrestricted => "VTI-APV-018",
            Self::ReduceUnrestricted => "VTI-APV-019",
            Self::LowerThreshold => "VTI-APV-020",
            Self::ChangeAuthorityPolicy(_) => "VTI-VTC-022",
            Self::OperatorWrite => "VTI-VTC-023",
            Self::ChangeRoles | Self::RestoreBackup => "VTI-APV-018",
            Self::GrantsReview => "VTI-ACL-071",
            // Queue items are decisions the community already asked for; what
            // they implement is the operation each one decides.
            Self::BreakGlassReview => "git-ns/right/ratify",
            Self::JoinReview => "vtc/join-requests/decide",
            Self::VettingReview => "vtc/vetting/revocations",
            // The community's own rule, not a fixed requirement: the
            // `admission` policy referred it.
            Self::DirectAdmission => "the admission policy",
            Self::ChangeStorage => "the storage tasks' consent",
            Self::ChangeTrustedWitnesses => "VTI-CMP-090",
            Self::ChangeDirectoryPrivacy => "VTI-DIR-024",
            Self::ChangeJoinCriteria
            | Self::ChangeHiddenVetting
            | Self::ChangeRecognitionPolicy(_) => "VTI-APV-023",
        }
    }

    pub(crate) fn approver_set(self) -> &'static str {
        match self {
            Self::ReduceUnrestricted | Self::GrantsReview => APPROVER_SET_EXCEPT_SUBJECT,
            Self::OperatorWrite => "administrators",
            Self::BreakGlassReview => "namespace-administrators-except-subject",
            Self::JoinReview => "join-deciders",
            Self::VettingReview => "vetting-managers-except-subject",
            Self::DirectAdmission => "member-managers-except-subject",
            _ => APPROVER_SET,
        }
    }

    /// Whether the subject is excluded from the approvers, beside the
    /// requester. For a reduction, where the subject is a party to it; and
    /// for a grants review, whose subject is the granter that left.
    pub(crate) fn excludes_subject(self) -> bool {
        matches!(
            self,
            Self::ReduceUnrestricted
                | Self::GrantsReview
                | Self::BreakGlassReview
                | Self::JoinReview
                | Self::VettingReview
                | Self::DirectAdmission
        )
    }

    /// Whether this is a **queue** item (`vtc-action-list.md` §8.2): an
    /// existing human decision surfaced in the action list and made by one
    /// holder of the capability it is about. Not a consent, so its deciders
    /// are the capability's *holders* ([`may_decide`]), not its approvers.
    pub(crate) fn is_queue(self) -> bool {
        matches!(
            self,
            Self::BreakGlassReview | Self::JoinReview | Self::VettingReview
        )
    }

    /// The stake an act carries when the caller names none: what its approvers
    /// must hold (`vtc-admin-roles.md` §7). A grant and a reduction always name
    /// theirs — the capabilities conferred or taken away.
    pub(crate) fn default_stake(self) -> Vec<CapRef> {
        match self {
            Self::GrantUnrestricted
            | Self::ReduceUnrestricted
            | Self::LowerThreshold
            | Self::OperatorWrite
            | Self::GrantsReview => vec![CapRef::all(Capability::RolesAssign)],
            Self::ChangeAuthorityPolicy(purpose) => vec![CapRef::new(
                Capability::PolicyAdmin,
                Some(ResourceQualifier::Policy(purpose)),
            )],
            // §6.2: "only through an N-of-M action under vtc.roles.assign +
            // vtc.approvals.admin".
            Self::ChangeRoles => vec![
                CapRef::all(Capability::RolesAssign),
                CapRef::all(Capability::ApprovalsAdmin),
            ],
            Self::RestoreBackup => vec![CapRef::all(Capability::BackupRestore)],
            // A break-glass item is raised with its namespace's `git.ns.admin`
            // as its stake; unqualified is the community-wide holder.
            Self::BreakGlassReview => vec![CapRef::all(Capability::GitNsAdmin)],
            Self::JoinReview => vec![CapRef::all(Capability::JoinDecide)],
            Self::VettingReview => vec![CapRef::all(Capability::VettingManage)],
            Self::DirectAdmission => vec![CapRef::all(Capability::MembersManage)],
            Self::ChangeStorage => vec![CapRef::all(Capability::RoomsAdmin)],
            Self::ChangeTrustedWitnesses => vec![CapRef::all(Capability::ConfigAdmin)],
            Self::ChangeJoinCriteria => vec![CapRef::all(Capability::SurfaceAdmin)],
            Self::ChangeHiddenVetting => vec![CapRef::all(Capability::VettingManage)],
            Self::ChangeDirectoryPrivacy => vec![CapRef::all(Capability::DirectoryAdmin)],
            Self::ChangeRecognitionPolicy(purpose) => vec![CapRef::new(
                Capability::PolicyAdmin,
                Some(ResourceQualifier::Policy(purpose)),
            )],
        }
    }

    /// `stake`, or [`Self::default_stake`] when it names nothing.
    pub(crate) fn stake_or_default(self, stake: &[CapRef]) -> Vec<CapRef> {
        if stake.is_empty() {
            self.default_stake()
        } else {
            stake.to_vec()
        }
    }

    /// The action-list `kind` this act is raised as, for the task carrying it
    /// (`vtc-action-list.md` §7a.2).
    pub(crate) fn kind(self, type_uri: &str) -> &'static str {
        use crate::admin_actions::summary as s;
        match self {
            Self::GrantUnrestricted
                if type_uri == crate::trust_tasks::admin_tasks::INVITES_CREATE_TYPE =>
            {
                s::KIND_INVITE_CREATE
            }
            Self::GrantUnrestricted => s::KIND_GRANT_AUTHORITY,
            Self::ReduceUnrestricted => s::KIND_REDUCE_AUTHORITY,
            Self::LowerThreshold => s::KIND_THRESHOLD_LOWER,
            Self::ChangeAuthorityPolicy(_) => s::KIND_POLICY_AUTHORITY,
            Self::OperatorWrite => s::KIND_OPERATOR_WRITE,
            Self::ChangeRoles if type_uri == crate::trust_tasks::role_tasks::DELETE_TYPE => {
                s::KIND_ROLE_DELETE
            }
            Self::ChangeRoles => s::KIND_ROLE_DEFINE,
            Self::RestoreBackup => s::KIND_BACKUP_RESTORE,
            Self::GrantsReview => s::KIND_GRANTS_REVIEW,
            Self::BreakGlassReview => s::KIND_BREAK_GLASS_REVIEW,
            Self::JoinReview => s::KIND_JOIN_REVIEW,
            Self::VettingReview => s::KIND_VETTING_REVIEW,
            Self::DirectAdmission
                if type_uri == crate::trust_tasks::admission_tasks::MAKE_MEMBERSHIP_TYPE =>
            {
                s::KIND_MEMBER_MAKE_MEMBERSHIP
            }
            Self::DirectAdmission => s::KIND_MEMBER_ADMIT,
            Self::ChangeStorage => match type_uri {
                crate::trust_tasks::storage_tasks::CREATE_TYPE => s::KIND_STORAGE_CONFIG_CREATE,
                crate::trust_tasks::storage_tasks::RETIRE_TYPE => s::KIND_STORAGE_CONFIG_RETIRE,
                crate::trust_tasks::storage_tasks::ASSIGN_TYPE => s::KIND_ROOM_STORAGE_ASSIGN,
                _ => s::KIND_STORAGE_CONFIG_UPDATE,
            },
            Self::ChangeTrustedWitnesses => s::KIND_WITNESSES_CHANGE,
            Self::ChangeJoinCriteria => s::KIND_CRITERIA_CHANGE,
            Self::ChangeHiddenVetting => s::KIND_HIDDEN_VETTING_CHANGE,
            Self::ChangeDirectoryPrivacy => s::KIND_DIRECTORY_FIELD_WIDEN,
            Self::ChangeRecognitionPolicy(_) => s::KIND_POLICY_RECOGNITION,
        }
    }
}

/// The operation being consented to: its task type and the payload the digest
/// is taken over.
///
/// Each door passes the payload it would execute — the signed document's own
/// payload — so the digest names the subject as well as the change.
#[derive(Debug, Clone, Copy)]
pub struct Operation<'a> {
    pub type_uri: &'a str,
    pub payload: &'a Value,
}

/// The authority-conferring capabilities `next` holds that `prev` did not hold
/// at a covering qualifier — **the VTI-APV-018 trigger**. Empty: no consent is
/// needed.
///
/// An expired `prev` holds nothing, so granting it again is a new conferral.
#[must_use]
pub fn newly_conferred(prev: Option<&VtcAclEntry>, next: &VtcAclEntry, now: u64) -> Vec<CapRef> {
    let held: Vec<CapRef> = prev
        .filter(|p| !p.is_expired(now))
        .map(|p| p.admin.conferring())
        .unwrap_or_default();
    next.admin
        .conferring()
        .into_iter()
        .filter(|c| !held.iter().any(|h| h.covers(c)))
        .collect()
}

/// The authority-conferring capabilities `prev` holds that `next` (`None`: the
/// entry is removed) no longer does — what a reduction takes away
/// (**VTI-APV-019**).
#[must_use]
pub fn lost_conferring(prev: &VtcAclEntry, next: Option<&VtcAclEntry>, now: u64) -> Vec<CapRef> {
    if prev.is_expired(now) {
        return vec![];
    }
    // A shorter life takes every capability away sooner: an expiry put on a
    // permanent entry, or brought forward, reduces all of them.
    let shortened = next.is_some_and(|n| match (prev.expires_at, n.expires_at) {
        (None, Some(_)) => true,
        (Some(was), Some(now)) => now < was,
        _ => false,
    });
    let kept: Vec<CapRef> = next
        .filter(|_| !shortened)
        .map(|n| n.admin.conferring())
        .unwrap_or_default();
    prev.admin
        .conferring()
        .into_iter()
        .filter(|c| !kept.iter().any(|k| k.covers(c)))
        .collect()
}

/// Whether `entry` may approve an action with this stake: live, and able to
/// approve every capability in it at a covering qualifier
/// (`vtc-admin-roles.md` §7).
///
/// Approve authority is **its own axis** (**VTI-ACL-040**): what decides
/// whether a subject may bless a change is its approve scope, not whether it
/// may also make the change. So the least-privilege approver — act `none`, an
/// approve scope (**VTI-ACL-041**; the built-in `approver` role, or any entry
/// granted `approveCapabilities` with act `none`) — counts for every kind of
/// action its approve scope reaches. Approve scope is itself bounded: by the
/// role's approve ceiling, and by the granter's own when it was conferred
/// (**VTI-ACL-042**), so it reaches no further than someone who held it chose.
///
/// A suspended entry approves nothing (`vtc-action-list.md` §8.2).
#[must_use]
pub fn may_approve(entry: &VtcAclEntry, stake: &[CapRef], now: u64) -> bool {
    !entry.is_expired(now) && stake.iter().all(|c| entry.can_approve(c))
}

/// Whether `entry` may decide an action of `act` with this stake. For a
/// consent, [`may_approve`]: approve authority, its own axis (VTI-ACL-040).
/// For a **queue** item, holding the capability it is about at a covering
/// qualifier: a queue item *is* the decision — the join review the Join
/// requests page has always taken to `vtc.join.decide` — so whoever may make
/// that decision decides it here (`vtc-action-list.md` §8.2).
#[must_use]
pub fn may_decide(entry: &VtcAclEntry, act: Act, stake: &[CapRef], now: u64) -> bool {
    if !act.is_queue() {
        return may_approve(entry, stake, now);
    }
    if entry.is_expired(now) {
        return false;
    }
    match act {
        // A criterion-qualified vetting manager manages vetting too; the
        // removal this item can start applies its own rules.
        Act::VettingReview => entry.can_any(Capability::VettingManage),
        _ => stake.iter().all(|c| entry.holds(c)),
    }
}

/// The DIDs of every live holder of `vtc.roles.assign`, unqualified — the
/// community's role assigners. The consent threshold is counted against them,
/// and the last of them is never removed.
///
/// A suspended entry is not one (`vtc-action-list.md` §8.2): while its
/// reduction cools off it can neither grant nor consent, so it never counts
/// toward the attrition guard either.
pub async fn role_assigners(state: &AppState, now: u64) -> Result<Vec<String>, AppError> {
    Ok(list_acl_entries(&state.acl_ks)
        .await?
        .into_iter()
        .filter(|e| is_live_role_assigner(e, now) && !e.is_suspended())
        .map(|e| e.did)
        .collect())
}

/// The threshold in force **now**.
///
/// Read through the config layers rather than from the in-memory `AppConfig`: a
/// runtime `config/patch` writes the database layer, and the in-memory copy only
/// follows on `config/reload`. A raised threshold must bind the next request,
/// not the one after the next reload.
pub async fn threshold(state: &AppState) -> Result<u64, AppError> {
    let fallback = state
        .config
        .read()
        .await
        .acl
        .unrestricted_admin_consent_threshold;
    crate::config_store::live_consent_threshold(
        fallback,
        &ConfigStore::new(state.config_ks.clone()),
    )
    .await
}

/// Refuse a threshold the community cannot meet (VTI-APV-009) — checked where
/// the value is written, not discovered when a grant is blocked by it.
///
/// Counted against the role assigners, who are the approvers of the widest
/// grant: a requester is one of them and never counts, so at most
/// `assigners - 1` can approve. The minimum, 1, is always accepted: refusing it
/// would not make the community able to meet it, and there is no lower value to
/// choose instead.
pub async fn check_threshold_meetable(state: &AppState, threshold: u64) -> Result<(), AppError> {
    if threshold <= 1 {
        return Ok(());
    }
    let admins = role_assigners(state, now_epoch()).await?.len() as u64;
    if threshold > admins.saturating_sub(1) {
        return Err(AppError::Validation(format!(
            "{UNRESTRICTED_ADMIN_CONSENT_THRESHOLD} = {threshold} could never be met: a grant of \
             an authority-conferring capability would need {threshold} holders of \
             vtc.roles.assign besides the one asking, and this community has {admins} in total. \
             Grant more community administrators first, or set it to at most {}",
            admins.saturating_sub(1).max(1)
        )));
    }
    Ok(())
}

/// Whether `entry` is a live holder of `vtc.roles.assign`, unqualified.
#[must_use]
pub fn is_live_role_assigner(entry: &VtcAclEntry, now: u64) -> bool {
    !entry.is_expired(now) && entry.admin.can(Capability::RolesAssign, None)
}

/// Refuse a change that takes `subject` — a live holder of `vtc.roles.assign`
/// — out of the role assigners, when what is left could never consent to
/// anything: nobody else holding it at all, or fewer than the threshold needs.
///
/// The attrition half of VTI-APV-009: a rule must not become unsatisfiable by
/// removal any more than by being written that way, and the community must never
/// lose its last holder of `vtc.roles.assign` (`vtc-admin-roles.md` C1 §3).
/// Callers are every door that can end one — a revocation, a removal from the
/// community, a demotion, a narrowing update — and each must hold the admin-set
/// lock ([`crate::ceremony::lock_admin_set`]) from this check through its
/// write, or two such changes could each pass it and together strand the
/// community.
///
/// A threshold of 1 needs only one other assigner, the same bound the
/// write-time check accepts, so a two-admin community can still remove a
/// compromised one. Above 1 the threshold has to come down first.
pub async fn check_attrition(state: &AppState, subject: &str) -> Result<(), AppError> {
    let remaining = role_assigners(state, now_epoch())
        .await?
        .into_iter()
        .filter(|d| d != subject)
        .count() as u64;
    if remaining == 0 {
        return Err(AppError::Conflict(format!(
            "refusing to end the last administrator holding vtc.roles.assign ({subject}): nobody would be \
             left who could grant or consent to authority (VTI-APV-009). Make another community \
             administrator first"
        )));
    }
    let threshold = threshold(state).await?;
    if threshold > 1 && threshold > remaining.saturating_sub(1) {
        return Err(AppError::Conflict(format!(
            "refusing to end {subject}'s vtc.roles.assign: {remaining} holder(s) would remain, so \
             {UNRESTRICTED_ADMIN_CONSENT_THRESHOLD} = {threshold} could never be met again \
             (VTI-APV-009). Lower it first — config/patch \
             {{\"{UNRESTRICTED_ADMIN_CONSENT_THRESHOLD}\": {}}} — then retry",
            remaining.saturating_sub(1).max(1)
        )));
    }
    Ok(())
}
/// Other administrators' consent, found sufficient for the operation now being
/// executed. Only an approved action's execution produces one
/// ([`crate::admin_actions`], VTI-APV-017): a submission parks instead.
///
/// Or, in single-administrator mode, the requester's own operation-bound
/// gesture standing in for that consent (**VTI-APV-022**).
#[derive(Debug)]
#[must_use = "a ReadyGrant authorizes nothing until it is spent with the write"]
pub struct ReadyGrant {
    ready: Ready,
}

#[derive(Debug)]
enum Ready {
    /// An approved action executing (VTI-APV-017).
    Approved { action_id: String },
    /// Consent waived by single-administrator mode (VTI-APV-022).
    Waived(Box<crate::admin_actions::Waiver>),
    /// A reduction landing now, without its cooling-off, in
    /// single-administrator mode (`vtc-action-list.md` §8.5).
    Immediate(Box<crate::admin_actions::Immediate>),
}

impl ReadyGrant {
    pub(crate) fn approved(action_id: String) -> Self {
        Self {
            ready: Ready::Approved { action_id },
        }
    }

    /// Whether this is single-administrator mode's waiver rather than other
    /// administrators' consent.
    pub fn is_waived(&self) -> bool {
        matches!(self.ready, Ready::Waived(_))
    }

    /// Spend the consent. Call it with the write, after every other check.
    ///
    /// The action itself is closed — and each approver's challenge consumed, as
    /// `task-consent/decision` requires — by the executor once the write has
    /// landed, under the same status transition that made this execution the
    /// only one ([`crate::admin_actions`]). This records that the gate was
    /// reached on the way.
    ///
    /// A waiver (VTI-APV-022 item 4) is audited here at `Critical`, and the
    /// operation is entered in the action list's history once its write lands
    /// ([`crate::admin_actions::record_effect`]).
    pub async fn spend(self, state: &AppState) -> Result<(), AppError> {
        match self.ready {
            Ready::Approved { action_id } => {
                crate::admin_actions::note_gate_spent(&action_id);
                Ok(())
            }
            Ready::Waived(waiver) => crate::admin_actions::spend_waiver(state, *waiver).await,
            Ready::Immediate(imm) => crate::admin_actions::spend_immediate(state, *imm).await,
        }
    }
}

/// Whether this node runs in **single-administrator mode** (VTI-APV-022).
///
/// Host configuration, read once at start: `[acl] single_admin_mode` is not in
/// the runtime config registry, so nothing on the operation surface — a
/// `config/patch`, an import, a reload — changes the value held here.
pub async fn single_admin_mode(state: &AppState) -> bool {
    state.config.read().await.acl.single_admin_mode
}

/// What the signed door has once it has asked for both things an unrestricted
/// grant needs.
#[derive(Debug)]
pub enum SignedGate {
    /// An approved action is executing this operation and its consent still
    /// holds. Spend it with the write.
    Ready(ReadyGrant),
    /// No gesture yet. A ceremony is parked; refuse with it inline. Nothing
    /// was asked of any other admin.
    StepUpRequired(Box<crate::acl::bound_step_up::ApproveRequest>),
}

/// The signed door's gate for a grant of authority-conferring capabilities:
/// the requester's operation-bound gesture, then the action their other
/// holders approve. `stake` is what is conferred ([`newly_conferred`]).
///
/// Parked comes back as [`AppError::ApprovalRequired`] carrying
/// [`crate::admin_actions::ACTION_PARKED`], which the dispatcher answers with a
/// `trust-task-next-step/0.1`.
pub async fn gesture_then_consent(
    state: &AppState,
    requester: &str,
    subject: &str,
    stake: &[CapRef],
    op: Operation<'_>,
    gesture_reason: &str,
    consent_summary: &str,
) -> Result<SignedGate, AppError> {
    gesture_then_consent_for(
        state,
        Act::GrantUnrestricted,
        stake,
        requester,
        subject,
        op,
        gesture_reason,
        consent_summary,
    )
    .await
}

/// [`gesture_then_consent`] for any [`Act`]. An empty `stake` takes the act's
/// [`Act::default_stake`].
///
/// On **submission**: the community must be able to consent at all, the
/// requester must be within the action-list limits, and the requester's
/// gesture — bound to this operation — is asked for and spent (VTI-APV-015).
/// Then the operation is parked. A second submission of the same operation
/// while its action is open answers with that action rather than raising
/// another.
///
/// On **execution** of an approved action (VTI-APV-017): the approvals are
/// re-checked against the community as it is now, and [`SignedGate::Ready`]
/// comes back only if they still suffice.
#[allow(clippy::too_many_arguments)]
pub async fn gesture_then_consent_for(
    state: &AppState,
    act: Act,
    stake: &[CapRef],
    requester: &str,
    subject: &str,
    op: Operation<'_>,
    gesture_reason: &str,
    consent_summary: &str,
) -> Result<SignedGate, AppError> {
    use super::bound_step_up::{self, EvidencedGate};

    let stake = act.stake_or_default(stake);

    if let Some(exec) = crate::admin_actions::executing() {
        let action_id =
            crate::admin_actions::recheck(state, &exec, act, requester, subject, op).await?;
        return Ok(SignedGate::Ready(ReadyGrant::approved(action_id)));
    }

    // The same operation already waiting: point at it, and ask nothing again.
    if let Some(open) = crate::admin_actions::open_for(state, requester, op).await? {
        return Err(crate::admin_actions::parked_error(state, &open).await);
    }

    let now = now_epoch();
    // A consent nobody can give makes the gesture pointless, so say so before
    // asking the requester for one.
    let approvers = approvers_for(state, act, &stake, requester, subject, now).await?;
    let threshold = threshold(state).await?;
    // VTI-APV-022: single-administrator mode waives the consent whether or not
    // other administrators' entries exist — the mode states they are all the
    // same person, under as many identifiers as they hold, and the node cannot
    // tell one person's identifiers from two people's. The requester's gesture
    // bound to this operation still stands in for it, and the waiver is
    // audited at `Critical`.
    let waive = single_admin_mode(state).await;
    if !waive {
        refuse_if_unmeetable(
            act,
            &stake,
            approvers.len() as u64,
            threshold,
            consent_summary,
        )?;
        // §7a.1: the action-list limits, before the gesture too.
        crate::admin_actions::check_limits(state, act, requester, subject).await?;
    }

    let evidence = match bound_step_up::redeem_or_request_with_evidence(
        state,
        requester,
        op.type_uri,
        op.payload,
        gesture_reason,
    )
    .await?
    {
        EvidencedGate::Required(request) => return Ok(SignedGate::StepUpRequired(request)),
        EvidencedGate::Satisfied(evidence) => evidence,
    };

    if waive {
        // The requester's gesture, bound to this operation and now spent,
        // stands in for the consent nobody else could give (VTI-APV-022).
        // Spending the grant audits it at `Critical`.
        return Ok(SignedGate::Ready(ReadyGrant {
            ready: Ready::Waived(Box::new(crate::admin_actions::Waiver::new(
                act,
                stake,
                requester,
                subject,
                op,
                consent_summary,
                evidence,
            )?)),
        }));
    }

    let pin = pin_for(state, act, subject).await?;
    let action = crate::admin_actions::park(
        state,
        crate::admin_actions::Parking {
            act,
            stake,
            requester,
            subject,
            op,
            summary: consent_summary,
            evidence,
            approvers,
            threshold,
            pin,
            cooling_off: None,
        },
    )
    .await?;
    Err(crate::admin_actions::parked_error(state, &action).await)
}

/// What the requester's side of a reduction has settled to, once the gesture is
/// spent — **VTI-APV-019**.
#[derive(Debug)]
#[must_use = "a consented reduction must spend its grant, and an unopposed one must be recorded"]
pub enum Reduction {
    /// The subject loses no authority-conferring capability (or is the
    /// requester): the gesture is the whole gate.
    StepUpOnly,
    /// Another holder of what the subject loses, neither the requester nor the
    /// subject, consented. Spend it with the write.
    Consented(ReadyGrant),
    /// The subject loses authority-conferring capabilities and nobody else is
    /// left who could consent. The gesture sufficed — after the cooling-off,
    /// when one is configured (`acl.removal_cooling_off`, §8.2), in which case
    /// this is the parked action landing and carries its grant. Once the write
    /// lands the caller records it at `Critical` and notifies the subject
    /// ([`after_reduction`]).
    Unopposed(Option<ReadyGrant>),
}

/// Whether anyone other than the requester and the subject agreed to a
/// reduction — the `agreement` an authority-reduced notice carries
/// (VTI-APV-019).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Agreement {
    /// Another holder of what the subject lost consented.
    Consented,
    /// The subject lost nothing authority-conferring: the requester's gesture
    /// is the whole gate, and no third party reviewed it.
    StepUpOnly,
    /// The subject lost authority-conferring capabilities and nobody else
    /// could consent: audited at `Critical`.
    Unopposed,
}

impl Agreement {
    /// The notice's `agreement`: `consented` only when a third party agreed.
    /// A step-up-only reduction is reported `unopposed` — nobody but the
    /// decider reviewed it, which is the distinction the subject is owed.
    pub fn wire(self) -> &'static str {
        match self {
            Self::Consented => "consented",
            Self::StepUpOnly | Self::Unopposed => "unopposed",
        }
    }
}

impl Reduction {
    /// Spend the consent, if this reduction carries one. Call it with the
    /// write, after every other check. What it comes to for the notice and
    /// the audit ([`after_reduction`]).
    pub async fn spend(self, state: &AppState) -> Result<Agreement, AppError> {
        match self {
            Self::StepUpOnly => Ok(Agreement::StepUpOnly),
            Self::Consented(ready) => ready.spend(state).await.map(|()| Agreement::Consented),
            Self::Unopposed(ready) => {
                if let Some(ready) = ready {
                    ready.spend(state).await?;
                }
                Ok(Agreement::Unopposed)
            }
        }
    }
}

/// [`gate_reduction`]'s answer.
#[derive(Debug)]
pub enum ReductionGate {
    /// The gesture is spent and the reduction may proceed as described.
    Cleared(Reduction),
    /// No gesture yet. A ceremony is parked; refuse with it inline.
    StepUpRequired(Box<crate::acl::bound_step_up::ApproveRequest>),
}

/// The gate on removing, demoting or narrowing an **administrator**'s entry —
/// `acl/revoke`, a downward `acl/change-role`, a narrowing `acl/update` or
/// `acl/grant` rewrite, `vtc/members/admin-remove` (`vtc-action-list.md` §7b).
///
/// Every such act takes the requester's operation-bound gesture. When the
/// subject is **another** live entry that loses an authority-conferring
/// capability (`after`: the entry as it will be, `None` for a removal), it is
/// also parked for the consent of a holder of what is lost who is neither the
/// requester nor the subject (**VTI-APV-019**), through the same machinery as
/// APV-018 ([`Act::ReduceUnrestricted`]).
///
/// Where no such holder exists — two community administrators in all — the VTC
/// cannot tell a removal of a compromised co-admin from a compromised admin's
/// removal of the other, and must not make the first impossible. So the gesture
/// alone suffices, but not at once: the reduction is parked for a
/// **cooling-off** (`acl.removal_cooling_off`, default 24 h, §8.2) that both
/// can see, and lands by itself when it ends unless the requester cancels it.
/// The subject is suspended meanwhile, so it can neither block it nor answer
/// with a counter-request; only one cooling-off runs on a subject at a time,
/// and raising one checks the attrition guard as though the subject were
/// already gone. A cooling-off of zero lands it at once
/// ([`Reduction::Unopposed`]), and so does `ext["org.openvtc"].immediate` in
/// single-administrator mode (`immediate_reduction`, §8.5).
///
/// The attrition guard ([`check_attrition`]) is asked first as well when the
/// subject loses `vtc.roles.assign`, so a reduction that would strand the
/// community is refused before anybody is asked for a gesture. It is not a
/// substitute for the caller's own check under the admin-set lock, which still
/// runs.
///
/// Call it after every check that decides whether the act may happen, and
/// before anything is written.
pub async fn gate_reduction(
    state: &AppState,
    requester: &str,
    subject: &VtcAclEntry,
    after: Option<&VtcAclEntry>,
    op: Operation<'_>,
    gesture_reason: &str,
    consent_summary: &str,
) -> Result<ReductionGate, AppError> {
    use super::bound_step_up::{self, EvidencedGate, Gate};

    let now = now_epoch();
    let lost = if subject.did == requester {
        vec![]
    } else {
        lost_conferring(subject, after, now)
    };
    let executing = crate::admin_actions::executing();
    // "Remove now" (`vtc-action-list.md` §8.5): asked for in the payload, so
    // the requester's gesture is bound to the immediate variant and never to
    // the delayed one (VTI-APV-015). Only single-administrator mode offers it.
    let immediate = crate::admin_actions::immediate_request(op.payload)?;
    if immediate.is_some() && executing.is_none() && !single_admin_mode(state).await {
        return Err(AppError::Forbidden(format!(
            "removing or reducing an administrator now, without its cooling-off \
             (ext.org.openvtc.immediate), is offered only in single-administrator mode \
             (VTI-APV-022), which is set on the host ([acl] single_admin_mode in config.toml) and \
             cannot be changed through this service. Without it the reduction of {} waits out \
             its cooling-off ({}), during which they are suspended — send it again without \
             `immediate`",
            subject.did,
            crate::config_store::REMOVAL_COOLING_OFF
        )));
    }
    if !lost.is_empty() {
        if is_live_role_assigner(subject, now)
            && !after.is_some_and(|a| is_live_role_assigner(a, now))
        {
            check_attrition(state, &subject.did).await?;
        }
        // A cooling-off landing: the reduction it parked, unopposed, now.
        if let Some(exec) = executing.as_ref().filter(|e| e.cooling_off) {
            let action_id =
                crate::admin_actions::recheck_cooling_off(state, exec, requester, &subject.did, op)
                    .await?;
            return Ok(ReductionGate::Cleared(Reduction::Unopposed(Some(
                ReadyGrant::approved(action_id),
            ))));
        }
        // VTI-APV-019 asks a third party's consent "wherever such a party
        // exists"; single-administrator mode does not require it (VTI-APV-022):
        // another of the requester's own entries is no third party. The
        // reduction then takes the unopposed path — the requester's gesture,
        // the subject told, a `Critical` row and the cooling-off, which is a
        // delay, not a consent, and stays.
        let third = if single_admin_mode(state).await {
            0
        } else {
            approvers_for(
                state,
                Act::ReduceUnrestricted,
                &lost,
                requester,
                &subject.did,
                now,
            )
            .await?
            .len()
        };
        // First to act wins (§8.2): with nobody else to decide, a
        // counter-request lands the earlier one.
        if executing.is_none() && third == 0 {
            crate::admin_actions::refuse_if_reduced_first(state, requester, &subject.did).await?;
        }
        // Remove now, in single-administrator mode (checked above): no
        // cooling-off, on a typed confirmation and the requester's gesture
        // bound to this immediate operation (`vtc-action-list.md` §8.5).
        if let Some(imm) = immediate.as_ref()
            && executing.is_none()
        {
            return immediate_reduction(
                state,
                requester,
                subject,
                op,
                imm,
                lost,
                gesture_reason,
                consent_summary,
            )
            .await;
        }
        // An approved action executing this reduction goes through its consent
        // whatever the count is now: approvals that no longer suffice fail it
        // closed, rather than letting the unopposed path run it on the gesture
        // the requester made when there *were* approvers (VTI-APV-017).
        if third > 0 || executing.is_some() {
            return Ok(
                match gesture_then_consent_for(
                    state,
                    Act::ReduceUnrestricted,
                    &lost,
                    requester,
                    &subject.did,
                    op,
                    gesture_reason,
                    consent_summary,
                )
                .await?
                {
                    SignedGate::Ready(ready) => ReductionGate::Cleared(Reduction::Consented(ready)),
                    SignedGate::StepUpRequired(r) => ReductionGate::StepUpRequired(r),
                },
            );
        }
        let window = crate::config_store::live_action_setting(
            crate::config_store::REMOVAL_COOLING_OFF,
            &state.config.read().await.clone(),
            &ConfigStore::new(state.config_ks.clone()),
        )
        .await?;
        if window > 0 {
            // The same operation already cooling off: point at it.
            if let Some(open) = crate::admin_actions::open_for(state, requester, op).await? {
                return Err(crate::admin_actions::parked_error(state, &open).await);
            }
            // One reduction cools off on a subject at a time: it is what
            // suspends them, and a second would only race the first.
            if let Some(other) =
                crate::admin_actions::open_cooling_off_on(state, &subject.did).await?
            {
                return Err(AppError::Conflict(format!(
                    "a reduction of {} is already cooling off ({}, requested by {}, lands {}), and \
                     they are suspended until it lands or is cancelled. Cancel that one first \
                     (vtc/admin/actions/cancel) to ask for something different",
                    subject.did,
                    other.id,
                    other.requester,
                    crate::admin_actions::rfc3339(other.cooling_off_until.unwrap_or_default()),
                )));
            }
            // The subject is suspended from the moment this is raised, so it
            // stops counting toward the attrition guard now, whatever the
            // reduction leaves it when it lands (`vtc-action-list.md` §8.2).
            if is_live_role_assigner(subject, now)
                && after.is_some_and(|a| is_live_role_assigner(a, now))
            {
                check_attrition(state, &subject.did).await?;
            }
            crate::admin_actions::check_limits(
                state,
                Act::ReduceUnrestricted,
                requester,
                &subject.did,
            )
            .await?;
            let evidence = match bound_step_up::redeem_or_request_with_evidence(
                state,
                requester,
                op.type_uri,
                op.payload,
                gesture_reason,
            )
            .await?
            {
                EvidencedGate::Required(request) => {
                    return Ok(ReductionGate::StepUpRequired(request));
                }
                EvidencedGate::Satisfied(evidence) => evidence,
            };
            warn!(
                requester,
                subject = %subject.did,
                task = op.type_uri,
                window,
                "ending an unrestricted admin's authority with nobody else left to consent \
                 (VTI-APV-019): parked for its cooling-off, the subject suspended until it lands"
            );
            let pin = pin_for(state, Act::ReduceUnrestricted, &subject.did).await?;
            let action = crate::admin_actions::park(
                state,
                crate::admin_actions::Parking {
                    act: Act::ReduceUnrestricted,
                    stake: lost.clone(),
                    requester,
                    subject: &subject.did,
                    op,
                    summary: consent_summary,
                    evidence,
                    approvers: Vec::new(),
                    threshold: 0,
                    pin,
                    cooling_off: Some(window),
                },
            )
            .await?;
            return Err(crate::admin_actions::parked_error(state, &action).await);
        }
    }
    Ok(
        match bound_step_up::redeem_or_request(
            state,
            requester,
            op.type_uri,
            op.payload,
            gesture_reason,
        )
        .await?
        {
            Gate::Satisfied if !lost.is_empty() => {
                warn!(
                    requester,
                    subject = %subject.did,
                    task = op.type_uri,
                    "taking authority-conferring capabilities away with nobody else left to \
                     consent (VTI-APV-019), with no cooling-off configured: the requester's \
                     step-up is the only gate"
                );
                ReductionGate::Cleared(Reduction::Unopposed(None))
            }
            Gate::Satisfied => ReductionGate::Cleared(Reduction::StepUpOnly),
            Gate::Required(r) => ReductionGate::StepUpRequired(r),
        },
    )
}

/// "Remove now" (`vtc-action-list.md` §8.5): a reduction of another
/// administrator that lands at once instead of waiting out its cooling-off —
/// or that lands an open cooling-off of the same operation now. Offered only in
/// single-administrator mode (the caller has checked it), where the cooling-off
/// is a delay one person imposes on themselves (VTI-APV-022).
///
/// It asks two deliberate things, in this order, before anything is written:
///
/// 1. a typed confirmation in the payload — the subject's DID, or the id of the
///    cooling-off being landed — refused without a gesture when it does not
///    match, so a slip costs nothing;
/// 2. the requester's gesture bound to **this** operation (VTI-APV-015), whose
///    payload carries `ext.org.openvtc.immediate`: a gesture made for the
///    delayed removal is bound to a different digest and is never spent here,
///    and this one is never spent on the delayed removal.
///
/// The attrition guard has already run ([`gate_reduction`]). Spending the grant
/// writes a `Critical` `SingleAdminMode { event: reductionImmediate }` row before
/// the write; the caller then records the unopposed reduction at `Critical` and
/// notifies the subject (VTI-APV-019, [`after_reduction`]).
#[allow(clippy::too_many_arguments)]
async fn immediate_reduction(
    state: &AppState,
    requester: &str,
    subject: &VtcAclEntry,
    op: Operation<'_>,
    imm: &crate::admin_actions::ImmediateRequest,
    lost: Vec<CapRef>,
    gesture_reason: &str,
    consent_summary: &str,
) -> Result<ReductionGate, AppError> {
    use super::bound_step_up::{self, EvidencedGate};

    let confirmed =
        imm.confirm == subject.did || imm.action_id.as_deref().is_some_and(|id| imm.confirm == id);
    if !confirmed {
        return Err(AppError::Validation(format!(
            "the confirmation does not match. To make this change now, without its cooling-off \
             ({consent_summary}), type the subject's DID ({}){} as \
             ext.org.openvtc.immediate.confirm",
            subject.did,
            imm.action_id
                .as_deref()
                .map(|id| format!(" or the action's id ({id})"))
                .unwrap_or_default(),
        )));
    }
    let target = crate::admin_actions::cooling_off_to_land(
        state,
        &subject.did,
        op,
        imm.action_id.as_deref(),
    )
    .await?;
    let evidence = match bound_step_up::redeem_or_request_with_evidence(
        state,
        requester,
        op.type_uri,
        op.payload,
        &format!("{gesture_reason} — now, without the cooling-off"),
    )
    .await?
    {
        EvidencedGate::Required(request) => return Ok(ReductionGate::StepUpRequired(request)),
        EvidencedGate::Satisfied(evidence) => evidence,
    };
    warn!(
        requester,
        subject = %subject.did,
        task = op.type_uri,
        landing = target.as_deref().unwrap_or("-"),
        "reducing an administrator now, without the cooling-off — single-administrator mode \
         (VTI-APV-022, VTI-APV-019)"
    );
    Ok(ReductionGate::Cleared(Reduction::Unopposed(Some(
        ReadyGrant {
            ready: Ready::Immediate(Box::new(crate::admin_actions::Immediate::new(
                lost,
                requester,
                &subject.did,
                op,
                consent_summary,
                evidence,
                target,
            )?)),
        },
    ))))
}

/// [`gate_reduction`] for a door about to end or reduce `prior` (to `after`,
/// `None` for a removal), settled to one answer: `Ok(None)` when nothing gated
/// it (not a live administrator's entry), `Ok(Some(agreement))` to go ahead and
/// then [`after_reduction`], or the refusal — [`TaskError::StepUp`] with the
/// ceremony inline when no gesture is recorded yet, or the parked action (an
/// approval, or a cooling-off).
///
/// Only an **administrator**'s live entry is gated (`vtc-action-list.md` §7b
/// item 1); ending an expired entry, or one with no administrative role, is
/// unchanged, and answers `Ok(None)` without asking anything. Call it last
/// before the write.
///
/// [`TaskError::StepUp`]: crate::error::TaskError::StepUp
pub async fn settle_reduction(
    state: &AppState,
    requester: &str,
    prior: &VtcAclEntry,
    after: Option<&VtcAclEntry>,
    op: Operation<'_>,
    gesture_reason: &str,
    consent_summary: &str,
) -> Result<Option<Agreement>, crate::error::TaskError> {
    if !prior.is_administrator() {
        return Ok(None);
    }
    match gate_reduction(
        state,
        requester,
        prior,
        after,
        op,
        gesture_reason,
        consent_summary,
    )
    .await?
    {
        ReductionGate::Cleared(reduction) => Ok(Some(reduction.spend(state).await?)),
        ReductionGate::StepUpRequired(request) => Err(crate::error::TaskError::step_up(request)),
    }
}

/// Once a gated reduction's write has landed: an unopposed one is recorded at
/// `Critical` ([`record_unopposed_reduction`], VTI-APV-019), and — unless the
/// subject was removed from the community, which the removal notice tells them
/// (`notify: false`) — the subject is sent `vtc/members/authority-reduced-notice`
/// saying what happened, on whose authority and whether anyone else agreed.
///
/// `after` is the subject's entry now (`None`: revoked). Called after the
/// write, never before: a refusal later in the write must not leave a row or a
/// notice claiming it happened. The notice is best-effort and durable; nothing
/// here undoes the write.
#[allow(clippy::too_many_arguments)]
pub async fn after_reduction(
    state: &AppState,
    decided_by: &str,
    prior: &VtcAclEntry,
    after: Option<&VtcAclEntry>,
    agreement: Agreement,
    task: &str,
    reason: Option<&str>,
    notify: bool,
) -> Result<(), AppError> {
    if agreement == Agreement::Unopposed {
        record_unopposed_reduction(state, decided_by, prior, task).await?;
    }
    if notify {
        crate::ceremony::authority_reduced_notice::send(
            state,
            prior,
            after,
            agreement,
            decided_by,
            chrono::Utc::now(),
            reason,
        )
        .await;
    }
    Ok(())
}

/// Record an unopposed reduction once its write has landed: a `Critical`
/// audit row (**VTI-APV-019**).
///
/// Called after the write, never before: a refusal later in the write (the
/// attrition guard under its lock) must not leave a row saying it happened.
pub async fn record_unopposed_reduction(
    state: &AppState,
    requester: &str,
    prior: &VtcAclEntry,
    task: &str,
) -> Result<(), AppError> {
    let Some(writer) = state.audit_writer.as_ref() else {
        return Ok(());
    };
    writer
        .write(
            requester,
            Some(&prior.did),
            AuditEvent::AuthorityReducedUnopposed(
                vti_common::audit::AuthorityReducedUnopposedData {
                    task: task.to_string(),
                    prior_role: prior
                        .admin
                        .admin_role
                        .as_ref()
                        .map(|r| r.to_string())
                        .unwrap_or_else(|| prior.role.to_string()),
                    // A VTC entry has no context scopes; what it held is its
                    // capabilities, recorded in the same slot.
                    prior_scopes: prior
                        .admin
                        .effective()
                        .iter()
                        .map(CapRef::display)
                        .collect(),
                },
            ),
        )
        .await?;
    Ok(())
}

/// The consent for an operation reached by a door with no signed document to
/// park — the session-gated role change.
///
/// Only an approved action's execution can satisfy it. Anything else is refused:
/// an operation that needs other administrators' approval waits in the action
/// list, and only a signed document can be parked there (`vtc-action-list.md`
/// §4.1 — the VTC executes its own stored copy of what the requester signed).
pub async fn require(
    state: &AppState,
    requester: &str,
    subject: &str,
    stake: &[CapRef],
    op: Operation<'_>,
    summary: &str,
) -> Result<ReadyGrant, AppError> {
    if let Some(exec) = crate::admin_actions::executing() {
        let action_id = crate::admin_actions::recheck(
            state,
            &exec,
            Act::GrantUnrestricted,
            requester,
            subject,
            op,
        )
        .await?;
        return Ok(ReadyGrant::approved(action_id));
    }
    let stake = Act::GrantUnrestricted.stake_or_default(stake);
    // A consent nobody could give is the more useful thing to say first.
    let approvers = approvers_for(
        state,
        Act::GrantUnrestricted,
        &stake,
        requester,
        subject,
        now_epoch(),
    )
    .await?
    .len() as u64;
    // Single-administrator mode waives the consent only on a passkey gesture
    // bound to the operation (VTI-APV-022, VTI-APV-015) — which only a signed
    // document carries.
    if single_admin_mode(state).await {
        return Err(AppError::Forbidden(format!(
            "{summary} needs, in single-administrator mode, your passkey gesture bound to the \
             operation (VTI-APV-022), which only a signed {} document can carry",
            op.type_uri
        )));
    }
    refuse_if_unmeetable(
        Act::GrantUnrestricted,
        &stake,
        approvers,
        threshold(state).await?,
        summary,
    )?;
    Err(AppError::Forbidden(format!(
        "{summary} needs the approval of another holder of {} (VTI-APV-018), which only a \
         signed {} document can wait for",
        stake_list(&stake),
        op.type_uri
    )))
}

fn stake_list(stake: &[CapRef]) -> String {
    stake
        .iter()
        .map(CapRef::display)
        .collect::<Vec<_>>()
        .join(", ")
}

/// Refuse, naming the fix, when there are fewer possible approvers than the
/// threshold needs. The operator's way out is the offline break-glass, which is
/// not reachable by a stolen session or key.
pub(crate) fn refuse_if_unmeetable(
    act: Act,
    stake: &[CapRef],
    approvers: u64,
    threshold: u64,
    summary: &str,
) -> Result<(), AppError> {
    if approvers < threshold {
        let others = if act.excludes_subject() {
            "holder(s) other than you and the subject"
        } else {
            "other holder(s)"
        };
        return Err(AppError::Forbidden(format!(
            "{summary} needs consent from {threshold} {others} of {}, and this community has \
             {approvers} ({}). Add another community administrator with the offline \
             break-glass while the daemon is stopped — `vtc acl add --did <did> --admin-role \
             community-admin` — and send this again",
            stake_list(stake),
            act.requirement()
        )));
    }
    Ok(())
}

/// Who may consent to `act` on `subject` now: every live entry that holds and
/// may approve all of `stake` ([`may_approve`]), but the requester
/// (VTI-APV-007) — and, for a reduction, but the subject (VTI-APV-019).
pub(crate) async fn approvers_for(
    state: &AppState,
    act: Act,
    stake: &[CapRef],
    requester: &str,
    subject: &str,
    now: u64,
) -> Result<Vec<String>, AppError> {
    let stake = act.stake_or_default(stake);
    Ok(list_acl_entries(&state.acl_ks)
        .await?
        .into_iter()
        .filter(|e| may_decide(e, act, &stake, now))
        .map(|e| e.did)
        .filter(|d| d != requester && !(act.excludes_subject() && d == subject))
        .collect())
}

/// Whether the requester of a parked `act` still holds the authority it needs:
/// live, and — for a grant — still holding what it would confer, since a
/// granter may grant only what it holds (VTI-ACL-071). The handler re-checks
/// everything when the action executes; this closes an action that can no
/// longer succeed (`vtc-action-list.md` §4.4).
pub(crate) fn requester_still_authorized(
    entry: &VtcAclEntry,
    act: Act,
    stake: &[CapRef],
    now: u64,
) -> bool {
    // A suspended requester authorizes nothing while its own reduction cools
    // off (`vtc-action-list.md` §8.2), so what it asked for can no longer run
    // as it.
    if entry.is_expired(now) || !entry.admin.is_administrator() || entry.is_suspended() {
        return false;
    }
    match act {
        Act::GrantUnrestricted => {
            entry.admin.can_any(Capability::RolesAssign)
                && act
                    .stake_or_default(stake)
                    .iter()
                    .all(|c| entry.admin.holds(c))
        }
        Act::ReduceUnrestricted => entry.admin.can_any(Capability::RolesAssign),
        Act::LowerThreshold => entry.admin.can(Capability::ConfigAdmin, None),
        Act::ChangeAuthorityPolicy(p) => entry
            .admin
            .can(Capability::PolicyAdmin, Some(&ResourceQualifier::Policy(p))),
        // An operator write has no requester authority to lose: it is an item
        // to acknowledge (VTI-VTC-023).
        Act::OperatorWrite => true,
        Act::ChangeRoles => {
            entry.admin.can(Capability::RolesAssign, None)
                && entry.admin.can(Capability::ApprovalsAdmin, None)
        }
        Act::RestoreBackup => entry.admin.can(Capability::BackupRestore, None),
        // Raised by the community itself: there is no requester to lose
        // anything (`requester_still_authorized` is never asked of it — see
        // `crate::admin_actions::settle`).
        Act::GrantsReview => true,
        // Queue items are raised by the community about a record; their
        // requester is the party the record is about, and is never asked this.
        Act::BreakGlassReview | Act::JoinReview | Act::VettingReview => true,
        // Admitting is `vtc.members.manage`'s; a role beyond `member` is
        // re-bounded by the handler when the action executes.
        Act::DirectAdmission => entry.admin.can(Capability::MembersManage, None),
        Act::ChangeStorage => entry.admin.can(Capability::RoomsAdmin, None),
        Act::ChangeTrustedWitnesses => entry.admin.can(Capability::ConfigAdmin, None),
        Act::ChangeJoinCriteria => entry.admin.can(Capability::SurfaceAdmin, None),
        Act::ChangeHiddenVetting => entry.admin.can(Capability::VettingManage, None),
        Act::ChangeDirectoryPrivacy => entry.admin.can(Capability::DirectoryAdmin, None),
        Act::ChangeRecognitionPolicy(p) => entry
            .admin
            .can(Capability::PolicyAdmin, Some(&ResourceQualifier::Policy(p))),
    }
}

/// The state a consent to `act` is pinned to: what the approvers saw, so a
/// change to it between the ask and the write invalidates the action.
pub(crate) async fn pin_for(
    state: &AppState,
    act: Act,
    subject: &str,
) -> Result<StatePin, AppError> {
    let value = match act {
        Act::GrantUnrestricted | Act::ReduceUnrestricted | Act::OperatorWrite => {
            return state_pin(state, subject).await;
        }
        // VTI-APV-020: the consent is to lowering *this* threshold. Once it
        // moves, what the approvers agreed to is not what would happen.
        Act::LowerThreshold => json!(threshold(state).await?),
        Act::ChangeAuthorityPolicy(purpose) | Act::ChangeRecognitionPolicy(purpose) => json!(
            crate::policy::get_active_policy_id(&state.active_policies_ks, purpose)
                .await?
                .map(|id| id.to_string())
        ),
        // The consent is to changing *this* definition: once it moves, what
        // the approvers agreed to is not what would happen.
        Act::ChangeRoles => json!(super::roles::get(&state.acl_ks, subject).await?),
        // Nothing to pin beside the bundle itself, whose bytes are fixed by
        // its committed digest: the restore replaces the ACL wholesale, and a
        // changed ACL in the meantime is exactly what it overwrites.
        Act::RestoreBackup => json!(subject),
        // A review re-affirms what is still under review at execution, and
        // nothing else; a change to one entry must not void the rest.
        Act::GrantsReview => json!(subject),
        // A queue item is settled against its record, never a pin
        // (`crate::admin_actions::queues::resolution`).
        Act::BreakGlassReview | Act::JoinReview | Act::VettingReview => json!(subject),
        // What the approvers were shown is a DID with this ACL entry (none, for
        // an add) and no live membership. Either moving — the entry granted,
        // changed or revoked, a member record written — means the admission
        // they agreed to is not the one that would run.
        Act::DirectAdmission => {
            let entry = get_acl_entry(&state.acl_ks, subject).await?;
            let member = crate::members::get_member(&state.members_ks, subject)
                .await?
                .map(|m| if m.is_removed() { "removed" } else { "active" });
            json!({ "entry": entry, "member": member })
        }
        // What the approvers were shown is this config (none, for a create) or
        // this room's assignment. Either moving means the change they agreed to
        // is not the one that would run.
        Act::ChangeStorage => json!({
            "config": state.room_storage.config(subject).await?,
            "assignment": state.room_storage.assignment(subject).await?,
        }),
        // The approvers were shown a change from *this* list. Once it moves —
        // another change landed first — what they agreed to is not what would
        // happen.
        Act::ChangeTrustedWitnesses => {
            crate::credentials::trusted_witnesses::current_value(state).await?
        }
        // The approvers were shown a change to *this* criterion (none, for a
        // new one). Any write to it in the meantime — another replacement, a
        // deletion, hidden vetting turned on or off — voids the action.
        Act::ChangeJoinCriteria | Act::ChangeHiddenVetting => {
            json!(crate::schemas::get_accepts(&state.schemas_ks, subject).await?)
        }
        // The approvers were shown a change from *this* definition. Any write to
        // the field in the meantime — a narrowing, another widening — voids the
        // action. `updatedAt` is when, not what, and is left out.
        Act::ChangeDirectoryPrivacy => {
            let mut f = crate::directory::fields::get(state.directory.ks(), subject).await?;
            if let Some(f) = f.as_mut() {
                f.updated_at = None;
            }
            json!(f)
        }
    };
    Ok(StatePin {
        resource: subject.to_string(),
        version: task_consent::domain_digest(SETTING_STATE_DOMAIN, subject, &value, None)?,
    })
}

/// The subject's ACL entry as the approvers see it, pinned. Any change to the
/// entry between the request and the write — its role, scopes, expiry, even its
/// label — changes the version, and an action raised over the old one is
/// invalidated (`vtc-action-list.md` §4.4).
async fn state_pin(state: &AppState, subject: &str) -> Result<StatePin, AppError> {
    let entry = get_acl_entry(&state.acl_ks, subject).await?;
    let value = serde_json::to_value(&entry)
        .map_err(|e| AppError::Internal(format!("serialise ACL entry for its state pin: {e}")))?;
    Ok(StatePin {
        resource: subject.to_string(),
        version: task_consent::domain_digest(STATE_DOMAIN, subject, &value, None)?,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::acl::{AdminAuthority, AdminRole, CapabilityScope, VtcRole};

    fn entry(admin: AdminAuthority, expires_at: Option<u64>) -> VtcAclEntry {
        VtcAclEntry {
            did: "did:key:zSubject".into(),
            role: VtcRole::Member,
            label: None,
            admin,
            delegated_by: None,
            created_at: 0,
            created_by: "did:key:zAdmin".into(),
            updated_at: None,
            updated_by: None,
            expires_at,
            resource_grants: Vec::new(),
            label_set_by_subject: false,
            suspension: None,
        }
    }

    fn listed(caps: &[&str]) -> CapabilityScope {
        CapabilityScope::listed(
            caps.iter()
                .map(|c| c.parse::<CapRef>().unwrap().into())
                .collect(),
        )
        .unwrap()
    }

    /// VTI-APV-018: the trigger is an authority-conferring capability the entry
    /// did not hold before — and only that.
    #[test]
    fn vti_apv_018_newly_conferred_is_the_new_authority_conferring_capabilities() {
        let now = 1_000;
        let admin = entry(AdminAuthority::community_admin(), None);
        // A new community administrator confers every authority-conferring cap.
        let fresh = newly_conferred(None, &admin, now);
        assert!(fresh.contains(&CapRef::all(Capability::RolesAssign)));
        assert!(fresh.contains(&CapRef::all(Capability::ConfigAdmin)));
        assert!(!fresh.contains(&CapRef::all(Capability::AuditRead)));

        // Already held and live: a label edit confers nothing.
        assert!(newly_conferred(Some(&admin), &admin, now).is_empty());

        // An expired holder, granted again, is a new conferral.
        let lapsed = entry(AdminAuthority::community_admin(), Some(now));
        assert!(!newly_conferred(Some(&lapsed), &admin, now).is_empty());

        // A moderator holds nothing authority-conferring.
        let moderator = entry(AdminAuthority::for_role(AdminRole::Moderator), None);
        assert!(newly_conferred(None, &moderator, now).is_empty());

        // A narrowed community-admin widened to include vtc.roles.assign.
        let mut narrow = AdminAuthority::community_admin();
        narrow.capabilities = listed(&["vtc.audit.read"]);
        let narrow = entry(narrow, None);
        let mut wider = AdminAuthority::community_admin();
        wider.capabilities = listed(&["vtc.audit.read", "vtc.roles.assign"]);
        let wider = entry(wider, None);
        assert_eq!(
            newly_conferred(Some(&narrow), &wider, now),
            vec![CapRef::all(Capability::RolesAssign)]
        );

        // A qualified repo manager confers git.ns.admin within its namespace.
        let mut rm = AdminAuthority::for_role(AdminRole::RepoManager);
        rm.capabilities = listed(&["git.ns.admin@git-ns:github.com/acme"]);
        assert_eq!(
            newly_conferred(None, &entry(rm, None), now),
            vec!["git.ns.admin@git-ns:github.com/acme".parse().unwrap()]
        );
    }

    /// VTI-APV-019: what a reduction takes away.
    #[test]
    fn vti_apv_019_lost_conferring_is_what_the_reduction_takes_away() {
        let now = 1_000;
        let admin = entry(AdminAuthority::community_admin(), None);
        assert!(lost_conferring(&admin, None, now).contains(&CapRef::all(Capability::RolesAssign)));
        let mut narrow = AdminAuthority::community_admin();
        narrow.capabilities = listed(&["vtc.audit.read"]);
        assert!(!lost_conferring(&admin, Some(&entry(narrow, None)), now).is_empty());
        assert!(lost_conferring(&admin, Some(&admin), now).is_empty());
        let moderator = entry(AdminAuthority::for_role(AdminRole::Moderator), None);
        assert!(lost_conferring(&moderator, None, now).is_empty());
    }

    /// Approvers hold and may approve what is at stake, at a covering
    /// qualifier (`vtc-admin-roles.md` §7).
    #[test]
    fn may_approve_needs_the_capability_and_approve_authority() {
        let now = 1_000;
        let stake = vec![CapRef::all(Capability::RolesAssign)];
        assert!(may_approve(
            &entry(AdminAuthority::community_admin(), None),
            &stake,
            now
        ));
        assert!(!may_approve(
            &entry(AdminAuthority::for_role(AdminRole::Moderator), None),
            &stake,
            now
        ));
        // Holds it, but approves nothing (VTI-ACL-040).
        let mut no_approve = AdminAuthority::community_admin();
        no_approve.approve = crate::acl::VtcActScope::None;
        assert!(!may_approve(&entry(no_approve, None), &stake, now));

        // A qualifier-bound approver approves only inside its qualifier.
        let mut rm = AdminAuthority::for_role(AdminRole::RepoManager);
        rm.capabilities = listed(&["git.ns.admin@git-ns:github.com/acme"]);
        rm.approve_capabilities = listed(&["git.ns.admin@git-ns:github.com/acme"]);
        let rm = entry(rm, None);
        let inside: Vec<CapRef> = vec!["git.ns.admin@git-ns:github.com/acme".parse().unwrap()];
        let outside: Vec<CapRef> = vec!["git.ns.admin@git-ns:github.com/other".parse().unwrap()];
        assert!(may_approve(&rm, &inside, now));
        assert!(!may_approve(&rm, &outside, now));
    }

    /// VTI-ACL-041: the least-privilege approver — act `none`, an approve
    /// scope — is an approver for every kind its approve scope reaches, though
    /// it holds nothing.
    #[test]
    fn vti_acl_041_a_least_privilege_approver_counts_for_every_act() {
        use crate::policy::PolicyPurpose;
        let now = 1_000;
        let approver = entry(AdminAuthority::for_role(AdminRole::Approver), None);
        assert!(!approver.admin.can(Capability::RolesAssign, None));
        for act in [
            Act::GrantUnrestricted,
            Act::ReduceUnrestricted,
            Act::LowerThreshold,
            Act::ChangeAuthorityPolicy(PolicyPurpose::Removal),
            Act::ChangeRoles,
            Act::RestoreBackup,
            Act::GrantsReview,
            Act::ChangeTrustedWitnesses,
            Act::ChangeJoinCriteria,
            Act::ChangeHiddenVetting,
            Act::ChangeDirectoryPrivacy,
            Act::ChangeRecognitionPolicy(PolicyPurpose::Personhood),
        ] {
            assert!(may_approve(&approver, &act.default_stake(), now), "{act:?}");
        }
        // Narrowed to approving vetting only, it approves nothing else.
        let mut vetting_only = AdminAuthority::for_role(AdminRole::Approver);
        vetting_only.approve_capabilities = listed(&["vtc.vetting.manage"]);
        let vetting_only = entry(vetting_only, None);
        assert!(may_approve(
            &vetting_only,
            &[CapRef::all(Capability::VettingManage)],
            now
        ));
        assert!(!may_approve(
            &vetting_only,
            &Act::GrantUnrestricted.default_stake(),
            now
        ));
        // An auditor approves nothing.
        let auditor = entry(AdminAuthority::for_role(AdminRole::Auditor), None);
        assert!(!may_approve(
            &auditor,
            &Act::LowerThreshold.default_stake(),
            now
        ));
    }

    /// Each act is raised as its own kind, and every (kind, task) a gate can
    /// raise has a summary template (VTI-APV-013).
    #[test]
    fn every_act_names_a_kind_with_a_template() {
        use crate::admin_actions::summary::template_for;
        use crate::policy::PolicyPurpose;
        use crate::trust_tasks as tt;
        for (act, uri) in [
            (Act::GrantUnrestricted, tt::ACL_GRANT_TYPE),
            (Act::GrantUnrestricted, tt::ACL_CHANGE_ROLE_TYPE),
            (Act::GrantUnrestricted, tt::ACL_UPDATE_TYPE),
            (Act::GrantUnrestricted, tt::ACL_GRANT_V0_2_TYPE),
            (Act::GrantUnrestricted, tt::ACL_CHANGE_ROLE_V0_2_TYPE),
            (Act::GrantUnrestricted, tt::ACL_UPDATE_V0_2_TYPE),
            (Act::GrantUnrestricted, tt::admin_tasks::INVITES_CREATE_TYPE),
            (Act::ReduceUnrestricted, tt::ACL_REVOKE_TYPE),
            (Act::ReduceUnrestricted, tt::ACL_REVOKE_V0_2_TYPE),
            (Act::ReduceUnrestricted, tt::ACL_CHANGE_ROLE_TYPE),
            (Act::ReduceUnrestricted, tt::ACL_CHANGE_ROLE_V0_2_TYPE),
            (Act::ReduceUnrestricted, tt::ACL_UPDATE_TYPE),
            (Act::ReduceUnrestricted, tt::ACL_UPDATE_V0_2_TYPE),
            (Act::ReduceUnrestricted, tt::ACL_GRANT_TYPE),
            (Act::ReduceUnrestricted, tt::MEMBER_ADMIN_REMOVE_TYPE),
            (Act::LowerThreshold, tt::admin_tasks::CONFIG_PATCH_TYPE),
            (Act::LowerThreshold, tt::CONFIG_IMPORT_TYPE),
            (
                Act::ChangeTrustedWitnesses,
                tt::admin_tasks::CONFIG_PATCH_TYPE,
            ),
            (Act::ChangeTrustedWitnesses, tt::CONFIG_IMPORT_TYPE),
            (
                Act::ChangeJoinCriteria,
                tt::surface_tasks::ACCEPTS_REGISTER_TYPE,
            ),
            (
                Act::ChangeJoinCriteria,
                tt::surface_tasks::ACCEPTS_DELETE_TYPE,
            ),
            (
                Act::ChangeHiddenVetting,
                crate::admin_actions::summary::HIDDEN_PUBLISH,
            ),
            (
                Act::ChangeDirectoryPrivacy,
                crate::trust_tasks::directory_tasks::FIELDS_UPDATE_TYPE,
            ),
            (
                Act::ChangeHiddenVetting,
                crate::admin_actions::summary::HIDDEN_WITHDRAW,
            ),
            (
                Act::ChangeRecognitionPolicy(PolicyPurpose::Personhood),
                tt::policy_tasks::POLICY_UPSERT_TYPE,
            ),
            (
                Act::ChangeRecognitionPolicy(PolicyPurpose::Personhood),
                tt::policy_tasks::POLICY_ACTIVATE_TYPE,
            ),
            (
                Act::ChangeAuthorityPolicy(PolicyPurpose::Removal),
                tt::policy_tasks::POLICY_UPSERT_TYPE,
            ),
            (
                Act::ChangeAuthorityPolicy(PolicyPurpose::Join),
                tt::policy_tasks::POLICY_ACTIVATE_TYPE,
            ),
        ] {
            assert!(
                template_for(act.kind(uri), uri).is_some(),
                "no summary template for ({}, {uri})",
                act.kind(uri)
            );
        }
        assert_eq!(
            Act::GrantUnrestricted.kind(tt::admin_tasks::INVITES_CREATE_TYPE),
            "admin.invite.create"
        );
    }
}