vta-service 0.36.0

Service for Verifiable Trust Agents operating in Verifiable Trust Communities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
//! Persona trust-task slice (`spec/persona/*`) — authorization.
//!
//! The holder's own identity: the attribute pool, the profiles that project
//! over it, the bindings that assign a profile to a persona DID, and the
//! contacts peers disclose.
//!
//! # The boundary is one-way, and this module is where it is enforced
//!
//! The pool and profiles are **agent-scoped**, above every trust context.
//! Bindings, contacts and disclosure records are **context-scoped**. Nothing
//! inside a context may read the pool: the holder pushes a materialised
//! projection down, and a context never pulls.
//!
//! That is a rule about *direction* rather than a permission, because the
//! permission form invites the wrong implementation. An access-control failure
//! over a readable pool discloses everything; a pool no context can address has
//! nothing to disclose. `vta-persona`'s key layout provides the second half —
//! separately addressable prefixes — and [`Reach`] below provides the first.
//!
//! # The trap this module exists to avoid
//!
//! A guard written as *"is this caller an administrator"* **passes for an
//! administrator scoped to a single context**, who would then read and write
//! identity data belonging to every other context. An admin in one context must
//! be as powerless over the pool as an application in that context.
//!
//! The correct gate is [`AuthClaims::require_super_admin`] — `Admin` **and**
//! unrestricted scope. `vti-common`'s own `act_scope` documentation warns about
//! the same edge from the other side: an empty context list means *unrestricted*
//! for `Admin` and *nothing at all* for every other role, so a call site testing
//! `is_empty()` without the role gets one of the two backwards.

use serde_json::{Value, json};
use trust_tasks_rs::{ErrorPayload, StandardCode, TrustTask, TrustTaskCode};
use vta_sdk::trust_tasks as uris;
use vti_common::error::AppError;

use crate::audit;
use crate::auth::AuthClaims;
use crate::server::AppState;

use super::helpers::{
    TrustTaskOutcome, error_response, parse_payload, reject_with_code, success_response,
};

/// The family namespace for codes shared across the slice. A proper path prefix
/// of each task slug, which SPEC §8.5 permits so a family-wide meaning is
/// defined once.
const FAMILY_SLUG: &str = "persona";

fn slug_from_doc(doc: &TrustTask<Value>) -> String {
    doc.type_uri
        .to_string()
        .strip_prefix("https://trusttasks.org/spec/")
        .and_then(|rest| rest.rsplit_once('/'))
        .map(|(slug, _ver)| slug.to_string())
        .unwrap_or_else(|| FAMILY_SLUG.to_string())
}

fn ext(slug: &str, local: &str) -> TrustTaskCode {
    TrustTaskCode::new_extended(slug, local).expect("persona extended code is grammar-valid")
}

/// Which side of the boundary a task sits on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Reach {
    /// Reachable only by an **unscoped holder** — `Admin` with unrestricted
    /// scope. A context-scoped caller is refused whatever its role.
    Holder,
    /// Reachable from inside a context, and confined to the caller's own.
    Context,
    /// Reachable by any authenticated caller, scoped or not.
    ///
    /// One task sits here, and it is not a hole. `renderers/list` returns a
    /// compile-time constant — the renderer ids this build ships and what each
    /// one discards — and carries nothing about the holder, any context, or
    /// any stored state at all.
    ///
    /// It needs its own variant because both of the others are wrong for it in
    /// opposite directions. `Context` refuses the unscoped holder: the payload
    /// schema has no `contextId`, so there is no context to name, and a
    /// handler that supplies one from the caller's own claims refuses the
    /// *most* privileged caller — an `Admin` with an unrestricted (empty)
    /// context list — while admitting every scoped one. `Holder` would refuse
    /// the callers who most need it: `disclosure/preview` is context-scoped
    /// and takes a renderer name, so an application that cannot list renderers
    /// cannot choose one, and choosing blind is how a holder ends up disclosing
    /// through a format that silently drops provenance.
    Any,
}

/// Every task in the family, paired with the side of the boundary it sits on.
///
/// Exhaustive by test. A task cannot join the family without someone deciding
/// which side it is on, because the census below fails until it appears here —
/// and defaulting a new task to `Context` is precisely how a pool read would
/// become reachable from inside one.
pub const REACH: &[(&str, Reach)] = &[
    // ── Agent-scoped: the holder's own, above every context ───────────────
    (uris::TASK_PERSONA_ATTRIBUTE_PUT_1_0, Reach::Holder),
    (uris::TASK_PERSONA_ATTRIBUTE_LIST_1_0, Reach::Holder),
    (uris::TASK_PERSONA_ATTRIBUTE_DELETE_1_0, Reach::Holder),
    (uris::TASK_PERSONA_PROFILE_PUT_1_0, Reach::Holder),
    (uris::TASK_PERSONA_PROFILE_GET_1_0, Reach::Holder),
    (uris::TASK_PERSONA_PROFILE_LIST_1_0, Reach::Holder),
    (uris::TASK_PERSONA_PROFILE_DELETE_1_0, Reach::Holder),
    // A facet states which of the holder's identities are, to them, parts of
    // one life — the linkage map the whole family exists to keep from being
    // assembled by anyone else, written down by the only person entitled to
    // write it. A context-scoped caller reading one would learn how the holder
    // arranges every *other* context.
    (uris::TASK_PERSONA_FACET_PUT_1_0, Reach::Holder),
    (uris::TASK_PERSONA_FACET_LIST_1_0, Reach::Holder),
    (uris::TASK_PERSONA_FACET_DELETE_1_0, Reach::Holder),
    // The critical gate. An application able to call this could bind any
    // profile to a persona it controls and read the result back through a
    // disclosure it requests of itself. Every other read leaks; this one is
    // directly exploitable.
    (uris::TASK_PERSONA_BINDING_SET_1_0, Reach::Holder),
    // Reads across every context, so it cannot be context-callable.
    (uris::TASK_PERSONA_DISCLOSURE_HISTORY_1_0, Reach::Holder),
    // Returns the linkage map between the holder's identities — the artifact
    // the whole family exists to keep from being assembled by anyone else.
    (uris::TASK_PERSONA_CORRELATION_ANALYZE_1_0, Reach::Holder),
    // ── Context-scoped: confined to the caller's own context ──────────────
    // Thin by construction: whether a profile is bound, its label, a claim
    // count. Never contents.
    (uris::TASK_PERSONA_BINDING_GET_1_0, Reach::Context),
    (uris::TASK_PERSONA_BINDING_LIST_1_0, Reach::Context),
    (uris::TASK_PERSONA_CONTACT_PUT_1_0, Reach::Context),
    (uris::TASK_PERSONA_CONTACT_GET_1_0, Reach::Context),
    (uris::TASK_PERSONA_CONTACT_LIST_1_0, Reach::Context),
    (uris::TASK_PERSONA_CONTACT_DELETE_1_0, Reach::Context),
    // The only path by which claim values reach an application — after a
    // human-visible summary. Being inside a context confers no privilege over
    // identity data: an application is a verifier, taking the same path as a
    // stranger's web page.
    (uris::TASK_PERSONA_DISCLOSURE_PREVIEW_1_0, Reach::Context),
    (uris::TASK_PERSONA_DISCLOSURE_PRESENT_1_0, Reach::Context),
    // ── Neither side: the agent's own advertised capabilities ─────────────
    (uris::TASK_PERSONA_RENDERERS_LIST_1_0, Reach::Any),
    (uris::TASK_PERSONA_CLAIM_TYPES_LIST_1_0, Reach::Any),
    // Authoring below the boundary is safe; the rule stops reading across it.
    (uris::TASK_PERSONA_LOCAL_PROFILE_PUT_1_0, Reach::Context),
    (uris::TASK_PERSONA_LOCAL_PROFILE_GET_1_0, Reach::Context),
    (uris::TASK_PERSONA_LOCAL_PROFILE_LIST_1_0, Reach::Context),
    (uris::TASK_PERSONA_LOCAL_PROFILE_DELETE_1_0, Reach::Context),
    // Safely context-callable — unlike `binding/set` — because both objects it
    // names live below the boundary. Its one load-bearing obligation is at the
    // handler: a `profileId` naming a POOL profile must be refused.
    (uris::TASK_PERSONA_LOCAL_BINDING_SET_1_0, Reach::Context),
];

/// The reach of a task, or `None` if this build does not know the URI.
///
/// Returning `None` rather than defaulting is deliberate. A task nobody
/// recognises must not be assumed safe to serve a context-scoped caller, and a
/// default of `Context` is exactly the shape of the leak this module prevents.
#[must_use]
pub fn reach_of(uri: &str) -> Option<Reach> {
    REACH.iter().find(|(u, _)| *u == uri).map(|(_, r)| *r)
}

/// Whether this caller has been granted holder authority by name.
///
/// Read from the ACL entry per call rather than from the access token, and the
/// direction matters: a *grant* carried in a JWT outlives its revocation for the
/// life of the token, so revoking holder authority would leave a window in which
/// the pool is still readable. (The capability *narrowing* gate reads per call
/// for the mirror-image reason — see `helpers::require_capability`.)
///
/// A store error is not a grant. It is logged with the real reason and answered
/// as "no", because the alternative — treating an unreadable ACL as permission —
/// turns a database blip into a boundary crossing.
/// Whether the caller acts for the holder — the same test [`authorize`] applies
/// to a holder-reach task, for the members of a context-reach response that
/// only the holder may read.
async fn is_holder(state: &AppState, claims: &AuthClaims) -> bool {
    claims.is_super_admin() || holder_capability_granted(state, claims).await
}

async fn holder_capability_granted(state: &AppState, claims: &AuthClaims) -> bool {
    match vti_common::acl::get_acl_entry(&state.acl_ks, &claims.did).await {
        Ok(Some(entry)) => vti_common::acl::entry_has_capability(
            &entry,
            vti_common::acl::Capability::PersonaHolder,
        ),
        // No entry, no grant. Unlike the narrowing gate, there is no role to
        // fall back to: no role derives this capability.
        Ok(None) => false,
        Err(e) => {
            tracing::error!(
                error = %e, did = %claims.did,
                "could not read the ACL entry for a persona holder check; refusing"
            );
            false
        }
    }
}

/// Gate a persona task on the reach its URI declares.
///
/// `Holder` is satisfied two ways, and only two: an **unscoped holder
/// credential** (`Admin` with unrestricted scope), or an entry granted
/// [`Capability::PersonaHolder`](vti_common::acl::Capability::PersonaHolder) by
/// name. A context-scoped admin holding neither is refused, which is the whole
/// point.
///
/// The capability exists because the first form was, until now, the *only*
/// form: managing your own identity from a client meant giving that client
/// authority over every context on the agent. It grants the pool without
/// granting that.
///
/// The ACL read happens only where it can change the answer — a `Holder` task,
/// for a caller who is not already unscoped — so the context-scoped tasks and
/// the super-admin path cost exactly what they did.
pub async fn authorize(
    state: &AppState,
    claims: &AuthClaims,
    uri: &str,
    context_id: Option<&str>,
) -> Result<(), AppError> {
    let granted = matches!(reach_of(uri), Some(Reach::Holder))
        && !claims.is_super_admin()
        && holder_capability_granted(state, claims).await;
    decide(claims, uri, context_id, granted)
}

/// The decision itself, given whether the caller holds the capability.
///
/// Split from [`authorize`] so the whole matrix — every URI against every role
/// and scope — is testable without standing up a store. The reach table is the
/// thing most likely to be got wrong, and a test that needs an `AppState` to
/// ask about it is a test nobody extends when they add a task.
fn decide(
    claims: &AuthClaims,
    uri: &str,
    context_id: Option<&str>,
    holder_granted: bool,
) -> Result<(), AppError> {
    match reach_of(uri) {
        None => Err(AppError::Forbidden(format!(
            "unknown persona task {uri}: refusing rather than defaulting a reach"
        ))),
        Some(Reach::Holder) => {
            if claims.is_super_admin() || holder_granted {
                return Ok(());
            }
            Err(AppError::Forbidden(
                "this task reads or writes the holder's attribute pool, which sits above every \
                 trust context. It requires an unscoped holder credential, or an ACL entry \
                 granted the `persona-holder` capability; an administrator scoped to a context \
                 and holding neither is refused here exactly as an application would be."
                    .into(),
            ))
        }
        Some(Reach::Context) => match context_id {
            Some(ctx) => claims.require_context(ctx),
            None => Err(AppError::Validation(
                "a context-scoped persona task must name the context it acts in".into(),
            )),
        },
        // Authentication is the whole gate. See `Reach::Any` for why this task
        // does not belong on either side of the boundary, and why supplying a
        // context on its behalf was a bug rather than a convenience.
        Some(Reach::Any) => Ok(()),
    }
}

// ─────────────────────────────────────────────────────────────────────────
// Handlers
// ─────────────────────────────────────────────────────────────────────────
//
// Request and response types come straight from `trust-tasks-rs` rather than
// hand-written SDK mirrors. `parse_payload` is generic over serde, so the
// generated types work as-is — and a mirror would be a second definition of the
// same contract, free to drift from the published schema without anything
// noticing. The generated types cannot.

use trust_tasks_rs::specs::persona as spec;
use vta_persona::{
    Listing, PersonaStore, ReleaseRequirement, Sensitivity, ValueType, ValueVisibility,
    new_attribute,
};

/// Open the store for this request.
///
/// The correlation key is derived per agent and lives beside the at-rest key;
/// it never leaves the agent, which is what makes the blinded index blinded.
pub(super) fn store(state: &AppState) -> PersonaStore {
    PersonaStore::new(state.persona_ks.clone(), state.persona_correlation_key)
}

/// Insert `key` into a response body only when `value` is `Some`.
///
/// `json!` renders a `None` as `null`, and every optional member in this
/// family's response schemas is typed `string`, `integer` or `date-time` —
/// none of which accepts null. An unset optional must be **absent**.
///
/// This is the response-side twin of the rule `payload_null_census` pins on
/// the request side in `vta-sdk`, and unlike that side it has no census: the
/// response-conformance layer catches it at run time in debug builds, which is
/// the only reason `disclosure/present`'s `credentialId` was ever noticed. Use
/// this rather than naming an `Option` inside `json!`.
fn put_opt<T: serde::Serialize>(body: &mut Value, key: &str, value: Option<T>) {
    if let Some(v) = value {
        body[key] = json!(v);
    }
}

/// Audit a persona task.
///
/// `detail` is a short human-readable sentence saying what the operation
/// *changed*, and it exists because the trail without one is unreadable. Every
/// write in this family used to record action, actor, resource and outcome and
/// nothing else, so an entire console audit pane read `persona.attribute.put`
/// against an opaque ULID, twenty rows deep, with no way to tell a created
/// attribute from an updated one or a cascade delete from a refused one. The
/// console was never the problem: `AuditEnvelope` renders `detail` in full as
/// `detail.reason`, and there was simply nothing to render.
///
/// # The attribute VALUE is never recorded — and the reason is LIFETIME
///
/// The obvious reading of that rule is an access-control one: that whoever
/// reads the audit log is less trusted than whoever reads the pool. That
/// reading is false here, and believing it leads to the wrong conclusion in
/// both directions.
///
/// Persona rows are recorded with `context_id: None`, and
/// [`crate::operations::audit`]'s `authorize` already refuses every entry not
/// confined to a named context to anyone but an **unrestricted (super) admin**
/// — precisely the caller [`Reach::Holder`] admits to `attribute/list`, which
/// hands back the plaintext values on request. So a value written here would
/// disclose nothing to anyone who could not already ask for it directly.
/// Nobody gains a read.
///
/// What they gain is a **second copy with a different lifetime**. The audit
/// keyspace is append-only and pruned on its own retention schedule
/// (`vta_audit::cleanup_expired_logs`); the pool is deleted when the holder
/// deletes an attribute. Copy a value across and `attribute/delete` quietly
/// stops being a delete: the value outlives the record it came from, in a
/// store the holder's delete does not reach and whose whole point is that it
/// is not rewritten afterwards.
///
/// The distinction is spelled out because "don't log values", stated as a bare
/// prohibition, is exactly the rule someone relaxes the first time an operator
/// asks for a more useful trail — and the access-control argument, being
/// false, does not survive that conversation. The lifetime argument does.
///
/// What `detail` may therefore carry: claim **types**, value *types*,
/// provenance kinds, counts, versions, and identifiers. Each of those
/// describes the shape of a change without being the personal data, and each
/// is already reconstructible from the live record — so none of them acquires
/// a life the record does not have.
async fn audit_persona(
    state: &AppState,
    action: &str,
    auth: &AuthClaims,
    resource: Option<&str>,
    context_id: Option<&str>,
    detail: Option<&str>,
) {
    if let Err(e) = audit::record_with_detail(
        &state.audit_sink,
        action,
        &auth.did,
        resource,
        "success",
        Some(super::helpers::TRANSPORT_TRUST_TASK),
        context_id,
        detail,
    )
    .await
    {
        tracing::warn!(error = %e, action = %action, "audit record failed for persona task");
    }
}

/// The `kind` discriminant of a provenance, as the wire spells it.
///
/// Matched rather than serialised because only the tag is wanted: serialising
/// a `CredentialBacked` provenance would carry `credentialId`, `claimPath` and
/// `issuerDid` into the audit row alongside it, and a claim path is a
/// description of what an issuer attested about the holder — an attribute with the
/// same lifetime problem as the value itself.
fn provenance_kind(p: &vta_persona::Provenance) -> &'static str {
    match p {
        vta_persona::Provenance::SelfAsserted => "selfAsserted",
        vta_persona::Provenance::CredentialBacked { .. } => "credentialBacked",
        vta_persona::Provenance::Generated { .. } => "generated",
    }
}

/// The wire spelling of a string-valued enum — `string`, `date`, `high`, …
///
/// Via serde rather than a second `match` per enum, so a variant added to
/// `ValueType` or `Sensitivity` cannot end up spelled one way in a response and
/// another in the audit row.
fn wire_name<T: serde::Serialize>(v: T) -> String {
    serde_json::to_value(v)
        .ok()
        .and_then(|j| j.as_str().map(str::to_string))
        .unwrap_or_else(|| "unknown".to_string())
}

/// Map a storage error onto the published error taxonomy.
///
/// Authorization failures use the framework's **standard** `permissionDenied`
/// rather than a task-namespaced synonym: the framework already names this
/// failure, and a duplicate would tell a client switching on the standard code
/// that something else went wrong.
fn reject(doc: &TrustTask<Value>, e: AppError) -> TrustTaskOutcome {
    let slug = slug_from_doc(doc);
    let message = e.to_string();
    let (code, details): (TrustTaskCode, Option<Value>) = match &e {
        AppError::Forbidden(_) | AppError::Unauthorized(_) => {
            (StandardCode::PermissionDenied.into(), None)
        }
        AppError::NotFound(_) => (ext(&slug, "notFound"), None),
        // The conflict carries the maintainer's view WITH the rejection. A bare
        // rejection obliges the caller to re-read, and between the rejection and
        // the re-read the record can change again — the pattern has no fixed
        // point under contention.
        AppError::Conflict(reason) => (
            ext(&slug, "versionConflict"),
            Some(json!({ "reason": reason })),
        ),
        AppError::Validation(reason) => (
            StandardCode::MalformedRequest.into(),
            Some(json!({ "reason": reason })),
        ),
        AppError::Gone(_) => (ext(&slug, "revisionReaped"), None),
        _ => (StandardCode::InternalError.into(), None),
    };

    let mut payload = ErrorPayload::new(code).with_message(message);
    if let Some(d) = details {
        payload = payload.with_details(d);
    }
    error_response(doc.reject_with(format!("urn:uuid:{}", uuid::Uuid::new_v4()), payload))
}

/// Refuse a disclosure for want of a fresh approval, with the code
/// `persona/disclosure/present/1.0` rule 6 declares.
///
/// A **specification-extended** code rather than `taskFailed`, because the two
/// say different things to a client. `taskFailed` means "attempted and could
/// not complete", and the whole point of this refusal is that nothing was
/// attempted: the preview is intact and the same request succeeds once the
/// holder approves. A client that cannot tell those apart cannot offer the
/// retry, which is the only useful thing it can do here.
///
/// The slug comes from the document, like every other extended code in this
/// slice, so the code and the task it refuses cannot drift into two spellings.
fn step_up_required(doc: &TrustTask<Value>, details: Value) -> TrustTaskOutcome {
    let payload = ErrorPayload::new(ext(&slug_from_doc(doc), "stepUpRequired"))
        .with_message("a claim in this preview requires a fresh approval")
        .with_details(details);
    error_response(doc.reject_with(format!("urn:uuid:{}", uuid::Uuid::new_v4()), payload))
}

pub(super) async fn handle_attribute_put(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: spec::attribute::put::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    if let Err(e) = authorize(state, auth, uris::TASK_PERSONA_ATTRIBUTE_PUT_1_0, None).await {
        return reject(&doc, e);
    }

    let value_type = match serde_json::to_string(&req.value_type)
        .ok()
        .and_then(|s| serde_json::from_str::<ValueType>(&s).ok())
    {
        Some(v) => v,
        None => {
            return reject(&doc, AppError::Validation("unrecognised valueType".into()));
        }
    };

    let provenance: vta_persona::Provenance = match serde_json::to_value(&req.provenance)
        .ok()
        .and_then(|v| serde_json::from_value(v).ok())
    {
        Some(p) => p,
        None => return reject(&doc, AppError::Validation("unrecognised provenance".into())),
    };

    // Read the discriminant before the value moves into the attribute. Only the
    // tag survives into the audit row; `provenance_kind` says why the rest of a
    // `CredentialBacked` provenance must not.
    let provenance_kind = provenance_kind(&provenance);

    // The holder's own decision, and only where they made one. Absent is not
    // `normal`: it records that nothing was decided, so the default resolves
    // from the claim-type registry at every read and a later tightening of that
    // registry protects the attributes already in the pool.
    //
    // Through the wire spelling rather than a match, for the reason `valueType`
    // above takes the same route: the generated enum is `#[non_exhaustive]`, so
    // a match needs a wildcard arm, and a wildcard arm is where a variant added
    // upstream would land silently.
    let sensitivity: Option<Sensitivity> = match req.sensitivity.as_ref() {
        None => None,
        Some(s) => match serde_json::to_value(s)
            .ok()
            .and_then(|v| serde_json::from_value(v).ok())
        {
            Some(parsed) => Some(parsed),
            None => {
                return reject(
                    &doc,
                    AppError::Validation("unrecognised sensitivity".into()),
                );
            }
        },
    };

    // Same route as `sensitivity` above, and for the same reason: through the
    // wire spelling rather than a match, because the generated enum is
    // `#[non_exhaustive]` and a wildcard arm is where a variant added upstream
    // would land silently.
    let release: Option<ReleaseRequirement> = match req.release.as_ref() {
        None => None,
        Some(r) => match serde_json::to_value(r)
            .ok()
            .and_then(|v| serde_json::from_value(v).ok())
        {
            Some(parsed) => Some(parsed),
            None => {
                return reject(&doc, AppError::Validation("unrecognised release".into()));
            }
        },
    };

    let mut attribute = new_attribute(
        req.type_.to_string(),
        value_type,
        req.value.clone(),
        provenance,
    );
    if let Some(id) = &req.attribute_id {
        attribute.attribute_id = id.to_string();
    }
    attribute.label = req.label.as_ref().map(|l| (**l).clone());
    attribute.sensitivity = sensitivity;
    attribute.release = release;

    let attribute_id = attribute.attribute_id.clone();
    let value = attribute.value.clone();
    let s = store(state);

    let written = match s.put(attribute, req.expected_version.map(|v| *v)).await {
        Ok(w) => w,
        Err(e) => return reject(&doc, e),
    };

    // Advisory, and computed after the write because the write has already
    // applied — a maintainer must not refuse on correlation grounds. The
    // holder decides.
    let shared = match &value {
        Some(v) => s.correlation_count(v, &attribute_id).await.unwrap_or(0),
        None => 0,
    };

    // A sensitivity override points either way — `normal` on a card is a
    // holder deciding their own tooling may show it — so the row records the
    // decision and not merely that a write happened. Without it a holder
    // reviewing the trail cannot see when the withholding stopped.
    let sensitivity_note = match sensitivity {
        Some(s) => format!(", sensitivity {} set by the holder", wire_name(s)),
        None => String::new(),
    };

    // Recorded for the same reason, and it matters more here: `release` decides
    // what it takes to let the value LEAVE, so a holder relaxing their own card
    // from `stepUp` to `consent` is the single most consequential thing this
    // task can do. A trail that showed only "attribute updated" would not let
    // them find the moment the gate came off.
    let release_note = match release {
        Some(r) => format!(", release {} set by the holder", wire_name(r)),
        None => String::new(),
    };

    // Type, value TYPE, provenance kind and version — never `value`. See
    // `audit_persona` for why that line is drawn on lifetime rather than on
    // who may read the row.
    let detail = format!(
        "{} attribute {attribute_id}: claim type {}, valueType {}, provenance {}{}{}, now at \
         version {}",
        if written.created {
            "created"
        } else {
            "updated"
        },
        req.type_.as_str(),
        wire_name(value_type),
        provenance_kind,
        sensitivity_note,
        release_note,
        written.version,
    );
    audit_persona(
        state,
        "persona.attribute.put",
        auth,
        Some(&attribute_id),
        None,
        Some(&detail),
    )
    .await;

    // Where the edit landed. Nothing references a brand-new attribute, so a
    // create has nothing to report and the scan is skipped.
    let reach = if written.created {
        vta_persona::AttributeReach::default()
    } else {
        s.attribute_reach(&attribute_id).await.unwrap_or_default()
    };

    let mut body = serde_json::json!({
        "attributeId": attribute_id,
        "version": written.version,
        "created": written.created,
        "updatedAt": chrono::Utc::now().to_rfc3339(),
        "correlation": {
            "severity": if shared > 0 { "high" } else { "none" },
            "sharedWithProfileCount": shared,
        },
    });
    if !reach.refreshed.is_empty() {
        body["refreshed"] = reach
            .refreshed
            .iter()
            .take(256)
            .map(|r| {
                json!({
                    "profileId": r.profile_id,
                    "contextId": r.context_id,
                    "personaDid": r.persona_did,
                })
            })
            .collect();
    }
    if !reach.held_by_pin.is_empty() {
        body["heldByPin"] = reach
            .held_by_pin
            .iter()
            .take(256)
            .map(|h| json!({ "profileId": h.profile_id, "pinVersion": h.pin_version }))
            .collect();
    }
    success_response(&doc, body)
}

pub(super) async fn handle_attribute_list(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: spec::attribute::list::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    if let Err(e) = authorize(state, auth, uris::TASK_PERSONA_ATTRIBUTE_LIST_1_0, None).await {
        return reject(&doc, e);
    }

    // Values are withheld unless asked for: the common case — rendering a
    // picker — needs type and label, not plaintext. `includeSensitive` widens
    // that request and can never be the member that introduces plaintext on its
    // own, so the two collapse into one visibility here rather than travelling
    // as a pair every reader has to remember the fourth state of.
    let visibility = ValueVisibility::from_flags(req.include_values, req.include_sensitive);
    let s = store(state);
    let prefix = req.type_prefix.as_ref().map(|p| p.as_str());
    let listing = match s.list_attributes(prefix, visibility).await {
        Ok(l) => l,
        Err(e) => return reject(&doc, e),
    };

    let detail = list_detail(&listing, visibility, prefix);
    audit_persona(
        state,
        "persona.attribute.list",
        auth,
        None,
        None,
        Some(&detail),
    )
    .await;
    success_response(
        &doc,
        serde_json::json!({ "attributes": listing.attributes }),
    )
}

/// What a listing did, for the audit trail.
///
/// A read is audited at all because this one enumerates the holder's identity;
/// what makes the row worth keeping is which of the three listings it was. A
/// trail in which "showed me the names" and "handed a process every card
/// number" are the same row cannot answer the question a holder reviewing it
/// actually has.
///
/// Counts, a claim-type prefix and the visibility — never a value. See
/// [`audit_persona`] for why that line is drawn on lifetime rather than on who
/// may read the row: `attribute/list` hands the values themselves to exactly
/// the caller who can read the audit log, so a value here would disclose
/// nothing new and would outlive the record it came from.
fn list_detail(listing: &Listing, visibility: ValueVisibility, prefix: Option<&str>) -> String {
    let scope = match prefix {
        Some(p) => format!(" under {p}"),
        None => String::new(),
    };
    let plaintext = match visibility {
        ValueVisibility::Metadata => "metadata only, no values".to_string(),
        ValueVisibility::Ordinary => format!(
            "values included, {} sensitive value(s) withheld",
            listing.withheld_sensitive
        ),
        ValueVisibility::All => "values included, sensitive values included".to_string(),
    };
    format!(
        "listed {} attribute(s){scope}: {plaintext}",
        listing.attributes.len()
    )
}

pub(super) async fn handle_attribute_delete(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: spec::attribute::delete::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    if let Err(e) = authorize(state, auth, uris::TASK_PERSONA_ATTRIBUTE_DELETE_1_0, None).await {
        return reject(&doc, e);
    }

    let id = req.attribute_id.to_string();
    let out = match store(state).delete(&id, req.cascade).await {
        Ok(o) => o,
        Err(e) => return reject(&doc, e),
    };

    // `existed` is the half a reader cannot reconstruct afterwards: the record
    // is gone either way, so a row that only says "delete" cannot distinguish a
    // removal from a no-op against a typo'd id.
    let detail = format!(
        "attribute {id} {}; cascade {}; removed from {} profile(s)",
        if out.existed {
            "deleted"
        } else {
            "did not exist"
        },
        req.cascade,
        out.referring_profiles.len(),
    );
    audit_persona(
        state,
        "persona.attribute.delete",
        auth,
        Some(&id),
        None,
        Some(&detail),
    )
    .await;
    success_response(
        &doc,
        serde_json::json!({
            "attributeId": id,
            "existed": out.existed,
            "removedFromProfiles": out.referring_profiles,
        }),
    )
}

// ─── Profiles ────────────────────────────────────────────────────────────

pub(super) async fn handle_profile_put(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: spec::profile::put::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    if let Err(e) = authorize(state, auth, uris::TASK_PERSONA_PROFILE_PUT_1_0, None).await {
        return reject(&doc, e);
    }

    // Entries round-trip through JSON into our own model. The generated
    // ProfileEntry and ours describe the same four shapes; going through the
    // wire form means the untagged discrimination is exercised exactly as a
    // peer's document would exercise it, rather than by a hand-written match
    // that could disagree with the schema.
    let entries = match serde_json::to_value(&req.entries)
        .ok()
        .and_then(|v| serde_json::from_value(v).ok())
    {
        Some(e) => e,
        None => {
            return reject(
                &doc,
                AppError::Validation("unrecognised profile entry".into()),
            );
        }
    };

    let mut profile = vta_persona::new_profile(req.name.to_string(), entries);
    if let Some(id) = &req.profile_id {
        profile.profile_id = id.to_string();
    }
    profile.credential_refs = req.credential_refs.iter().map(|c| (**c).clone()).collect();
    let profile_id = profile.profile_id.clone();
    let entry_count = profile.entries.len();

    let written = match store(state)
        .put_profile(profile, req.expected_version.map(|v| *v))
        .await
    {
        Ok(w) => w,
        Err(e) => return reject(&doc, e),
    };

    // The entry COUNT, not the entries. An entry is either a pool reference —
    // an identifier, safe — or an inline value, which is a claim value under
    // another name and carries the whole lifetime problem with it.
    let detail = format!(
        "{} profile {profile_id} with {} entr{}, now at version {}",
        if written.created {
            "created"
        } else {
            "updated"
        },
        entry_count,
        if entry_count == 1 { "y" } else { "ies" },
        written.version,
    );
    audit_persona(
        state,
        "persona.profile.put",
        auth,
        Some(&profile_id),
        None,
        Some(&detail),
    )
    .await;
    success_response(
        &doc,
        json!({
            "profileId": profile_id,
            "version": written.version,
            "created": written.created,
            "updatedAt": chrono::Utc::now().to_rfc3339(),
        }),
    )
}

pub(super) async fn handle_profile_get(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: spec::profile::get::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    if let Err(e) = authorize(state, auth, uris::TASK_PERSONA_PROFILE_GET_1_0, None).await {
        return reject(&doc, e);
    }

    let id = req.profile_id.to_string();
    let s = store(state);
    let Some(profile) = (match s.get_profile(&id).await {
        Ok(p) => p,
        Err(e) => return reject(&doc, e),
    }) else {
        // Not an empty success: a caller that cannot tell "absent" from "empty"
        // treats a typo as a profile that discloses nothing.
        return reject(&doc, AppError::NotFound(format!("profile {id}")));
    };

    // Resolution is opt-in because it is the expensive AND the disclosing
    // answer — it decrypts values and re-derives credential-backed ones.
    let resolved = if req.resolve {
        match s.resolve_profile(&id).await {
            Ok(r) => Some(r),
            Err(e) => return reject(&doc, e),
        }
    } else {
        None
    };

    audit_persona(state, "persona.profile.get", auth, Some(&id), None, None).await;
    let mut body = json!({ "profile": profile });
    if let Some(r) = resolved {
        // A resolved entry is a `ResolvedClaim`, not the pool `Attribute`, so an
        // INLINE entry is describable: `attributeId`, `version` and `updatedAt`
        // are optional there, and their absence is what says "this value lives
        // only in this profile".
        //
        // Until trust-tasks-rs 0.18 the array was typed as `Attribute`, which
        // required all three, and this handler refused rather than answer
        // non-conformantly — a synthesised `attributeId` would have been a lie
        // about where a value lives, and omitting the entry would have returned
        // a profile that appears to present less than it does. The schema is
        // fixed upstream (dtgwg-trust-tasks-tf#370) and the refusal is gone.
        body["resolved"] = json!(
            r.iter()
                .map(|c| {
                    let mut row = json!({
                        "type": c.r#type,
                        "value": c.value,
                        "valueType": c.value_type,
                        "provenance": c.provenance,
                        "stale": c.stale,
                    });
                    // Absent, not null — see `put_opt`.
                    put_opt(&mut row, "attributeId", c.attribute_id.clone());
                    put_opt(&mut row, "label", c.label.clone());
                    put_opt(&mut row, "version", c.version);
                    put_opt(&mut row, "updatedAt", c.updated_at.clone());
                    row
                })
                .collect::<Vec<_>>()
        );
    }
    success_response(&doc, body)
}

pub(super) async fn handle_profile_list(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let _req: spec::profile::list::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    if let Err(e) = authorize(state, auth, uris::TASK_PERSONA_PROFILE_LIST_1_0, None).await {
        return reject(&doc, e);
    }
    // No resolve option, deliberately: resolving every profile at once would
    // decrypt the holder's entire pool to answer a question about names.
    let profiles = match store(state).list_profiles().await {
        Ok(p) => p,
        Err(e) => return reject(&doc, e),
    };
    audit_persona(state, "persona.profile.list", auth, None, None, None).await;
    success_response(&doc, json!({ "profiles": profiles }))
}

pub(super) async fn handle_profile_delete(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: spec::profile::delete::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    if let Err(e) = authorize(state, auth, uris::TASK_PERSONA_PROFILE_DELETE_1_0, None).await {
        return reject(&doc, e);
    }

    let id = req.profile_id.to_string();
    let s = store(state);

    // Refuse while a persona is bound unless the holder said unbind. A persona
    // that silently stopped presenting anything is a failure they discover from
    // the other side of a disclosure that did not happen.
    let bound = match s.personas_bound_to_anywhere(&id).await {
        Ok(b) => b,
        Err(e) => return reject(&doc, e),
    };
    if !bound.is_empty() && !req.unbind {
        let mut payload = ErrorPayload::new(ext(&slug_from_doc(&doc), "bound")).with_message(
            format!("{} persona(s) are bound to this profile", bound.len()),
        );
        payload = payload.with_details(json!({ "personaDids": bound }));
        return error_response(
            doc.reject_with(format!("urn:uuid:{}", uuid::Uuid::new_v4()), payload),
        );
    }
    if req.unbind
        && let Err(e) = s.unbind_everywhere(&id).await
    {
        return reject(&doc, e);
    }

    let existed = match s.delete_profile(&id).await {
        Ok(e) => e,
        Err(e) => return reject(&doc, e),
    };
    // How many personas were left presenting nothing is the consequence a
    // holder most needs to find later, and it is the one fact that survives
    // nowhere else: the bindings it describes have already been cleared.
    let detail = format!(
        "profile {id} {}; {}; {} persona(s) unbound",
        if existed { "deleted" } else { "did not exist" },
        if req.unbind {
            "unbind requested"
        } else {
            "no unbind requested"
        },
        bound.len(),
    );
    audit_persona(
        state,
        "persona.profile.delete",
        auth,
        Some(&id),
        None,
        Some(&detail),
    )
    .await;
    success_response(
        &doc,
        json!({ "profileId": id, "existed": existed, "unboundPersonas": bound }),
    )
}

// ─── Bindings ────────────────────────────────────────────────────────────

pub(super) async fn handle_binding_set(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: spec::binding::set::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    // Holder-only, and the critical gate: an application able to call this
    // could bind any profile to a persona it controls and read the result back
    // through a disclosure it requests of itself.
    if let Err(e) = authorize(state, auth, uris::TASK_PERSONA_BINDING_SET_1_0, None).await {
        return reject(&doc, e);
    }

    let ctx = req.context_id.to_string();
    let persona = req.persona_did.to_string();
    let profile_id = req.profile_id.as_ref().map(|p| p.to_string());
    let public = req.public_entries.iter().map(|e| e.to_string()).collect();

    let bound = match store(state)
        .set_binding(
            &ctx,
            &persona,
            profile_id.as_deref(),
            public,
            req.label.as_ref().map(|l| l.to_string()),
            req.expected_version.map(|v| *v),
        )
        .await
    {
        Ok(b) => b,
        Err(e) => return reject(&doc, e),
    };

    // The materialised claim count is what changed on the far side of the
    // boundary: this write is a PUSH into a context, and the count is how much
    // that context can now present. "unbound" is spelled out rather than left
    // as an absent profileId, because a binding cleared and a binding never
    // made read identically otherwise.
    let detail = format!(
        "persona {persona} in context {ctx} bound to {}; {} claim(s) materialised, now at \
         version {}",
        profile_id
            .as_deref()
            .map_or_else(|| "unbound".to_string(), |p| format!("profile {p}")),
        bound.materialised_claim_count,
        bound.version,
    );
    audit_persona(
        state,
        "persona.binding.set",
        auth,
        Some(&persona),
        Some(&ctx),
        Some(&detail),
    )
    .await;
    success_response(
        &doc,
        json!({
            "contextId": ctx,
            "personaDid": persona,
            "profileId": profile_id,
            "version": bound.version,
            "materialisedClaimCount": bound.materialised_claim_count,
            "correlation": {
                // Binding one profile to a second persona makes them the same
                // person by construction, and no later narrowing undoes it.
                "severity": if bound.also_bound_persona_count > 0 { "high" } else { "none" },
                "alsoBoundPersonaCount": bound.also_bound_persona_count,
            },
            "boundAt": chrono::Utc::now().to_rfc3339(),
        }),
    )
}

pub(super) async fn handle_binding_get(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: spec::binding::get::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let ctx = req.context_id.to_string();
    if let Err(e) = authorize(state, auth, uris::TASK_PERSONA_BINDING_GET_1_0, Some(&ctx)).await {
        return reject(&doc, e);
    }

    let persona = req.persona_did.to_string();
    let sum = match store(state).binding_summary(&ctx, &persona).await {
        Ok(s) => s,
        Err(e) => return reject(&doc, e),
    };
    audit_persona(
        state,
        "persona.binding.get",
        auth,
        Some(&persona),
        Some(&ctx),
        None,
    )
    .await;
    // Thin by construction: whether bound, the label, a claim count. Never
    // contents — those reach an application only through the disclosure path.
    //
    // Four of the seven members are absent for an *unbound* persona, and
    // absent is not null — see `put_opt`. The bound case conformed; the
    // unbound one emitted four nulls and failed schema validation, which is
    // the reading a caller most needs to be able to trust: "nobody is bound
    // here" is an answer, not an error.
    let mut body = json!({
        "contextId": ctx,
        "personaDid": sum.persona_did,
        "bound": sum.bound,
        // Not optional, and 0 for an unbound persona — a count of nothing is
        // still a count.
        "claimCount": sum.claim_count,
    });
    put_opt(&mut body, "profileId", sum.profile_id);
    put_opt(&mut body, "label", sum.label);
    // The holder's OWN name for the face, which a context-scoped caller must
    // not be handed: it is their filing ("the divorce"), and wearing a face in
    // a context is not consent to tell the context what they call it. The
    // context reads `label`, the name the holder chose for it.
    if is_holder(state, auth).await {
        put_opt(&mut body, "profileName", sum.profile_name);
    }
    put_opt(&mut body, "boundAt", sum.bound_at);
    success_response(&doc, body)
}

pub(super) async fn handle_binding_list(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: spec::binding::list::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let ctx = req.context_id.to_string();
    if let Err(e) = authorize(state, auth, uris::TASK_PERSONA_BINDING_LIST_1_0, Some(&ctx)).await {
        return reject(&doc, e);
    }

    let sums = match store(state).list_binding_summaries(&ctx).await {
        Ok(s) => s,
        Err(e) => return reject(&doc, e),
    };
    audit_persona(state, "persona.binding.list", auth, None, Some(&ctx), None).await;
    // See `handle_binding_get`: the face's own name is the holder's alone.
    let holder = is_holder(state, auth).await;
    let personas: Vec<Value> = sums
        .iter()
        .map(|s| {
            let mut row = json!({
                "personaDid": s.persona_did,
                "bound": s.bound,
                "claimCount": s.claim_count,
            });
            put_opt(&mut row, "label", s.label.clone());
            if holder {
                put_opt(&mut row, "profileName", s.profile_name.clone());
            }
            row
        })
        .collect();
    success_response(&doc, json!({ "personas": personas }))
}

// ─── Contacts ────────────────────────────────────────────────────────────

pub(super) async fn handle_contact_put(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: spec::contact::put::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let ctx = req.context_id.to_string();
    if let Err(e) = authorize(state, auth, uris::TASK_PERSONA_CONTACT_PUT_1_0, Some(&ctx)).await {
        return reject(&doc, e);
    }

    let document = match serde_json::to_value(&req.document)
        .ok()
        .and_then(|v| serde_json::from_value(v).ok())
    {
        Some(d) => d,
        None => {
            return reject(
                &doc,
                AppError::Validation("unrecognised contact document".into()),
            );
        }
    };

    let filed = match store(state)
        .file_contact(
            &ctx,
            &req.subject_did.to_string(),
            &req.known_by_persona.to_string(),
            document,
            req.credential_refs.iter().map(|c| c.to_string()).collect(),
            req.notes.as_ref().map(|n| n.to_string()),
        )
        .await
    {
        Ok(f) => f,
        Err(e) => return reject(&doc, e),
    };

    audit_persona(
        state,
        "persona.contact.put",
        auth,
        Some(&filed.contact_id),
        Some(&ctx),
        None,
    )
    .await;
    success_response(
        &doc,
        json!({
            "contactId": filed.contact_id,
            "rev": filed.rev,
            "created": filed.created,
            // Types, not values. A producer needing the old value reads the
            // prior revision, which is an explicit act.
            "changedClaims": filed.changed_claims,
        }),
    )
}

pub(super) async fn handle_contact_get(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: spec::contact::get::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let ctx = req.context_id.to_string();
    if let Err(e) = authorize(state, auth, uris::TASK_PERSONA_CONTACT_GET_1_0, Some(&ctx)).await {
        return reject(&doc, e);
    }
    let id = req.contact_id.to_string();
    let s = store(state);

    let Some(contact) = (match s.get_contact(&ctx, &id).await {
        Ok(c) => c,
        Err(e) => return reject(&doc, e),
    }) else {
        return reject(&doc, AppError::NotFound(format!("contact {id}")));
    };

    // A named revision resolves through the store, which distinguishes reaped
    // (Gone) from never-existed (NotFound) — a caller comparing against history
    // must be able to tell those apart.
    let document = match req.rev {
        None => serde_json::to_value(&contact.document).unwrap_or(Value::Null),
        Some(rev) => match s.get_contact_revision(&ctx, &id, rev.get()).await {
            Ok(r) => serde_json::to_value(&r.document).unwrap_or(Value::Null),
            Err(e) => return reject(&doc, e),
        },
    };

    let history = if req.include_history {
        match s.contact_history(&ctx, &id).await {
            // Metadata without documents: a timeline is cheap and the documents
            // behind it are not.
            Ok(h) => Some(
                h.iter()
                    .map(|(rev, at, cited)| json!({ "rev": rev, "receivedAt": at, "cited": cited }))
                    .collect::<Vec<_>>(),
            ),
            Err(e) => return reject(&doc, e),
        }
    } else {
        None
    };

    audit_persona(
        state,
        "persona.contact.get",
        auth,
        Some(&id),
        Some(&ctx),
        None,
    )
    .await;
    let mut body = json!({
        "contactId": contact.contact_id,
        "subjectDid": contact.subject_did,
        "knownByPersona": contact.known_by_persona,
        "rev": req.rev.map_or(contact.rev, std::num::NonZeroU64::get),
        "document": document,
        "credentialRefs": contact.credential_refs,
    });
    // The holder's private annotation is optional, and an unset optional must be
    // absent rather than null — see `put_opt`. Naming it inside `json!` emitted
    // `"notes": null` and failed the response schema.
    put_opt(&mut body, "notes", contact.notes.clone());
    if let Some(h) = history {
        body["history"] = json!(h);
    }
    success_response(&doc, body)
}

pub(super) async fn handle_contact_list(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: spec::contact::list::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let ctx = req.context_id.to_string();
    if let Err(e) = authorize(state, auth, uris::TASK_PERSONA_CONTACT_LIST_1_0, Some(&ctx)).await {
        return reject(&doc, e);
    }

    let persona = req.known_by_persona.as_ref().map(|p| p.to_string());
    let sums = match store(state)
        .list_contact_summaries(&ctx, persona.as_deref())
        .await
    {
        Ok(s) => s,
        Err(e) => return reject(&doc, e),
    };

    audit_persona(state, "persona.contact.list", auth, None, Some(&ctx), None).await;
    success_response(
        &doc,
        json!({
            // Summaries carry no claim values: finding one contact does not
            // require disclosing the details of every contact.
            "contacts": sums.iter().map(|s| json!({
                "contactId": s.contact_id,
                "subjectDid": s.subject_did,
                "knownByPersona": s.known_by_persona,
                "rev": s.rev,
                "claimCount": s.claim_count,
                "receivedAt": s.received_at,
                "hasUnreviewedChange": s.has_unreviewed_change,
            })).collect::<Vec<_>>()
        }),
    )
}

pub(super) async fn handle_contact_delete(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: spec::contact::delete::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let ctx = req.context_id.to_string();
    if let Err(e) = authorize(
        state,
        auth,
        uris::TASK_PERSONA_CONTACT_DELETE_1_0,
        Some(&ctx),
    )
    .await
    {
        return reject(&doc, e);
    }
    let id = req.contact_id.to_string();

    let (existed, removed, retained) = match store(state).delete_contact(&ctx, &id).await {
        Ok(o) => o,
        Err(e) => return reject(&doc, e),
    };

    audit_persona(
        state,
        "persona.contact.delete",
        auth,
        Some(&id),
        Some(&ctx),
        None,
    )
    .await;
    success_response(
        &doc,
        json!({
            "contactId": id,
            "existed": existed,
            "revisionsRemoved": removed,
            // Reported rather than glossed: an incomplete erasure the holder
            // believes is complete is worse than one they know about.
            "retainedForDisclosure": retained,
        }),
    )
}

// ─── Disclosure history, correlation, renderers ──────────────────────────

pub(super) async fn handle_disclosure_history(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: spec::disclosure::history::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    // Holder-only: omitting contextId queries across every context, which only
    // the holder may do and is the reason this sits above the boundary.
    if let Err(e) = authorize(state, auth, uris::TASK_PERSONA_DISCLOSURE_HISTORY_1_0, None).await {
        return reject(&doc, e);
    }

    let ctx = req.context_id.as_ref().map(|c| c.to_string());
    let verifier = req.verifier_did.as_ref().map(|v| v.to_string());
    let claim = req.attribute_type.as_ref().map(|t| t.to_string());
    let since = req.since.map(|s| s.to_rfc3339());

    let records = match store(state)
        .disclosure_history(&vta_persona::HistoryQuery {
            context_id: ctx.as_deref(),
            verifier_did: verifier.as_deref(),
            claim_type: claim.as_deref(),
            since: since.as_deref(),
        })
        .await
    {
        Ok(r) => r,
        Err(e) => return reject(&doc, e),
    };

    // Built member by member against the published row rather than by
    // serialising `DisclosureRecord`, whose shape is the store's: its `claims`
    // pairs and `citedContactRevisions` are not members of the row, which is
    // `additionalProperties: false`, so a non-empty history failed validation
    // whole. It went unnoticed because the only test read an empty one.
    let s = store(state);
    let mut rows = Vec::with_capacity(records.len());
    for r in &records {
        let currency = match s.claim_currency(r).await {
            Ok(c) => c,
            Err(e) => return reject(&doc, e),
        };
        let mut row = json!({
            "disclosureId": r.disclosure_id,
            "contextId": r.context_id,
            "verifierDid": r.verifier_did,
            "personaDid": r.persona_did,
            "claimTypes": r.claims.iter().map(|c| c.r#type.clone()).collect::<Vec<_>>(),
            "rungs": r.claims.iter().map(|c| c.rung).collect::<Vec<_>>(),
            "claimCurrency": currency,
            "disclosedAt": r.disclosed_at,
        });
        put_opt(&mut row, "subject", r.subject.clone());
        put_opt(&mut row, "purpose", r.purpose.clone());
        put_opt(&mut row, "renderer", r.renderer.clone());
        put_opt(
            &mut row,
            "durableCredentialId",
            r.durable_credential_id.clone(),
        );
        rows.push(row);
    }

    audit_persona(
        state,
        "persona.disclosure.history",
        auth,
        None,
        ctx.as_deref(),
        None,
    )
    .await;
    success_response(&doc, json!({ "disclosures": rows }))
}

pub(super) async fn handle_correlation_analyze(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: spec::correlation::analyze::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    // Holder-only: the response is the linkage map between the holder's own
    // identities — the artifact the family exists to keep from being assembled
    // by anyone else.
    if let Err(e) = authorize(
        state,
        auth,
        uris::TASK_PERSONA_CORRELATION_ANALYZE_1_0,
        None,
    )
    .await
    {
        return reject(&doc, e);
    }

    let s = store(state);
    let attribute_id = req.attribute_id.as_ref().map(|a| a.to_string());
    let candidate = req
        .candidate
        .as_ref()
        .and_then(|c| serde_json::to_value(&c.value).ok());

    // `profileId` names a face to analyse. It was accepted and ignored before
    // this, so `pnm persona correlate --profile-id` analysed the whole pool and
    // reported it as the face.
    let mut findings = Vec::new();
    if let Some(profile_id) = &req.profile_id {
        match s.analyze_face_correlation(&profile_id.to_string()).await {
            Ok(f) => findings.extend(f),
            Err(e) => return reject(&doc, e),
        }
    }
    // The whole store is analysed only when nothing narrower was named.
    if req.profile_id.is_none() || attribute_id.is_some() || candidate.is_some() {
        match s
            .analyze_correlation(attribute_id.as_deref(), candidate.as_ref())
            .await
        {
            Ok(f) => findings.extend(f),
            Err(e) => return reject(&doc, e),
        }
    }
    findings.truncate(256);

    audit_persona(state, "persona.correlation.analyze", auth, None, None, None).await;
    success_response(&doc, json!({ "findings": findings }))
}

pub(super) async fn handle_renderers_list(
    // Unused: this task describes the agent's declared capabilities, which are
    // a compile-time constant, not stored state. Taking the parameter anyway
    // keeps every handler one shape for the dispatch table.
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let _req: spec::renderers::list::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    // `Reach::Any`: authentication is the gate. This response is a
    // compile-time constant and names nothing the caller does not already know
    // about themselves.
    //
    // This used to pass `auth.allowed_contexts.first()` as the context, on the
    // reasoning that a caller should name one so the request is attributable.
    // That reasoning was wrong twice over. The context did not come from the
    // request, so it attributed nothing; and reading the caller's own list
    // inverted the gate — an `Admin` with an unrestricted (empty) list is the
    // most privileged caller there is, and was the only one refused.
    if let Err(e) = authorize(state, auth, uris::TASK_PERSONA_RENDERERS_LIST_1_0, None).await {
        return reject(&doc, e);
    }

    // Two renderers ship. Lossiness is DECLARED rather than discovered, so a
    // preview can tell the holder what a format will not carry before they
    // decide. Sourced from vta_persona::RENDERERS so this response and the
    // negotiation that enforces it cannot disagree.
    success_response(
        &doc,
        json!({
            "renderers": vta_persona::present::RENDERERS.iter().map(|r| json!({
                "id": r.id,
                "canonical": r.canonical,
                "drops": if r.carries_provenance { vec![] } else { vec!["provenance"] },
                "canCarryPredicates": r.carries_predicates,
            })).collect::<Vec<_>>()
        }),
    )
}

/// Serve the claim-type registry this agent resolves against.
pub(super) async fn handle_claim_types_list(
    // Unused for the same reason as `handle_renderers_list`: the table is a
    // compile-time constant, not stored state.
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let _req: spec::claim_types::list::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    // `Reach::Any`, and neither of the other two would do. An unscoped holder
    // only would refuse the application that needs this most — one inside a
    // context, deciding how to render a preview it was just shown. A context
    // requirement would refuse the holder's own tooling, which has no context
    // to name. The response describes a vocabulary and carries nothing about
    // the holder, any context, or any stored state.
    if let Err(e) = authorize(state, auth, uris::TASK_PERSONA_CLAIM_TYPES_LIST_1_0, None).await {
        return reject(&doc, e);
    }

    // Sourced from `vta_persona::claim_types` — the same table `defaults_for`
    // resolves against — so what is served and what is enforced cannot
    // disagree. That is the task's central MUST, and building the response
    // from a second literal here would break it on day one.
    let l = vta_persona::claim_types::registry_listing();
    let axes = |a: &vta_persona::Axes| {
        json!({
            "sensitivity": wire_name(a.sensitivity),
            "release": wire_name(a.release),
            "mask": wire_name(a.mask),
        })
    };
    // What this deployment declared and the agent would not apply.
    //
    // Carried under `ext`, the specification's vendor-namespaced member
    // (SPEC §4.5.1), because the response's own members are fixed and this is
    // not registry data — it is this *agent* reporting on its own
    // configuration. A client that does not know the key ignores it, which is
    // the correct behaviour for one that cannot act on it.
    //
    // It is here at all because a refused row is invisible otherwise: the token
    // resolves from the core table exactly as it would have with no file, and
    // the operator's intended tightening is quietly not in force. A log line is
    // where that goes to be missed — this is where a person is looking.
    let rejected = vta_persona::claim_types::rejected_extensions();
    let file_error = vta_persona::claim_types::extension_file_error();
    let mut body = json!({
        "registryVersion": l.registry_version,
        "entries": l.entries.iter().map(|r| {
            let mut e = axes(&r.axes);
            e["type"] = json!(r.claim_type);
            e
        }).collect::<Vec<_>>(),
        "unregistered": axes(&l.unregistered),
        "strictness": {
            "sensitivity": l.strictness.sensitivity.iter().map(|v| wire_name(*v)).collect::<Vec<_>>(),
            "release": l.strictness.release.iter().map(|v| wire_name(*v)).collect::<Vec<_>>(),
            "mask": l.strictness.mask.iter().map(|v| wire_name(*v)).collect::<Vec<_>>(),
        },
    });
    if !rejected.is_empty() || file_error.is_some() {
        let mut report = serde_json::Map::new();
        if !rejected.is_empty() {
            report.insert(
                "rejected".into(),
                json!(
                    rejected
                        .iter()
                        .map(|r| json!({ "type": r.token, "reason": r.why }))
                        .collect::<Vec<_>>()
                ),
            );
        }
        if let Some(e) = file_error {
            report.insert("fileError".into(), json!(e));
        }
        body["ext"] = json!({ "org.openvtc.claim-types": report });
    }
    success_response(&doc, body)
}

// ─── Context-local surface ───────────────────────────────────────────────
//
// Authoring BELOW the boundary is safe; the rule exists to stop reading ACROSS
// it. These are context-callable for that reason, and the store keeps them in
// their own address space so a scan here cannot reach a pool profile.

pub(super) async fn handle_local_profile_put(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: spec::local::profile::put::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let ctx = req.context_id.to_string();
    if let Err(e) = authorize(
        state,
        auth,
        uris::TASK_PERSONA_LOCAL_PROFILE_PUT_1_0,
        Some(&ctx),
    )
    .await
    {
        return reject(&doc, e);
    }

    // The schema admits only inline entries, so a reference is unrepresentable
    // rather than rejected. The store re-checks anyway: two independent guards
    // on the property that keeps a context-authored object from acquiring pool
    // reach.
    //
    // **A context-local entry carries no `provenance`, and the store's does.**
    // The published local shape is `{type, valueType, value, label?}` — narrower
    // than a pool profile's inline entry, which requires `provenance` — so the
    // two types are mapped member by member here rather than round-tripped
    // through JSON. The round-trip is what this used to do, and because
    // `InlineValue::provenance` has no default it failed for *every* valid
    // request, rejecting them all as "unrecognised local entry". Nothing caught
    // it: the only test of this task asserted that an invalid entry is refused,
    // which a handler that refuses everything also passes.
    //
    // `SelfAsserted` is the only honest answer, not a placeholder. A
    // credential-backed provenance names a `credentialId` and a `claimPath`,
    // and the local shape has nowhere to put either — so a value authored
    // inside a context cannot be attested, and presenting one as though it were
    // would let a context assert an issuer's authority over a value that issuer
    // never saw. That is the same boundary the missing `ref` forms enforce,
    // one field along.
    let entries: Option<Vec<vta_persona::ProfileEntry>> = req
        .entries
        .iter()
        .map(|e| {
            // Same JSON round-trip the pool handler uses for `valueType`: the
            // two enums serialise to identical strings, and going through serde
            // keeps the mapping honest if either side ever gains a variant the
            // other lacks.
            let value_type = serde_json::to_string(&e.inline.value_type)
                .ok()
                .and_then(|s| serde_json::from_str::<ValueType>(&s).ok())?;
            Some(vta_persona::ProfileEntry::Inline {
                inline: vta_persona::InlineValue {
                    // Generated newtypes `Deref` to `String` but do not impl
                    // `Display`, so a method call auto-derefs where a function
                    // path does not.
                    r#type: e.inline.type_.to_string(),
                    value_type,
                    value: e.inline.value.clone(),
                    label: e.inline.label.as_ref().map(|l| l.to_string()),
                    provenance: vta_persona::Provenance::SelfAsserted,
                },
            })
        })
        .collect();
    let Some(entries) = entries else {
        return reject(&doc, AppError::Validation("unrecognised valueType".into()));
    };

    let mut profile = vta_persona::new_profile(req.name.to_string(), entries);
    if let Some(id) = &req.profile_id {
        profile.profile_id = id.to_string();
    }
    let profile_id = profile.profile_id.clone();
    let entry_count = profile.entries.len();
    let s = store(state);

    let written = match s
        .put_local_profile(&ctx, profile, req.expected_version.map(|v| *v))
        .await
    {
        Ok(w) => w,
        Err(e) => return reject(&doc, e),
    };

    // Local profiles ARE correlation-indexed. The naive implementation skips
    // them — "they are local, they do not matter" — and loses the guard exactly
    // where a human most needs it: a throwaway identity is precisely where
    // somebody reuses a real value.
    let matches_pool = match s.get_local_profile(&ctx, &profile_id).await {
        Ok(Some(p)) => {
            let mut found = false;
            for entry in &p.entries {
                if let vta_persona::ProfileEntry::Inline { inline } = entry
                    && s.correlation_count(&inline.value, "").await.unwrap_or(0) > 0
                {
                    found = true;
                    break;
                }
            }
            found
        }
        _ => false,
    };

    // `matchesPoolValue` is carried because it is the reason this task is
    // correlation-indexed at all: a throwaway identity is precisely where
    // somebody reuses a real value, and a holder auditing that later needs to
    // see WHICH local write raised the flag, not merely that one did. The flag
    // is a boolean about a value, never the value.
    let detail = format!(
        "{} context-local profile {profile_id} in context {ctx} with {} entr{}, now at version \
         {}; matches a pool value: {matches_pool}",
        if written.created {
            "created"
        } else {
            "updated"
        },
        entry_count,
        if entry_count == 1 { "y" } else { "ies" },
        written.version,
    );
    audit_persona(
        state,
        "persona.local.profile.put",
        auth,
        Some(&profile_id),
        Some(&ctx),
        Some(&detail),
    )
    .await;
    success_response(
        &doc,
        json!({
            "profileId": profile_id,
            "version": written.version,
            "created": written.created,
            "correlation": {
                "severity": if matches_pool { "high" } else { "none" },
                "matchesPoolValue": matches_pool,
            }
        }),
    )
}

pub(super) async fn handle_local_profile_get(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: spec::local::profile::get::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let ctx = req.context_id.to_string();
    if let Err(e) = authorize(
        state,
        auth,
        uris::TASK_PERSONA_LOCAL_PROFILE_GET_1_0,
        Some(&ctx),
    )
    .await
    {
        return reject(&doc, e);
    }
    let id = req.profile_id.to_string();
    // Resolves nothing against the pool, because a local profile references
    // nothing there.
    match store(state).get_local_profile(&ctx, &id).await {
        Ok(Some(p)) => {
            audit_persona(
                state,
                "persona.local.profile.get",
                auth,
                Some(&id),
                Some(&ctx),
                None,
            )
            .await;
            // Built member by member rather than serialising the stored
            // `Profile`. The local response schema closes the object to
            // `{profileId, name, entries, version}`, and the stored shape also
            // carries `createdAt`/`updatedAt` — serialising it whole failed
            // response conformance with "Additional properties are not allowed".
            //
            // The narrower shape is right: those timestamps are pool-record
            // metadata, and a context-local profile is not a pool record.
            success_response(
                &doc,
                json!({
                    "profile": {
                        "profileId": p.profile_id,
                        "name": p.name,
                        "entries": p.entries,
                        "version": p.version,
                    }
                }),
            )
        }
        Ok(None) => reject(&doc, AppError::NotFound(format!("local profile {id}"))),
        Err(e) => reject(&doc, e),
    }
}

pub(super) async fn handle_local_profile_list(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: spec::local::profile::list::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let ctx = req.context_id.to_string();
    if let Err(e) = authorize(
        state,
        auth,
        uris::TASK_PERSONA_LOCAL_PROFILE_LIST_1_0,
        Some(&ctx),
    )
    .await
    {
        return reject(&doc, e);
    }
    let profiles = match store(state).list_local_profiles(&ctx).await {
        Ok(p) => p,
        Err(e) => return reject(&doc, e),
    };
    audit_persona(
        state,
        "persona.local.profile.list",
        auth,
        None,
        Some(&ctx),
        None,
    )
    .await;
    success_response(
        &doc,
        json!({
            "profiles": profiles.iter().map(|p| json!({
                "profileId": p.profile_id,
                "name": p.name,
                "entryCount": p.entries.len(),
            })).collect::<Vec<_>>()
        }),
    )
}

pub(super) async fn handle_local_profile_delete(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: spec::local::profile::delete::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let ctx = req.context_id.to_string();
    if let Err(e) = authorize(
        state,
        auth,
        uris::TASK_PERSONA_LOCAL_PROFILE_DELETE_1_0,
        Some(&ctx),
    )
    .await
    {
        return reject(&doc, e);
    }
    let id = req.profile_id.to_string();
    let s = store(state);

    let mut unbound = 0usize;
    if req.unbind {
        // Clear every persona bound to this profile in this context.
        //
        // This used to call `set_local_binding(&ctx, "", None)` — with an
        // *empty* persona DID, which clears the binding of nobody. `--unbind`
        // therefore unbound nothing, and the delete either failed on the
        // still-bound personas or left them pointing at a profile that no
        // longer exists. It went unnoticed because nothing exercised the local
        // family beyond asserting that an invalid entry is refused.
        //
        // Leaves those personas presenting nothing, which is legal and which
        // the holder is told about rather than discovering from the other side.
        let bound = match s.personas_bound_to(&ctx, &id).await {
            Ok(p) => p,
            Err(e) => return reject(&doc, e),
        };
        unbound = bound.len();
        for persona_did in bound {
            if let Err(e) = s.set_local_binding(&ctx, &persona_did, None, None).await {
                return reject(&doc, e);
            }
        }
    }

    let existed = match s.delete_local_profile(&ctx, &id).await {
        Ok(e) => e,
        Err(e) => return reject(&doc, e),
    };
    // The unbind count is the only surviving trace of the silent-unbind bug
    // this handler used to have: `--unbind` cleared nobody, and nothing said
    // so. A row reading "0 persona(s) unbound" against a profile that had
    // bindings is now visible after the fact rather than only reproducible.
    let detail = format!(
        "context-local profile {id} in context {ctx} {}; {unbound} persona(s) unbound",
        if existed { "deleted" } else { "did not exist" },
    );
    audit_persona(
        state,
        "persona.local.profile.delete",
        auth,
        Some(&id),
        Some(&ctx),
        Some(&detail),
    )
    .await;
    success_response(&doc, json!({ "profileId": id, "existed": existed }))
}

pub(super) async fn handle_local_binding_set(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: spec::local::binding::set::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let ctx = req.context_id.to_string();
    // Safely context-callable — unlike binding/set — because both objects it
    // names live below the boundary.
    if let Err(e) = authorize(
        state,
        auth,
        uris::TASK_PERSONA_LOCAL_BINDING_SET_1_0,
        Some(&ctx),
    )
    .await
    {
        return reject(&doc, e);
    }

    let persona = req.persona_did.to_string();
    let profile_id = req.profile_id.as_ref().map(|p| p.to_string());

    // The store refuses an identifier naming a POOL profile. That refusal is
    // the whole distinction from binding/set, and it lives in one place so this
    // handler cannot forget it.
    let version = match store(state)
        .set_local_binding(
            &ctx,
            &persona,
            profile_id.as_deref(),
            req.label.as_ref().map(|l| l.to_string()),
        )
        .await
    {
        Ok(v) => v,
        Err(e) => return reject(&doc, e),
    };

    // No materialised count here, unlike `binding/set`: a context-local entry
    // IS its own value, so there is no pool projection to count — the store
    // takes the profile's inline entries as the claims directly. Saying so is
    // better than reporting a count that would mean something different from
    // the one on the pool task with the same name.
    let detail = format!(
        "persona {persona} in context {ctx} bound to {}, now at version {version}",
        profile_id.as_deref().map_or_else(
            || "unbound".to_string(),
            |p| format!("context-local profile {p}")
        ),
    );
    audit_persona(
        state,
        "persona.local.binding.set",
        auth,
        Some(&persona),
        Some(&ctx),
        Some(&detail),
    )
    .await;
    success_response(
        &doc,
        json!({
            "contextId": ctx,
            "personaDid": persona,
            "profileId": profile_id,
            "version": version,
        }),
    )
}

// ─── Disclosure: preview, then present ───────────────────────────────────

pub(super) async fn handle_disclosure_preview(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: spec::disclosure::preview::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let ctx = req.context_id.to_string();
    if let Err(e) = authorize(
        state,
        auth,
        uris::TASK_PERSONA_DISCLOSURE_PREVIEW_1_0,
        Some(&ctx),
    )
    .await
    {
        return reject(&doc, e);
    }

    let requested: Option<Vec<String>> = if req.requested_claims.is_empty() {
        None
    } else {
        Some(req.requested_claims.iter().map(|c| c.to_string()).collect())
    };

    let preview = match store(state)
        .create_preview(
            &ctx,
            &req.persona_did.to_string(),
            &req.verifier_did.to_string(),
            req.purpose.as_ref().map(|p| p.to_string()).as_deref(),
            requested.as_deref(),
            req.renderer.as_ref().map(|r| r.to_string()).as_deref(),
        )
        .await
    {
        Ok(p) => p,
        Err(e) => return reject(&doc, e),
    };

    // Recorded even though nothing was disclosed: a pattern of previews the
    // holder declined is itself something they may want to see.
    audit_persona(
        state,
        "persona.disclosure.preview",
        auth,
        Some(&preview.preview_id),
        Some(&ctx),
        None,
    )
    .await;

    success_response(
        &doc,
        json!({
            "previewId": preview.preview_id,
            "subject": preview.subject,
            "claims": preview.claims,
            "renderer": { "id": preview.renderer_id, "drops": preview.renderer_drops },
            "expiresAt": preview.expires_at,
        }),
    )
}

pub(super) async fn handle_disclosure_present(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: spec::disclosure::present::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let ctx = req.context_id.to_string();
    if let Err(e) = authorize(
        state,
        auth,
        uris::TASK_PERSONA_DISCLOSURE_PRESENT_1_0,
        Some(&ctx),
    )
    .await
    {
        return reject(&doc, e);
    }

    let durable = req.mint.as_ref().is_some_and(|m| m.durable);
    let preview_id = req.preview_id.to_string();

    // The step-up gate runs BEFORE the preview is taken.
    //
    // `present` consumes the preview as its first act, so a refusal after that
    // point would cost the holder the decision they already made — and the one
    // refusal that is *retryable* is this one. It is retryable precisely
    // because the preview survives it: the holder obtains an approval and
    // presents the same preview again.
    //
    // A peek rather than a read-modify-write: nothing here mutates, and the
    // consume below re-reads under the store's own lock.
    match store(state).peek_preview(&preview_id).await {
        Ok(Some(preview)) => {
            if PersonaStore::requires_step_up(&preview) && preview.approved_at.is_none() {
                let claim_types: Vec<String> =
                    preview.claims.iter().map(|c| c.r#type.clone()).collect();
                return match super::step_up::initiate_disclosure_step_up(
                    state,
                    auth,
                    &preview_id,
                    &preview.verifier_did,
                    preview.purpose.as_deref(),
                    &claim_types,
                )
                .await
                {
                    Ok(details) => step_up_required(&doc, details),
                    Err(reason) => super::helpers::reject_with(&doc, reason),
                };
            }
        }
        // Absent is not this gate's business. The consume below distinguishes
        // unknown from consumed from expired and has the error vocabulary for
        // it; guessing here would give two paths for one answer.
        Ok(None) => {}
        Err(e) => return reject(&doc, e),
    }

    // The store consumes the preview, refuses an expired one, refuses whole on
    // a stale claim, and writes the disclosure record BEFORE returning the
    // artifact — a crash between signing and recording would release data the
    // holder could never afterwards discover they had released.
    let (artifact, record) = match store(state)
        .present(
            &preview_id,
            req.challenge.as_ref().map(|c| c.to_string()).as_deref(),
            durable,
        )
        .await
    {
        Ok(o) => o,
        Err(e) => return reject(&doc, e),
    };

    audit_persona(
        state,
        "persona.disclosure.present",
        auth,
        Some(&record.disclosure_id),
        Some(&ctx),
        None,
    )
    .await;

    // `credentialId` is present only when the holder asked for the disclosure
    // to be minted as a self-issued credential. It is built member-by-member
    // rather than with `json!`, because `json!` renders a `None` as `null` and
    // the schema types the member `string` — the same defect
    // `payload_null_census` guards against on the request side, where an unset
    // optional must be *absent* rather than null. There is no equivalent
    // census for responses; the response-conformance layer catches it at run
    // time instead, which is how this one was found.
    let mut body = json!({
        "disclosureId": record.disclosure_id,
        "artifact": artifact,
        "subject": record.subject,
        "disclosedAt": record.disclosed_at,
    });
    put_opt(
        &mut body,
        "credentialId",
        record.durable_credential_id.clone(),
    );
    success_response(&doc, body)
}

// ─────────────────────────────────────────────────────────────────────────
// Tests
// ─────────────────────────────────────────────────────────────────────────

// ── Facets: the holder's own arrangement of their own identity ──────────────

pub(super) async fn handle_facet_put(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: spec::facet::put::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    if let Err(e) = authorize(state, auth, uris::TASK_PERSONA_FACET_PUT_1_0, None).await {
        return reject(&doc, e);
    }

    let s = store(state);
    // `.map(|u| u.to_string())` rather than `.map(ToString::to_string)`: the
    // generated `Ulid` is a newtype with `Deref` and no `Display`, so the
    // method call auto-derefs to `String` while the function path does not.
    let face_ids: Vec<String> = req.face_ids.iter().map(|u| u.to_string()).collect();
    let attribute_ids: Vec<String> = req.attribute_ids.iter().map(|u| u.to_string()).collect();
    let Some(colour) = colour_of(&req.colour) else {
        return reject_with_code(
            &doc,
            ext(&slug_from_doc(&doc), "unsupportedColour"),
            "this agent does not know that colour",
            Some(json!({ "colour": req.colour.to_string() })),
        );
    };
    let mut facet = vta_persona::new_facet(
        req.name.to_string(),
        colour,
        req.icon.as_ref().map(|i| i.to_string()),
        face_ids,
        attribute_ids,
    );
    // A supplied id addresses an existing record; an absent one keeps the
    // minted ULID, which is what makes a create idempotent under retry only
    // when the producer chose the id itself.
    if let Some(id) = req.facet_id.as_ref() {
        facet.facet_id = id.to_string();
    }
    let facet_id = facet.facet_id.clone();

    // The exclusivity refusal is its own extended code rather than a validation
    // string, because the details are what make it actionable: told only that
    // the write failed, a consumer can do nothing but send the holder off to
    // find where the face already is.
    let clash = match s
        .placement_conflicts(&facet.face_ids, Some(&facet_id))
        .await
    {
        Ok(c) => c,
        Err(e) => return reject(&doc, e),
    };
    if !clash.placed.is_empty() {
        return reject_with_code(
            &doc,
            ext(&slug_from_doc(&doc), "faceAlreadyPlaced"),
            "one or more faces already belong to another facet",
            Some(json!({ "placed": clash.placed })),
        );
    }

    let written = match s
        .put_facet(facet, req.expected_version.map(u64::from))
        .await
    {
        Ok(w) => w,
        Err(e) => return reject(&doc, e),
    };
    // The name is the most revealing member in the record and never reaches an
    // audit line: "Work" discloses nothing and "the divorce" discloses a great
    // deal, and a holder naming a part of their life is not thinking about logs.
    audit_persona(state, "persona.facet.put", auth, None, None, None).await;
    success_response(
        &doc,
        json!({
            "facetId": facet_id,
            "version": written.version,
            "created": written.created,
            "updatedAt": chrono::Utc::now().to_rfc3339(),
        }),
    )
}

pub(super) async fn handle_facet_list(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let _req: spec::facet::list::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    if let Err(e) = authorize(state, auth, uris::TASK_PERSONA_FACET_LIST_1_0, None).await {
        return reject(&doc, e);
    }
    let facets = match store(state).list_facets().await {
        Ok(f) => f,
        Err(e) => return reject(&doc, e),
    };
    audit_persona(state, "persona.facet.list", auth, None, None, None).await;
    // No `nextCursor`: this maintainer returns every facet in one page. The
    // member is absent rather than null, which is what says the listing is
    // complete — a consumer following the cursor sees exactly one page.
    success_response(&doc, json!({ "facets": facets }))
}

pub(super) async fn handle_facet_delete(
    state: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: spec::facet::delete::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    if let Err(e) = authorize(state, auth, uris::TASK_PERSONA_FACET_DELETE_1_0, None).await {
        return reject(&doc, e);
    }
    // Touches no profile and no attribute. There is no cascading form of this
    // call because there is no cascading form of the idea: a facet is an
    // arrangement, not a container.
    let (existed, released) = match store(state)
        .delete_facet(
            &req.facet_id.to_string(),
            req.expected_version.map(u64::from),
        )
        .await
    {
        Ok(r) => r,
        Err(e) => return reject(&doc, e),
    };
    audit_persona(state, "persona.facet.delete", auth, None, None, None).await;
    success_response(
        &doc,
        json!({ "existed": existed, "releasedFaces": released }),
    )
}

/// The wire colour to the store's.
///
/// **Returns `None` for a colour this build does not know, and the caller
/// refuses the document.** The generated enum is `#[non_exhaustive]`, so the
/// compiler cannot make this match exhaustive across the crate boundary and a
/// wildcard arm is mandatory — which means the choice is what the wildcard
/// *does*. Mapping an unknown colour to a default would be a facet silently
/// changing colour: a small thing the holder cannot explain and cannot fix,
/// arriving with no error anywhere. Refusing says which member this build did
/// not understand.
///
/// Unreachable from the wire today — serde rejects an unknown string before the
/// payload parses — but reachable the moment `trust-tasks-rs` is bumped to a
/// version declaring a ninth colour, which is exactly when it should be loud.
fn colour_of(c: &spec::facet::put::v1_0::FacetColour) -> Option<vta_persona::FacetColour> {
    use spec::facet::put::v1_0::FacetColour as W;
    use vta_persona::FacetColour as S;
    Some(match c {
        W::Slate => S::Slate,
        W::Indigo => S::Indigo,
        W::Teal => S::Teal,
        W::Moss => S::Moss,
        W::Sand => S::Sand,
        W::Clay => S::Clay,
        W::Rose => S::Rose,
        W::Plum => S::Plum,
        _ => return None,
    })
}

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

    fn claims(role: Role, contexts: &[&str]) -> AuthClaims {
        AuthClaims {
            role,
            allowed_contexts: contexts.iter().map(|s| (*s).to_string()).collect(),
            ..Default::default()
        }
    }

    /// The census. A task cannot join the family without someone deciding which
    /// side of the boundary it is on.
    #[test]
    fn every_persona_task_declares_a_reach() {
        let classified: std::collections::HashSet<&str> = REACH.iter().map(|(u, _)| *u).collect();
        let missing: Vec<&&str> = uris::ALL_URIS
            .iter()
            .filter(|u| u.starts_with("https://trusttasks.org/spec/persona/"))
            .filter(|u| !classified.contains(*u))
            .collect();
        assert!(
            missing.is_empty(),
            "these persona tasks declare no reach — add them to REACH. When unsure, \
             `Holder` is the conservative answer: it refuses too much rather than \
             disclosing the pool to a context. {missing:#?}"
        );
    }

    #[test]
    fn no_reach_without_a_task() {
        let catalog: std::collections::HashSet<&str> = uris::ALL_URIS.iter().copied().collect();
        let orphans: Vec<&&str> = REACH
            .iter()
            .map(|(u, _)| u)
            .filter(|u| !catalog.contains(*u))
            .collect();
        assert!(
            orphans.is_empty(),
            "reach entries for tasks that do not exist: {orphans:#?}"
        );
    }

    /// The trap, asserted directly. This is the test that would have caught a
    /// guard written as `role == Admin`.
    #[test]
    fn a_context_scoped_admin_is_refused_every_holder_task() {
        let scoped_admin = claims(Role::Admin, &["ctx-work"]);
        for (uri, reach) in REACH {
            if *reach != Reach::Holder {
                continue;
            }
            let err = decide(&scoped_admin, uri, Some("ctx-work"), false).unwrap_err();
            assert!(
                matches!(err, AppError::Forbidden(_)),
                "{uri} admitted an admin scoped to one context — an admin in ctx-work must be \
                 as powerless over the pool as an application in ctx-work"
            );
        }
    }

    #[test]
    fn an_unscoped_holder_reaches_the_pool() {
        let holder = claims(Role::Admin, &[]);
        for (uri, reach) in REACH {
            if *reach == Reach::Holder {
                decide(&holder, uri, None, false).unwrap_or_else(|e| {
                    panic!("{uri} refused an unscoped holder: {e:?}");
                });
            }
        }
    }

    /// The capability's whole reason to exist: a context-scoped admin reaches
    /// the pool **only** where holder authority was granted by name.
    ///
    /// Before it there was one way in — an admin with unrestricted scope — so
    /// managing your own identity from a client meant handing that client every
    /// context on the agent.
    #[test]
    fn a_granted_scoped_admin_reaches_the_pool() {
        let scoped_admin = claims(Role::Admin, &["ctx-work"]);
        for (uri, reach) in REACH {
            if *reach != Reach::Holder {
                continue;
            }
            assert!(
                decide(&scoped_admin, uri, Some("ctx-work"), false).is_err(),
                "{uri} admitted a scoped admin who was granted nothing"
            );
            decide(&scoped_admin, uri, Some("ctx-work"), true)
                .unwrap_or_else(|e| panic!("{uri} refused a granted holder: {e:?}"));
        }
    }

    /// The grant is not a role promotion. It opens the holder-scoped tasks and
    /// changes nothing else — a reader granted it is still a reader everywhere
    /// a role is what decides.
    #[test]
    fn the_grant_does_not_widen_a_context_task() {
        let app = claims(Role::Application, &["ctx-a"]);
        assert!(
            decide(
                &app,
                uris::TASK_PERSONA_BINDING_GET_1_0,
                Some("ctx-b"),
                true
            )
            .is_err(),
            "holder authority must not carry a caller into a context it has no claim to"
        );
    }

    /// An unknown task is refused whatever the caller holds. A grant is not a
    /// reason to guess at a reach.
    #[test]
    fn a_granted_holder_is_still_refused_an_unclassified_task() {
        let holder = claims(Role::Admin, &["ctx-work"]);
        // Built rather than written: the produced-URI census sweeps this file's
        // source text, and a literal that looks like a spec URI is reported as
        // a task shipped without a schema. The neighbouring unknown-task test
        // does the same.
        let unknown = format!("https://trusttasks.org/spec/persona/{}/9.9", "not-a-task");
        assert!(decide(&holder, &unknown, None, true).is_err());
    }

    /// No role reaches the pool by being itself — not even one whose empty
    /// context list looks like an unrestricted admin's.
    ///
    /// "Refused" here means *ungranted*. Holder authority is granted by name
    /// and is deliberately not tied to a role: a personal agent running as
    /// `application` can be given it, by a super admin, on purpose. What this
    /// pins is that none of them arrive holding it.
    #[test]
    fn every_non_admin_role_is_refused_the_pool() {
        // An empty context list means *unrestricted* for Admin and *nothing at
        // all* for every other role. A gate testing emptiness without the role
        // gets one of those backwards, so both halves are asserted.
        for role in [
            Role::Application,
            Role::Reader,
            Role::Initiator,
            Role::Monitor,
        ] {
            let label = format!("{role:?}");
            let c = claims(role, &[]);
            let err = decide(&c, uris::TASK_PERSONA_ATTRIBUTE_LIST_1_0, None, false).unwrap_err();
            assert!(
                matches!(err, AppError::Forbidden(_)),
                "{label} reached the pool"
            );
        }
    }

    #[test]
    fn a_context_task_is_confined_to_its_own_context() {
        let app = claims(Role::Application, &["ctx-a"]);
        decide(
            &app,
            uris::TASK_PERSONA_BINDING_GET_1_0,
            Some("ctx-a"),
            false,
        )
        .expect("own context");
        assert!(
            decide(
                &app,
                uris::TASK_PERSONA_BINDING_GET_1_0,
                Some("ctx-b"),
                false
            )
            .is_err(),
            "a caller scoped to ctx-a must not learn about ctx-b"
        );
    }

    #[test]
    fn an_unknown_task_is_refused_rather_than_defaulted() {
        let app = claims(Role::Application, &["ctx"]);
        // Built rather than written as a literal, deliberately. `produced_census`
        // scans this crate's source for spec-URI literals and asks who publishes
        // each one — correctly, because a produced document with no schema has
        // validation on neither side. This fixture never goes on a wire, so it
        // takes the `format!` shape the census already documents as "not a URI
        // that goes on a wire", rather than being allowlisted as produced.
        let unknown = format!("https://trusttasks.org/spec/persona/{}/9.9", "made-up");
        let err = decide(&app, &unknown, Some("ctx"), false).unwrap_err();
        assert!(matches!(err, AppError::Forbidden(_)));
    }

    #[test]
    fn binding_set_is_holder_only_and_local_binding_set_is_not() {
        // The pair that most invites being collapsed. One crosses the boundary
        // and one does not.
        assert_eq!(
            reach_of(uris::TASK_PERSONA_BINDING_SET_1_0),
            Some(Reach::Holder)
        );
        assert_eq!(
            reach_of(uris::TASK_PERSONA_LOCAL_BINDING_SET_1_0),
            Some(Reach::Context)
        );
    }
}