secretspec 0.20.0

A declarative interface for every secret provider.
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
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
//! Core secrets management functionality

use crate::CallerContext;
use crate::audit::{AuditAction, AuditContext, AuditLogger, AuditOutcome};
use crate::cache::{self, CacheEntryStatus, CacheOwnership};
use crate::compiled_spec::{CompiledSpec, MissingPolicy};
use crate::config::{
    Config, CredentialSource, ExtractFormat, GlobalConfig, NativeAddress, Profile, ProviderAlias,
    RequireReason, Resolved, SecretEncoding, SecretExtract,
};
use crate::error::{Result, SecretSpecError};
use crate::plan::{PlannedSecret, ResolutionPlan, ResolvedCache, Route};
use crate::provider::{
    Address, OwnedAddress, ProducedValuePersistence, Provider as ProviderTrait,
    ProviderCredentials, same_storage_container,
};
use crate::report::{ResolutionReport, ResolutionStatus, SecretResolution};
use crate::resolve::{
    NamedResolution, RESOLVE_SCHEMA_VERSION, ResolveResponse, ResolvedSecret, ResolvedSource,
};
use crate::spec::Spec;
use crate::validation::{ConstraintKind, ConstraintViolation, ValidatedSecrets, ValidationErrors};
use colored::Colorize;
use data_encoding::{
    BASE64, BASE64_NOPAD, BASE64URL, BASE64URL_NOPAD, Encoding, HEXLOWER, HEXLOWER_PERMISSIVE,
};
use secrecy::{ExposeSecret, SecretSlice, SecretString};
#[cfg(unix)]
use signal_hook::consts::signal::{SIGHUP, SIGINT, SIGTERM};
#[cfg(unix)]
use signal_hook::iterator::{Handle as SignalHandle, Signals};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::env;
use std::hash::Hash;
use std::io::{self, IsTerminal, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus};
use std::sync::{Arc, Mutex};
#[cfg(unix)]
use std::thread::JoinHandle;
use std::time::Duration;

#[cfg(unix)]
struct ChildSignalForwarder {
    signals: Option<Signals>,
    handle: SignalHandle,
    thread: Option<JoinHandle<()>>,
}

#[cfg(unix)]
impl ChildSignalForwarder {
    /// Install handlers before spawning the child so a signal cannot slip
    /// through while SecretSpec is becoming the child's supervisor.
    fn prepare() -> io::Result<Self> {
        let signals = Signals::new([SIGTERM, SIGINT, SIGHUP])?;
        let handle = signals.handle();
        Ok(Self {
            signals: Some(signals),
            handle,
            thread: None,
        })
    }

    fn start(&mut self, child_pid: u32) {
        let mut signals = self
            .signals
            .take()
            .expect("signal forwarder can only be started once");
        self.thread = Some(std::thread::spawn(move || {
            for signal in signals.forever() {
                // `kill` is async-signal-safe, and this call runs on an ordinary
                // thread rather than inside the installed signal handler. The
                // child may already have exited, in which case ESRCH is benign.
                unsafe {
                    libc::kill(child_pid as libc::pid_t, signal);
                }
            }
        }));
    }
}

#[cfg(unix)]
impl Drop for ChildSignalForwarder {
    fn drop(&mut self) {
        self.handle.close();
        if let Some(thread) = self.thread.take() {
            let _ = thread.join();
        }
    }
}

fn command_exit_code(status: ExitStatus) -> i32 {
    if let Some(code) = status.code() {
        return code;
    }

    #[cfg(unix)]
    {
        use std::os::unix::process::ExitStatusExt;
        if let Some(signal) = status.signal() {
            return 128 + signal;
        }
    }

    1
}

/// Format the human-facing name and optional description used by status output.
///
/// The name carries the visual emphasis while the description is secondary.
/// When no description is available, omit it entirely instead of printing a
/// repetitive placeholder (and avoid leaving a dangling separator).
fn format_secret_label(name: &str, description: Option<&str>) -> String {
    match description {
        Some(description) => format!(
            "{} {} {}",
            name.cyan().bold(),
            "-".dimmed(),
            description.dimmed()
        ),
        None => name.cyan().bold().to_string(),
    }
}

/// Preserve the established missing-secret error for ordinary required fields,
/// while retaining structured group diagnostics for cross-secret constraints.
fn validation_failure(errors: ValidationErrors) -> SecretSpecError {
    if errors.constraint_violations.is_empty() {
        SecretSpecError::RequiredSecretMissing(errors.missing_required.join(", "))
    } else {
        SecretSpecError::ValidationFailed(Box::new(errors))
    }
}

/// Which declared secrets a single-secret resolution can see.
///
/// A scope narrows what a session resolves, but it is a `check`/`run`/`export`
/// concept: `secretspec get NAME` names one secret and has no `--scope`, so it
/// reads the whole profile. The SDK's [`Secrets::resolve_named`] resolves the
/// session's surface instead, scope included.
#[derive(Clone, Copy)]
enum Surface {
    /// The scope intersection, or the whole profile when no scope is active.
    Scoped,
    /// Every secret the profile declares, whatever the active scope.
    WholeProfile,
}

impl Surface {
    fn names(self, secrets: &Secrets, profile: &str) -> Result<Vec<String>> {
        match self {
            Self::Scoped => secrets.resolve_profile_secret_names(Some(profile)),
            Self::WholeProfile => secrets.profile_secret_names_unscoped(Some(profile)),
        }
    }
}

/// Translates a resolution entry's provenance flags into the value-carrying
/// response's [`ResolvedSource`]. Shared so a batch resolve and a named one
/// cannot disagree about where a value came from.
fn resolved_source(entry: &SecretResolution) -> ResolvedSource {
    if entry.generated {
        ResolvedSource::Generated
    } else if entry.default_applied {
        ResolvedSource::Default
    } else if entry.composed {
        ResolvedSource::Composed
    } else {
        ResolvedSource::Provider
    }
}

/// Stands in for a secret's name in diagnostics when the active scope hides it.
///
/// Every accessed-but-not-visible secret is by construction a dependency of a
/// visible composed secret, so this describes what it is without disclosing
/// which secret it is.
pub(crate) const HIDDEN_SECRET_LABEL: &str = "a hidden composition input";

/// Emits a warning when a provider in a fallback chain fails so the user
/// can see why a particular link was skipped, without aborting the chain.
///
/// `display_uri` must already be credential-free: pass the provider's
/// reconstructed [`uri()`](ProviderTrait::uri) when a provider was built, or
/// [`redact_uri_strict`] of the raw alias when construction itself failed. This
/// function does not redact, so it never strips legitimate attribution (e.g. an
/// `awssm://…?prefix=…`) from a provider's own `uri()`.
///
/// [`redact_uri_strict`]: crate::audit::redact_uri_strict
fn warn_provider_failure(display_uri: &str, secret_name: &str, err: &SecretSpecError) {
    eprintln!(
        "{} provider {} failed for {}: {}; trying next provider in chain",
        "warning:".yellow(),
        display_uri.bold(),
        secret_name.bold(),
        err
    );
}

/// The error for a declared provider credential that could not be found in its
/// source provider. Names the credential, the provider needing it, the exact
/// location searched, and how to fix it.
fn credential_missing_error(name: &str, alias_spec: &str, location: &str) -> SecretSpecError {
    SecretSpecError::ProviderOperationFailed(format!(
        "credential '{name}' for provider '{alias_spec}' was not found in {location}; \
         store it there with `secretspec config provider login {alias_spec}`"
    ))
}

/// An alias's credential entries sorted by semantic name. The one
/// ordering rule, so fetch order, validation-error order, and the login prompt
/// order all agree.
fn sorted_credential_entries(
    credentials: &HashMap<String, CredentialSource>,
) -> Vec<(&String, &CredentialSource)> {
    let mut entries: Vec<(&String, &CredentialSource)> = credentials.iter().collect();
    entries.sort_by_key(|(name, _)| name.as_str());
    entries
}

/// Warn that a cache operation failed. A cache only accelerates a route, so its
/// failures are reported and never turn a successful operation into an error.
fn cache_warning(secret_name: &str, message: impl std::fmt::Display) {
    eprintln!(
        "{} cache failed for {}: {}",
        "warning:".yellow(),
        secret_name.bold(),
        message
    );
}

/// As [`cache_warning`], for a failure on the read path, where the authoritative
/// route still gets its turn.
fn cache_read_warning(secret_name: &str, message: impl std::fmt::Display) {
    cache_warning(
        secret_name,
        format!("{message}; consulting authoritative providers"),
    );
}

/// The secrets of one cache group, for a warning that covers all of them: a
/// cache store that cannot be built or read fails every secret it holds, and
/// naming them once is more useful than one warning per secret.
fn group_names(group: &[&PlannedSecret]) -> String {
    group
        .iter()
        .map(|planned| planned.name.as_str())
        .collect::<Vec<_>>()
        .join(", ")
}

/// What a stored cache entry can do for the read that found it.
enum CachedEntry {
    /// Fresh, and written for this route: serve it.
    Fresh(SecretString),
    /// A SecretSpec entry no read will serve: expired regardless of owner, or
    /// ours but unreadable or written for another route or freshness policy.
    /// Safe to drop.
    Stale,
    /// Not ours to serve *or* to drop: another project's entry, or a value
    /// SecretSpec never wrote.
    Foreign,
}

/// Decide what a stored entry is worth to this read.
///
/// Most cache stores cannot expire a value on their own, so this check *is* the
/// expiry: the envelope records its absolute expiration time. An entry that
/// merely no longer applies (route change, expiry) is a silent miss; one that
/// belongs to someone else is warned about, since it means this route is
/// addressing a store something else writes to.
fn cached_entry(
    planned: &PlannedSecret,
    cache: &ResolvedCache,
    stored: &SecretString,
    project: &str,
    profile: &str,
) -> CachedEntry {
    let route_fingerprint = planned.cache_fingerprint(cache, project, profile);
    match cache::inspect_entry(
        stored,
        project,
        profile,
        &route_fingerprint,
        cache.max_age_secs,
    ) {
        Ok(CacheEntryStatus::Fresh(value)) => CachedEntry::Fresh(value),
        Ok(CacheEntryStatus::Stale) => CachedEntry::Stale,
        Ok(CacheEntryStatus::OursUnreadable) => {
            cache_read_warning(&planned.name, "the cache entry could not be read");
            CachedEntry::Stale
        }
        Ok(CacheEntryStatus::Foreign { project, profile }) => {
            cache_read_warning(
                &planned.name,
                format!("the cache holds {project}/{profile}'s entry at this address"),
            );
            CachedEntry::Foreign
        }
        Ok(CacheEntryStatus::Unrecognized) => {
            cache_read_warning(
                &planned.name,
                "the cache holds a value SecretSpec did not write",
            );
            CachedEntry::Foreign
        }
        Err(error) => {
            cache_read_warning(&planned.name, error);
            CachedEntry::Stale
        }
    }
}

/// Convention-path profile segment for provider credentials. A provider's
/// authentication (an access token, an AppRole id) is a property of the alias,
/// not of any one profile, so a convention-path credential is stored under one
/// fixed segment rather than the active profile. Scoping it by profile would
/// make a credential stored via `config provider login` (which runs under the
/// session profile) invisible when the provider is later used under a different
/// profile, hard-erroring with "credential not found".
const PROVIDER_CREDENTIAL_SCOPE: &str = "_provider";

impl CredentialSource {
    /// Credential-free provider text for prompts and diagnostics.
    pub(crate) fn display_provider(&self) -> String {
        crate::audit::redact_uri_strict(&self.provider)
    }

    /// The store location this source reads and writes: the pinned `ref`, or
    /// the profile-independent convention path for the active project. The
    /// single derivation both [`Secrets::resolve_provider_credentials`] (read)
    /// and [`Secrets::store_provider_credential`] (write) use, so
    /// login-then-resolve round-trips regardless of the profile either runs
    /// under.
    fn address<'a>(&'a self, project: &'a str, name: &'a str) -> Address<'a> {
        match &self.reference {
            Some(reference) => Address::Native(reference),
            None => Address::convention(project, PROVIDER_CREDENTIAL_SCOPE, name),
        }
    }

    /// Human-readable `<provider> at <location>` for prompts and errors,
    /// describing exactly what [`Self::address`] resolves to. The source spec
    /// is redacted: a URI-form source may embed an inline credential
    /// (`onepassword+token://tok@Vault`), and this string reaches stderr and
    /// the `config provider login` output.
    fn location(&self, project: &str, name: &str) -> String {
        let provider = self.display_provider();
        match &self.reference {
            Some(reference) => format!("{provider} at {}", reference.render()),
            None => format!("{provider} at {project}/{PROVIDER_CREDENTIAL_SCOPE}/{name}"),
        }
    }
}

type ProviderCredentialsKey = (String, String);
type ProviderKey = (String, String);
type GroupFetch<'a> = (
    Option<&'a str>,
    Vec<&'a PlannedSecret>,
    Box<dyn ProviderTrait>,
);

struct FallbackReadRequest<'a> {
    planned: &'a PlannedSecret,
    diagnostic_name: &'a str,
    provider_specs: &'a [String],
    project: &'a str,
    profile: &'a str,
}

struct FallbackRead {
    value: Option<SecretString>,
    provider_uri: Option<String>,
    native_address: Option<NativeAddress>,
}

impl FallbackRead {
    fn missing(provider_uri: Option<String>, native_address: Option<NativeAddress>) -> Self {
        Self {
            value: None,
            provider_uri,
            native_address,
        }
    }
}

type FallbackReadResult = Result<FallbackRead>;

struct PreparedImport {
    planned: PlannedSecret,
    target_provider: Box<dyn ProviderTrait>,
    source_address: OwnedAddress,
    target_address: OwnedAddress,
    source_value: Option<SecretString>,
    target_value: Option<SecretString>,
    copied: bool,
    source_deleted: bool,
}

/// One selectable alias whose address mapping diverges from a literal import
/// source even though both providers address the same storage container.
struct ImportAliasDivergence {
    alias: String,
    affected_secrets: Vec<String>,
}

#[derive(Default)]
struct ImportSummary {
    imported: usize,
    already_exists: usize,
    not_found: usize,
    deleted_from_source: usize,
    kept_in_source: usize,
}

impl ImportSummary {
    fn audit_outcome(&self) -> AuditOutcome {
        if self.imported > 0 {
            AuditOutcome::Written
        } else if self.already_exists > 0 {
            AuditOutcome::Found
        } else {
            AuditOutcome::Missing
        }
    }
}

/// Stateful import operation whose methods mirror the mutation boundary:
/// prepare first, copy second, verify third, and only then delete sources.
struct ImportPlan<'a> {
    secrets: &'a Secrets,
    from_provider: &'a str,
    profile: String,
    delete_source: bool,
    source_provider: Option<Arc<dyn ProviderTrait>>,
    source_uri: Option<String>,
    source_display: Option<String>,
    entries: Vec<PreparedImport>,
    read_names: Vec<String>,
    summary: ImportSummary,
}

impl<'a> ImportPlan<'a> {
    fn new(
        secrets: &'a Secrets,
        from_provider: &'a str,
        profile: String,
        delete_source: bool,
    ) -> Self {
        Self {
            secrets,
            from_provider,
            profile,
            delete_source,
            source_provider: None,
            source_uri: None,
            source_display: None,
            entries: Vec::new(),
            read_names: Vec::new(),
            summary: ImportSummary::default(),
        }
    }

    fn run(&mut self) -> Result<()> {
        self.prepare_source()?;
        self.prepare_entries()?;
        self.validate_target_collisions()?;
        if self.delete_source {
            self.validate_cleanup_collisions()?;
        }
        self.copy_missing_targets()?;
        if self.delete_source {
            self.verify_copied_targets()?;
            self.delete_matching_sources()?;
        }
        self.report_entries();
        Ok(())
    }

    fn prepare_source(&mut self) -> Result<()> {
        let source = self
            .secrets
            .build_provider(self.from_provider.to_string(), Some(&self.profile))?;
        let provider_uri = source.uri();
        self.source_uri = Some(provider_uri.clone());
        self.source_display = Some(
            if self
                .secrets
                .lookup_provider_alias_entry(self.from_provider)
                .is_some()
            {
                format!("provider alias '{}' ({provider_uri})", self.from_provider)
            } else {
                provider_uri.clone()
            },
        );

        if self.delete_source
            && !crate::provider::spec_provider_deletes(
                &self
                    .secrets
                    .resolve_provider_spec(self.from_provider.to_string()),
            )
        {
            return Err(SecretSpecError::ProviderOperationFailed(format!(
                "provider '{}' does not support deleting secrets and cannot be used with import --delete-source",
                source.name()
            )));
        }

        eprintln!(
            "Importing secrets from {} (profile: {})...\n",
            self.source_display
                .as_deref()
                .expect("source display is set with the provider URI")
                .blue(),
            self.profile.cyan()
        );
        self.source_provider = Some(Arc::from(source));
        Ok(())
    }

    fn prepare_entries(&mut self) -> Result<()> {
        let source_provider = Arc::clone(
            self.source_provider
                .as_ref()
                .expect("the source provider is prepared first"),
        );
        let import_names = self
            .secrets
            .profile_secret_names_unscoped(Some(&self.profile))?;
        let mut planned_imports = Vec::new();

        for name in import_names {
            let planned = self
                .secrets
                .plan_secret(&name, &self.profile, None)?
                .expect("Secret should exist since we're iterating over it");
            if planned.route.is_none() {
                continue;
            }
            if planned.extract().is_some() {
                return Err(SecretSpecError::ExtractedSecretReadOnly(
                    planned.name.clone(),
                ));
            }
            planned_imports.push(planned);
        }

        let divergences = self.secrets.literal_import_alias_divergences(
            self.from_provider,
            source_provider.as_ref(),
            &planned_imports,
            &self.profile,
        );
        Secrets::warn_literal_import_alias_divergences(
            self.source_uri
                .as_deref()
                .expect("the source URI is prepared first"),
            &divergences,
        );

        for planned in planned_imports {
            let route = planned
                .route
                .as_ref()
                .expect("planned imports are provider-backed");

            self.read_names.push(planned.name.clone());
            let source_address = self.secrets.address_for_spec(
                &planned,
                Some(self.from_provider),
                &self.secrets.config.project.name,
                &self.profile,
            )?;
            let target_address = self.secrets.address_for_spec(
                &planned,
                route.group_key(),
                &self.secrets.config.project.name,
                &self.profile,
            )?;
            let target_provider = self
                .secrets
                .write_provider_for_route(route, Some(&self.profile))?;

            if self.delete_source
                && source_provider.same_entries(
                    source_address.as_address(),
                    target_provider.as_ref(),
                    target_address.as_address(),
                )?
            {
                return Err(SecretSpecError::ProviderOperationFailed(format!(
                    "refusing to delete '{}' from the import source because source and destination resolve to the same provider entry ({})",
                    planned.name,
                    source_provider.uri()
                )));
            }

            let source_value = source_provider.get(source_address.as_address())?;
            let target_value = target_provider.get(target_address.as_address())?;
            if let Some(value) = &source_value {
                Secrets::validate_import_value(&planned, &planned.name, value)?;
                if target_value.is_none() {
                    target_provider.check_writable(target_address.as_address())?;
                }
                let target_will_match = target_value
                    .as_ref()
                    .is_none_or(|existing| existing.expose_secret() == value.expose_secret());
                if self.delete_source && target_will_match {
                    source_provider.check_deletable(source_address.as_address())?;
                }
            }

            self.entries.push(PreparedImport {
                planned,
                target_provider,
                source_address,
                target_address,
                source_value,
                target_value,
                copied: false,
                source_deleted: false,
            });
        }
        Ok(())
    }

    fn validate_target_collisions(&self) -> Result<()> {
        for left_index in 0..self.entries.len() {
            let left = &self.entries[left_index];
            for right in &self.entries[left_index + 1..] {
                if left.target_provider.same_entries(
                    left.target_address.as_address(),
                    right.target_provider.as_ref(),
                    right.target_address.as_address(),
                )? {
                    return Err(SecretSpecError::ProviderOperationFailed(format!(
                        "refusing to import '{}' and '{}' because they resolve to the same destination provider entry ({})",
                        left.planned.name,
                        right.planned.name,
                        left.target_provider.uri()
                    )));
                }
            }
        }
        Ok(())
    }

    fn validate_cleanup_collisions(&self) -> Result<()> {
        let source_provider = self
            .source_provider
            .as_ref()
            .expect("the source provider is prepared first");
        for (source_index, source) in self.entries.iter().enumerate() {
            let Some(source_value) = &source.source_value else {
                continue;
            };
            let source_will_be_deleted = source.target_value.as_ref().is_none_or(|target_value| {
                source_value.expose_secret() == target_value.expose_secret()
            });
            if !source_will_be_deleted {
                continue;
            }

            for (target_index, target) in self.entries.iter().enumerate() {
                if source_index == target_index {
                    continue;
                }
                if source_provider.same_entries(
                    source.source_address.as_address(),
                    target.target_provider.as_ref(),
                    target.target_address.as_address(),
                )? {
                    return Err(SecretSpecError::ProviderOperationFailed(format!(
                        "refusing to delete '{}' from the import source because it resolves to the destination provider entry for '{}' ({})",
                        source.planned.name,
                        target.planned.name,
                        target.target_provider.uri()
                    )));
                }
            }
        }
        Ok(())
    }

    fn copy_missing_targets(&mut self) -> Result<()> {
        for entry in &mut self.entries {
            let (Some(value), None) = (&entry.source_value, &entry.target_value) else {
                continue;
            };
            let route = entry
                .planned
                .route
                .as_ref()
                .expect("prepared imports are provider-backed");
            let set_result = entry
                .target_provider
                .set(entry.target_address.as_address(), value);
            self.secrets.audit_write_result(
                &set_result,
                &entry.planned.name,
                &self.profile,
                Some(entry.target_provider.uri()),
                entry.target_address.native(),
                None,
            );
            set_result?;
            self.secrets
                .sync_cache_after_write(&entry.planned, route, &self.profile, value);
            entry.copied = true;
            self.summary.imported += 1;
        }
        Ok(())
    }

    fn verify_copied_targets(&mut self) -> Result<()> {
        for entry in self.entries.iter_mut().filter(|entry| entry.copied) {
            let expected = entry
                .source_value
                .as_ref()
                .expect("copied entries have source values");
            let stored = entry
                .target_provider
                .get(entry.target_address.as_address())?
                .ok_or_else(|| {
                    SecretSpecError::ProviderOperationFailed(format!(
                        "destination verification failed for '{}'; the source value was retained",
                        entry.planned.name
                    ))
                })?;
            if stored.expose_secret() != expected.expose_secret() {
                return Err(SecretSpecError::ProviderOperationFailed(format!(
                    "destination verification failed for '{}'; the source value was retained",
                    entry.planned.name
                )));
            }
            Secrets::validate_import_value(&entry.planned, &entry.planned.name, &stored)?;
            entry.target_value = Some(stored);
        }
        Ok(())
    }

    fn delete_matching_sources(&mut self) -> Result<()> {
        let source_provider = Arc::clone(
            self.source_provider
                .as_ref()
                .expect("the source provider is prepared first"),
        );
        for entry in &mut self.entries {
            let (Some(source), Some(target)) = (&entry.source_value, &entry.target_value) else {
                continue;
            };
            if source.expose_secret() != target.expose_secret() {
                continue;
            }
            let delete_result = source_provider.delete(entry.source_address.as_address());
            self.secrets.audit_delete_result(
                &delete_result,
                &entry.planned.name,
                &self.profile,
                Some(source_provider.uri()),
                entry.source_address.native(),
            );
            entry.source_deleted = delete_result?;
            self.summary.deleted_from_source += usize::from(entry.source_deleted);
        }
        Ok(())
    }

    fn report_entries(&mut self) {
        for entry in &self.entries {
            let name = &entry.planned.name;
            let label = format_secret_label(name, entry.planned.config().description.as_deref());
            let target_name = entry.target_provider.name().blue();

            if entry.copied {
                if self.delete_source && entry.source_deleted {
                    eprintln!(
                        "{} {} (→ {}; deleted from source)",
                        "✓".green(),
                        label,
                        target_name
                    );
                } else {
                    eprintln!("{} {} (→ {})", "✓".green(), label, target_name);
                }
                continue;
            }

            match (&entry.source_value, &entry.target_value) {
                (Some(source), Some(target)) => {
                    self.summary.already_exists += 1;
                    if self.delete_source && source.expose_secret() != target.expose_secret() {
                        self.summary.kept_in_source += 1;
                        eprintln!(
                            "{} {} {} (→ {}; source retained)",
                            "â—‹".yellow(),
                            label,
                            "(target value differs)".yellow(),
                            target_name
                        );
                    } else if self.delete_source && entry.source_deleted {
                        eprintln!(
                            "{} {} {} (→ {}; deleted from source)",
                            "✓".green(),
                            label,
                            "(already exists in target)".yellow(),
                            target_name
                        );
                    } else {
                        eprintln!(
                            "{} {} {} (→ {})",
                            "â—‹".yellow(),
                            label,
                            "(already exists in target)".yellow(),
                            target_name
                        );
                    }
                }
                (None, Some(_)) => {
                    self.summary.already_exists += 1;
                    eprintln!(
                        "{} {} {} (→ {})",
                        "â—‹".blue(),
                        label,
                        "(already in target, not in source)".blue(),
                        target_name
                    );
                }
                (None, None) => {
                    self.summary.not_found += 1;
                    eprintln!("{} {} {}", "✗".red(), label, "(not found in source)".red());
                }
                (Some(_), None) => {
                    unreachable!("a prepared missing target was copied or returned an error")
                }
            }
        }
    }
}

type SingleFlightSlot<V> = Arc<Mutex<Option<V>>>;

/// A retry-on-error, single-flight value cache.
///
/// Population for one key runs while holding that key's slot, so concurrent
/// callers share the first successful value. Different keys initialize
/// independently because the outer map lock is released before initialization.
/// Failed attempts remove their slot instead of being memoized, allowing a
/// later call to retry after an external dependency becomes available.
struct RetryingOnceMap<K, V> {
    entries: Mutex<HashMap<K, SingleFlightSlot<V>>>,
}

impl<K, V> Default for RetryingOnceMap<K, V> {
    fn default() -> Self {
        Self {
            entries: Mutex::new(HashMap::new()),
        }
    }
}

impl<K, V> RetryingOnceMap<K, V>
where
    K: Clone + Eq + Hash,
    V: Clone,
{
    fn get_or_try_init<E, F>(&self, key: K, initialize: F) -> std::result::Result<V, E>
    where
        F: FnOnce() -> std::result::Result<V, E>,
    {
        let slot = {
            let mut entries = self.entries.lock().unwrap();
            Arc::clone(
                entries
                    .entry(key.clone())
                    .or_insert_with(|| Arc::new(Mutex::new(None))),
            )
        };

        let mut cached = slot.lock().unwrap();
        if let Some(value) = cached.as_ref() {
            return Ok(value.clone());
        }

        match initialize() {
            Ok(value) => {
                *cached = Some(value.clone());
                Ok(value)
            }
            Err(error) => {
                drop(cached);
                let mut entries = self.entries.lock().unwrap();
                if entries
                    .get(&key)
                    .is_some_and(|current| Arc::ptr_eq(current, &slot))
                {
                    entries.remove(&key);
                }
                Err(error)
            }
        }
    }

    #[cfg(any(feature = "cli", test))]
    fn clear(&self) {
        self.entries.lock().unwrap().clear();
    }
}

/// Memoized provider credentials with single-flight population per key.
///
/// The outer mutex protects only the key-to-slot map. Resolution runs while
/// holding the selected slot, so callers for the same alias/profile wait for
/// its first fetch while unrelated keys can populate concurrently.
#[derive(Default)]
struct ProviderCredentialsCache {
    entries: RetryingOnceMap<ProviderCredentialsKey, ProviderCredentials>,
}

impl ProviderCredentialsCache {
    fn get_or_try_init<F>(
        &self,
        key: ProviderCredentialsKey,
        resolve: F,
    ) -> Result<ProviderCredentials>
    where
        F: FnOnce() -> Result<ProviderCredentials>,
    {
        self.entries.get_or_try_init(key, resolve)
    }

    #[cfg(any(feature = "cli", test))]
    fn clear(&self) {
        self.entries.clear();
    }
}

/// Operation-scoped built providers with single-flight construction per key.
///
/// A provider memoizes connection state to serve a batch, but a fallback chain
/// is walked per secret, so rebuilding there discards it every time: with
/// `akv?auth=cli` each rebuild re-spawns the Azure CLI. Locking mirrors
/// [`ProviderCredentialsCache`]: the outer mutex guards only the key-to-slot
/// map, so callers for one spec wait on its first construction while unrelated
/// specs build concurrently. A fresh cache is created for every resolution so
/// provider-local snapshots cannot leak into a later operation.
#[derive(Default)]
struct ProviderCache {
    entries: RetryingOnceMap<ProviderKey, Arc<dyn ProviderTrait>>,
}

impl ProviderCache {
    fn get_or_try_init<F>(&self, key: ProviderKey, build: F) -> Result<Arc<dyn ProviderTrait>>
    where
        F: FnOnce() -> Result<Box<dyn ProviderTrait>>,
    {
        self.entries.get_or_try_init(key, || build().map(Arc::from))
    }
}

/// Emits a warning when the primary provider for a batch fetch fails (either
/// during construction or during `get_many`); affected secrets will still be
/// retried via their per-secret fallback chain below.
///
/// Like [`warn_provider_failure`], `display_uri` must already be credential-free
/// (a provider's reconstructed `uri()`, or [`redact_uri_strict`] of a raw alias).
/// `None` renders as `<default>` (no per-secret provider was configured).
///
/// [`redact_uri_strict`]: crate::audit::redact_uri_strict
fn warn_primary_provider_failure(display_uri: Option<&str>, err: &SecretSpecError) {
    eprintln!(
        "{} primary provider {} failed: {}; will try fallback chain for affected secrets",
        "warning:".yellow(),
        display_uri.unwrap_or("<default>").bold(),
        err
    );
}

/// Whether a resolution pass may produce side effects and persist secrets.
///
/// A resolution pass always queries providers to learn what is present, but the
/// two value-free entry points ([`Secrets::report`], [`Secrets::resolve_without_values`])
/// must not change anything as a side effect of reading. This flag gates the two
/// mutating steps of a pass so those entry points can share the exact same
/// resolution logic without inheriting its side effects.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Materialize {
    /// Full pass: mint-and-store a missing generatable secret and write each
    /// `as_path` secret to a temp file. Backs `validate()`/`resolve()`/`check`.
    Values,
    /// Full pass for `run`: the same materialization as `Values`, plus secure
    /// controlling-terminal input for declarations with `prompt = true`.
    Run,
    /// Value-free pass: never write a generated secret back to a provider and
    /// never persist a secret to disk. A generatable-but-absent secret is
    /// reported as it *would* resolve, without minting it — unless it is
    /// required and its store would keep the minted value, in which case the
    /// value is simply not provisioned yet and is reported missing. Backs
    /// `report()` and `resolve_without_values()`.
    None,
}

impl Materialize {
    fn values(self) -> bool {
        self != Self::None
    }

    fn prompts(self) -> bool {
        self == Self::Run
    }
}

type ExecutionResult = Result<std::result::Result<ValidatedSecrets, ValidationErrors>>;

/// Mutable state for one resolution pass.
///
/// The phase methods keep provider I/O, value decisions, composition, and
/// validation ordered without forcing [`Secrets::execute_plan`] to carry every
/// intermediate map and output collection in one method.
struct ResolutionExecution<'secrets, 'plan, 'filter, 'addresses> {
    manager: &'secrets Secrets,
    plan: &'plan ResolutionPlan,
    materialize: Materialize,
    output_filter: Option<&'filter HashSet<String>>,
    read_addresses: Option<&'addresses mut HashMap<String, NativeAddress>>,
    values: HashMap<String, SecretString>,
    missing_required: Vec<String>,
    missing_optional: Vec<String>,
    with_defaults: Vec<(String, String)>,
    temp_files: Vec<tempfile::NamedTempFile>,
    resolution: Vec<SecretResolution>,
    group_uris: HashMap<Option<&'plan str>, String>,
    fetched_values: HashMap<String, SecretString>,
    failed_primary_uris: HashMap<Option<&'plan str>, SecretSpecError>,
    cached_uris: HashMap<String, String>,
    fallback_results: HashMap<String, FallbackReadResult>,
}

impl<'secrets, 'plan, 'filter, 'addresses>
    ResolutionExecution<'secrets, 'plan, 'filter, 'addresses>
{
    fn new(
        manager: &'secrets Secrets,
        plan: &'plan ResolutionPlan,
        materialize: Materialize,
        output_filter: Option<&'filter HashSet<String>>,
        read_addresses: Option<&'addresses mut HashMap<String, NativeAddress>>,
    ) -> Self {
        Self {
            manager,
            plan,
            materialize,
            output_filter,
            read_addresses,
            values: HashMap::new(),
            missing_required: Vec::new(),
            missing_optional: Vec::new(),
            with_defaults: Vec::new(),
            temp_files: Vec::new(),
            resolution: Vec::new(),
            group_uris: HashMap::new(),
            fetched_values: HashMap::new(),
            failed_primary_uris: HashMap::new(),
            cached_uris: HashMap::new(),
            fallback_results: HashMap::new(),
        }
    }

    fn run(mut self) -> ExecutionResult {
        if self.plan.secrets.is_empty() {
            return Ok(Ok(ValidatedSecrets {
                resolved: Resolved::new(HashMap::new(), String::new(), self.plan.profile.clone()),
                missing_optional: Vec::new(),
                with_defaults: Vec::new(),
                resolution: Vec::new(),
                temp_files: Vec::new(),
            }));
        }

        self.read_cached_values();
        self.fetch_primary_values()?;
        self.fetch_fallback_values();
        self.resolve_provider_backed_values()?;
        self.resolve_composed_values()?;
        self.finish()
    }

    fn read_cached_values(&mut self) {
        for (name, (value, uri)) in self
            .manager
            .read_cached_group(self.plan, &self.plan.profile)
        {
            self.cached_uris.insert(name.clone(), uri);
            self.fetched_values.insert(name, value);
        }
    }

    fn fetch_primary_values(&mut self) -> Result<()> {
        let plan = self.plan;
        let project = self.manager.config.project.name.as_str();
        let profile = plan.profile.as_str();
        let mut group_fetches: Vec<GroupFetch<'plan>> = Vec::new();

        // Construction stays on this thread so every single-store ref can be
        // checked before any provider is contacted.
        for (provider_uri, group) in plan.groups() {
            let group: Vec<&PlannedSecret> = group
                .into_iter()
                .filter(|planned| !self.cached_uris.contains_key(&planned.name))
                .collect();
            if group.is_empty() {
                continue;
            }
            match self
                .manager
                .get_route_provider(provider_uri, Some(&plan.profile))
            {
                Ok(provider) => {
                    self.group_uris.insert(provider_uri, provider.uri());
                    group_fetches.push((provider_uri, group, provider));
                }
                Err(error) => {
                    let shown = provider_uri.map(crate::audit::redact_uri_strict);
                    warn_primary_provider_failure(shown.as_deref(), &error);
                    self.failed_primary_uris.insert(provider_uri, error);
                }
            }
        }

        for (provider_spec, group, provider) in &group_fetches {
            self.manager.check_single_store_ref_coords(
                *provider_spec,
                group,
                provider.as_ref(),
                project,
                profile,
            )?;
        }

        fn fetch_group<'a>(
            manager: &Secrets,
            (provider_uri, group, provider): GroupFetch<'a>,
            project: &str,
            profile: &str,
        ) -> (Option<&'a str>, Result<HashMap<String, SecretString>>) {
            let result = manager.fetch_group(&*provider, provider_uri, &group, project, profile);
            (provider_uri, result)
        }

        let fetch_results: Vec<(Option<&'plan str>, Result<_>)> = if group_fetches.len() <= 1 {
            group_fetches
                .into_iter()
                .map(|group| fetch_group(self.manager, group, project, profile))
                .collect()
        } else {
            std::thread::scope(|scope| {
                let handles: Vec<_> = group_fetches
                    .into_iter()
                    .map(|group| scope.spawn(|| fetch_group(self.manager, group, project, profile)))
                    .collect();
                handles
                    .into_iter()
                    .map(|handle| handle.join().expect("group fetch thread panicked"))
                    .collect()
            })
        };

        for (provider_uri, result) in fetch_results {
            match result {
                Ok(batch_results) => self.fetched_values.extend(batch_results),
                Err(error) => {
                    let display_uri = self.group_uris.get(&provider_uri).map(String::as_str);
                    warn_primary_provider_failure(display_uri, &error);
                    self.failed_primary_uris.insert(provider_uri, error);
                }
            }
        }
        Ok(())
    }

    fn fetch_fallback_values(&mut self) {
        let project = self.manager.config.project.name.as_str();
        let profile = self.plan.profile.as_str();
        let provider_cache = ProviderCache::default();
        let pending_fallbacks: Vec<&PlannedSecret> = self
            .plan
            .secrets
            .iter()
            .filter(|planned| {
                !self.fetched_values.contains_key(&planned.name)
                    && planned
                        .route
                        .as_ref()
                        .and_then(Route::fallback_specs)
                        .is_some()
            })
            .collect();

        self.fallback_results = crate::provider::map_concurrently(
            &pending_fallbacks,
            crate::provider::get_each_concurrency(),
            |planned| {
                let route = planned
                    .route
                    .as_ref()
                    .expect("pending fallback has a provider route");
                let fallback = route
                    .fallback_specs()
                    .expect("pending fallback has fallback specs");
                let result = self.manager.read_fallback_chain(
                    &provider_cache,
                    FallbackReadRequest {
                        planned,
                        diagnostic_name: Secrets::diagnostic_secret_name(
                            &planned.name,
                            self.output_filter,
                        ),
                        provider_specs: fallback,
                        project,
                        profile,
                    },
                );
                (planned.name.clone(), result)
            },
        )
        .into_iter()
        .collect();
    }

    fn resolve_provider_backed_values(&mut self) -> Result<()> {
        let manager = self.manager;
        let plan = self.plan;
        let materialize = self.materialize;
        let output_filter = self.output_filter;
        let project = manager.config.project.name.as_str();
        let profile = plan.profile.as_str();

        for planned in &plan.secrets {
            let Some(route) = &planned.route else {
                continue;
            };
            let name = &planned.name;
            let required = planned.required();
            let diagnostic_name = Secrets::diagnostic_secret_name(name, output_filter);
            let primary_uri = route.group_key();

            let status;
            let mut source_provider = None;
            let mut default_applied = false;
            let mut generated = false;

            match self.fetched_values.remove(name.as_str()) {
                Some(value) => {
                    let was_cached = self.cached_uris.contains_key(name);
                    source_provider = self
                        .cached_uris
                        .remove(name)
                        .or_else(|| self.group_uris.get(&primary_uri).cloned());
                    if !was_cached
                        && let Some(addresses) = self.read_addresses.as_deref_mut()
                        && let Ok(address) =
                            manager.address_for_spec(planned, primary_uri, project, profile)
                        && let Some(native) = address.native()
                    {
                        addresses.insert(name.clone(), native.clone());
                    }
                    if !was_cached && materialize.values() {
                        manager.write_cached_secret(planned, route, profile, &value);
                    }
                    if materialize.values() {
                        manager.insert_resolved(
                            &mut self.values,
                            &mut self.temp_files,
                            planned,
                            diagnostic_name,
                            value,
                            ResolvedRepresentation::Stored,
                        )?;
                    }
                    status = ResolutionStatus::Resolved;
                }
                None => {
                    let primary_failed = self.failed_primary_uris.contains_key(&primary_uri);

                    if let Some(addresses) = self.read_addresses.as_deref_mut()
                        && let Ok(address) =
                            manager.address_for_spec(planned, primary_uri, project, profile)
                        && let Some(native) = address.native()
                    {
                        addresses.insert(name.clone(), native.clone());
                    }

                    let fallback_result = match route.fallback_specs() {
                        Some(_) => {
                            let resolved = self
                                .fallback_results
                                .remove(name)
                                .expect("primary miss with fallback was prefetched")?;
                            if resolved.value.is_none() && primary_failed {
                                let error = self
                                    .failed_primary_uris
                                    .remove(&primary_uri)
                                    .expect("primary_failed implies entry present");
                                return Err(error);
                            }
                            resolved
                        }
                        None if primary_failed => {
                            let error = self
                                .failed_primary_uris
                                .remove(&primary_uri)
                                .expect("primary_failed implies entry present");
                            return Err(error);
                        }
                        None => FallbackRead::missing(None, None),
                    };
                    let FallbackRead {
                        value: fallback_value,
                        provider_uri: fallback_uri,
                        native_address: fallback_reference,
                    } = fallback_result;

                    if let Some(addresses) = self.read_addresses.as_deref_mut()
                        && let Some(reference) = fallback_reference
                    {
                        addresses.insert(name.clone(), reference);
                    }
                    if let Some(value) = fallback_value {
                        source_provider = fallback_uri;
                        if materialize.values() {
                            manager.write_cached_secret(planned, route, profile, &value);
                            manager.insert_resolved(
                                &mut self.values,
                                &mut self.temp_files,
                                planned,
                                diagnostic_name,
                                value,
                                ResolvedRepresentation::Stored,
                            )?;
                        }
                        status = ResolutionStatus::Resolved;
                    } else {
                        match planned.secret.missing {
                            MissingPolicy::Prompt => {
                                if materialize.prompts()
                                    && output_filter.is_none_or(|filter| filter.contains(name))
                                {
                                    let prompted = manager.try_prompt_secret(planned, profile)?;
                                    manager.insert_resolved(
                                        &mut self.values,
                                        &mut self.temp_files,
                                        planned,
                                        diagnostic_name,
                                        prompted,
                                        ResolvedRepresentation::Logical,
                                    )?;
                                    status = ResolutionStatus::Resolved;
                                } else if required {
                                    self.missing_required.push(name.clone());
                                    status = ResolutionStatus::MissingRequired;
                                } else {
                                    self.missing_optional.push(name.clone());
                                    status = ResolutionStatus::MissingOptional;
                                }
                            }
                            MissingPolicy::Generate => {
                                if materialize.values() {
                                    generated = true;
                                    let generated_value = manager
                                        .try_generate_secret(planned, profile)?
                                        .expect("compiled Generate policy has a generator");
                                    manager.insert_resolved(
                                        &mut self.values,
                                        &mut self.temp_files,
                                        planned,
                                        diagnostic_name,
                                        generated_value,
                                        ResolvedRepresentation::Logical,
                                    )?;
                                    status = ResolutionStatus::Resolved;
                                } else if required
                                    && manager.generated_value_is_stored(planned, profile)
                                {
                                    self.missing_required.push(name.clone());
                                    status = ResolutionStatus::MissingRequired;
                                } else {
                                    generated = true;
                                    status = ResolutionStatus::Resolved;
                                }
                            }
                            MissingPolicy::UseDefault => {
                                let default_value = planned
                                    .config()
                                    .default
                                    .as_ref()
                                    .expect("compiled UseDefault policy has a default");
                                default_applied = true;
                                if materialize.values() {
                                    manager.insert_resolved(
                                        &mut self.values,
                                        &mut self.temp_files,
                                        planned,
                                        diagnostic_name,
                                        SecretString::new(default_value.clone().into()),
                                        ResolvedRepresentation::Logical,
                                    )?;
                                    self.with_defaults
                                        .push((name.clone(), default_value.clone()));
                                }
                                status = ResolutionStatus::Resolved;
                            }
                            MissingPolicy::Error => {
                                self.missing_required.push(name.clone());
                                status = ResolutionStatus::MissingRequired;
                            }
                            MissingPolicy::Omit => {
                                self.missing_optional.push(name.clone());
                                status = ResolutionStatus::MissingOptional;
                            }
                        }
                    }
                }
            }

            self.resolution.push(SecretResolution {
                name: name.clone(),
                status,
                required,
                source_provider,
                default_applied,
                generated,
                composed: false,
                as_path: planned.as_path(),
            });
        }
        Ok(())
    }

    fn resolve_composed_values(&mut self) -> Result<()> {
        fn composition_order<'a>(
            planned: &'a PlannedSecret,
            composed: &HashMap<&str, &'a PlannedSecret>,
            visited: &mut HashSet<&'a str>,
            ordered: &mut Vec<&'a PlannedSecret>,
        ) {
            if !visited.insert(planned.name.as_str()) {
                return;
            }
            let template = planned
                .composition()
                .expect("only composed nodes are ordered");
            for dependency in template.dependencies() {
                if let Some(dependency) = composed.get(dependency.as_str()) {
                    composition_order(dependency, composed, visited, ordered);
                }
            }
            ordered.push(planned);
        }

        let composed: HashMap<&str, &PlannedSecret> = self
            .plan
            .secrets
            .iter()
            .filter(|secret| secret.is_composed())
            .map(|secret| (secret.name.as_str(), secret))
            .collect();
        let mut ordered = Vec::with_capacity(composed.len());
        let mut visited = HashSet::new();
        for planned in self
            .plan
            .secrets
            .iter()
            .filter(|secret| secret.is_composed())
        {
            composition_order(planned, &composed, &mut visited, &mut ordered);
        }

        if ordered.is_empty() {
            return Ok(());
        }

        let mut statuses: HashMap<String, ResolutionStatus> = self
            .resolution
            .iter()
            .map(|entry| (entry.name.clone(), entry.status.clone()))
            .collect();
        for planned in ordered {
            let template = planned
                .composition()
                .expect("only composed nodes are ordered");
            let dependencies_resolved = template
                .dependencies()
                .iter()
                .all(|dependency| statuses.get(dependency) == Some(&ResolutionStatus::Resolved));
            let status = if dependencies_resolved {
                if self.materialize.values() {
                    let rendered = template
                        .render(|dependency| {
                            self.values
                                .get(dependency)
                                .map(|value| value.expose_secret())
                        })
                        .map_err(SecretSpecError::CompositionFailed)?;
                    self.manager.insert_resolved(
                        &mut self.values,
                        &mut self.temp_files,
                        planned,
                        Secrets::diagnostic_secret_name(&planned.name, self.output_filter),
                        SecretString::new(rendered.into()),
                        ResolvedRepresentation::Logical,
                    )?;
                }
                ResolutionStatus::Resolved
            } else {
                match planned.secret.missing {
                    MissingPolicy::Error => {
                        self.missing_required.push(planned.name.clone());
                        ResolutionStatus::MissingRequired
                    }
                    MissingPolicy::Omit => {
                        self.missing_optional.push(planned.name.clone());
                        ResolutionStatus::MissingOptional
                    }
                    MissingPolicy::Generate | MissingPolicy::UseDefault | MissingPolicy::Prompt => {
                        unreachable!("composed source conflicts are rejected at load time")
                    }
                }
            };

            statuses.insert(planned.name.clone(), status.clone());
            self.resolution.push(SecretResolution {
                name: planned.name.clone(),
                status,
                required: planned.required(),
                source_provider: None,
                default_applied: false,
                generated: false,
                composed: true,
                as_path: planned.as_path(),
            });
        }
        Ok(())
    }

    fn apply_output_filter(&mut self) {
        let Some(filter) = self.output_filter else {
            return;
        };
        self.values.retain(|name, _| filter.contains(name));
        self.resolution.retain(|entry| filter.contains(&entry.name));
        self.missing_required.retain(|name| filter.contains(name));
        self.missing_optional.retain(|name| filter.contains(name));
        self.with_defaults.retain(|(name, _)| filter.contains(name));
    }

    fn constraint_violations(&self) -> Vec<ConstraintViolation> {
        let resolved_names: HashSet<&str> = self
            .resolution
            .iter()
            .filter(|entry| entry.status == ResolutionStatus::Resolved)
            .map(|entry| entry.name.as_str())
            .collect();
        let compiled_profile = self
            .manager
            .manifest
            .profile(&self.plan.profile)
            .expect("profile is validated before execution");
        let constraints = (self.output_filter.is_some()
            || self.plan.secrets.len() == compiled_profile.secrets.len())
        .then_some(&compiled_profile.constraints);
        let Some(constraints) = constraints else {
            return Vec::new();
        };

        let visible_members = |members: &Vec<String>| -> Vec<String> {
            match self.output_filter {
                Some(filter) => members
                    .iter()
                    .filter(|name| filter.contains(name.as_str()))
                    .cloned()
                    .collect(),
                None => members.clone(),
            }
        };
        let mut violations = Vec::new();
        for group in &constraints.at_least_one {
            let members = visible_members(&group.members);
            if members.is_empty() {
                continue;
            }
            let present: Vec<String> = members
                .iter()
                .filter(|name| resolved_names.contains(name.as_str()))
                .cloned()
                .collect();
            if present.is_empty() {
                violations.push(ConstraintViolation {
                    kind: ConstraintKind::AtLeastOne,
                    group: group.name.clone(),
                    secrets: members,
                    present,
                });
            }
        }
        for group in &constraints.exactly_one {
            let members = visible_members(&group.members);
            if members.is_empty() {
                continue;
            }
            let present: Vec<String> = members
                .iter()
                .filter(|name| resolved_names.contains(name.as_str()))
                .cloned()
                .collect();
            if present.len() != 1 {
                violations.push(ConstraintViolation {
                    kind: ConstraintKind::ExactlyOne,
                    group: group.name.clone(),
                    secrets: members,
                    present,
                });
            }
        }
        violations
    }

    fn finish(mut self) -> ExecutionResult {
        let report_provider_uri = self.manager.validation_report_provider_uri(
            self.plan.override_uri.as_deref(),
            self.plan
                .secrets
                .iter()
                .filter_map(|secret| secret.route.as_ref())
                .map(|route| route.primary()),
            Some(&self.plan.profile),
        )?;

        self.apply_output_filter();
        let constraint_violations = self.constraint_violations();
        if !self.missing_required.is_empty() || !constraint_violations.is_empty() {
            let mut errors = ValidationErrors::new(
                self.missing_required,
                self.missing_optional,
                self.with_defaults,
                report_provider_uri,
                self.plan.profile.clone(),
            );
            errors.resolution = self.resolution;
            errors.constraint_violations = constraint_violations;
            Ok(Err(errors))
        } else {
            Ok(Ok(ValidatedSecrets {
                resolved: Resolved::new(
                    self.values,
                    report_provider_uri,
                    self.plan.profile.clone(),
                ),
                missing_optional: self.missing_optional,
                with_defaults: self.with_defaults,
                resolution: self.resolution,
                temp_files: self.temp_files,
            }))
        }
    }
}

/// A logical value in the shape exposed to callers. Inline values remain
/// secret strings; file-shaped values carry their owner so the caller decides
/// whether cleanup follows the resolved-value lifetime or the path is kept.
enum PreparedSecret {
    Inline(SecretString),
    File {
        owner: tempfile::NamedTempFile,
        path: String,
    },
}

/// Whether a resolved string came from a storage boundary and is eligible for
/// decoding, or is already the logical value produced inside SecretSpec.
#[derive(Clone, Copy)]
enum ResolvedRepresentation {
    Stored,
    Logical,
}

/// Walks up from the current directory looking for `secretspec.toml`.
pub(crate) fn find_config_file() -> Result<PathBuf> {
    find_config_file_from(std::env::current_dir()?)
}

/// Walks up from `start` looking for `secretspec.toml`, returning the path to the
/// nearest one. Factored out of [`find_config_file`] so the walk can be tested
/// against an explicit starting directory without mutating the process-global
/// current directory (which is racy under `cargo test`).
fn find_config_file_from(start: PathBuf) -> Result<PathBuf> {
    let mut dir = start;
    loop {
        let candidate = dir.join("secretspec.toml");
        if candidate.exists() {
            return Ok(candidate);
        }
        if !dir.pop() {
            return Err(SecretSpecError::NoManifest);
        }
    }
}

/// The main entry point for the secretspec library
///
/// `Secrets` manages the loading, validation, and retrieval of secrets
/// based on the project and global configuration files.
///
/// # Example
///
/// ```no_run
/// use secretspec::Secrets;
///
/// // Load configuration and validate secrets
/// let mut spec = Secrets::load().unwrap();
/// spec.check(false).unwrap();
/// ```
pub struct Secrets {
    /// The project-specific configuration
    config: Config,
    /// Effective profile semantics compiled once from `config` and shared by
    /// planning, runtime resolution, and inventory surfaces.
    pub(crate) manifest: CompiledSpec,
    /// Directory containing the loaded `secretspec.toml`. Relative filesystem
    /// paths held by file-backed providers (e.g. `dotenv`) are resolved against
    /// this rather than the process's current working directory, so running
    /// from a subdirectory with `--file ../secretspec.toml` still finds the
    /// `.env` files next to the config.
    pub(crate) config_dir: PathBuf,
    /// Optional global user configuration
    global_config: Option<GlobalConfig>,
    /// The provider to use (if set via builder)
    provider: Option<String>,
    /// The profile to use (if set via builder)
    profile: Option<String>,
    /// The active secret scope (if set via builder/`--scope`/`SECRETSPEC_SCOPE`).
    /// `None` resolves the complete profile; a scope narrows resolution to the
    /// intersection of the merged profile and the scope's secret list.
    scope: Option<String>,
    /// When `true`, [`Self::resolve_scope_name`] does not fall back to the
    /// ambient `SECRETSPEC_SCOPE` environment variable. Set by the typed loaders
    /// that `secretspec-derive` generates: they expect the full generated shape,
    /// so an environment scope narrowing the resolved set below that shape would
    /// surface as a spurious `RequiredSecretMissing`. An explicitly set scope
    /// (builder/`set_scope`) is still honored — only the ambient fallback is cut.
    ignore_ambient_scope: bool,
    /// Reason for this session's secret access, forwarded to providers that
    /// support audit logging (set via [`Secrets::with_reason`]).
    reason: Option<String>,
    /// Software integration that invoked SecretSpec. This is audit context, not
    /// a user-supplied reason, and never satisfies `require_reason`.
    caller: Option<CallerContext>,
    /// Project policy (`[project].require_reason` in secretspec.toml) controlling
    /// when secret access requires an explicit reason.
    require_reason: RequireReason,
    /// Audit logger, if auditing is enabled (user-global `[audit]` config). `None`
    /// disables auditing. Built once per `Secrets` so all events share a session id.
    audit: Option<AuditLogger>,
    /// Provider credentials memoized per (profile, raw provider spec), so N
    /// secrets routed at one alias fetch its credentials from the source provider
    /// once per session, not once per provider build. The stored *values* are
    /// profile-independent (see `PROVIDER_CREDENTIAL_SCOPE`); the profile is kept
    /// in the key only so each profile's operations audit their own credential
    /// read. Cleared by [`Secrets::store_provider_credential`] so a freshly
    /// stored credential is re-read.
    provider_credentials_cache: ProviderCredentialsCache,
    /// Optional CLI-owned observer for writes that are about to prompt for or
    /// consume a value. Library and SDK instances leave this unset, so planning
    /// a write never produces unsolicited output outside the CLI.
    write_target_reporter: Option<WriteTargetReporter>,
    /// Test seam for deterministic run-prompt coverage. Production CLI
    /// instances leave this unset and use the controlling terminal.
    prompt_reader: Option<PromptReader>,
}

/// Credential-free description of one provider write, computed after routing
/// and writability checks but before the value is read or prompted for.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct WriteTarget {
    pub name: String,
    pub provider_uri: String,
    pub profile: String,
    pub target: String,
}

type WriteTargetReporter = Arc<dyn Fn(&WriteTarget) + Send + Sync>;
type PromptReader = Arc<dyn Fn(&str, &str) -> Result<SecretString> + Send + Sync>;

/// secretspec's own opt-in for marking the current process as an agent. Lets any
/// harness that the `detect-coding-agent` crate does not recognize identify itself.
const AGENT_OPT_IN_ENV: &str = "SECRETSPEC_AGENT";

/// A UTF-8 snapshot of the process environment, dropping any non-UTF-8 entries.
///
/// `detect-coding-agent`'s `detect()`/`is_agent()` capture the environment with
/// `std::env::vars()`, which **panics** on any non-UTF-8 variable — and env vars
/// are arbitrary byte strings on Unix. Building the map ourselves with `vars_os`
/// and silently skipping non-UTF-8 entries lets detection run safely: the
/// agent-signal variables the crate looks for are always plain ASCII, so a stray
/// non-UTF-8 var cannot abort an otherwise-fine secretspec command. Feeds the
/// crate's `*_with_env` variants, which take the map instead of reading the
/// environment directly.
fn utf8_env() -> std::collections::HashMap<String, String> {
    utf8_env_from(std::env::vars_os())
}

/// [`utf8_env`] over an explicit iterator, so the non-UTF-8 filtering can be tested
/// without mutating the process environment (which is global and racy under `cargo
/// test`).
fn utf8_env_from<I>(vars: I) -> std::collections::HashMap<String, String>
where
    I: IntoIterator<Item = (std::ffi::OsString, std::ffi::OsString)>,
{
    vars.into_iter()
        .filter_map(|(k, v)| Some((k.into_string().ok()?, v.into_string().ok()?)))
        .collect()
}

/// The child-process environment for `run`: the parent environment plus the
/// resolved secrets.
///
/// Kept as `OsString` end to end and captured with `vars_os` (never `vars`,
/// whose iterator panics on non-UTF-8 entries — env vars are arbitrary bytes on
/// Unix). Unlike agent detection ([`utf8_env`]), which may safely *drop*
/// non-UTF-8 entries, `run` must stay transparent: the child inherits every
/// parent variable untouched, UTF-8 or not. Secrets overwrite same-named vars.
fn child_env_from<I, S>(
    vars: I,
    secrets: S,
) -> std::collections::HashMap<std::ffi::OsString, std::ffi::OsString>
where
    I: IntoIterator<Item = (std::ffi::OsString, std::ffi::OsString)>,
    S: IntoIterator<Item = (String, String)>,
{
    let mut env: std::collections::HashMap<std::ffi::OsString, std::ffi::OsString> =
        vars.into_iter().collect();
    env.extend(secrets.into_iter().map(|(k, v)| (k.into(), v.into())));
    env
}

/// The id of the detected coding agent (e.g. `"claude-code"`), or `None`.
///
/// Routes through [`detect_with_env`](detect_coding_agent::detect_with_env) with a
/// [`utf8_env`] snapshot so a non-UTF-8 environment cannot panic the process.
pub(crate) fn detect_agent_id() -> Option<&'static str> {
    detect_coding_agent::detect_with_env(utf8_env()).map(|a| a.id)
}

/// Whether secretspec is currently running as an AI coding agent.
///
/// Detection of the known agents (Claude Code, Cursor, Codex, Gemini CLI, Copilot,
/// ...) is delegated to the [`detect-coding-agent`] crate, which maintains the
/// per-tool signal list. This covers autonomous and hybrid environments (not
/// human-driven interactive editors), mirroring the crate's own `is_agent()`.
/// `SECRETSPEC_AGENT` is an additional explicit opt-in for harnesses the crate does
/// not yet recognize. Detection goes through [`utf8_env`] so a non-UTF-8
/// environment variable cannot panic the process.
///
/// [`detect-coding-agent`]: https://crates.io/crates/detect-coding-agent
pub(crate) fn running_as_agent() -> bool {
    std::env::var_os(AGENT_OPT_IN_ENV).is_some_and(|v| !v.is_empty())
        || detect_coding_agent::detect_with_env(utf8_env())
            .is_some_and(|a| a.is_agent() || a.is_hybrid())
}

/// Pure policy decision: does `mode` require a reason given whether the caller is
/// an agent? Kept separate from [`running_as_agent`] so it is deterministically testable.
fn policy_requires_reason(mode: RequireReason, is_agent: bool) -> bool {
    match mode {
        RequireReason::Never => false,
        RequireReason::Always => true,
        RequireReason::Agents => is_agent,
    }
}

/// Environment variable holding the session reason for SDK/library callers. This is
/// the counterpart to the CLI `--reason` flag: it lets any caller — including code
/// generated by `secretspec-derive`, which never calls [`Secrets::with_reason`] —
/// satisfy the `require_reason` policy and supply an audit reason without code
/// changes, mirroring how `SECRETSPEC_PROVIDER`/`SECRETSPEC_PROFILE` are honored.
const REASON_ENV: &str = "SECRETSPEC_REASON";

/// Trims `value` and returns it owned when non-empty, or `None` when the input
/// is blank (empty or whitespace-only). The single choke point for the "blank
/// means unset" rule: a stray empty `--provider`/`--profile`, a whitespace-only
/// override, or a padded env var (a trailing newline from `$(cat file)` is the
/// common CI case) neither shadows the configured fallback chain nor is stored
/// verbatim — the value that survives is always trimmed.
pub(crate) fn non_blank(value: &str) -> Option<String> {
    let trimmed = value.trim();
    (!trimmed.is_empty()).then(|| trimmed.to_string())
}

/// Normalizes a session reason: trims surrounding whitespace and treats a blank
/// result as "no reason given". Applied to every reason source so the policy gate
/// and the audit log agree on what counts as a real reason (a blank `--reason ""`
/// or `SECRETSPEC_REASON=` must not satisfy the policy). Kept pure for testability.
///
/// Shared with providers (e.g. Proton Pass) so the gate and the audit reason agree
/// on what counts as a real reason.
pub(crate) fn normalize_reason(reason: &str) -> Option<String> {
    non_blank(reason)
}

/// Resolves the session reason from the `SECRETSPEC_REASON` environment variable,
/// normalized via [`normalize_reason`]. An explicit [`Secrets::with_reason`] takes
/// precedence over this.
fn env_reason() -> Option<String> {
    std::env::var(REASON_ENV)
        .ok()
        .as_deref()
        .and_then(normalize_reason)
}

/// The variable, per-call fields of an audit event. Session-constant fields
/// (project, session reason, whether auditing is enabled) are filled by
/// [`Secrets::record`], so call sites specify only what differs and default the
/// rest with `..Default::default()`.
#[derive(Default)]
struct AuditFields<'a> {
    /// The single secret involved (`get`/`set`); `None` for bulk actions.
    key: Option<&'a str>,
    /// The secrets involved in a bulk action (`check`/`run`/`import`).
    keys: &'a [String],
    /// For `run`, the executed program (argv[0] only).
    command: Option<&'a str>,
    /// Redacted provider URI the access is attributed to.
    provider_uri: Option<String>,
    /// The secret's native `ref` coordinates, when the access resolved them;
    /// rendered for the log by [`Secrets::record`].
    reference: Option<&'a NativeAddress>,
    /// Stable error-variant token when the outcome is an error.
    error_kind: Option<&'a str>,
}

impl Secrets {
    /// Creates a new `Secrets` instance with the given configurations
    ///
    /// # Arguments
    ///
    /// * `config` - The project configuration
    /// * `global_config` - Optional global user configuration
    /// * `provider` - Optional provider to use
    /// * `profile` - Optional profile to use
    ///
    /// # Returns
    ///
    /// A new `Secrets` instance
    #[cfg(test)]
    pub(crate) fn new(
        config: Config,
        global_config: Option<GlobalConfig>,
        provider: Option<String>,
        profile: Option<String>,
    ) -> Self {
        let manifest = CompiledSpec::compile(&config);
        Self {
            config,
            manifest,
            config_dir: PathBuf::from("."),
            global_config,
            provider,
            profile,
            scope: None,
            ignore_ambient_scope: false,
            reason: None,
            caller: None,
            require_reason: RequireReason::Never,
            audit: None,
            provider_credentials_cache: ProviderCredentialsCache::default(),
            write_target_reporter: None,
            prompt_reader: None,
        }
    }

    /// Loads a `Secrets` by walking up from the current directory to find `secretspec.toml`
    ///
    /// This method searches the current directory and all parent directories for
    /// a `secretspec.toml` file, similar to how `cargo` and `git` find their configs.
    ///
    /// # Returns
    ///
    /// A loaded `Secrets` instance
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - No `secretspec.toml` file is found in the current or any parent directory
    /// - Configuration files are invalid
    /// - The project revision is unsupported
    ///
    /// # Example
    ///
    /// ```no_run
    /// use secretspec::Secrets;
    ///
    /// let mut spec = Secrets::load().unwrap();
    /// spec.set_provider("keyring");
    /// spec.check(false).unwrap();
    /// ```
    pub fn load() -> Result<Self> {
        let config_path = find_config_file()?;
        Self::load_from(&config_path)
    }

    /// Loads a `Secrets` from an explicit config file path
    ///
    /// Use this when the path to `secretspec.toml` is known, e.g. via the `--file` flag.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the `secretspec.toml` file
    pub fn load_from(path: &Path) -> Result<Self> {
        let spec = Spec::try_from(path)?;
        Self::from_spec(spec)
    }

    /// Creates a resolver from a Rust-built or parsed [`Spec`].
    ///
    /// A spec loaded from a path with [`Spec::try_from`] retains the manifest's
    /// directory for relative provider paths. Rust-built specs and TOML strings
    /// use the process's current working directory. [`Self::from_spec_at`]
    /// explicitly overrides either behavior.
    ///
    /// Available starting with SecretSpec 0.20.
    pub fn from_spec(spec: Spec) -> Result<Self> {
        let base_dir = spec.base_dir.clone().unwrap_or_else(|| PathBuf::from("."));
        Self::from_spec_at(spec, base_dir)
    }

    /// Creates a resolver from a [`Spec`] with an explicit logical base directory.
    ///
    /// `base_dir` resolves relative paths held by providers, just as
    /// [`Self::load_from`] uses the directory containing `secretspec.toml`. The
    /// path is not canonicalized and does not need to exist at construction
    /// time.
    ///
    /// Available starting with SecretSpec 0.20.
    pub fn from_spec_at(spec: Spec, base_dir: impl Into<PathBuf>) -> Result<Self> {
        // A Spec already owns the exact compiled view produced by validation,
        // so file and Rust frontends both arrive here without recompiling.
        let (config, manifest) = spec.into_parts();
        let global_config = GlobalConfig::load()?;
        // Auditing is a per-machine concern configured in the user-global config
        // (`[audit]` in ~/.config/secretspec/config.toml), not the project. It is
        // on by default when unconfigured.
        let audit = AuditLogger::from_config(
            &global_config
                .as_ref()
                .and_then(|g| g.audit.clone())
                .unwrap_or_default(),
        );
        Ok(Self {
            require_reason: config.project.require_reason.unwrap_or_default(),
            config,
            manifest,
            config_dir: base_dir.into(),
            global_config,
            provider: None,
            profile: None,
            scope: None,
            ignore_ambient_scope: false,
            reason: env_reason(),
            caller: None,
            audit,
            provider_credentials_cache: ProviderCredentialsCache::default(),
            write_target_reporter: None,
            prompt_reader: None,
        })
    }

    pub(crate) fn load_config(config: Config, config_dir: PathBuf) -> Result<Self> {
        let spec = Spec::from_config_document(config)?;
        Self::from_spec_at(spec, config_dir)
    }

    /// Installs the CLI's write-target observer. The provider and core library
    /// only compute credential-free target metadata; presentation stays with
    /// the caller that explicitly opts in.
    #[cfg(any(feature = "cli", test))]
    pub(crate) fn set_write_target_reporter(
        &mut self,
        reporter: impl Fn(&WriteTarget) + Send + Sync + 'static,
    ) {
        self.write_target_reporter = Some(Arc::new(reporter));
    }

    #[cfg(test)]
    pub(crate) fn set_prompt_reader(
        &mut self,
        reader: impl Fn(&str, &str) -> Result<SecretString> + Send + Sync + 'static,
    ) {
        self.prompt_reader = Some(Arc::new(reader));
    }

    /// Sets the provider to use for secret operations
    ///
    /// This overrides the provider from global configuration.
    /// Blank input (empty or whitespace-only) is ignored, so a blank
    /// `--provider` or `SECRETSPEC_PROVIDER` cannot shadow the configured
    /// fallback chain. CI templates and workflow `env:` maps routinely
    /// materialize unset values as empty strings. A padded-but-nonblank value
    /// is trimmed before it is stored, so a trailing newline from `$(cat file)`
    /// does not select a nonexistent provider (see [`non_blank`]).
    ///
    /// # Arguments
    ///
    /// * `provider` - The provider name or URI (e.g., "keyring", "dotenv:/path/to/.env")
    ///
    /// # Example
    ///
    /// ```no_run
    /// use secretspec::Secrets;
    ///
    /// let mut spec = Secrets::load().unwrap();
    /// spec.set_provider("dotenv:.env.production");
    /// spec.check(false).unwrap();
    /// ```
    pub fn set_provider(&mut self, provider: impl Into<String>) {
        if let Some(provider) = non_blank(&provider.into()) {
            self.provider = Some(provider);
        }
    }

    /// Sets the profile to use for secret operations
    ///
    /// This overrides the profile from global configuration.
    /// Blank input is ignored, matching [`Secrets::set_provider`].
    ///
    /// # Arguments
    ///
    /// * `profile` - The profile name (e.g., "development", "staging", "production")
    ///
    /// # Example
    ///
    /// ```no_run
    /// use secretspec::Secrets;
    ///
    /// let mut spec = Secrets::load().unwrap();
    /// spec.set_profile("production");
    /// spec.check(false).unwrap();
    /// ```
    pub fn set_profile(&mut self, profile: impl Into<String>) {
        if let Some(profile) = non_blank(&profile.into()) {
            self.profile = Some(profile);
        }
    }

    /// Sets the active secret scope for resolution.
    ///
    /// A scope narrows every subsequent resolution (`check`, `run`, `export`, and
    /// the SDK resolve paths) to the intersection of the selected profile and the
    /// scope's declared secrets, so a single service loads only what it needs.
    /// Leaving the scope unset resolves the complete profile, exactly as before
    /// scopes existed.
    ///
    /// Blank input is ignored, matching [`Secrets::set_provider`]/[`Secrets::set_profile`].
    /// Note that ignoring it is *not* on its own enough to stop a blank
    /// `--scope` from narrowing: with no scope stored, resolution falls back to
    /// an ambient `SECRETSPEC_SCOPE`. A caller that means "resolve the whole
    /// profile" must also call [`Self::set_ignore_ambient_scope`], as the CLI
    /// does for a blank flag.
    ///
    /// # Arguments
    ///
    /// * `scope` - The scope name as declared under `[scopes]` in `secretspec.toml`
    pub fn set_scope(&mut self, scope: impl Into<String>) {
        if let Some(scope) = non_blank(&scope.into()) {
            self.scope = Some(scope);
        }
    }

    /// Suppresses the ambient `SECRETSPEC_SCOPE` fallback in scope resolution.
    ///
    /// This says "the scope has been decided by this caller; do not consult the
    /// environment". Two callers mean it: the typed loaders generated by
    /// `secretspec-derive`, so an environment scope cannot narrow a typed load
    /// below the full generated struct shape it expects, and the CLI on a blank
    /// `--scope`, so an explicit opt-out clears an inherited scope instead of
    /// deferring to it. An explicitly set scope ([`Self::set_scope`]) is still
    /// honored — only the environment fallback is cut. Untyped SDK and FFI
    /// resolution that sets no scope keeps honoring `SECRETSPEC_SCOPE`.
    pub fn set_ignore_ambient_scope(&mut self, ignore: bool) {
        self.ignore_ambient_scope = ignore;
    }

    /// Sets a human-readable reason for this session's secret access.
    ///
    /// The reason is forwarded to providers that support audit logging. For
    /// example, the Proton Pass provider passes it to `pass-cli` agent sessions,
    /// which require a reason for every audited item operation; providers that do
    /// not support auditing ignore it.
    ///
    /// Takes precedence over the `SECRETSPEC_REASON` environment variable, which
    /// [`Secrets::load`]/[`Secrets::load_from`] already resolve. A blank or
    /// whitespace-only reason is ignored (it neither satisfies the `require_reason`
    /// policy nor overrides a reason already resolved from the environment).
    ///
    /// # Example
    ///
    /// ```no_run
    /// use secretspec::Secrets;
    ///
    /// let spec = Secrets::load().unwrap().with_reason("deploy web frontend");
    /// spec.check(false).unwrap();
    /// ```
    pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
        if let Some(reason) = normalize_reason(&reason.into()) {
            self.reason = Some(reason);
        }
        self
    }

    /// Records the software integration that invoked SecretSpec.
    ///
    /// Caller context describes *what* is requesting secrets, while
    /// [`Secrets::with_reason`] records the user-supplied explanation of *why*.
    /// It is included in audit events and forwarded to providers, but it never
    /// satisfies the project's `require_reason` policy.
    ///
    /// Blank names are ignored. Optional fields are trimmed and blank values are
    /// dropped. The context is caller-asserted metadata rather than an
    /// authenticated identity; it must not contain credentials or secret values.
    ///
    /// Available since SecretSpec 0.20.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use secretspec::{CallerContext, Secrets};
    ///
    /// let spec = Secrets::load().unwrap().with_caller(
    ///     CallerContext::new("git")
    ///         .with_operation("credential_get")
    ///         .with_resource("github.com"),
    /// );
    /// spec.check(false).unwrap();
    /// ```
    pub fn with_caller(mut self, caller: CallerContext) -> Self {
        if let Some(caller) = caller.normalized() {
            self.caller = Some(caller);
        }
        self
    }

    /// Sets a session reason only when none is already in effect.
    ///
    /// This is the "supply a fallback" form of [`Secrets::with_reason`]: an
    /// embedding application can describe *itself* ("nightly export job") without
    /// overwriting the more specific reason its own caller passed through
    /// `SECRETSPEC_REASON`. Calling `with_reason` for that purpose would silently
    /// discard the user's reason and put the wrapper's boilerplate in every audit
    /// log entry instead.
    ///
    /// The reason is normalized like every other source, so a blank or
    /// whitespace-only argument still leaves the session without a reason rather
    /// than storing an empty one. Precedence is therefore: an explicit
    /// [`Secrets::with_reason`], then `SECRETSPEC_REASON`, then this default.
    /// A default reason still counts as a reason for policy purposes. An
    /// integration that only wants to identify itself should use
    /// [`Secrets::with_caller`] instead.
    ///
    /// Available since SecretSpec 0.19.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use secretspec::Secrets;
    ///
    /// // Uses SECRETSPEC_REASON when the caller set one, "nightly export" otherwise.
    /// let spec = Secrets::load().unwrap().with_default_reason("nightly export");
    /// spec.check(false).unwrap();
    /// ```
    pub fn with_default_reason(mut self, reason: impl Into<String>) -> Self {
        if self.reason.is_none() {
            self.reason = normalize_reason(&reason.into());
        }
        self
    }

    /// Enforces the project's `require_reason` policy.
    ///
    /// Depending on `[project].require_reason` in `secretspec.toml` (`"agents"` by
    /// default, or a boolean), secret access may require an explicit reason
    /// (`--reason`, `SECRETSPEC_REASON`, or [`Secrets::with_reason`]). Because this
    /// is enforced by the tool itself, the policy applies uniformly to every
    /// caller — humans, CI, and any AI agent — and none can bypass it. Called at
    /// the start of each public secret-accessing operation.
    fn ensure_reason(&self) -> Result<()> {
        // A supplied reason satisfies every policy, so short-circuit before any agent
        // detection (this also makes the redundant call cheap when check()/get()
        // delegate to validate()).
        if self.reason.is_some() {
            return Ok(());
        }
        // running_as_agent() probes the environment/process; only the Agents policy
        // consults it, so skip that work for the Never/Always policies.
        let is_agent = self.require_reason == RequireReason::Agents && running_as_agent();
        if policy_requires_reason(self.require_reason, is_agent) {
            return Err(SecretSpecError::ReasonRequired);
        }
        Ok(())
    }

    /// Builds a provider from a generic leaf spec (name or URI).
    ///
    /// Provider construction converges in [`Self::build_provider_with_credentials`]
    /// so the reason set via [`Secrets::with_reason`] reaches every instance.
    ///
    /// `profile` is the profile the caller resolved for the surrounding
    /// operation (`None` falls back to the session profile): an alias's
    /// convention-path credentials live at `{project}/{profile}/{credential}`,
    /// so the provider must be built for the same profile its secrets are
    /// addressed under.
    pub(crate) fn build_provider(
        &self,
        spec: String,
        profile: Option<&str>,
    ) -> Result<Box<dyn ProviderTrait>> {
        self.build_provider_for_use(spec, profile, false)
    }

    /// Builds the authoritative leaf selected by a planned route.
    ///
    /// The 0.19+ inline cache form is both a complete route and the alias for
    /// its one authoritative URI. Only planned route execution may unwrap that
    /// alias into the leaf; generic provider inputs (for example an import
    /// source) must still reject cached aliases as routes rather than silently
    /// bypassing their cache policy.
    fn build_route_provider(
        &self,
        spec: String,
        profile: Option<&str>,
    ) -> Result<Box<dyn ProviderTrait>> {
        self.build_provider_for_use(spec, profile, true)
    }

    fn build_provider_for_use(
        &self,
        spec: String,
        profile: Option<&str>,
        allow_inline_cached: bool,
    ) -> Result<Box<dyn ProviderTrait>> {
        // Reject a route where a leaf is required before resolving any of the
        // alias's credentials. Besides producing the route-specific error
        // consistently, this keeps an invalid import/source use from touching
        // credential stores merely to discover that it cannot build the alias.
        self.ensure_provider_use_allowed(&spec, allow_inline_cached)?;

        // When `spec` names an alias with a `credentials` map, resolve those
        // values from their source providers and hand them to the built provider.
        // Memoized per (profile, spec) so rebuilding a provider (per-secret chain walks,
        // interactive prompting) does not refetch the same credentials from
        // the source store, while a profile switch on this instance does not
        // reuse the other profile's credentials.
        let profile = self.resolve_profile_name(profile);
        let key = (profile.clone(), spec.clone());
        let credentials = self
            .provider_credentials_cache
            .get_or_try_init(key, || self.resolve_provider_credentials(&spec, &profile))?;
        self.build_provider_with_credentials(
            &spec,
            credentials,
            allow_inline_cached,
            Some(&profile),
        )
    }

    /// [`Self::build_provider`], memoized within one resolution so repeated
    /// builds of one spec share one provider and the connection state it holds.
    /// The caller owns the cache to prevent provider-local snapshots and session
    /// metadata from surviving into a later operation.
    fn shared_provider(
        &self,
        cache: &ProviderCache,
        spec: &str,
        profile: Option<&str>,
        allow_inline_cached: bool,
    ) -> Result<Arc<dyn ProviderTrait>> {
        let key = (self.resolve_profile_name(profile), spec.to_string());
        cache.get_or_try_init(key, || {
            self.build_provider_for_use(spec.to_string(), profile, allow_inline_cached)
        })
    }
    /// Rejects cached routes in construction contexts that require one leaf.
    /// Planned execution may unwrap only the inline form into its authoritative
    /// URI; a fallback-based cached alias remains a complete multi-store route.
    fn ensure_provider_use_allowed(&self, spec: &str, allow_inline_cached: bool) -> Result<()> {
        if self
            .cached_alias(spec)
            .is_some_and(|alias| !allow_inline_cached || alias.authoritative_uri().is_none())
        {
            return Err(SecretSpecError::ProviderOperationFailed(format!(
                "cached provider alias '{spec}' is a complete route; select it through a \
                 secret's providers list, the default provider, or --provider"
            )));
        }
        Ok(())
    }

    /// Builds a leaf provider without resolving its declared credentials: for a
    /// credential source, so credential-source chains are at most one hop and
    /// cannot recurse, and for cache remediation, where the credential source
    /// itself may be what failed.
    ///
    /// Deliberately hands the provider no profile: a credential belongs to the
    /// alias rather than to any one profile ([`PROVIDER_CREDENTIAL_SCOPE`]), and
    /// [`CredentialSource::address`] must round-trip whichever profile stores and
    /// reads it. A `ref`-addressed credential would otherwise resolve in the
    /// storing profile's Infisical environment and read from the reading
    /// profile's, so a credential stored under `prod` would be missing under
    /// `dev`. Such a ref keeps needing an explicit `?env=`, which is
    /// profile-independent by construction.
    ///
    /// Cache remediation is the other caller and needs no profile either: it
    /// addresses through [`Self::cache_address`], which is a convention address
    /// carrying its own.
    pub(crate) fn build_source_provider(&self, spec: &str) -> Result<Box<dyn ProviderTrait>> {
        self.build_provider_with_credentials(spec, ProviderCredentials::new(), false, None)
    }

    /// The shared construction body behind generic, routed, and credential
    /// source providers: alias expansion, error enrichment, and the
    /// base-dir/reason/caller hooks live only here, so those paths cannot drift.
    fn build_provider_with_credentials(
        &self,
        spec: &str,
        credentials: ProviderCredentials,
        allow_inline_cached: bool,
        profile: Option<&str>,
    ) -> Result<Box<dyn ProviderTrait>> {
        // `build_source_provider` calls this body directly, so retain the guard
        // here as well as before credential initialization in the generic path.
        self.ensure_provider_use_allowed(spec, allow_inline_cached)?;
        // Resolve provider aliases here, at the single construction chokepoint, so
        // every caller that hands us a user-supplied spec gets alias expansion for
        // free and no new entry point can forget it. Resolution is a no-op on an
        // already-resolved URI (a `scheme://...` string is never an alias key), so
        // callers that pass pre-resolved URIs (the per-secret chain) are unaffected.
        let resolved = self.resolve_provider_spec(spec.to_string());
        let mut provider = crate::provider::provider_from_spec(resolved.as_str(), credentials)
            .map_err(|err| self.explain_unknown_provider(err, &resolved))?;
        provider.with_base_dir(&self.config_dir);
        provider.set_reason(self.reason.clone());
        provider.set_caller(self.caller.clone());
        // Context a native address cannot carry: a `ref` names coordinates only,
        // so a provider whose store is partitioned by something outside them
        // (Infisical's environment) reads the operation's profile here. It is
        // the profile the caller already resolved, so a provider and the
        // addresses handed to it never disagree about which profile is running.
        // `None` is for a credential source, which is profile-independent by
        // contract. Naming stays with the address; this never reaches
        // `uri`/`storage_identity`.
        if let Some(profile) = profile {
            provider.set_profile(profile);
        }
        Ok(provider)
    }

    /// Resolves the credentials declared by a provider alias, fetching each
    /// semantic `(name, source)` entry from its source provider.
    ///
    /// `profile` scopes the convention path a bare-string source reads from.
    /// Returns an empty map for a spec that is not an alias, or an alias with
    /// no credentials. A declared credential that cannot be found is a
    /// hard error naming exactly how to fix it. Sources pass
    /// [`Self::validate_credential_sources`] and are built without credentials, so a
    /// chain is at most one hop and cannot recurse. Each source read is audited
    /// with a `credential` marker, so the audit trail explains why the source
    /// store was touched during an operation on the target provider.
    pub(crate) fn resolve_provider_credentials(
        &self,
        spec: &str,
        profile: &str,
    ) -> Result<ProviderCredentials> {
        let mut credentials = ProviderCredentials::new();
        let Some(declared) = self
            .lookup_provider_alias_entry(spec)
            .and_then(ProviderAlias::credentials)
            .filter(|credentials| !credentials.is_empty())
        else {
            return Ok(credentials);
        };
        self.validate_credential_sources(spec)?;

        let project = self.config.project.name.clone();

        // One provider per distinct source spec, so credentials sharing a source
        // (e.g. AppRole role and secret ids from one vault) reuse the instance
        // and whatever it caches, instead of authenticating once per variable.
        let mut sources: HashMap<String, Box<dyn ProviderTrait>> = HashMap::new();

        for (name, source) in sorted_credential_entries(declared) {
            let source_provider = match sources.entry(source.provider.clone()) {
                std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut(),
                std::collections::hash_map::Entry::Vacant(entry) => {
                    entry.insert(self.build_source_provider(&source.provider)?)
                }
            };
            let fetched = source_provider.get(source.address(&project, name));
            // Audit the source read (design: every secret access is recorded).
            // The key is the semantic credential name and the event carries a
            // `credential` marker plus the source provider's credential-free
            // `uri()`, so the trail explains why this store was touched.
            let (outcome, error_kind) = match &fetched {
                Ok(Some(_)) => (AuditOutcome::Found, None),
                Ok(None) => (AuditOutcome::Missing, None),
                Err(e) => (AuditOutcome::Error, Some(e.kind())),
            };
            self.record(
                AuditAction::Get,
                profile,
                outcome,
                AuditFields {
                    key: Some(name),
                    command: Some("credential"),
                    provider_uri: Some(source_provider.uri()),
                    reference: source.reference.as_ref(),
                    error_kind,
                    ..Default::default()
                },
            );
            match fetched? {
                Some(value) => {
                    credentials.insert(name.clone(), value);
                }
                None => {
                    return Err(credential_missing_error(
                        name,
                        spec,
                        &source.location(&project, name),
                    ));
                }
            }
        }

        Ok(credentials)
    }

    /// The credentials a provider alias declares, sorted by semantic name
    /// name, for the `config provider login` flow. Validates every source before
    /// returning any credentials. Errors if the alias is not defined; returns
    /// an empty list for an alias with no `credentials`.
    #[cfg(any(feature = "cli", test))]
    pub(crate) fn declared_provider_credentials(
        &self,
        alias: &str,
    ) -> Result<Vec<(String, CredentialSource)>> {
        // Validate the complete map before returning any entry. The login CLI
        // prompts and writes only after this method succeeds, so a later-sorted
        // invalid source cannot leave earlier credentials partially stored.
        self.validate_credential_sources(alias)?;
        let entry = self
            .lookup_provider_alias_entry(alias)
            .ok_or_else(|| SecretSpecError::ProviderNotFound(alias.to_string()))?;
        Ok(entry
            .credentials()
            .map(sorted_credential_entries)
            .unwrap_or_default()
            .into_iter()
            .map(|(name, source)| (name.clone(), source.clone()))
            .collect())
    }

    /// Stores one provider credential at its source provider — the exact
    /// location [`Self::resolve_provider_credentials`] later reads it from (a `ref`
    /// or the profile-independent convention path for the active project). Errors
    /// if the source provider is read-only. Returns a human-readable description
    /// of where it was stored.
    ///
    /// Like every other write path, the write is gated by the `require_reason`
    /// policy and audited (with a `credential` marker). A successful store also
    /// clears the credential memo, so a credential rotated through this instance
    /// is re-read instead of resolving to the stale cached value.
    #[cfg(any(feature = "cli", test))]
    pub(crate) fn store_provider_credential(
        &self,
        source: &CredentialSource,
        name: &str,
        value: &SecretString,
    ) -> Result<String> {
        self.ensure_reason_for(AuditAction::Set, Some(name))?;
        // The store location is profile-independent (see `PROVIDER_CREDENTIAL_SCOPE`);
        // the session profile attributes the audit event, and is the session
        // context handed to the provider.
        let profile = self.resolve_profile_name(None);
        let provider = self.build_source_provider(&source.provider)?;
        let project = self.config.project.name.clone();
        let address = source.address(&project, name);
        let result = provider
            .check_writable(address)
            .and_then(|()| provider.set(address, value));
        self.audit_write_result(
            &result,
            name,
            &profile,
            Some(provider.uri()),
            source.reference.as_ref(),
            Some("credential"),
        );
        result?;
        // The stored credential replaces whatever an earlier resolution
        // memoized; drop the memo so the next build re-reads it.
        self.provider_credentials_cache.clear();
        Ok(source.location(&project, name))
    }

    /// Validates a spec's `credentials` (pure map lookups, no I/O): every name
    /// must be accepted by the target provider, every source must resolve to a
    /// known provider, and no source may itself declare credentials. Credential
    /// chains are limited to one hop, which also makes cycles impossible.
    /// Run at plan time to fail fast on a routed primary or override, and again
    /// by [`Self::resolve_provider_credentials`], so every construction path —
    /// fallback links and the default provider included — enforces the same
    /// invariants instead of silently dropping a chained source's credentials.
    pub(crate) fn validate_credential_sources(&self, spec: &str) -> Result<()> {
        let Some(alias) = self.lookup_provider_alias_entry(spec) else {
            return Ok(());
        };
        let Some(credentials) = alias.credentials() else {
            return Ok(());
        };
        let resolved_target = self.resolve_provider_spec(spec.to_string());
        let supported = crate::provider::credential_names_for_spec(&resolved_target);
        let provider_name = crate::provider::provider_display_name_for_spec(&resolved_target);
        for (name, source) in sorted_credential_entries(credentials) {
            if !supported.contains(&name.as_str()) {
                let supported_display = if supported.is_empty() {
                    "none".to_string()
                } else {
                    supported.join(", ")
                };
                return Err(SecretSpecError::ProviderOperationFailed(format!(
                    "credential '{name}' is not supported by provider '{provider_name}' \
                     for alias '{spec}' (supported credentials: {supported_display})"
                )));
            }
            // Compose the underlying error into the message instead of
            // replacing it: it carries the corrective guidance (the
            // `1password` -> `onepassword` hint, the defined-aliases listing)
            // that the other resolution paths give for the same mistakes.
            let context = |err: SecretSpecError| {
                SecretSpecError::ProviderOperationFailed(format!(
                    "credential source for '{name}' in provider alias '{spec}': {err}"
                ))
            };
            let resolved = self
                .resolve_one_provider(&source.provider)
                .map_err(context)?;
            // `resolve_one_provider` passes URI-form specs through untouched,
            // so gate the resolved spec's scheme against the registry here:
            // a typo'd scheme should fail at plan time, not surface later as
            // a construction failure a fallback chain downgrades to a warning.
            let known = crate::provider::spec_names_known_provider(&resolved).map_err(context)?;
            if !known {
                return Err(SecretSpecError::ProviderOperationFailed(format!(
                    "credential source for '{name}' in provider alias '{spec}' names an unknown \
                     provider '{}'",
                    crate::audit::redact_uri_strict(&source.provider)
                )));
            }
            if let Some(source_alias) = self.lookup_provider_alias_entry(&source.provider)
                && source_alias
                    .credentials()
                    .is_some_and(|credentials| !credentials.is_empty())
            {
                return Err(SecretSpecError::ProviderOperationFailed(format!(
                    "provider alias '{}' cannot be a credential source for '{spec}' because it \
                     declares its own credentials; credential chains are limited to one hop",
                    source.provider
                )));
            }
        }
        Ok(())
    }

    /// Enriches a provider-construction failure: when a bare token (no scheme
    /// separator) matched neither a built-in provider nor a known alias, the
    /// raw "provider not found" error is unhelpful. List the defined aliases so a
    /// mistyped alias points the user at the right names, matching the guidance
    /// [`Self::resolve_one_provider`] gives for per-secret provider chains.
    fn explain_unknown_provider(&self, err: SecretSpecError, spec: &str) -> SecretSpecError {
        match err {
            SecretSpecError::ProviderNotFound(_) if !spec.contains(':') => {
                let known = self.known_provider_aliases();
                if known.is_empty() {
                    return err;
                }
                SecretSpecError::ProviderNotFound(format!(
                    "{} (not a known provider or alias; available aliases: {})",
                    spec,
                    known.join(", ")
                ))
            }
            _ => err,
        }
    }

    /// Records one audit event with the given variable fields, if auditing is
    /// enabled (a no-op otherwise). Session-constant fields — project, caller,
    /// session reason, and whether auditing is on — are filled here so call sites
    /// specify only what varies. Single-secret (`get`/`set`/`delete`) and bulk
    /// (`check`/`run`/`import`) events go through this one method.
    fn record(
        &self,
        action: AuditAction,
        profile: &str,
        outcome: AuditOutcome,
        fields: AuditFields<'_>,
    ) {
        if let Some(logger) = &self.audit {
            // Scopes affect only these bulk resolution surfaces. `get`, `set`,
            // and `import` deliberately ignore an ambient scope, so attaching it
            // to those events would falsely imply that it constrained the action.
            let scope = match action {
                AuditAction::Check | AuditAction::Run | AuditAction::Export => {
                    self.resolve_scope_name(None)
                }
                AuditAction::Get
                | AuditAction::Set
                | AuditAction::Delete
                | AuditAction::Import
                | AuditAction::CacheClear
                | AuditAction::CacheRefresh => None,
            };
            logger.record(
                action,
                AuditContext {
                    project: &self.config.project.name,
                    profile,
                    scope: scope.as_deref(),
                    key: fields.key,
                    keys: fields.keys,
                    command: fields.command,
                    provider_uri: fields.provider_uri,
                    reference: fields.reference.map(NativeAddress::render),
                    outcome,
                    error_kind: fields.error_kind,
                    reason: self.reason.as_deref(),
                    caller: self.caller.as_ref(),
                },
            );
        }
    }

    /// Audits the result of a single secret or provider-credential write: a
    /// `Written` event on success, an `Error` event (tagged with
    /// the error kind) on failure. Centralizes the write-audit so every write
    /// path records the same way and a new one cannot accidentally diverge or
    /// skip auditing. `command` marks a special-purpose credential store;
    /// `None` denotes a plain secret write.
    fn audit_write_result(
        &self,
        result: &Result<()>,
        key: &str,
        profile: &str,
        provider_uri: Option<String>,
        reference: Option<&NativeAddress>,
        command: Option<&str>,
    ) {
        let (outcome, error_kind) = match result {
            Ok(()) => (AuditOutcome::Written, None),
            Err(e) => (AuditOutcome::Error, Some(e.kind())),
        };
        self.record(
            AuditAction::Set,
            profile,
            outcome,
            AuditFields {
                key: Some(key),
                command,
                provider_uri,
                reference,
                error_kind,
                ..Default::default()
            },
        );
    }

    /// Audits one durable provider deletion. `Ok(false)` is a successful,
    /// idempotent no-op and is recorded as `Missing`; cache invalidation has its
    /// own `CacheClear` events and is never conflated with this operation.
    fn audit_delete_result(
        &self,
        result: &Result<bool>,
        key: &str,
        profile: &str,
        provider_uri: Option<String>,
        reference: Option<&NativeAddress>,
    ) {
        let (outcome, error_kind) = match result {
            Ok(true) => (AuditOutcome::Deleted, None),
            Ok(false) => (AuditOutcome::Missing, None),
            Err(error) => (AuditOutcome::Error, Some(error.kind())),
        };
        self.record(
            AuditAction::Delete,
            profile,
            outcome,
            AuditFields {
                key: Some(key),
                provider_uri,
                reference,
                error_kind,
                ..Default::default()
            },
        );
    }

    /// Records a failed single-secret operation (`get`/`set`/`delete`) as an `Error`
    /// event attributed to `key` — and to a provider and native `ref`
    /// coordinates, when they were determined before the failure. The one shape
    /// every `get`/`set` failure path records, so the paths cannot drift on
    /// which fields a failure carries.
    fn record_key_error(
        &self,
        action: AuditAction,
        profile: &str,
        key: &str,
        provider_uri: Option<String>,
        reference: Option<&NativeAddress>,
        err: &SecretSpecError,
    ) {
        self.record(
            action,
            profile,
            AuditOutcome::Error,
            AuditFields {
                key: Some(key),
                provider_uri,
                reference,
                error_kind: Some(err.kind()),
                ..Default::default()
            },
        );
    }

    /// Enforces the `require_reason` policy and, when it denies access, records the
    /// blocked attempt as an `Error` event before returning, so a policy denial
    /// still leaves an audit trace. `action`/`key` describe the attempted
    /// operation. Used at every public secret-accessing entry point.
    fn ensure_reason_for(&self, action: AuditAction, key: Option<&str>) -> Result<()> {
        if let Err(e) = self.ensure_reason() {
            let profile = self.resolve_profile_name(None);
            self.record(
                action,
                &profile,
                AuditOutcome::Error,
                AuditFields {
                    key,
                    error_kind: Some(e.kind()),
                    ..Default::default()
                },
            );
            return Err(e);
        }
        Ok(())
    }

    /// Decode a stored textual representation. Exactly one trailing LF or CRLF
    /// is ignored to accommodate a value captured from command output; every
    /// other non-alphabet character remains a hard error.
    fn decode_stored_value(
        encoding: SecretEncoding,
        diagnostic_name: &str,
        value: &SecretString,
    ) -> Result<SecretSlice<u8>> {
        let encoded = value
            .expose_secret()
            .strip_suffix("\r\n")
            .or_else(|| value.expose_secret().strip_suffix('\n'))
            .unwrap_or_else(|| value.expose_secret());

        fn decode_base(
            encoded: &[u8],
            padded: &Encoding,
            unpadded: &Encoding,
        ) -> std::result::Result<Vec<u8>, String> {
            if encoded.contains(&b'=') {
                padded.decode(encoded).map_err(|error| error.to_string())
            } else {
                padded
                    .decode(encoded)
                    .or_else(|_| unpadded.decode(encoded))
                    .map_err(|error| error.to_string())
            }
        }

        let decoded = match encoding {
            SecretEncoding::Base64 => decode_base(encoded.as_bytes(), &BASE64, &BASE64_NOPAD),
            SecretEncoding::Base64Url => {
                decode_base(encoded.as_bytes(), &BASE64URL, &BASE64URL_NOPAD)
            }
            SecretEncoding::Hex => HEXLOWER_PERMISSIVE
                .decode(encoded.as_bytes())
                .map_err(|error| error.to_string()),
        }
        .map_err(|reason| SecretSpecError::DecodeFailed {
            name: diagnostic_name.to_string(),
            encoding: encoding.as_str(),
            reason,
        })?;

        Ok(decoded.into())
    }

    /// Encode a logical UTF-8 value into the canonical stored representation
    /// for its declared encoding.
    fn encode_logical_value(encoding: SecretEncoding, value: &SecretString) -> SecretString {
        let bytes = value.expose_secret().as_bytes();
        let encoded = match encoding {
            SecretEncoding::Base64 => BASE64.encode(bytes),
            SecretEncoding::Base64Url => BASE64URL_NOPAD.encode(bytes),
            SecretEncoding::Hex => HEXLOWER.encode(bytes),
        };
        SecretString::new(encoded.into())
    }

    /// Return an encoded copy only when this secret declares an encoding. The
    /// caller can otherwise pass the original value through without cloning it.
    fn encoded_for_storage(planned: &PlannedSecret, value: &SecretString) -> Option<SecretString> {
        planned
            .encoding()
            .map(|encoding| Self::encode_logical_value(encoding, value))
    }

    /// Validate a stored value before import copies it into another provider.
    /// Import moves the stored representation verbatim, so an invalid encoded
    /// source must fail before any target write (and especially before source
    /// cleanup) instead of creating an unreadable destination.
    fn validate_import_value(
        planned: &PlannedSecret,
        diagnostic_name: &str,
        value: &SecretString,
    ) -> Result<()> {
        let Some(encoding) = planned.encoding() else {
            return Ok(());
        };
        let decoded = Self::decode_stored_value(encoding, diagnostic_name, value)?;
        if !planned.as_path() {
            std::str::from_utf8(decoded.expose_secret()).map_err(|error| {
                SecretSpecError::DecodeFailed {
                    name: diagnostic_name.to_string(),
                    encoding: encoding.as_str(),
                    reason: format!(
                        "decoded bytes are not valid UTF-8 ({error}); set `as_path = true` to expose binary data"
                    ),
                }
            })?;
        }
        Ok(())
    }

    /// Select one logical value from a structured stored representation.
    /// Diagnostics deliberately include only the secret name, format, pointer,
    /// and parser location — never the stored document or selected value.
    pub(crate) fn extract_stored_value(
        extract: &SecretExtract,
        diagnostic_name: &str,
        value: &str,
    ) -> Result<SecretString> {
        let failed = |reason: String| SecretSpecError::DecodeFailed {
            name: diagnostic_name.to_string(),
            encoding: extract.format.as_str(),
            reason,
        };
        match extract.format {
            ExtractFormat::Json => {
                let document: serde_json::Value = serde_json::from_str(value)
                    .map_err(|error| failed(format!("stored value is not valid JSON: {error}")))?;
                let selected = document.pointer(&extract.pointer).ok_or_else(|| {
                    failed(format!(
                        "JSON Pointer '{}' did not match the stored document",
                        extract.pointer
                    ))
                })?;
                // Rendering is shared with the awssm and scaleway providers.
                // A null renders as "null" here: this caller was asked for one
                // pointer and reports what the document holds, unlike a
                // provider `field`, where a null means "not set" and the chain
                // continues. See crate::json_field.
                Ok(crate::json_field::render(selected))
            }
            // The pointer grammar and the lookup that follows it live together
            // in crate::ini_field, next to the validation that rejects every
            // other shape at config time.
            ExtractFormat::Ini => crate::ini_field::select(value, &extract.pointer)
                .map(|selected| SecretString::new(selected.into()))
                .map_err(failed),
        }
    }

    /// Decode and extract a stored representation independently of its exposure
    /// shape, then either return UTF-8 text or materialize the bytes to an
    /// owner-only file. Extraction follows decoding and applies only across a
    /// storage boundary; defaults and generated values are already logical.
    fn prepare_resolved(
        &self,
        planned: &PlannedSecret,
        diagnostic_name: &str,
        value: SecretString,
        representation: ResolvedRepresentation,
    ) -> Result<PreparedSecret> {
        let decoded = match (representation, planned.encoding()) {
            (ResolvedRepresentation::Stored, Some(encoding)) => {
                let value = Self::decode_stored_value(encoding, diagnostic_name, &value)?;
                Some((encoding, value))
            }
            _ => None,
        };

        let extracted = match (representation, planned.extract()) {
            (ResolvedRepresentation::Stored, Some(extract)) => {
                let text = match &decoded {
                    Some((encoding, decoded)) => {
                        std::str::from_utf8(decoded.expose_secret()).map_err(|error| {
                            SecretSpecError::DecodeFailed {
                                name: diagnostic_name.to_string(),
                                encoding: encoding.as_str(),
                                reason: format!(
                                    "decoded bytes are not valid UTF-8 and cannot be extracted as {} ({error})",
                                    extract.format.as_str()
                                ),
                            }
                        })?
                    }
                    None => value.expose_secret(),
                };
                Some(Self::extract_stored_value(extract, diagnostic_name, text)?)
            }
            _ => None,
        };

        if planned.as_path() {
            let bytes = extracted
                .as_ref()
                .map(|value| value.expose_secret().as_bytes())
                .or_else(|| decoded.as_ref().map(|(_, decoded)| decoded.expose_secret()))
                .unwrap_or_else(|| value.expose_secret().as_bytes());
            let (owner, path) = self.write_secret_to_temp_file(bytes)?;
            Ok(PreparedSecret::File { owner, path })
        } else if let Some(extracted) = extracted {
            Ok(PreparedSecret::Inline(extracted))
        } else if let Some((encoding, decoded)) = decoded {
            let text = std::str::from_utf8(decoded.expose_secret()).map_err(|error| {
                SecretSpecError::DecodeFailed {
                    name: diagnostic_name.to_string(),
                    encoding: encoding.as_str(),
                    reason: format!(
                        "decoded bytes are not valid UTF-8 ({error}); set `as_path = true` to expose binary data"
                    ),
                }
            })?;
            Ok(PreparedSecret::Inline(SecretString::new(
                text.to_owned().into(),
            )))
        } else {
            Ok(PreparedSecret::Inline(value))
        }
    }

    /// Inserts a resolved secret into the working set, applying its optional
    /// storage decoding and extraction when the value crossed a storage
    /// boundary, then transparently materializing an `as_path` value to an
    /// owner-only temp file whose lifetime is tied to `temp_files`. Shared by
    /// every resolution branch so stored-value transforms cannot drift.
    fn insert_resolved(
        &self,
        secrets: &mut HashMap<String, SecretString>,
        temp_files: &mut Vec<tempfile::NamedTempFile>,
        planned: &PlannedSecret,
        diagnostic_name: &str,
        value: SecretString,
        representation: ResolvedRepresentation,
    ) -> Result<()> {
        match self.prepare_resolved(planned, diagnostic_name, value, representation)? {
            PreparedSecret::Inline(value) => {
                secrets.insert(planned.name.clone(), value);
            }
            PreparedSecret::File { owner, path } => {
                temp_files.push(owner);
                secrets.insert(planned.name.clone(), SecretString::new(path.into()));
            }
        }
        Ok(())
    }

    /// Get a reference to the project configuration. Used by `secretspec
    /// codegen` (which needs the manifest, not a provider) and by tests.
    #[cfg(any(feature = "cli", test))]
    pub(crate) fn config(&self) -> &Config {
        &self.config
    }

    /// Get a reference to the global configuration (for testing)
    #[cfg(test)]
    pub(crate) fn global_config(&self) -> &Option<GlobalConfig> {
        &self.global_config
    }

    /// Attach an audit logger (for testing which events an operation emits).
    #[cfg(test)]
    pub(crate) fn set_audit_for_test(&mut self, logger: crate::audit::AuditLogger) {
        self.audit = Some(logger);
    }

    /// Override the `require_reason` policy (for testing the gate without going
    /// through `load`/`load_from`, which would build a real audit logger and write
    /// to the user's real audit log).
    #[cfg(test)]
    pub(crate) fn set_require_reason(&mut self, policy: RequireReason) {
        self.require_reason = policy;
    }

    /// Resolves the profile to use based on the provided value and configuration
    ///
    /// Profile resolution order:
    /// 1. Provided profile argument
    /// 2. Profile set via set_profile()
    /// 3. SECRETSPEC_PROFILE environment variable
    /// 4. Global configuration default profile
    /// 5. "default" profile
    ///
    /// # Arguments
    ///
    /// * `profile` - Optional profile name to use
    ///
    /// # Returns
    ///
    /// The resolved profile name
    pub(crate) fn resolve_profile_name(&self, profile: Option<&str>) -> String {
        profile
            .map(|p| p.to_string())
            .or_else(|| self.profile.clone())
            .or_else(|| {
                env::var("SECRETSPEC_PROFILE")
                    .ok()
                    .as_deref()
                    .and_then(non_blank)
            })
            .or_else(|| {
                self.global_config
                    .as_ref()
                    .and_then(|gc| gc.defaults.profile.clone())
            })
            .unwrap_or_else(|| "default".to_string())
    }

    /// Resolves the active scope name, or `None` when resolution should cover the
    /// complete profile.
    ///
    /// Precedence mirrors [`Self::resolve_profile_name`] minus the global default:
    /// an explicit argument, then the builder value ([`Self::set_scope`]), then
    /// `SECRETSPEC_SCOPE`. There is deliberately **no** user-global default — an
    /// unset scope always means "the whole profile", so a machine-level default
    /// can never silently drop secrets a project expects to resolve.
    pub(crate) fn resolve_scope_name(&self, scope: Option<&str>) -> Option<String> {
        scope
            .map(str::to_string)
            .or_else(|| self.scope.clone())
            .or_else(|| {
                // Typed loaders opt out of the ambient fallback (see
                // `ignore_ambient_scope`); an explicit scope above still applies.
                if self.ignore_ambient_scope {
                    return None;
                }
                env::var("SECRETSPEC_SCOPE")
                    .ok()
                    .as_deref()
                    .and_then(non_blank)
            })
    }

    /// The set of secret names the active scope admits, or `None` when no scope
    /// is active (meaning "no filtering — the whole profile participates").
    ///
    /// A scope's membership is profile-independent; the *effective* set is the
    /// intersection of this membership with the selected profile, which callers
    /// obtain by filtering the profile's names through the returned set.
    ///
    /// # Errors
    ///
    /// Returns [`SecretSpecError::InvalidScope`] when a scope is selected but not
    /// declared under `[scopes]` in `secretspec.toml`, listing the available
    /// scopes.
    fn active_scope_members(&self) -> Result<Option<HashSet<&str>>> {
        let Some(scope_name) = self.resolve_scope_name(None) else {
            return Ok(None);
        };
        let scope = self
            .config
            .scopes
            .as_ref()
            .and_then(|scopes| scopes.get(&scope_name))
            .ok_or_else(|| {
                let mut available: Vec<&str> = self
                    .config
                    .scopes
                    .iter()
                    .flat_map(|scopes| scopes.keys())
                    .map(String::as_str)
                    .collect();
                available.sort();
                let available = if available.is_empty() {
                    "none defined".to_string()
                } else {
                    available.join(", ")
                };
                SecretSpecError::InvalidScope(format!(
                    "'{}' is not defined in secretspec.toml. Available scopes: {}",
                    scope_name, available
                ))
            })?;
        Ok(Some(scope.secrets.iter().map(String::as_str).collect()))
    }

    /// The manifest-declared names an active scope does **not** admit. Empty
    /// when no scope is active.
    ///
    /// `run --scope` must actively remove these from the child's inherited
    /// environment. Injecting only the scoped subset is not enough on its own: a
    /// shell that already loaded the full profile (a devenv `secretspec run`, a
    /// prior `eval "$(secretspec export)"`) would otherwise pass the excluded
    /// values straight through to the child. This is secret minimization, not an
    /// authorization boundary — a child still holding provider credentials could
    /// resolve another scope itself.
    ///
    /// Membership, not the visible set (scope ∩ profile), decides this. A secret
    /// the scope lists is admitted even when the *selected* profile does not
    /// declare it: the scope said this consumer may hold it, and scopes are
    /// reusable across profiles that declare different subsets, so narrowing by
    /// profile here would unset a name the operator explicitly allowed. The
    /// same rule already governs an admitted secret that fails to resolve.
    /// Composed-secret dependencies the scope leaves out are not admitted, so
    /// they stay scrubbed: they are resolved to build a value, never exposed.
    fn scope_excluded_names(&self) -> Result<Vec<String>> {
        let Some(admitted) = self.active_scope_members()? else {
            return Ok(Vec::new());
        };
        // Scrub across *all* profiles, not only the selected one: a secret
        // declared under another profile can reach the child through the
        // inherited parent environment (a devenv shell, a prior `eval
        // "$(secretspec export)"`), and filtering only the selected profile
        // would let it leak.
        let mut excluded: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
        for profile in self.manifest.profiles.values() {
            for name in profile.secrets.keys() {
                if !admitted.contains(name.as_str()) {
                    excluded.insert(name.clone());
                }
            }
        }
        Ok(excluded.into_iter().collect())
    }

    /// Returns the named profile or an `InvalidProfile` error listing the profiles
    /// defined in `secretspec.toml`.
    fn require_profile(&self, profile_name: &str) -> Result<&Profile> {
        self.config.profiles.get(profile_name).ok_or_else(|| {
            let mut available: Vec<&str> =
                self.config.profiles.keys().map(String::as_str).collect();
            available.sort();
            SecretSpecError::InvalidProfile(format!(
                "'{}' is not defined in secretspec.toml. Available profiles: {}",
                profile_name,
                available.join(", ")
            ))
        })
    }

    /// Validates that the profile exists and returns its effective secret names
    /// in sorted order — the union of the profile's own and the `default`
    /// profile's secrets, as the compiled manifest records them.
    ///
    /// # Arguments
    ///
    /// * `profile` - Optional profile name to resolve (if None, uses resolved profile name)
    ///
    /// # Errors
    ///
    /// Returns `InvalidProfile` when the named profile is not defined.
    pub(crate) fn resolve_profile_secret_names(
        &self,
        profile: Option<&str>,
    ) -> Result<Vec<String>> {
        let all = self.profile_secret_names_unscoped(profile)?;
        // An active scope narrows the profile to its membership intersection —
        // the single worklist that scopes every consumer at once, failing on an
        // unknown scope before any provider is touched.
        match self.active_scope_members()? {
            None => Ok(all),
            Some(members) => Ok(all
                .into_iter()
                .filter(|name| members.contains(name.as_str()))
                .collect()),
        }
    }

    /// Every secret name in `profile` (∪ `default`), sorted, with no scope
    /// filtering. `import` uses this directly so an ambient `SECRETSPEC_SCOPE`
    /// can't narrow a command that has no `--scope`.
    pub(crate) fn profile_secret_names_unscoped(
        &self,
        profile: Option<&str>,
    ) -> Result<Vec<String>> {
        let profile_name = profile
            .map(str::to_string)
            .unwrap_or_else(|| self.resolve_profile_name(None));
        self.require_profile(&profile_name)?;
        let compiled = self
            .manifest
            .profile(&profile_name)
            .expect("raw and compiled profile sets stay identical");
        // `CompiledProfile.secrets` is a sorted `BTreeMap`.
        Ok(compiled.secrets.keys().cloned().collect())
    }

    /// Expands the *visible* set (the scope ∩ profile output) to the set
    /// resolution must **access**: `visible` plus the transitive composed-secret
    /// dependency closure. An in-scope composed secret (e.g. `DATABASE_URL`) may
    /// reference secrets the scope leaves out (`DB_USER`, `DB_PASSWORD`); those
    /// must be fetched to render the composition, but they are dropped from the
    /// output afterwards so the scope never exposes them. Names not reachable
    /// from `visible` are never planned, so no provider is contacted for them.
    ///
    /// Sorted for a deterministic plan. Used only when a scope is active; with no
    /// scope the closure equals the whole profile and this is not called.
    fn accessed_names(&self, profile_name: &str, visible: &[String]) -> Vec<String> {
        fn visit(
            name: &str,
            profile: &crate::compiled_spec::CompiledProfile,
            acc: &mut HashSet<String>,
        ) {
            if !acc.insert(name.to_string()) {
                return;
            }
            if let Some(secret) = profile.secrets.get(name)
                && let Some(template) = &secret.composition
            {
                for dependency in template.dependencies() {
                    visit(dependency, profile, acc);
                }
            }
        }

        let Some(profile) = self.manifest.profile(profile_name) else {
            return visible.to_vec();
        };
        let mut acc = HashSet::new();
        for name in visible {
            visit(name, profile, &mut acc);
        }
        let mut names: Vec<String> = acc.into_iter().collect();
        names.sort();
        names
    }

    /// Returns the effective configuration for a specific secret, or `None` if
    /// the profile does not carry it. The field-level merge with the `default`
    /// profile and `[defaults]` already happened once during manifest
    /// compilation ([`crate::config::Secret::resolved`]); this only reads it.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the secret
    /// * `profile` - Optional profile to search in (if None, uses resolved profile)
    pub(crate) fn resolve_secret_config(
        &self,
        name: &str,
        profile: Option<&str>,
    ) -> Option<crate::config::Secret> {
        let profile_name = self.resolve_profile_name(profile);
        self.manifest
            .profile(&profile_name)
            .and_then(|profile| profile.secrets.get(name))
            .map(|secret| secret.config.clone())
    }

    /// The effective (field-level merged) secrets of `profile_name` in
    /// name-sorted order, read directly off the compiled manifest. This is the
    /// view `check`/`run` list, matching what resolution acts on.
    ///
    /// Backs the `check` display, which runs only after resolution has already
    /// validated the active scope, so an unknown scope cannot reach here in
    /// practice. The error is propagated rather than discarded anyway: swallowing
    /// it would silently display the *whole* profile under a scope, which is the
    /// one thing this filter exists to prevent. The displayed set stays identical
    /// to the resolved set.
    fn effective_secrets(
        &self,
        profile_name: &str,
    ) -> Result<Vec<(String, crate::config::Secret)>> {
        let members = self.active_scope_members()?;
        Ok(self
            .manifest
            .profile(profile_name)
            .into_iter()
            .flat_map(|profile| &profile.secrets)
            .filter(|(name, _)| members.as_ref().is_none_or(|m| m.contains(name.as_str())))
            .map(|(name, secret)| (name.clone(), secret.config.clone()))
            .collect())
    }

    /// Provider-alias maps in lookup order: project `secretspec.toml` first,
    /// then user-global config. Project entries win on conflict so teams can
    /// pin shareable mappings in version control while still allowing per-user
    /// overrides via the global config.
    fn provider_alias_sources(&self) -> impl Iterator<Item = &HashMap<String, ProviderAlias>> {
        self.config.providers.iter().chain(
            self.global_config
                .as_ref()
                .and_then(|gc| gc.defaults.providers.as_ref()),
        )
    }

    /// Resolves a provider alias to its full entry (URI plus any provider
    /// credentials), walking [`Self::provider_alias_sources`] in order. Project
    /// entries win over user-global ones.
    pub(crate) fn lookup_provider_alias_entry(&self, alias: &str) -> Option<&ProviderAlias> {
        self.provider_alias_sources().find_map(|m| m.get(alias))
    }

    /// Resolves a single provider alias to its URI, walking
    /// [`Self::provider_alias_sources`] in order.
    fn lookup_provider_alias(&self, alias: &str) -> Option<String> {
        self.lookup_provider_alias_entry(alias)
            // An inline cached alias still names one leaf URI. Route planning
            // sees its cache policy first; provider construction resolves the
            // same alias to this URI so its credentials remain available.
            .and_then(|alias| alias.authoritative_uri())
            .map(str::to_string)
    }

    /// The cached route `spec` names, if it names one at all.
    ///
    /// A cached alias is a complete route rather than a store, so the paths that
    /// build or display a single provider all have to recognize one; asking here
    /// keeps that one question in one place.
    pub(crate) fn cached_alias(&self, spec: &str) -> Option<&ProviderAlias> {
        self.lookup_provider_alias_entry(spec)
            .filter(|alias| alias.is_cached())
    }

    pub(crate) fn resolve_provider_spec(&self, spec: String) -> String {
        self.lookup_provider_alias(&spec).unwrap_or(spec)
    }

    /// Returns the union of alias names known across all sources, sorted.
    fn known_provider_aliases(&self) -> Vec<String> {
        let mut names: Vec<String> = self
            .provider_alias_sources()
            .flat_map(|m| m.keys().cloned())
            .collect::<HashSet<_>>()
            .into_iter()
            .collect();
        names.sort();
        names
    }

    /// Resolves a single provider spec to its URI. A defined alias is expanded
    /// via [`Self::lookup_provider_alias`]. A spec that is already a URI
    /// (contains `://`) passes through unchanged, so a chain can point at a
    /// store inline — `providers = ["onepassword://Production"]` — without
    /// declaring an alias for it; a `scheme://` string is never an alias key,
    /// so the two forms cannot collide. A non-alias spec that names a
    /// registered provider (a bare name like `keyring`, or `scheme:path`
    /// shorthand like `dotenv:.env.production`) also passes through, so the
    /// chain and the resolved override accept exactly the specs `--provider`
    /// and the default provider accept; `build_provider` constructs it later.
    /// Only a token that names neither an alias nor a provider errors — with
    /// the corrective "use `onepassword` instead" message when it is the
    /// common `1password` misspelling.
    ///
    /// Used both to resolve a chain's primary up front and to resolve each
    /// fallback entry lazily, in order, as a read actually reaches it.
    pub(crate) fn resolve_one_provider(&self, spec: &str) -> Result<String> {
        if spec.contains("://") {
            return Ok(spec.to_string());
        }
        if self.cached_alias(spec).is_some() {
            return Err(SecretSpecError::ProviderOperationFailed(format!(
                "cached provider alias '{spec}' is a complete route and cannot be used where a \
                 leaf provider is required"
            )));
        }
        if let Some(uri) = self.lookup_provider_alias(spec) {
            return Ok(uri);
        }
        if crate::provider::spec_names_known_provider(spec)? {
            return Ok(spec.to_string());
        }
        let known = self.known_provider_aliases();
        let msg = if known.is_empty() {
            format!(
                "Provider alias '{}' is not defined. Declare it in [providers] in secretspec.toml or in the global config.",
                spec
            )
        } else {
            format!(
                "Provider alias '{}' is not defined. Available aliases: {}",
                spec,
                known.join(", ")
            )
        };
        Err(SecretSpecError::ProviderNotFound(msg))
    }

    /// Returns the explicit provider spec from caller arg, builder, or env, in
    /// that priority order.
    ///
    /// Used as the shared head of provider resolution so the precedence between
    /// the `--provider` flag (forwarded via `set_provider`) and the
    /// `SECRETSPEC_PROVIDER` env var stays consistent across resolvers.
    pub(crate) fn explicit_provider_spec(&self, override_arg: Option<&str>) -> Option<String> {
        override_arg
            .map(|spec| spec.to_string())
            .or_else(|| self.provider.clone())
            .or_else(|| {
                env::var("SECRETSPEC_PROVIDER")
                    .ok()
                    .as_deref()
                    .and_then(non_blank)
            })
    }

    /// Fetches one provider group's secrets through the provider's batch
    /// surface: every planned secret's [`Address`] (native `ref` coordinates or
    /// convention naming) is handed to `get_many`, which dedupes identical
    /// coordinates and batches or parallelizes as the store allows. The address
    /// is the one the plan already derived, so naming lives in exactly one place.
    fn fetch_group(
        &self,
        provider: &dyn ProviderTrait,
        provider_spec: Option<&str>,
        group: &[&PlannedSecret],
        project: &str,
        profile: &str,
    ) -> Result<HashMap<String, SecretString>> {
        let addresses = group
            .iter()
            .map(|planned| self.address_for_spec(planned, provider_spec, project, profile))
            .collect::<Result<Vec<_>>>()?;
        let requests: Vec<(&str, Address<'_>)> = group
            .iter()
            .zip(&addresses)
            .map(|(planned, address)| (planned.name.as_str(), address.as_address()))
            .collect();
        provider.get_many(&requests)
    }

    /// Cache-first read for a whole plan: one provider per distinct cache store,
    /// one batched read each.
    ///
    /// The per-secret path would build a provider and make a round trip for every
    /// cached secret before the authoritative route is even consulted — for a
    /// dotenv cache, re-reading and re-parsing the same file once per secret.
    /// Batching mirrors what [`Self::fetch_group`] already does for authoritative
    /// stores. Returns the fresh values by secret name, with the serving store's
    /// URI for provenance.
    fn read_cached_group(
        &self,
        plan: &ResolutionPlan,
        profile: &str,
    ) -> HashMap<String, (SecretString, String)> {
        // Grouped by cache spec (not URI) so an alias's `credentials` stays
        // reachable at build time, and sorted so warnings come out in a stable
        // order.
        let mut groups: BTreeMap<&str, Vec<&PlannedSecret>> = BTreeMap::new();
        for planned in &plan.secrets {
            if let Some(cache) = planned.route.as_ref().and_then(Route::cache) {
                groups.entry(cache.spec.as_str()).or_default().push(planned);
            }
        }

        let mut cached = HashMap::new();
        for (spec, group) in groups {
            let provider = match self.build_provider(spec.to_string(), Some(profile)) {
                Ok(provider) => provider,
                Err(error) => {
                    // One warning per unusable cache store, not per secret.
                    cache_read_warning(&group_names(&group), error);
                    continue;
                }
            };
            let requests: Vec<(&str, Address<'_>)> = group
                .iter()
                .map(|planned| {
                    (
                        planned.name.as_str(),
                        self.cache_address(profile, &planned.name),
                    )
                })
                .collect();
            let stored = match provider.get_many(&requests) {
                Ok(stored) => stored,
                Err(error) => {
                    cache_read_warning(&group_names(&group), error);
                    continue;
                }
            };
            let uri = provider.uri();
            for planned in group {
                let Some(stored) = stored.get(&planned.name) else {
                    continue;
                };
                let cache = planned
                    .route
                    .as_ref()
                    .and_then(Route::cache)
                    .expect("the group was built from secrets with a cached route");
                match cached_entry(planned, cache, stored, &self.config.project.name, profile) {
                    CachedEntry::Fresh(value) => {
                        cached.insert(planned.name.clone(), (value, uri.clone()));
                    }
                    CachedEntry::Stale => {
                        self.evict_cache_entry(provider.as_ref(), &planned.name, profile)
                    }
                    CachedEntry::Foreign => {}
                }
            }
        }
        cached
    }

    /// The address a cached entry lives at: SecretSpec's logical
    /// `{project}/{profile}/{secret}` naming, even when the authoritative
    /// provider addresses the secret through a native `ref`. One place, so the
    /// read, refresh, and invalidation paths cannot address different entries.
    fn cache_address<'a>(&'a self, profile: &'a str, name: &'a str) -> Address<'a> {
        Address::convention(&self.config.project.name, profile, name)
    }

    /// Refresh a cached route after its authoritative provider returns or
    /// accepts a value. Cache writes are best-effort: losing the acceleration
    /// layer must never turn a successful authoritative operation into failure.
    ///
    /// A refresh that fails drops the entry instead of leaving it: the value it
    /// holds has been superseded, so serving it until it expired would be worse
    /// than a cache miss.
    fn write_cached_secret(
        &self,
        planned: &PlannedSecret,
        route: &Route,
        profile: &str,
        value: &SecretString,
    ) {
        let Some(cache) = route.cache() else {
            return;
        };
        let provider = match self.build_provider(cache.spec.clone(), Some(profile)) {
            Ok(provider) => provider,
            Err(error) => {
                self.remediate_failed_cache_refresh(planned, cache, profile, error, None);
                return;
            }
        };
        // Refusing here rather than through the remediation path: what is at that
        // address is not ours, so it must be neither overwritten nor removed.
        if let Err(error) =
            self.check_cache_address_is_ours(provider.as_ref(), &planned.name, profile)
        {
            cache_warning(&planned.name, format!("not caching: {error}"));
            return;
        }
        let serialized = match cache::encode_entry(
            &self.config.project.name,
            profile,
            cache.max_age_secs,
            planned.cache_fingerprint(cache, &self.config.project.name, profile),
            value,
        ) {
            Ok(serialized) => serialized,
            Err(error) => {
                self.remediate_failed_cache_refresh(
                    planned,
                    cache,
                    profile,
                    error,
                    Some(provider.as_ref()),
                );
                return;
            }
        };
        let address = self.cache_address(profile, &planned.name);
        // Ask the store to expire the entry at the same age the envelope does.
        // Providers that cannot expire a value write it plainly; the envelope's
        // own `expires_at` is the freshness authority either way. A store that
        // *can* expire but fails to arrange it refuses the write, which lands
        // here as a warning and drops the entry — no unexpiring copy is left.
        let result = provider.check_writable(address).and_then(|()| {
            provider.set_expiring(
                address,
                &serialized,
                Duration::from_secs(cache.max_age_secs),
            )
        });
        let (outcome, error_kind) = match &result {
            Ok(()) => (AuditOutcome::Written, None),
            Err(error) => (AuditOutcome::Error, Some(error.kind())),
        };
        self.record(
            AuditAction::CacheRefresh,
            profile,
            outcome,
            AuditFields {
                key: Some(&planned.name),
                provider_uri: Some(provider.uri()),
                error_kind,
                ..Default::default()
            },
        );
        if let Err(error) = result {
            self.remediate_failed_cache_refresh(
                planned,
                cache,
                profile,
                error,
                Some(provider.as_ref()),
            );
        }
    }

    /// Report a failed refresh and make the superseded entry unusable.
    ///
    /// When normal cache construction failed (most commonly because a declared
    /// credential source is temporarily unavailable), retry construction
    /// without those declared credentials for remediation only. Providers may
    /// still authenticate from their standard environment or agent, allowing
    /// the old entry to be removed even though the configured credential source
    /// could not be read. If a provider was already built, reuse it.
    fn remediate_failed_cache_refresh(
        &self,
        planned: &PlannedSecret,
        cache: &ResolvedCache,
        profile: &str,
        failure: impl std::fmt::Display,
        provider: Option<&dyn ProviderTrait>,
    ) {
        cache_warning(&planned.name, failure);
        let result = match provider {
            Some(provider) => self.delete_cache_entry(provider, &planned.name, profile),
            None => self
                .build_source_provider(&cache.spec)
                .and_then(|provider| {
                    self.delete_cache_entry(provider.as_ref(), &planned.name, profile)
                }),
        };
        if let Err(error) = result {
            cache_warning(
                &planned.name,
                format!(
                    "could not drop the superseded entry either: {error}. Run \
                     `secretspec cache clear {}` — until then a read may serve the old value",
                    planned.name
                ),
            );
        }
    }

    /// Drop an entry a read found unusable.
    ///
    /// Most cache stores cannot expire a value themselves, so without this an
    /// entry the route can no longer serve would sit there — plaintext, past its
    /// `max_age` — until something happened to overwrite it. A refresh only
    /// overwrites it when the authoritative read succeeds *and* the pass
    /// materializes values, so neither an offline resolve nor a value-free
    /// `check` would ever clear it.
    ///
    /// Best effort: the read has already decided not to serve this entry, so a
    /// failure to remove it cannot change the outcome of the operation.
    fn evict_cache_entry(&self, provider: &dyn ProviderTrait, name: &str, profile: &str) {
        if let Err(error) = self.delete_cache_entry(provider, name, profile) {
            cache_warning(
                name,
                format!("could not drop an unusable cache entry: {error}"),
            );
        }
    }

    /// Whether this project and profile may write to or remove what sits at a
    /// cache address, naming the reason when they may not.
    ///
    /// A cache store can be shared: a flat dotenv file gives every project the
    /// same key for a given secret name, and a store may hold values SecretSpec
    /// never wrote. Overwriting is as destructive as deleting, so both go through
    /// here, and both refuse only on *positive* evidence that the value belongs
    /// to someone else. Silence is not evidence — an address that cannot be read
    /// is still ours to write and clear, which is what keeps an
    /// expired-but-recoverable KV v2 version destroyable.
    fn check_cache_address_is_ours(
        &self,
        provider: &dyn ProviderTrait,
        name: &str,
        profile: &str,
    ) -> Result<()> {
        let Ok(Some(stored)) = provider.get(self.cache_address(profile, name)) else {
            return Ok(());
        };
        match cache::ownership(&stored, &self.config.project.name, profile) {
            CacheOwnership::Ours | CacheOwnership::Expired | CacheOwnership::OursUnreadable => {
                Ok(())
            }
            CacheOwnership::Foreign { project, profile } => {
                Err(SecretSpecError::ProviderOperationFailed(format!(
                    "the cache holds {project}/{profile}'s entry for '{name}' at this address, so \
                     it is not ours to change. Give this project's cache a store or path of its own."
                )))
            }
            CacheOwnership::Unrecognized => Err(SecretSpecError::ProviderOperationFailed(format!(
                "the value stored for '{name}' is not a SecretSpec cache entry, so it is not ours \
                 to change. Check that the cache provider addresses a store only SecretSpec writes \
                 to."
            ))),
        }
    }

    /// Drop the cached entry for `name`, reporting whether one existed.
    ///
    /// A delete that removed nothing is not audited: no secret was touched, and
    /// recording it would make an empty cache indistinguishable from a real
    /// invalidation in the audit log.
    fn delete_cache_entry(
        &self,
        provider: &dyn ProviderTrait,
        name: &str,
        profile: &str,
    ) -> Result<bool> {
        self.check_cache_address_is_ours(provider, name, profile)?;
        let result = provider.delete(self.cache_address(profile, name));
        match &result {
            Ok(true) => self.record(
                AuditAction::CacheClear,
                profile,
                AuditOutcome::Deleted,
                AuditFields {
                    key: Some(name),
                    provider_uri: Some(provider.uri()),
                    ..Default::default()
                },
            ),
            Ok(false) => {}
            Err(error) => self.record_key_error(
                AuditAction::CacheClear,
                profile,
                name,
                Some(provider.uri()),
                None,
                error,
            ),
        }
        result
    }

    /// Drop the cached entry a route holds, reporting whether one existed.
    /// `Ok(false)` for a route with no cache: there is nothing to invalidate.
    fn invalidate_cached_secret(
        &self,
        planned: &PlannedSecret,
        route: &Route,
        profile: &str,
    ) -> Result<bool> {
        let Some(cache) = route.cache() else {
            return Ok(false);
        };
        let provider = self.build_provider(cache.spec.clone(), Some(profile))?;
        self.delete_cache_entry(provider.as_ref(), &planned.name, profile)
    }

    /// Keep the cache consistent with a successful authoritative write.
    ///
    /// A write through the cached route refreshes the entry. A write that
    /// *bypassed* the cache — the documented `--provider <leaf>` escape hatch,
    /// `SECRETSPEC_PROVIDER`, the builder — has to drop the entry it superseded
    /// instead, or every later read would serve the old value until it expired.
    fn sync_cache_after_write(
        &self,
        planned: &PlannedSecret,
        route: &Route,
        profile: &str,
        value: &SecretString,
    ) {
        if route.cache().is_some() {
            self.write_cached_secret(planned, route, profile, value);
            return;
        }
        // Only re-plan when the declared routing could name a cached route at
        // all: re-planning unconditionally would report an unrelated routing
        // problem (an undefined alias the override sidestepped) as a cache
        // warning on a write that succeeded.
        let default_spec = self.configured_default_provider_spec();
        let names_cache = planned
            .config()
            .providers
            .as_deref()
            .unwrap_or_default()
            .iter()
            .map(String::as_str)
            .chain(default_spec.as_deref())
            .any(|spec| self.cached_alias(spec).is_some());
        if !names_cache {
            return;
        }
        // An override collapses the route and drops its cache, so ask what the
        // manifest declares to find the entry this write just superseded.
        let declared = match self.route_for(planned.config(), &None) {
            Ok(declared) => declared,
            Err(error) => {
                cache_warning(&planned.name, error);
                return;
            }
        };
        if let Err(error) = self.invalidate_cached_secret(planned, &declared, profile) {
            cache_warning(
                &planned.name,
                format!(
                    "could not drop the cache entry this write superseded: {error}. Run \
                     `secretspec cache clear {}` — until then a read may serve the old value",
                    planned.name
                ),
            );
        }
    }

    /// Drop any cache entry that could otherwise keep serving a value after its
    /// authoritative copy was deleted. As with direct writes, a provider
    /// override hides the manifest's cached route, so re-plan only when the
    /// declaration could actually name a cache.
    fn sync_cache_after_delete(&self, planned: &PlannedSecret, route: &Route, profile: &str) {
        if route.cache().is_some() {
            if let Err(error) = self.invalidate_cached_secret(planned, route, profile) {
                cache_warning(
                    &planned.name,
                    format!(
                        "could not drop the cache entry for the deleted secret: {error}. Run \
                         `secretspec cache clear {}` — until then a read may serve the deleted value",
                        planned.name
                    ),
                );
            }
            return;
        }

        let default_spec = self.configured_default_provider_spec();
        let names_cache = planned
            .config()
            .providers
            .as_deref()
            .unwrap_or_default()
            .iter()
            .map(String::as_str)
            .chain(default_spec.as_deref())
            .any(|spec| self.cached_alias(spec).is_some());
        if !names_cache {
            return;
        }
        let declared = match self.route_for(planned.config(), &None) {
            Ok(declared) => declared,
            Err(error) => {
                cache_warning(&planned.name, error);
                return;
            }
        };
        if let Err(error) = self.invalidate_cached_secret(planned, &declared, profile) {
            cache_warning(
                &planned.name,
                format!(
                    "could not drop the cache entry for the deleted secret: {error}. Run \
                     `secretspec cache clear {}` — until then a read may serve the deleted value",
                    planned.name
                ),
            );
        }
    }

    /// Builds the provider a write goes to for a resolved [`Route`]: the primary
    /// store, or the default provider when the route sets none. A write never
    /// consults the fallback, so an undefined alias further down the chain does
    /// not affect it. `profile` is the profile the write is addressed under.
    fn write_provider_for_route(
        &self,
        route: &Route,
        profile: Option<&str>,
    ) -> Result<Box<dyn ProviderTrait>> {
        // Build from the primary spec (not the resolved URI) so an alias's
        // `credentials` is applied to the write target too.
        self.get_route_provider(route.group_key(), profile)
    }

    /// Refuses an invalid write before the value is requested, then reports
    /// its credential-free destination when the caller installed a reporter.
    /// Both `set` and interactive `check` use this one pre-write path so their
    /// target preview and refusal behavior cannot drift apart.
    fn preflight_write(
        &self,
        planned: &PlannedSecret,
        profile: &str,
        backend: &dyn ProviderTrait,
    ) -> Result<()> {
        let address = self.address_for_spec(
            planned,
            planned.route.as_ref().and_then(Route::group_key),
            &self.config.project.name,
            profile,
        )?;
        let addr = address.as_address();
        backend.check_writable(addr)?;

        let Some(reporter) = &self.write_target_reporter else {
            return Ok(());
        };
        reporter(&WriteTarget {
            name: planned.name.clone(),
            provider_uri: backend.uri(),
            profile: profile.to_string(),
            target: backend.describe_write_target(addr)?,
        });
        Ok(())
    }

    /// Gets the provider instance to use for secret operations
    ///
    /// Provider resolution order:
    /// 1. Provided provider argument
    /// 2. Provider set via builder (used by the CLI to forward `--provider`)
    /// 3. Environment variable (SECRETSPEC_PROVIDER)
    /// 4. Global configuration default provider
    /// 5. Error if no provider is configured
    ///
    /// # Arguments
    ///
    /// * `provider_arg` - Optional provider specification (name or URI)
    /// * `profile` - The profile the operation is addressed under (`None`
    ///   falls back to the session profile); scopes any provider credentials
    ///   fetched during construction
    ///
    /// # Returns
    ///
    /// A boxed provider instance
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - No provider is configured
    /// - The specified provider is not found
    pub(crate) fn get_provider(
        &self,
        provider_arg: Option<&str>,
        profile: Option<&str>,
    ) -> Result<Box<dyn ProviderTrait>> {
        let provider_spec = self.default_provider_spec(provider_arg)?;

        // Alias resolution happens inside `build_provider`.
        let provider = self.build_provider(provider_spec, profile)?;

        Ok(provider)
    }

    /// The routed sibling of [`Self::get_provider`]: resolves `provider_arg`
    /// against the default provider, then builds it as a planned route's
    /// primary, so an inline cached alias (0.19+) unwraps to its authoritative
    /// leaf instead of being rejected as a route.
    fn get_route_provider(
        &self,
        provider_arg: Option<&str>,
        profile: Option<&str>,
    ) -> Result<Box<dyn ProviderTrait>> {
        let provider_spec = self.default_provider_spec(provider_arg)?;
        self.build_route_provider(provider_spec, profile)
    }

    /// The raw provider spec [`Self::get_provider`] would build for
    /// `provider_arg`: the explicit override, else the user-global default.
    /// Split out so display paths can name the provider without constructing
    /// it (construction fetches provider credentials, so a display-only build
    /// could fail or do I/O).
    fn default_provider_spec(&self, provider_arg: Option<&str>) -> Result<String> {
        self.explicit_provider_spec(provider_arg)
            .or_else(|| self.configured_default_provider_spec())
            .ok_or(SecretSpecError::NoProviderConfigured)
    }

    /// User-global default provider spec, without applying explicit overrides.
    /// Planning uses this only when it names a cached alias; ordinary defaults
    /// retain the existing lazy `Route { primary: None }` representation.
    pub(crate) fn configured_default_provider_spec(&self) -> Option<String> {
        self.global_config
            .as_ref()
            .and_then(|config| config.defaults.provider.clone())
    }

    /// Returns a provider URI for validation result metadata without forcing a
    /// user-global default when every secret used an explicit or per-secret provider.
    ///
    /// The returned URI lands in the `provider` field of the resolution report and
    /// the resolve response, which `check --explain` prints, `--json` emits, and the
    /// other-language SDKs read over the FFI boundary. A user-authored alias or
    /// override may embed a credential (`vault+token:s3cr3t@host`,
    /// `vault://host?token=...`), so raw URIs are run through `redact_uri_strict`
    /// first. The `provider.uri()` paths below are already credential-free.
    fn validation_report_provider_uri<'a>(
        &self,
        override_uri: Option<&str>,
        primary_uris: impl Iterator<Item = Option<&'a str>>,
        profile: Option<&str>,
    ) -> Result<String> {
        if let Some(uri) = override_uri {
            return Ok(crate::audit::redact_uri_strict(uri));
        }

        // Collecting into `Option` yields `None` as soon as any secret sits on
        // the default provider, which then names the report.
        let provider_uris: Option<Vec<&str>> = primary_uris.collect();
        match provider_uris.and_then(|uris| uris.into_iter().min()) {
            Some(uri) => Ok(crate::audit::redact_uri_strict(uri)),
            // A secret on the default provider, or no secrets at all.
            None => {
                let spec = self.default_provider_spec(None)?;
                // A cached default alias cannot be constructed — it is a route,
                // not a store — so name the store it reads first instead of
                // failing a report that needed no provider at all.
                if self.cached_alias(&spec).is_some() {
                    return Ok(crate::audit::redact_uri_strict(
                        &self.override_display_uri(&spec)?,
                    ));
                }
                self.get_provider(Some(&spec), profile)
                    .map(|provider| provider.uri())
            }
        }
    }

    /// Gets a secret from a chain of provider specs with fallback.
    ///
    /// Walks one secret's fallback chain lazily until a provider answers.
    ///
    /// A broken alias, provider construction failure, or read error warns and
    /// advances to the next link. If every attempted provider errored without
    /// any healthy "not found" response, the last error is returned so an
    /// outage is not silently downgraded to a missing secret.
    fn read_fallback_chain(
        &self,
        provider_cache: &ProviderCache,
        request: FallbackReadRequest<'_>,
    ) -> Result<FallbackRead> {
        let mut last_error: Option<SecretSpecError> = None;
        let mut any_healthy = false;
        let mut last_uri: Option<String> = None;
        let mut last_reference: Option<NativeAddress> = None;

        for spec in request.provider_specs {
            // Resolve each link only when the preceding providers have missed.
            let uri = match self.resolve_one_provider(spec) {
                Ok(uri) => uri,
                Err(error) => {
                    warn_provider_failure(
                        &crate::audit::redact_uri_strict(spec),
                        request.diagnostic_name,
                        &error,
                    );
                    last_error = Some(error);
                    continue;
                }
            };

            // Build from the raw spec so alias credentials are applied. The
            // operation-scoped cache shares provider connection state between
            // concurrent per-secret fallback walks.
            let provider =
                match self.shared_provider(provider_cache, spec, Some(request.profile), false) {
                    Ok(provider) => provider,
                    Err(error) => {
                        warn_provider_failure(
                            &crate::audit::redact_uri_strict(&uri),
                            request.diagnostic_name,
                            &error,
                        );
                        last_error = Some(error);
                        continue;
                    }
                };

            let provider_uri = provider.uri();
            last_uri = Some(provider_uri.clone());
            let address = self.address_for_spec(
                request.planned,
                Some(spec),
                request.project,
                request.profile,
            )?;
            last_reference = address.native().cloned();
            match provider.get(address.as_address()) {
                Ok(Some(value)) => {
                    return Ok(FallbackRead {
                        value: Some(value),
                        provider_uri: Some(provider_uri),
                        native_address: last_reference,
                    });
                }
                Ok(None) => {
                    any_healthy = true;
                }
                Err(error) => {
                    warn_provider_failure(&provider_uri, request.diagnostic_name, &error);
                    last_error = Some(error);
                }
            }
        }

        match last_error {
            Some(error) if !any_healthy => Err(error),
            _ => Ok(FallbackRead::missing(last_uri, last_reference)),
        }
    }
    ///
    /// When `name` is `None`, every declared secret using a cached route is
    /// cleared. A named secret must exist and use a cached route.
    ///
    /// The count is the number of entries actually removed, not the number of
    /// cached secrets declared, so an empty cache reports `0` and a real
    /// invalidation is distinguishable from a no-op.
    ///
    /// Provider overrides are ignored: this maintains the cache the manifest
    /// declares, and an override would collapse the route and hide the very
    /// entry that needs clearing.
    pub fn clear_cache(&self, name: Option<&str>) -> Result<usize> {
        self.ensure_reason_for(AuditAction::CacheClear, name)?;
        let profile = self.resolve_profile_name(None);
        let named = name.is_some();
        let names = match name {
            Some(name) => {
                // `resolve_profile_secret_names` validates the profile for the
                // sweep; a named secret needs the same check explicitly, or an
                // unknown profile would be reported as an unknown secret.
                self.require_profile(&profile)?;
                vec![name.to_string()]
            }
            None => self.resolve_profile_secret_names(Some(&profile))?,
        };
        let mut cleared = 0;
        let mut failures: Vec<(String, SecretSpecError)> = Vec::new();

        for name in names {
            let planned = match self.plan_declared_secret(&name, &profile)? {
                Some(planned) => planned,
                None => {
                    return Err(SecretSpecError::SecretNotFound(format!(
                        "Secret '{name}' is not defined in profile '{profile}'"
                    )));
                }
            };
            let Some(route) = &planned.route else {
                if named {
                    return Err(SecretSpecError::ProviderOperationFailed(format!(
                        "secret '{name}' is composed and has no provider cache"
                    )));
                }
                continue;
            };
            if route.cache().is_none() {
                if named {
                    return Err(SecretSpecError::ProviderOperationFailed(format!(
                        "secret '{name}' does not use a cached provider route"
                    )));
                }
                continue;
            }
            match self.invalidate_cached_secret(&planned, route, &profile) {
                Ok(deleted) => cleared += usize::from(deleted),
                // One unreachable cache store must not leave the rest of the
                // profile's entries in place: clear what can be cleared, then
                // report what could not, with the count that did succeed.
                Err(error) if named => return Err(error),
                Err(error) => failures.push((name, error)),
            }
        }

        if let Some((name, error)) = failures.first() {
            return Err(SecretSpecError::ProviderOperationFailed(format!(
                "cleared {cleared} cache {entries}, but {count} could not be cleared \
                 ('{name}': {error})",
                entries = if cleared == 1 { "entry" } else { "entries" },
                count = failures.len(),
            )));
        }
        Ok(cleared)
    }

    /// Sets a secret value in the provider
    ///
    /// If no value is provided, the user will be prompted to enter it securely.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the secret to set
    /// * `value` - Optional value to set (prompts if None)
    /// * `provider_arg` - Optional provider to use
    /// * `profile` - Optional profile to use
    ///
    /// # Returns
    ///
    /// `Ok(())` if the secret was successfully set
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The secret is not defined in the specification
    /// - The provider doesn't support setting values
    /// - The storage operation fails
    ///
    /// # Example
    ///
    /// ```no_run
    /// use secretspec::Secrets;
    ///
    /// let mut spec = Secrets::load().unwrap();
    /// spec.set("DATABASE_URL", Some("postgres://localhost".to_string())).unwrap();
    /// ```
    pub fn set(&self, name: &str, value: Option<String>) -> Result<()> {
        self.ensure_reason_for(AuditAction::Set, Some(name))?;
        // Check if the secret exists in the spec
        let profile_name = self.resolve_profile_name(None);
        self.require_profile(&profile_name)?;

        // Plan the secret exactly as batch resolution would, so the write
        // target, address, and effective config are the same decisions
        // `check`/`run` make. `None` means it is not declared in this profile.
        let planned = match self.plan_secret(name, &profile_name, None) {
            Ok(Some(planned)) => planned,
            // Planning failed (e.g. an undefined provider alias). Still an
            // attempted write, so audit it like the batch path audits every
            // planning failure; no provider can be attributed yet.
            Err(err) => {
                self.record_key_error(AuditAction::Set, &profile_name, name, None, None, &err);
                return Err(err);
            }
            Ok(None) => {
                // Unscoped, like `import`: `set` has no `--scope`, so an ambient
                // `SECRETSPEC_SCOPE` must not hide names from the listing (it
                // does not restrict what `set` may write) nor turn an undefined
                // scope into an early return that skips the audit record below.
                let available_secrets = self.profile_secret_names_unscoped(Some(&profile_name))?;

                let err = SecretSpecError::SecretNotFound(format!(
                    "Secret '{}' is not defined in profile '{}'. Available secrets: {}",
                    name,
                    profile_name,
                    available_secrets.join(", ")
                ));
                // Provider is unknown for an undefined secret, so attribute to None.
                self.record_key_error(AuditAction::Set, &profile_name, name, None, None, &err);
                return Err(err);
            }
        };

        // A composed secret plans no route: its value is derived, so a write
        // has nowhere to go.
        let Some(route) = &planned.route else {
            let err = SecretSpecError::ComposedSecretReadOnly(name.to_string());
            self.record_key_error(AuditAction::Set, &profile_name, name, None, None, &err);
            return Err(err);
        };

        if planned.extract().is_some() {
            let err = SecretSpecError::ExtractedSecretReadOnly(name.to_string());
            self.record_key_error(
                AuditAction::Set,
                &profile_name,
                name,
                route.primary().map(str::to_string),
                planned.reference(),
                &err,
            );
            return Err(err);
        }

        let backend = match self.write_provider_for_route(route, Some(&profile_name)) {
            Ok(backend) => backend,
            Err(err) => {
                self.record_key_error(AuditAction::Set, &profile_name, name, None, None, &err);
                return Err(err);
            }
        };

        let address = self.address_for_spec(
            &planned,
            route.group_key(),
            &self.config.project.name,
            &profile_name,
        )?;
        let addr = address.as_address();
        // Refuse before prompting for a value. The provider states the reason:
        // a store may be writable through the convention layout yet reject the
        // `ref` this secret names. A CLI-owned reporter also previews the
        // resolved destination here; SDK/library callers install none.
        if let Err(err) = self.preflight_write(&planned, &profile_name, backend.as_ref()) {
            self.record_key_error(
                AuditAction::Set,
                &profile_name,
                name,
                Some(backend.uri()),
                None,
                &err,
            );
            return Err(err);
        }

        let value = if let Some(v) = value {
            SecretString::new(v.into())
        } else if io::stdin().is_terminal() {
            let secret = inquire::Password::new(&format!(
                "Enter value for {name} (profile: {profile_name}):"
            ))
            .without_confirmation()
            .prompt()?;
            SecretString::new(secret.into())
        } else {
            // Read from stdin when input is piped
            let mut buffer = String::new();
            io::stdin().read_to_string(&mut buffer)?;
            SecretString::new(buffer.trim().to_string().into())
        };

        if value.expose_secret().is_empty() {
            let err = SecretSpecError::ProviderOperationFailed(
                "Secret value cannot be empty".to_string(),
            );
            self.record_key_error(
                AuditAction::Set,
                &profile_name,
                name,
                Some(backend.uri()),
                None,
                &err,
            );
            return Err(err);
        }

        let encoded_value = Self::encoded_for_storage(&planned, &value);
        let stored_value = encoded_value.as_ref().unwrap_or(&value);
        let result = backend.set(addr, stored_value);
        self.audit_write_result(
            &result,
            name,
            &profile_name,
            Some(backend.uri()),
            address.native(),
            None,
        );
        result?;
        self.sync_cache_after_write(&planned, route, &profile_name, stored_value);

        eprintln!(
            "{} Secret '{}' saved to {} (profile: {})",
            "✓".green(),
            name,
            backend.name(),
            profile_name
        );

        Ok(())
    }

    /// Deletes one secret value from its authoritative provider. Available
    /// since SecretSpec 0.18.
    ///
    /// The provider route and address are resolved exactly as for [`Self::set`]:
    /// without an override, only the primary write provider is changed; fallback
    /// copies are never traversed and deleted implicitly. A successful deletion
    /// also invalidates the manifest's cache so a later read cannot return the
    /// removed value. Missing values are an idempotent `Ok(false)`.
    pub fn delete(&self, name: &str) -> Result<bool> {
        self.ensure_reason_for(AuditAction::Delete, Some(name))?;
        let profile_name = self.resolve_profile_name(None);
        self.require_profile(&profile_name)?;

        let planned = match self.plan_secret(name, &profile_name, None) {
            Ok(Some(planned)) => planned,
            Err(error) => {
                self.record_key_error(AuditAction::Delete, &profile_name, name, None, None, &error);
                return Err(error);
            }
            Ok(None) => {
                let available = self.profile_secret_names_unscoped(Some(&profile_name))?;
                let error = SecretSpecError::SecretNotFound(format!(
                    "Secret '{name}' is not defined in profile '{profile_name}'. Available secrets: {}",
                    available.join(", ")
                ));
                self.record_key_error(AuditAction::Delete, &profile_name, name, None, None, &error);
                return Err(error);
            }
        };

        let Some(route) = &planned.route else {
            let error = SecretSpecError::ComposedSecretReadOnly(name.to_string());
            self.record_key_error(AuditAction::Delete, &profile_name, name, None, None, &error);
            return Err(error);
        };
        if planned.extract().is_some() {
            let error = SecretSpecError::ExtractedSecretReadOnly(name.to_string());
            self.record_key_error(
                AuditAction::Delete,
                &profile_name,
                name,
                route.primary().map(str::to_string),
                planned.reference(),
                &error,
            );
            return Err(error);
        }
        let backend = match self.write_provider_for_route(route, Some(&profile_name)) {
            Ok(backend) => backend,
            Err(error) => {
                self.record_key_error(
                    AuditAction::Delete,
                    &profile_name,
                    name,
                    None,
                    planned.reference(),
                    &error,
                );
                return Err(error);
            }
        };

        let address = self.address_for_spec(
            &planned,
            route.group_key(),
            &self.config.project.name,
            &profile_name,
        )?;
        let result = backend.delete(address.as_address());
        self.audit_delete_result(
            &result,
            name,
            &profile_name,
            Some(backend.uri()),
            address.native(),
        );
        let deleted = result?;
        // Even a no-op authoritative delete must invalidate the cache: the
        // cache may still contain the only surviving copy of the value.
        self.sync_cache_after_delete(&planned, route, &profile_name);
        Ok(deleted)
    }

    /// Resolves one secret and prints it to stdout: the CLI's `secretspec get`.
    ///
    /// A secret declared `as_path` prints the path to its materialized file,
    /// which outlives this process; every other secret prints its value. A
    /// value from the manifest's `default`, a `generate` config, or a
    /// composition prints like any other.
    ///
    /// Library callers want [`Self::resolve_named`], which returns the value
    /// instead of printing it and distinguishes an undeclared name from a
    /// declared secret with no value.
    ///
    /// # Errors
    ///
    /// [`SecretSpecError::SecretNotFound`] when the name is not declared on the
    /// active profile and scope, or is declared but produced no value. Provider
    /// and configuration failures surface as their own errors.
    pub fn get(&self, name: &str) -> Result<()> {
        // A printer over the library API, so the CLI's single-secret read makes
        // exactly the resolution decisions `resolve_named` makes (and audits
        // them once, there) rather than maintaining a second single-secret path.
        match self.resolve_named_within(name, Surface::WholeProfile)? {
            NamedResolution::Resolved(secret) => {
                // `as_path` secrets are materialized and their temp file
                // persisted during resolution, so a printed path is still valid
                // after this process exits.
                let rendered = secret
                    .value
                    .or(secret.path)
                    .expect("a resolved secret carries either a value or a path");
                println!("{rendered}");
                Ok(())
            }
            // Undeclared and missing are one error for the CLI: either way there
            // is nothing to print. Both are already audited by `resolve_named`.
            NamedResolution::Missing { .. } | NamedResolution::Undeclared => {
                Err(SecretSpecError::SecretNotFound(name.to_string()))
            }
        }
    }

    /// Ensures all required secrets are present, optionally prompting for missing ones
    ///
    /// This method validates all secrets and, in interactive mode, prompts the
    /// user to provide values for any missing required secrets.
    ///
    /// # Arguments
    ///
    /// * `provider_arg` - Optional provider to use
    /// * `profile` - Optional profile to use
    /// * `interactive` - Whether to prompt for missing secrets
    ///
    /// # Returns
    ///
    /// A `ValidatedSecrets` with the final state of all secrets
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Required secrets are missing and interactive mode is disabled
    /// - Storage operations fail
    pub fn ensure_secrets(
        &self,
        provider_arg: Option<String>,
        profile: Option<String>,
        interactive: bool,
    ) -> Result<ValidatedSecrets> {
        let profile_display = self.resolve_profile_name(profile.as_deref());

        // First validate to see what's missing. Use the non-auditing variant:
        // the caller that owns this operation (`check`, `run`) records its own
        // audit event, so re-validating here must not emit another `Check`. This
        // is the value-injecting path (`run`), so it materializes fully.
        let validation_result = self.validate_audited(false, Materialize::Values)?;

        match validation_result {
            Ok(valid_secrets) => Ok(valid_secrets),
            Err(validation_errors) => {
                // If we're in interactive mode and have missing required secrets, prompt for them
                if interactive && !validation_errors.missing_required.is_empty() {
                    if !io::stdin().is_terminal() {
                        return Err(validation_failure(validation_errors));
                    }

                    let missing =
                        self.scoped_promptable_missing(&validation_errors, &profile_display)?;
                    if missing.is_empty() {
                        return Err(validation_failure(validation_errors));
                    }
                    // Extraction cannot be inverted into a containing document.
                    // Reject the whole interactive write pass before prompting
                    // for (and possibly storing) any earlier secret.
                    if let Some(name) = missing.iter().find(|name| {
                        self.resolve_secret_config(name, Some(&profile_display))
                            .is_some_and(|secret| secret.extract.is_some())
                    }) {
                        return Err(SecretSpecError::ExtractedSecretReadOnly(name.clone()));
                    }
                    let total = missing.len();
                    // Name the provider without constructing it: this value is
                    // display-only (each prompted write builds its own route's
                    // provider below), and construction now fetches provider
                    // credentials, so a display-only build could hard-error on
                    // a credential-backed default alias no missing secret routes to.
                    let default_backend_name = crate::provider::provider_display_name_for_spec(
                        &self.resolve_provider_spec(
                            self.default_provider_spec(provider_arg.as_deref())?,
                        ),
                    );

                    // List all missing secrets upfront
                    eprintln!(
                        "\n{} required {} missing in profile {} with provider {}:\n",
                        total,
                        if total == 1 {
                            "secret is"
                        } else {
                            "secrets are"
                        },
                        profile_display.bold(),
                        default_backend_name.bold(),
                    );
                    for secret_name in &missing {
                        let description = self
                            .resolve_secret_config(secret_name, Some(&profile_display))
                            .and_then(|c| c.description)
                            .unwrap_or_default();
                        if description.is_empty() {
                            eprintln!("  {} {}", "-".dimmed(), secret_name.bold());
                        } else {
                            eprintln!(
                                "  {} {} - {}",
                                "-".dimmed(),
                                secret_name.bold(),
                                description
                            );
                        }
                    }
                    eprintln!();

                    // Prompt for each missing secret. Each write goes through the
                    // plan's route and address, the same decisions `set` executes.
                    for (i, secret_name) in missing.iter().enumerate() {
                        if let Some(planned) = self.plan_secret(
                            secret_name,
                            &profile_display,
                            provider_arg.as_deref(),
                        )? {
                            let route = planned
                                .route
                                .as_ref()
                                .expect("prompted names are provider-backed leaves");
                            let backend =
                                self.write_provider_for_route(route, Some(&profile_display))?;
                            if let Err(error) =
                                self.preflight_write(&planned, &profile_display, backend.as_ref())
                            {
                                self.record_key_error(
                                    AuditAction::Set,
                                    &profile_display,
                                    secret_name,
                                    Some(backend.uri()),
                                    planned.reference(),
                                    &error,
                                );
                                return Err(error);
                            }

                            let prompt_msg =
                                format!("[{}/{}] Enter value for {}:", i + 1, total, secret_name,);
                            let prompt = inquire::Password::new(&prompt_msg).without_confirmation();

                            let value = SecretString::new(prompt.prompt()?.into());

                            let encoded_value = Self::encoded_for_storage(&planned, &value);
                            let stored_value = encoded_value.as_ref().unwrap_or(&value);
                            let address = self.address_for_spec(
                                &planned,
                                route.group_key(),
                                &self.config.project.name,
                                &profile_display,
                            )?;
                            let set_result = backend.set(address.as_address(), stored_value);
                            self.audit_write_result(
                                &set_result,
                                secret_name,
                                &profile_display,
                                Some(backend.uri()),
                                address.native(),
                                None,
                            );
                            set_result?;
                            self.sync_cache_after_write(
                                &planned,
                                route,
                                &profile_display,
                                stored_value,
                            );
                            eprintln!(
                                "{} Secret '{}' saved to {} (profile: {})",
                                "✓".green(),
                                secret_name,
                                backend.name(),
                                profile_display
                            );
                        }
                    }

                    eprintln!("\nAll required secrets have been set.");

                    // Re-validate to get the updated results
                    // Re-validate after prompting; still part of the same
                    // operation, so do not emit another `Check` event.
                    match self.validate_audited(false, Materialize::Values)? {
                        Ok(valid_secrets) => Ok(valid_secrets),
                        Err(still_errors) => Err(validation_failure(still_errors)),
                    }
                } else {
                    // Not interactive or no missing required secrets
                    Err(validation_failure(validation_errors))
                }
            }
        }
    }

    /// Checks the status of all secrets and optionally prompts for missing required ones
    ///
    /// This method displays the status of all secrets defined in the specification,
    /// showing which are present, missing, or using defaults. Unless `no_prompt` is set,
    /// it then prompts the user to provide values for any missing required secrets.
    ///
    /// # Arguments
    ///
    /// * `no_prompt` - If true, don't prompt for missing secrets and return an error instead
    ///
    /// # Returns
    ///
    /// A `ValidatedSecrets` if all required secrets are present
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The provider cannot be initialized
    /// - Storage operations fail
    /// - Required secrets are missing (when `no_prompt` is true)
    ///
    /// # Example
    ///
    /// ```no_run
    /// use secretspec::Secrets;
    ///
    /// let mut spec = Secrets::load().unwrap();
    /// let validated = spec.check(false).unwrap();
    /// ```
    pub fn check(&self, no_prompt: bool) -> Result<ValidatedSecrets> {
        self.check_with_writer(no_prompt, &mut io::stderr())
    }

    /// Checks the status of all secrets, writing the human-readable report to `out`.
    ///
    /// This is the writer-based counterpart to [`Self::check`]. Prompts and
    /// diagnostics still use their standard streams; only the report containing
    /// the header, per-secret statuses, constraint violations, and summary is
    /// written to `out`.
    pub fn check_with_writer(
        &self,
        no_prompt: bool,
        out: &mut dyn Write,
    ) -> Result<ValidatedSecrets> {
        self.ensure_reason_for(AuditAction::Check, None)?;
        let profile_display = self.resolve_profile_name(None);

        writeln!(
            out,
            "Checking secrets in {} (profile: {})...\n",
            self.config.project.name.bold(),
            profile_display.cyan()
        )?;

        // Validate and display results
        // The read is audited inside `validate()`, so no bulk event here.
        match self.validate()? {
            Ok(valid) => {
                self.display_validation_success(out, &valid)?;
                // All secrets present - return early without re-validating
                Ok(valid)
            }
            Err(errors) => {
                self.display_validation_errors(out, &errors)?;
                // Missing secrets - prompt if interactive (and not no_prompt) and re-validate
                self.ensure_secrets(None, None, !no_prompt)
            }
        }
    }

    /// Display validation success results
    fn display_validation_success(
        &self,
        out: &mut dyn Write,
        valid: &ValidatedSecrets,
    ) -> Result<()> {
        let mut found_count = 0;
        let mut optional_count = 0;
        let default_names = valid
            .with_defaults
            .iter()
            .map(|(name, _)| name)
            .collect::<HashSet<_>>();
        let missing_optional: HashSet<&String> = valid.missing_optional.iter().collect();

        for (name, config) in &self.effective_secrets(&valid.resolved.profile)? {
            let label = format_secret_label(name, config.description.as_deref());
            if missing_optional.contains(&name) {
                optional_count += 1;
                writeln!(out, "{} {} {}", "â—‹".blue(), label, "(optional)".blue())?;
            } else if config.default.is_some() && default_names.contains(&name) {
                found_count += 1;
                writeln!(
                    out,
                    "{} {} {}",
                    "â—‹".yellow(),
                    label,
                    "(has default)".yellow()
                )?;
            } else {
                found_count += 1;
                writeln!(out, "{} {}", "✓".green(), label)?;
            }
        }

        writeln!(
            out,
            "\n{}",
            Self::format_summary(found_count, 0, optional_count)
        )?;

        Ok(())
    }

    /// Display validation error results
    fn display_validation_errors(
        &self,
        out: &mut dyn Write,
        errors: &ValidationErrors,
    ) -> Result<()> {
        let mut found_count = 0;
        let mut missing_count = 0;
        let mut optional_count = 0;
        let default_names = errors
            .with_defaults
            .iter()
            .map(|(name, _)| name)
            .collect::<HashSet<_>>();

        for (name, config) in &self.effective_secrets(&errors.profile)? {
            let label = format_secret_label(name, config.description.as_deref());
            if errors.missing_required.contains(name) {
                missing_count += 1;
                writeln!(out, "{} {} {}", "✗".red(), label, "(required)".red())?;
            } else if errors.missing_optional.contains(name) {
                optional_count += 1;
                writeln!(out, "{} {} {}", "â—‹".blue(), label, "(optional)".blue())?;
            } else {
                found_count += 1;
                if default_names.contains(name) {
                    writeln!(
                        out,
                        "{} {} {}",
                        "â—‹".yellow(),
                        label,
                        "(has default)".yellow()
                    )?;
                } else {
                    writeln!(out, "{} {}", "✓".green(), label)?;
                }
            }
        }

        writeln!(
            out,
            "\n{}",
            Self::format_summary(found_count, missing_count, optional_count)
        )?;
        for violation in &errors.constraint_violations {
            writeln!(out, "{} {}", "Constraint failed:".red().bold(), violation)?;
        }

        Ok(())
    }

    /// Build the trailing "Summary: X found, Y missing[, Z optional]" line.
    /// The `optional` segment is appended only when at least one optional
    /// secret is unset, so the all-set output keeps its previous two-segment
    /// form.
    pub(crate) fn format_summary(found: usize, missing: usize, optional: usize) -> String {
        if optional > 0 {
            format!(
                "Summary: {} found, {} missing, {} optional",
                found.to_string().green(),
                missing.to_string().red(),
                optional.to_string().blue()
            )
        } else {
            format!(
                "Summary: {} found, {} missing",
                found.to_string().green(),
                missing.to_string().red()
            )
        }
    }

    /// Finds effective leaf aliases whose provider shares a storage container
    /// with a literal import source but whose active address mapping reaches a
    /// different entry for at least one imported secret.
    ///
    /// This is diagnostic only. A literal keeps convention semantics even when
    /// exactly one alias matches, because aliases are identities and multiple
    /// aliases may intentionally map one container in different ways. Candidate
    /// providers are built without resolving their declared credentials so a
    /// warning can never touch credential stores or break an otherwise valid
    /// literal import.
    fn literal_import_alias_divergences(
        &self,
        source_spec: &str,
        source_provider: &dyn ProviderTrait,
        planned: &[PlannedSecret],
        profile: &str,
    ) -> Vec<ImportAliasDivergence> {
        if self.lookup_provider_alias_entry(source_spec).is_some() {
            return Vec::new();
        }

        self.known_provider_aliases()
            .into_iter()
            .filter_map(|alias_name| {
                let alias = self.lookup_provider_alias_entry(&alias_name)?;
                if alias.is_cached() {
                    return None;
                }

                let has_active_mapping = alias.reference_template().is_some()
                    || planned.iter().any(|secret| {
                        secret
                            .config()
                            .refs
                            .as_ref()
                            .is_some_and(|refs| refs.contains_key(&alias_name))
                    });
                if !has_active_mapping {
                    return None;
                }

                // Identity comparison needs only provider configuration. Do not
                // resolve this alias's credentials merely to produce a warning.
                let alias_provider = self.build_source_provider(&alias_name).ok()?;
                if !same_storage_container(source_provider, alias_provider.as_ref()) {
                    return None;
                }

                let affected_secrets = planned
                    .iter()
                    .filter_map(|secret| {
                        let literal_address = self
                            .address_for_spec(
                                secret,
                                Some(source_spec),
                                &self.config.project.name,
                                profile,
                            )
                            .ok()?;
                        let alias_address = self
                            .address_for_spec(
                                secret,
                                Some(&alias_name),
                                &self.config.project.name,
                                profile,
                            )
                            .ok()?;

                        let differs = match source_provider.same_entries(
                            literal_address.as_address(),
                            alias_provider.as_ref(),
                            alias_address.as_address(),
                        ) {
                            Ok(same) => !same,
                            // An alias address that the provider cannot compare
                            // still represents behavior the literal bypasses.
                            // Keep the warning non-fatal and suppress it only if
                            // both address models are structurally identical.
                            Err(_) => literal_address != alias_address,
                        };
                        differs.then(|| secret.name.clone())
                    })
                    .collect::<Vec<_>>();

                (!affected_secrets.is_empty()).then_some(ImportAliasDivergence {
                    alias: alias_name,
                    affected_secrets,
                })
            })
            .collect()
    }

    fn warn_literal_import_alias_divergences(
        source_uri: &str,
        divergences: &[ImportAliasDivergence],
    ) {
        for divergence in divergences {
            let count = divergence.affected_secrets.len();
            let noun = if count == 1 { "secret" } else { "secrets" };
            let example = &divergence.affected_secrets[0];
            eprintln!(
                "{} import source {} uses convention naming, but provider alias {} addresses {} {} differently in the same storage container (for example, {}). Use that alias as the source if its alias-specific coordinates are intended; keep the literal source to use convention-named entries.",
                "warning:".yellow(),
                source_uri.bold(),
                format!("'{}'", divergence.alias).bold(),
                count,
                noun,
                example.bold(),
            );
        }
    }

    /// Imports secrets from one provider to another
    ///
    /// This method copies all secrets defined in the specification from the
    /// source provider to the default provider configured in the global settings.
    ///
    /// # Arguments
    ///
    /// * `from_provider` - The provider specification to import from
    ///
    /// # Returns
    ///
    /// `Ok(())` if the import completes (even if some secrets were not found)
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The source provider cannot be initialized
    /// - The target provider cannot be initialized
    /// - Storage operations fail
    ///
    /// # Example
    ///
    /// ```no_run
    /// use secretspec::Secrets;
    ///
    /// let spec = Secrets::load().unwrap();
    /// spec.import("dotenv://.env.production").unwrap();
    /// ```
    pub fn import(&self, from_provider: &str) -> Result<()> {
        self.import_internal(from_provider, false)
    }

    /// Imports secrets and deletes each source value only after the destination
    /// is verified to contain the same value. Available since SecretSpec 0.18.
    ///
    /// A destination value that already differs is never overwritten and its
    /// source is retained. The source and destination must be different stores.
    pub fn import_with_delete_source(&self, from_provider: &str) -> Result<()> {
        self.import_internal(from_provider, true)
    }

    fn import_internal(&self, from_provider: &str, delete_source: bool) -> Result<()> {
        self.ensure_reason_for(AuditAction::Import, None)?;

        let mut plan = ImportPlan::new(
            self,
            from_provider,
            self.resolve_profile_name(None),
            delete_source,
        );
        if let Err(error) = plan.run() {
            self.record(
                AuditAction::Import,
                &plan.profile,
                AuditOutcome::Error,
                AuditFields {
                    keys: &plan.read_names,
                    provider_uri: plan.source_uri.clone(),
                    error_kind: Some(error.kind()),
                    ..Default::default()
                },
            );
            return Err(error);
        }

        eprintln!(
            "\nSummary: {} imported, {} already exists, {} not found in source",
            plan.summary.imported.to_string().green(),
            plan.summary.already_exists.to_string().yellow(),
            plan.summary.not_found.to_string().red()
        );
        if delete_source {
            eprintln!(
                "Source cleanup: {} deleted, {} retained because the target differs",
                plan.summary.deleted_from_source.to_string().green(),
                plan.summary.kept_in_source.to_string().yellow()
            );
        }

        if plan.summary.imported > 0 {
            eprintln!(
                "\n{} Successfully imported {} secrets from {}",
                "✓".green(),
                plan.summary.imported,
                plan.source_display
                    .as_deref()
                    .unwrap_or("configured provider"),
            );
        }

        self.record(
            AuditAction::Import,
            &plan.profile,
            plan.summary.audit_outcome(),
            AuditFields {
                keys: &plan.read_names,
                provider_uri: plan.source_uri.clone(),
                ..Default::default()
            },
        );

        Ok(())
    }

    /// Whether a generated value for this secret would outlive the resolution
    /// that mints it, i.e. whether its write route actually stores it.
    ///
    /// Capability inspection only: `generated_value_persistence` is documented
    /// as pure, so this asks the store nothing over the wire and mints nothing.
    /// A store that cannot even be built cannot be shown to be ephemeral, so it
    /// counts as storing — the answer that reports a required secret as missing
    /// rather than promising a value that may never materialize.
    fn generated_value_is_stored(&self, planned: &PlannedSecret, profile_name: &str) -> bool {
        planned
            .route
            .as_ref()
            .and_then(|route| {
                self.write_provider_for_route(route, Some(profile_name))
                    .ok()
            })
            .is_none_or(|backend| {
                backend.generated_value_persistence() == ProducedValuePersistence::Persist
            })
    }

    /// Attempts to generate a secret if it has generation config.
    ///
    /// Returns `Ok(Some(value))` if generation succeeded,
    /// `Ok(None)` if generation is not configured,
    /// or `Err` if generation was configured but failed.
    fn try_generate_secret(
        &self,
        planned: &PlannedSecret,
        profile_name: &str,
    ) -> Result<Option<SecretString>> {
        let name = planned.name.as_str();
        let gen_config = match &planned.config().generate {
            Some(config) if config.is_enabled() => config,
            _ => return Ok(None),
        };
        if planned.extract().is_some() {
            return Err(SecretSpecError::ExtractedSecretReadOnly(
                planned.name.clone(),
            ));
        }

        let secret_type = match &planned.config().secret_type {
            Some(t) => t.as_str(),
            None => {
                return Err(SecretSpecError::GenerationFailed(format!(
                    "Secret '{}' has generate config but no type",
                    name
                )));
            }
        };

        let value = crate::generator::generate(secret_type, gen_config)?;

        // Store the generated value at the plan's address, through the plan's
        // write route: the same decisions every other write path executes.
        let route = planned
            .route
            .as_ref()
            .expect("a generating secret is provider-backed");
        let address = self.address_for_spec(
            planned,
            route.group_key(),
            &self.config.project.name,
            profile_name,
        )?;
        let addr = address.as_address();
        let backend = self.write_provider_for_route(route, Some(profile_name))?;

        if backend.generated_value_persistence() == ProducedValuePersistence::Ephemeral {
            eprintln!(
                "{} {} - generated for this resolution without provider storage (profile: {})",
                "✓".green(),
                name,
                profile_name
            );
            return Ok(Some(value));
        }

        // The provider states why a write is refused; wrapping it here would
        // only nest a second "Provider operation failed" prefix.
        backend.check_writable(addr)?;
        let encoded_value = Self::encoded_for_storage(planned, &value);
        let stored_value = encoded_value.as_ref().unwrap_or(&value);
        let set_result = backend.set(addr, stored_value);
        // Generating a secret writes a brand-new value to the provider; record it
        // like any other write so the audit log captures every stored secret.
        self.audit_write_result(
            &set_result,
            name,
            profile_name,
            Some(backend.uri()),
            address.native(),
            None,
        );
        set_result?;
        self.sync_cache_after_write(
            planned,
            planned
                .route
                .as_ref()
                .expect("a generating secret is provider-backed"),
            profile_name,
            stored_value,
        );

        eprintln!(
            "{} {} - generated and saved to {} (profile: {})",
            "✓".green(),
            name,
            backend.name(),
            profile_name
        );

        Ok(Some(value))
    }

    /// Reads one missing value from the controlling terminal during `run`.
    /// Inquire's crossterm backend opens `/dev/tty` on Unix (and the console
    /// input handle on Windows) when stdin is redirected, so the child retains
    /// its original stdin stream. Persistence is deliberately handled by
    /// [`Self::try_prompt_secret`], after this input-only step succeeds.
    fn prompt_run_secret(&self, name: &str, profile: &str) -> Result<SecretString> {
        let value = if let Some(reader) = &self.prompt_reader {
            reader(name, profile)?
        } else {
            let message = format!("Enter value for {name} (profile: {profile}):");
            let entered = inquire::Password::new(&message)
                .without_confirmation()
                .prompt()
                .map_err(|error| match error {
                    inquire::InquireError::NotTTY | inquire::InquireError::IO(_) => {
                        SecretSpecError::PromptUnavailable(name.to_string())
                    }
                    other => SecretSpecError::InquireError(other),
                })?;
            SecretString::new(entered.into())
        };

        if value.expose_secret().is_empty() {
            return Err(SecretSpecError::PromptValueEmpty(name.to_string()));
        }
        Ok(value)
    }

    /// Acquires a missing value for `prompt = true` and applies the primary
    /// provider's persistence policy. Storage providers persist by default,
    /// making the prompt a first-use provisioning step; explicitly ephemeral
    /// providers such as `null` return the answer only to this `run`.
    fn try_prompt_secret(
        &self,
        planned: &PlannedSecret,
        profile_name: &str,
    ) -> Result<SecretString> {
        let name = planned.name.as_str();
        let route = planned
            .route
            .as_ref()
            .expect("a prompted secret is provider-backed");
        let address = self.address_for_spec(
            planned,
            route.group_key(),
            &self.config.project.name,
            profile_name,
        )?;
        let addr = address.as_address();
        let backend = self.write_provider_for_route(route, Some(profile_name))?;
        let persistence = backend.prompted_value_persistence();

        // A durable answer is a write. Resolve and preview the exact target,
        // and reject a read-only destination, before asking the operator for a
        // value. Ephemeral providers explicitly bypass the write path.
        if persistence == ProducedValuePersistence::Persist {
            self.preflight_write(planned, profile_name, backend.as_ref())?;
        }

        let value = self.prompt_run_secret(name, profile_name)?;
        if persistence == ProducedValuePersistence::Ephemeral {
            eprintln!(
                "{} {} - entered for this run without provider storage (profile: {})",
                "✓".green(),
                name,
                profile_name
            );
            return Ok(value);
        }

        let encoded_value = Self::encoded_for_storage(planned, &value);
        let stored_value = encoded_value.as_ref().unwrap_or(&value);
        let set_result = backend.set(addr, stored_value);
        self.audit_write_result(
            &set_result,
            name,
            profile_name,
            Some(backend.uri()),
            address.native(),
            None,
        );
        set_result?;
        self.sync_cache_after_write(planned, route, profile_name, stored_value);

        eprintln!(
            "{} {} - entered and saved to {} (profile: {})",
            "✓".green(),
            name,
            backend.name(),
            profile_name
        );
        Ok(value)
    }

    /// Writes secret bytes to a temporary file and returns the file handle and path
    ///
    /// # Arguments
    ///
    /// * `secret` - The secret bytes to write
    ///
    /// # Returns
    ///
    /// A tuple containing the temporary file handle and the path as a string
    ///
    /// # Errors
    ///
    /// Returns an error if the temporary file cannot be created or written to
    fn write_secret_to_temp_file(
        &self,
        secret: &[u8],
    ) -> Result<(tempfile::NamedTempFile, String)> {
        use std::io::Write;

        let mut temp_file = tempfile::NamedTempFile::new().map_err(SecretSpecError::Io)?;

        temp_file.write_all(secret).map_err(SecretSpecError::Io)?;

        // Flush to ensure the data is written
        temp_file.flush().map_err(SecretSpecError::Io)?;

        // Set restrictive permissions (0o400) so only the owner can read
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = temp_file
                .as_file()
                .metadata()
                .map_err(SecretSpecError::Io)?
                .permissions();
            perms.set_mode(0o400);
            temp_file
                .as_file()
                .set_permissions(perms)
                .map_err(SecretSpecError::Io)?;
        }

        // Get the path as a string
        let path_str = temp_file
            .path()
            .to_str()
            .ok_or_else(|| {
                SecretSpecError::Io(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "Temporary file path is not valid UTF-8",
                ))
            })?
            .to_string();

        Ok((temp_file, path_str))
    }

    /// Validates all secrets in the specification
    ///
    /// This method checks all secrets defined in the current profile (and default
    /// profile if different) and returns detailed information about their status.
    ///
    /// Uses batch fetching when possible to improve performance with providers
    /// that have high latency (like 1Password).
    ///
    /// # Returns
    ///
    /// A `ValidatedSecrets` containing the status of all secrets
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The provider cannot be initialized
    /// - The specified profile doesn't exist
    /// - Storage operations fail
    ///
    /// # Example
    ///
    /// ```no_run
    /// use secretspec::Secrets;
    ///
    /// let mut spec = Secrets::load().unwrap();
    /// let result = spec.validate().unwrap();
    /// if let Ok(validated) = result {
    ///     println!("All required secrets are present!");
    /// }
    /// ```
    ///
    /// This is the public read/resolution entry point — used directly by the SDK
    /// and by `secretspec-derive`-generated code — so it records exactly one
    /// `Check` audit event per call.
    pub fn validate(&self) -> Result<std::result::Result<ValidatedSecrets, ValidationErrors>> {
        self.validate_audited(true, Materialize::Values)
    }

    /// Resolve every declared secret into a value-carrying [`ResolveResponse`],
    /// the authoritative output other-language SDKs consume over the C ABI.
    ///
    /// Unlike [`Self::validate`], the returned payload **carries secret
    /// values** (or, for `as_path` secrets, the path to a persisted temp file).
    /// Treat its bytes as sensitive. When a required secret is missing the
    /// resolution failed: `secrets` is empty and `missing_required` is
    /// populated, mirroring the derive crate's `load()`.
    ///
    /// `as_path` temp files are persisted so the returned paths stay valid for
    /// the caller; this is a one-shot boundary and the caller owns their
    /// lifetime thereafter.
    pub fn resolve(&self) -> Result<ResolveResponse> {
        self.resolve_impl(true)
    }

    /// Like [`Self::resolve`], but value-free and side-effect-free: every
    /// `value`/`path` in the response is `None`, no `as_path` temp file is ever
    /// written, and no missing generatable secret is minted or stored. Structure
    /// and provenance (`as_path`, `source`, `source_provider`,
    /// `missing_optional`) are still populated. This backs the `no_values`
    /// request path, so a policy/preflight consumer gets the resolve shape
    /// without persisting a secret to disk or mutating a provider. Resolution
    /// still queries providers so provenance can be reported — a value may
    /// transit memory transiently to learn whether it is present — but nothing
    /// is materialized; a missing required secret still fails the same way as
    /// [`Self::resolve`]. For a value-free view that tolerates missing required
    /// secrets, use [`Self::report`].
    pub fn resolve_without_values(&self) -> Result<ResolveResponse> {
        self.resolve_impl(false)
    }

    /// Resolve one declared secret by name.
    ///
    /// [`Self::resolve`] answers "can this whole profile be satisfied", which is
    /// the wrong question for a consumer that needs a single secret: an
    /// unrelated missing required secret fails the call and yields nothing, even
    /// though the requested secret is sitting there. This resolves only `name`
    /// and the composition inputs it derives from, so no other declaration can
    /// fail it, and it separates the outcomes a batch resolve conflates — see
    /// [`NamedResolution`].
    ///
    /// The active profile and scope both apply. A secret the scope hides is
    /// reported as [`NamedResolution::Undeclared`]: it is not on the surface
    /// this session resolves, and reporting it as merely missing would leak that
    /// the scope hides it. Genuine provider and configuration failures (an
    /// undefined alias, an unreachable vault) stay errors instead of collapsing
    /// into a missing value.
    ///
    /// Whole-profile presence constraints (`at_least_one`, `exactly_one`) are
    /// not evaluated, matching the CLI's single-secret `get`: whether a group is
    /// satisfied is a property of the profile, and this read deliberately never
    /// looks at the rest of it.
    ///
    /// Like [`Self::resolve`], this carries the value, mints a generatable
    /// secret, and persists an `as_path` temp file so the returned path outlives
    /// the call. Treat the payload as sensitive.
    ///
    /// Available since SecretSpec 0.19.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use secretspec::{NamedResolution, Secrets};
    ///
    /// let spec = Secrets::load().unwrap();
    /// match spec.resolve_named("DATABASE_URL").unwrap() {
    ///     NamedResolution::Resolved(secret) => println!("got {:?}", secret.source),
    ///     NamedResolution::Missing { required } => println!("missing (required: {required})"),
    ///     NamedResolution::Undeclared => println!("not declared in this profile"),
    /// }
    /// ```
    pub fn resolve_named(&self, name: &str) -> Result<NamedResolution> {
        self.resolve_named_within(name, Surface::Scoped)
    }

    /// Shared core of [`Self::resolve_named`] and [`Self::get`].
    ///
    /// They differ only in which surface decides that a name exists: the SDK
    /// resolves what the session exposes (a scope narrows it), while the CLI's
    /// `get` names one secret and has no `--scope`, so an ambient or configured
    /// scope must not hide a secret from it.
    fn resolve_named_within(&self, name: &str, surface: Surface) -> Result<NamedResolution> {
        self.ensure_reason_for(AuditAction::Get, Some(name))?;
        let profile_name = self.resolve_profile_name(None);

        // Decide whether this surface offers the name at all, before any
        // provider is contacted.
        let visible = match surface.names(self, &profile_name) {
            Ok(visible) => visible,
            Err(err) => {
                self.record_key_error(AuditAction::Get, &profile_name, name, None, None, &err);
                return Err(err);
            }
        };
        if !visible.iter().any(|declared| declared == name) {
            // An attempted read of a name this surface does not offer is still
            // an attempted read, and is audited as one (matching how `set`
            // records an undefined secret). No provider can be attributed.
            let err = SecretSpecError::SecretNotFound(name.to_string());
            self.record_key_error(AuditAction::Get, &profile_name, name, None, None, &err);
            return Ok(NamedResolution::Undeclared);
        }

        // The target plus its transitive composition inputs: the same
        // least-access plan `get` builds, so an unrelated required secret is
        // never read and can never fail this call.
        let names = self.composed_dependency_names(name, &profile_name);
        let plan = match self.build_plan_from_names(profile_name.clone(), names) {
            Ok(plan) => plan,
            Err(err) => {
                self.record_key_error(AuditAction::Get, &profile_name, name, None, None, &err);
                return Err(err);
            }
        };
        // No output filter: the dependency closure has to resolve, and a filter
        // would additionally enable the whole-profile constraint checks that a
        // single-secret read does not own.
        let mut read_addresses = HashMap::new();
        let outcome =
            match self.execute_plan(&plan, Materialize::Values, None, Some(&mut read_addresses)) {
                Ok(outcome) => outcome,
                Err(err) => {
                    let reference = read_addresses.get(name);
                    self.record_key_error(
                        AuditAction::Get,
                        &profile_name,
                        name,
                        None,
                        reference,
                        &err,
                    );
                    return Err(err);
                }
            };
        // Exactly the coordinates the read reached, never the declared ones: an
        // alias `ref` template resolves to a different address per provider, and
        // a read served from cache addressed no authoritative store at all.
        let reference = read_addresses.get(name);

        match outcome {
            Ok(mut validated) => {
                // Cloned so the entry outlives the `&mut` borrow that persisting
                // the temp files needs.
                let entry = validated
                    .resolution
                    .iter()
                    .find(|entry| entry.name == name)
                    .expect("the planned target always has a resolution entry")
                    .clone();
                if entry.status != ResolutionStatus::Resolved {
                    self.record(
                        AuditAction::Get,
                        &profile_name,
                        AuditOutcome::Missing,
                        AuditFields {
                            key: Some(name),
                            reference,
                            ..Default::default()
                        },
                    );
                    return Ok(NamedResolution::Missing {
                        required: entry.required,
                    });
                }

                // Persist as_path temp files so the returned path stays valid
                // for the caller, exactly as `resolve` does.
                validated.keep_temp_files()?;
                let raw = validated
                    .resolved
                    .secrets
                    .get(name)
                    .expect("a Resolved entry always has a value")
                    .expose_secret()
                    .to_string();
                let (value, path) = if entry.as_path {
                    (None, Some(raw))
                } else {
                    (Some(raw), None)
                };

                self.record(
                    AuditAction::Get,
                    &profile_name,
                    if entry.default_applied {
                        AuditOutcome::Default
                    } else {
                        AuditOutcome::Found
                    },
                    AuditFields {
                        key: Some(name),
                        provider_uri: entry.source_provider.clone(),
                        reference,
                        ..Default::default()
                    },
                );
                Ok(NamedResolution::Resolved(ResolvedSecret {
                    value,
                    path,
                    as_path: entry.as_path,
                    source: resolved_source(&entry),
                    source_provider: entry.source_provider,
                }))
            }
            Err(errors) => {
                // Constraints are skipped for this partial plan, so a violation
                // here would mean the resolver changed its mind about that;
                // surface it rather than reporting a missing value.
                if !errors.constraint_violations.is_empty() {
                    let err = SecretSpecError::ValidationFailed(Box::new(errors));
                    self.record_key_error(
                        AuditAction::Get,
                        &profile_name,
                        name,
                        None,
                        reference,
                        &err,
                    );
                    return Err(err);
                }
                // The target is missing; a composed target whose input is
                // missing reports against the target, which is what the caller
                // asked about.
                let required = errors
                    .resolution
                    .iter()
                    .find(|entry| entry.name == name)
                    .is_none_or(|entry| entry.required);
                self.record(
                    AuditAction::Get,
                    &profile_name,
                    AuditOutcome::Missing,
                    AuditFields {
                        key: Some(name),
                        reference,
                        ..Default::default()
                    },
                );
                Ok(NamedResolution::Missing { required })
            }
        }
    }

    /// Shared core of [`Self::resolve`]/[`Self::resolve_without_values`].
    /// `include_values` gates whether resolved secret values are copied into the
    /// response and, in turn, whether the underlying pass mints generated
    /// secrets and writes `as_path` temp files at all.
    fn resolve_impl(&self, include_values: bool) -> Result<ResolveResponse> {
        let materialize = if include_values {
            Materialize::Values
        } else {
            Materialize::None
        };
        match self.validate_audited(true, materialize)? {
            Ok(mut validated) => {
                // Persist as_path temp files so returned paths outlive this call.
                // Only the full pass writes any: under `Materialize::None` no
                // temp file is ever created, so there is nothing to persist and
                // nothing is left on disk.
                if include_values {
                    validated.keep_temp_files()?;
                }

                let mut secrets = BTreeMap::new();
                for entry in &validated.resolution {
                    if entry.status != ResolutionStatus::Resolved {
                        continue;
                    }
                    let source = resolved_source(entry);
                    // Only copy the secret value out when the caller wants it;
                    // otherwise the bytes never enter the response.
                    let (value, path) = if !include_values {
                        (None, None)
                    } else {
                        let raw = validated
                            .resolved
                            .secrets
                            .get(&entry.name)
                            .expect("a Resolved entry always has a value")
                            .expose_secret()
                            .to_string();
                        if entry.as_path {
                            (None, Some(raw))
                        } else {
                            (Some(raw), None)
                        }
                    };
                    secrets.insert(
                        entry.name.clone(),
                        ResolvedSecret {
                            value,
                            path,
                            as_path: entry.as_path,
                            source,
                            source_provider: entry.source_provider.clone(),
                        },
                    );
                }

                let mut missing_optional = validated.missing_optional.clone();
                missing_optional.sort();

                Ok(ResolveResponse {
                    schema_version: RESOLVE_SCHEMA_VERSION,
                    provider: validated.resolved.provider.clone(),
                    profile: validated.resolved.profile.clone(),
                    scope: self.resolve_scope_name(None),
                    secrets,
                    missing_required: Vec::new(),
                    missing_optional,
                })
            }
            Err(errors) => {
                if !errors.constraint_violations.is_empty() {
                    return Err(SecretSpecError::ValidationFailed(Box::new(errors)));
                }
                let mut missing_required = errors.missing_required.clone();
                missing_required.sort();
                let mut missing_optional = errors.missing_optional.clone();
                missing_optional.sort();
                Ok(ResolveResponse {
                    schema_version: RESOLVE_SCHEMA_VERSION,
                    provider: errors.provider.clone(),
                    profile: errors.profile.clone(),
                    scope: self.resolve_scope_name(None),
                    secrets: BTreeMap::new(),
                    missing_required,
                    missing_optional,
                })
            }
        }
    }

    /// Resolve every declared secret into a value-free [`ResolutionReport`]:
    /// per-secret status (resolved / missing-required / missing-optional) plus
    /// provenance, never a value. Unlike [`Self::resolve`], a missing required
    /// secret is reported as a `MissingRequired` status rather than failing the
    /// call, so this is the inventory/preflight view: it answers "what is
    /// declared and how would each secret resolve" even for a profile whose
    /// secrets the caller cannot fully provide. It is the same report the CLI
    /// surfaces as `check --json` / `check --explain`, exposed to the SDKs.
    ///
    /// This pass is value-free and side-effect-free: it never mints or stores a
    /// generatable secret and never writes an `as_path` temp file. A secret that
    /// *would* be generated on a real resolve is reported as resolved
    /// (`generated`) when generation is how its value is meant to appear — an
    /// optional secret, or a store that never retains a generated value. A
    /// required secret whose store keeps what it mints is reported
    /// `MissingRequired` until a pass actually provisions it, so this preflight
    /// never reports a value the store does not hold.
    pub fn report(&self) -> Result<ResolutionReport> {
        let mut report = match self.validate_audited(true, Materialize::None)? {
            Ok(validated) => validated.report(),
            Err(errors) => errors.report(),
        };
        // Surface the active scope so `check --json`/`--explain` shows the scoped
        // surface it resolved against; `None` (unscoped) is omitted from output.
        report.scope = self.resolve_scope_name(None);
        Ok(report)
    }

    /// Resolves all secrets. `emit_check` controls whether this pass records a
    /// `Check` audit event.
    ///
    /// Top-level reads ([`Self::validate`], `check`) pass `true`. Internal
    /// re-validations inside [`Self::ensure_secrets`] and the `run` resolver pass
    /// `false`, so one user action does not also emit a `Check`. The trade-off:
    /// a direct
    /// `ensure_secrets` call (rare; not the path `secretspec-derive` uses) does
    /// not emit a `Check` read event, though any writes it performs are audited.
    ///
    /// `materialize` gates value production, generated-secret persistence,
    /// `as_path` files, and run-only prompting for missing values.
    /// [`Materialize::None`] runs the same provider resolution without those
    /// effects; see [`Materialize`].
    fn validate_audited(
        &self,
        emit_check: bool,
        materialize: Materialize,
    ) -> Result<std::result::Result<ValidatedSecrets, ValidationErrors>> {
        // Enforce the reason policy. For the top-level read (`emit_check`) a denial
        // is itself audited; internal re-validations (emit_check=false) re-check the
        // gate silently, since the reason is already present by the time they run.
        if emit_check {
            self.ensure_reason_for(AuditAction::Check, None)?;
        } else {
            self.ensure_reason()?;
        }

        let profile_name = self.resolve_profile_name(None);
        // The *visible* set (scope ∩ profile, or the whole profile when no scope
        // is active) is what the action exposes and audits. Resolved once; its
        // sorted names are the audit keys, and — when unscoped — the plan's input
        // directly.
        let visible_result = self.resolve_profile_secret_names(Some(&profile_name));
        let visible: Vec<String> = visible_result.as_ref().ok().cloned().unwrap_or_default();

        // When a scope is active, resolution must additionally fetch the
        // composed-secret dependency closure of the visible set (an in-scope
        // `DATABASE_URL` may reference out-of-scope `DB_USER`/`DB_PASSWORD`), then
        // filter the output back to `visible` so those inputs resolve without
        // being exposed. Unscoped, the closure equals the whole profile, so the
        // worklist is just `visible` and nothing is filtered.
        // Unscoped, `visible` moves into the worklist rather than being cloned:
        // there is no filter to build from it afterwards.
        let scoped = self.resolve_scope_name(None).is_some();
        let (worklist, output_filter): (Vec<String>, Option<HashSet<String>>) = if scoped {
            let worklist = self.accessed_names(&profile_name, &visible);
            (worklist, Some(visible.into_iter().collect()))
        } else {
            (visible, None)
        };

        // Keys for the single read-audit event, computed before any planning can
        // fail (e.g. on an undefined alias) so a failed read is still attributed
        // to every secret it attempted; they stay empty only if the
        // profile/scope itself fails to resolve. This is the *accessed* set, not
        // the visible one: the audit answers "what was read from a provider",
        // and a hidden composition input is read even though it is never
        // exposed. Recording only the visible names would understate provider
        // access, which is the one thing the log exists to capture. Cloned only
        // when auditing is on, like the other event sites.
        let audit_keys: Vec<String> = if self.audit.is_some() {
            worklist.clone()
        } else {
            Vec::new()
        };

        // Decide the whole plan up front (pure, no I/O), then execute it. Each
        // step returns `Result`, so *any* error — an undefined alias, an
        // unsupported `ref` coordinate, a fallback-chain outage, a report-URI
        // failure — is captured in `result` and recorded as the single `Check`
        // event below rather than escaping unaudited. `record` is a no-op when
        // auditing is off.
        let result: Result<std::result::Result<ValidatedSecrets, ValidationErrors>> =
            visible_result
                .and_then(|_| self.build_plan_from_names(profile_name.clone(), worklist))
                .and_then(|plan| {
                    self.execute_plan(&plan, materialize, output_filter.as_ref(), None)
                });

        // Record exactly one `Check` event for the whole batch when this is a
        // top-level read, regardless of how the resolution exited — so a failed
        // attempt (bad alias, fallback-chain error, report-URI failure) is audited
        // too, not only success/missing. `record` is a no-op when auditing is off.
        if emit_check {
            let (outcome, error_kind) = match &result {
                Ok(Ok(_)) => (AuditOutcome::Found, None),
                Ok(Err(_)) => (AuditOutcome::Missing, None),
                Err(e) => (AuditOutcome::Error, Some(e.kind())),
            };
            self.record(
                AuditAction::Check,
                &profile_name,
                outcome,
                AuditFields {
                    keys: &audit_keys,
                    error_kind,
                    ..Default::default()
                },
            );
        }

        result
    }

    /// The target plus its transitive declared dependencies, sorted for a
    /// deterministic, least-access `get` plan.
    fn composed_dependency_names(&self, target: &str, profile_name: &str) -> Vec<String> {
        fn visit(
            name: &str,
            profile: &crate::compiled_spec::CompiledProfile,
            names: &mut HashSet<String>,
        ) {
            if !names.insert(name.to_string()) {
                return;
            }
            if let Some(template) = &profile.secrets[name].composition {
                for dependency in template.dependencies() {
                    visit(dependency, profile, names);
                }
            }
        }

        let profile = self
            .manifest
            .profile(profile_name)
            .expect("profile is validated before dependency planning");
        let mut names = HashSet::new();
        visit(target, profile, &mut names);
        let mut names: Vec<String> = names.into_iter().collect();
        names.sort();
        names
    }

    /// Replace missing derived nodes with the unresolved provider-backed leaves
    /// a user can actually set. This also permits an optional leaf to be
    /// prompted when a required composition depends on it.
    fn promptable_missing_names(
        &self,
        errors: &ValidationErrors,
        profile_name: &str,
    ) -> Vec<String> {
        let statuses: HashMap<&str, &ResolutionStatus> = errors
            .resolution
            .iter()
            .map(|entry| (entry.name.as_str(), &entry.status))
            .collect();
        let profile = self
            .manifest
            .profile(profile_name)
            .expect("profile is validated before prompting");

        fn visit(
            name: &str,
            profile: &crate::compiled_spec::CompiledProfile,
            statuses: &HashMap<&str, &ResolutionStatus>,
            promptable: &mut HashSet<String>,
        ) {
            let Some(template) = &profile.secrets[name].composition else {
                promptable.insert(name.to_string());
                return;
            };
            for dependency in template.dependencies() {
                if statuses.get(dependency.as_str()).copied() != Some(&ResolutionStatus::Resolved) {
                    visit(dependency, profile, statuses, promptable);
                }
            }
        }

        let mut promptable = HashSet::new();
        for name in &errors.missing_required {
            visit(name, profile, &statuses, &mut promptable);
        }
        let mut promptable: Vec<String> = promptable.into_iter().collect();
        promptable.sort();
        promptable
    }

    /// The secrets an interactive resolution may prompt the operator for: the
    /// promptable missing leaves ([`Self::promptable_missing_names`]), restricted
    /// to the visible set when a scope is active.
    ///
    /// The restriction is load-bearing. A missing out-of-scope composition
    /// dependency reaches `promptable_missing_names` because the visible-only
    /// resolution list makes its status look unresolved, so the raw set descends
    /// into hidden leaves. Prompting for those would disclose a hidden secret's
    /// name (and overwrite an already-present value on entry), breaking the scope
    /// guarantee. When a scope is active the operator may therefore be prompted
    /// only for secrets the scope itself exposes; unscoped, nothing is filtered.
    pub(crate) fn scoped_promptable_missing(
        &self,
        errors: &ValidationErrors,
        profile_name: &str,
    ) -> Result<Vec<String>> {
        let mut missing = self.promptable_missing_names(errors, profile_name);
        if self.resolve_scope_name(None).is_some() {
            let visible: HashSet<String> = self
                .resolve_profile_secret_names(Some(profile_name))?
                .into_iter()
                .collect();
            missing.retain(|name| visible.contains(name));
        }
        Ok(missing)
    }

    /// What a provider diagnostic may call `name` under `output_filter`.
    ///
    /// A scoped resolution fetches the composed-secret dependencies of the
    /// visible set and then drops them from the output, so the consumer never
    /// receives their values. Naming one in a warning would hand over exactly
    /// what the filter removed, which is why prompting is filtered the same way
    /// (see [`Self::scoped_promptable_missing`]). The real name is still what
    /// the read is addressed by; only the text a human sees changes.
    ///
    /// Unfiltered (no scope active), every name is its own label.
    ///
    /// This governs secretspec's own diagnostics. A provider's error string is
    /// authored by the provider and may still embed the address it searched.
    pub(crate) fn diagnostic_secret_name<'a>(
        name: &'a str,
        output_filter: Option<&HashSet<String>>,
    ) -> &'a str {
        match output_filter {
            Some(filter) if !filter.contains(name) => HIDDEN_SECRET_LABEL,
            _ => name,
        }
    }

    /// Rejects a `ref` routed at exactly one store that cannot honor its
    /// coordinates. Run per primary-store group right after the provider is
    /// built and before any fetch is spawned, so the definite error surfaces up
    /// front (and, in the value-free report, without a fetch at all).
    ///
    /// A single store is consulted when the route has no fallback — an
    /// override, a single-provider chain, or the default provider — so no other
    /// store could answer instead. A `ref` on a multi-store chain is
    /// deliberately skipped: its coordinates are validated per store as the
    /// chain is walked at read time, so a coordinate a later store cannot
    /// express never blocks a primary that can.
    ///
    /// [`Provider::resolve_coords`](crate::provider::Provider::resolve_coords)
    /// reads the provider's declared supported coordinates and does no I/O for
    /// a native address.
    fn check_single_store_ref_coords(
        &self,
        provider_spec: Option<&str>,
        group: &[&PlannedSecret],
        provider: &dyn ProviderTrait,
        project: &str,
        profile: &str,
    ) -> Result<()> {
        for planned in group {
            // Only the routes that consult exactly one store; a chain with a
            // fallback defers coordinate checking to per-store read time.
            // (Groups never contain a routeless composed secret.)
            let Some(route) = &planned.route else {
                continue;
            };
            if route.fallback_specs().is_some() {
                continue;
            }
            let address = self.address_for_spec(planned, provider_spec, project, profile)?;
            if address.native().is_some() {
                provider.resolve_coords(address.as_address())?;
            }
        }
        Ok(())
    }

    /// Executes a [`ResolutionPlan`]: the I/O half of resolution.
    ///
    /// Consumes the plan's already-decided groups, routes, and addresses — it
    /// derives nothing itself. It builds a provider per primary-store group,
    /// fetches the groups concurrently, then walks each secret: a primary hit is
    /// recorded; a miss falls through the secret's resolved fallback chain, then
    /// its compiled missing-value policy (prompt, generation, default, or
    /// absence). A
    /// primary that *errored* (rather than merely lacked the secret) with no
    /// fallback to try surfaces that error instead of a spurious "missing", so a
    /// machine consumer can tell an outage from an unprovisioned secret.
    ///
    /// `materialize` gates values and their effects. [`Materialize::Run`] also
    /// enables explicit missing-value prompts; [`Materialize::None`] skips all value
    /// production, provider/cache writes, and temp files.
    ///
    /// `read_addresses` collects the native coordinates each secret was actually
    /// read from, for the callers that audit a single secret. A cache hit
    /// contributes nothing: the authoritative coordinates were not consulted, so
    /// recording them would overstate what the read touched.
    fn execute_plan(
        &self,
        plan: &ResolutionPlan,
        materialize: Materialize,
        output_filter: Option<&HashSet<String>>,
        read_addresses: Option<&mut HashMap<String, NativeAddress>>,
    ) -> ExecutionResult {
        ResolutionExecution::new(self, plan, materialize, output_filter, read_addresses).run()
    }

    /// Runs a command with secrets injected as environment variables
    ///
    /// This method validates that all required secrets are present, then runs
    /// the specified command with all secrets injected as environment variables.
    ///
    /// # Arguments
    ///
    /// * `command` - The command and arguments to run
    /// * `provider_arg` - Optional provider to use
    /// * `profile` - Optional profile to use
    ///
    /// # Returns
    ///
    /// This method executes the command and exits with the command's exit code.
    /// It only returns an error if validation fails or the command cannot be started.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - No command is specified
    /// - Required secrets are missing
    /// - The command cannot be executed
    ///
    /// # Example
    ///
    /// ```no_run
    /// use secretspec::Secrets;
    ///
    /// let mut spec = Secrets::load().unwrap();
    /// spec.run(vec!["npm".to_string(), "start".to_string()]).unwrap();
    /// ```
    pub fn run(&self, command: Vec<String>) -> Result<()> {
        self.ensure_reason_for(AuditAction::Run, None)?;
        let exit_code = self.run_command(command)?;
        std::process::exit(exit_code);
    }

    /// Runs a command with secrets injected and returns its exit code.
    ///
    /// Splitting this out from [`Self::run`] ensures that any temporary files
    /// backing `as_path` secrets are dropped (and removed from disk) before
    /// `std::process::exit` is called — `exit` does not run destructors.
    pub(crate) fn run_command(&self, command: Vec<String>) -> Result<i32> {
        if command.is_empty() {
            return Err(SecretSpecError::Io(io::Error::new(
                io::ErrorKind::InvalidInput,
                "No command specified. Usage: secretspec run -- <command> [args...]",
            )));
        }

        // Resolve all secrets for this invocation. `Materialize::Run` is the
        // only mode allowed to ask for an explicitly `prompt = true` value;
        // the prompt backend uses the controlling terminal and leaves the
        // child's inherited stdin untouched.
        // `validation_result` owns the temp files for `as_path` secrets and
        // must stay alive until the child process has terminated.
        let resolution = self
            .validate_audited(false, Materialize::Run)
            .and_then(|result| result.map_err(validation_failure));
        let validation_result = match resolution {
            Ok(v) => v,
            Err(e) => {
                // Record the attempt even when validation fails and the command
                // never runs, so a failed/blocked run is still auditable.
                self.record(
                    AuditAction::Run,
                    &self.resolve_profile_name(None),
                    AuditOutcome::Error,
                    AuditFields {
                        command: Some(&command[0]),
                        error_kind: Some(e.kind()),
                        ..Default::default()
                    },
                );
                return Err(e);
            }
        };

        // When a scope is active, the secrets it does not admit must not reach
        // the child even if the parent already holds them (a devenv shell, a
        // prior `eval "$(secretspec export)"`). Computed here and stripped at the
        // `Command` level below — filtering the overlay map is not enough, since
        // the child inherits the real parent environment by default. Resolution
        // already validated the scope (`ensure_secrets` above), so this cannot
        // fail on an unknown scope here.
        let excluded = self.scope_excluded_names()?;
        let env_vars = child_env_from(
            env::vars_os(),
            validation_result
                .resolved
                .secrets
                .iter()
                .map(|(key, secret)| (key.clone(), secret.expose_secret().to_string())),
        );

        // Record which secrets were injected into which command (argv[0] only —
        // arguments may contain secrets). Keys are computed before the spawn but
        // the event is emitted after it so the outcome reflects whether the
        // command actually started.
        let keys: Vec<String> = if self.audit.is_some() {
            let mut keys: Vec<String> =
                validation_result.resolved.secrets.keys().cloned().collect();
            keys.sort();
            keys
        } else {
            Vec::new()
        };

        let mut cmd = Command::new(&command[0]);
        cmd.args(&command[1..]);
        cmd.envs(&env_vars);
        // `env_remove` overrides inheritance, so a scope-excluded secret the
        // parent exported is unset in the child rather than merely left out of
        // the overlay. No-ops when no scope is active (`excluded` is empty).
        for key in &excluded {
            cmd.env_remove(key);
        }

        // Set up Unix signal handling before `spawn`: when SecretSpec is PID 1,
        // the kernel ignores terminating signals with their default disposition,
        // and any signal received in a post-spawn setup window would be lost.
        #[cfg(unix)]
        let mut signal_forwarder = ChildSignalForwarder::prepare()?;

        // Spawn (rather than `status`) so the Run event is recorded the moment the
        // child starts, before the potentially long-running wait. A long-lived
        // command (e.g. a dev server) would otherwise not be logged until it exits,
        // and would be lost entirely if secretspec were killed first. A failure to
        // start is recorded as an error. `Child::wait` closes stdin and inherits
        // stdio just like `Command::status`, so behavior is otherwise unchanged.
        let child = cmd.spawn();
        let (outcome, error_kind) = match &child {
            Ok(_) => (AuditOutcome::Started, None),
            Err(_) => (AuditOutcome::Error, Some("io")),
        };
        // `record` is a no-op when auditing is off, so no `self.audit.is_some()`
        // guard is needed here (the `keys` collection above is still guarded to
        // skip the sort).
        self.record(
            AuditAction::Run,
            &validation_result.resolved.profile,
            outcome,
            AuditFields {
                keys: &keys,
                command: Some(&command[0]),
                error_kind,
                ..Default::default()
            },
        );

        let mut child = child?;
        #[cfg(unix)]
        signal_forwarder.start(child.id());

        let status = child.wait()?;
        Ok(command_exit_code(status))
    }

    /// Resolves every secret for the active profile and emits them in `format`,
    /// without executing a command. This is the non-interactive, scripting
    /// counterpart to [`Secrets::run`]: it never prompts and errors when a
    /// required secret is missing, so CI can gate on it.
    ///
    /// `as_path` secrets keep their backing temp files, like [`Secrets::check`],
    /// so the emitted paths stay valid for whatever consumes the output.
    ///
    /// Output is written to `out` rather than directly to stdout, so an SDK/FFI
    /// caller can capture the formatted bytes and a broken pipe surfaces as a
    /// returned error (and is audited) instead of a panic. The CLI passes a
    /// locked stdout handle.
    pub fn export(&self, format: ExportFormat, out: &mut dyn io::Write) -> Result<()> {
        self.ensure_reason_for(AuditAction::Export, None)?;
        let profile = self.resolve_profile_name(None);

        let mut validated = match self.ensure_secrets(None, None, false) {
            Ok(v) => v,
            Err(e) => {
                self.record(
                    AuditAction::Export,
                    &profile,
                    AuditOutcome::Error,
                    AuditFields {
                        error_kind: Some(e.kind()),
                        ..Default::default()
                    },
                );
                return Err(e);
            }
        };

        // Persist as_path temp files *before* emitting, so a persistence failure
        // aborts up front rather than after the paths have already been written
        // out (a consumer captures stdout regardless of the exit code) and the
        // temp files are then deleted on drop. The path strings already live in
        // `resolved.secrets`, so keeping first does not change what is emitted.
        if let Err(e) = validated.keep_temp_files() {
            let err = SecretSpecError::Io(e);
            self.record(
                AuditAction::Export,
                &validated.resolved.profile,
                AuditOutcome::Error,
                AuditFields {
                    error_kind: Some(err.kind()),
                    ..Default::default()
                },
            );
            return Err(err);
        }

        // Deterministic key order regardless of HashMap iteration. Values are
        // borrowed (not copied) out of the resolved map, so secret material is
        // not duplicated into a second set of heap buffers.
        let mut entries: Vec<(&str, &str)> = validated
            .resolved
            .secrets
            .iter()
            .map(|(key, value)| (key.as_str(), value.expose_secret()))
            .collect();
        entries.sort_by(|(a, _), (b, _)| a.cmp(b));

        let keys: Vec<String> = if self.audit.is_some() {
            entries.iter().map(|(key, _)| key.to_string()).collect()
        } else {
            Vec::new()
        };

        let result = write_export(format, &entries, out);
        self.record(
            AuditAction::Export,
            &validated.resolved.profile,
            if result.is_ok() {
                AuditOutcome::Found
            } else {
                AuditOutcome::Error
            },
            AuditFields {
                keys: &keys,
                error_kind: result.as_ref().err().map(|e| e.kind()),
                ..Default::default()
            },
        );
        result?;

        Ok(())
    }
}

/// Output format for [`Secrets::export`]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
pub enum ExportFormat {
    /// `export KEY='value'` lines for `eval "$(secretspec export)"`
    #[default]
    Shell,
    /// `KEY=value` lines in dotenv syntax
    Dotenv,
    /// A single JSON object mapping each secret name to its value
    Json,
    /// GitHub/Forgejo Actions `$GITHUB_ENV` file plus `::add-mask::` on stdout
    Gha,
}

/// Write entries (pre-sorted by key) to `out` in the given format. Writing to
/// an injected sink (rather than `print!`) lets an SDK caller capture the bytes
/// and turns a broken pipe into a returned error instead of a panic.
fn write_export(
    format: ExportFormat,
    entries: &[(&str, &str)],
    out: &mut dyn io::Write,
) -> Result<()> {
    match format {
        ExportFormat::Shell => {
            let mut buf = String::new();
            for (key, value) in entries {
                buf.push_str("export ");
                buf.push_str(key);
                buf.push('=');
                buf.push_str(&shell_single_quote(value));
                buf.push('\n');
            }
            out.write_all(buf.as_bytes()).map_err(SecretSpecError::Io)?;
        }
        ExportFormat::Dotenv => {
            // entries are already sorted, so serialize them directly instead of
            // rebuilding and re-sorting a map (which would also re-copy values).
            let content = crate::provider::dotenv::serialize_dotenv_pairs(
                entries.iter().map(|(key, value)| (*key, *value)),
            )?;
            out.write_all(content.as_bytes())
                .map_err(SecretSpecError::Io)?;
        }
        ExportFormat::Json => {
            let map: BTreeMap<&str, &str> = entries.iter().copied().collect();
            let json = serde_json::to_string(&map)
                .map_err(|e| SecretSpecError::Io(io::Error::other(e)))?;
            out.write_all(json.as_bytes())
                .and_then(|()| out.write_all(b"\n"))
                .map_err(SecretSpecError::Io)?;
        }
        ExportFormat::Gha => write_gha(entries, out)?,
    }

    Ok(())
}

/// POSIX single-quote escaping so the value survives `eval` verbatim
pub(crate) fn shell_single_quote(value: &str) -> String {
    let mut out = String::with_capacity(value.len() + 2);
    out.push('\'');
    for ch in value.chars() {
        if ch == '\'' {
            out.push_str("'\\''");
        } else {
            out.push(ch);
        }
    }
    out.push('\'');
    out
}

/// GitHub/Forgejo Actions writer that masks every value line on `out` and
/// appends the assignments to `$GITHUB_ENV`. Multi-line values use the heredoc
/// form so they survive. Errors when `$GITHUB_ENV` is unset.
fn write_gha(entries: &[(&str, &str)], out: &mut dyn io::Write) -> Result<()> {
    use std::io::Write;

    let github_env = env::var("GITHUB_ENV").map_err(|_| {
        SecretSpecError::Io(io::Error::new(
            io::ErrorKind::NotFound,
            "GITHUB_ENV is not set; `--format gha` only works inside a GitHub/Forgejo Actions runner",
        ))
    })?;

    // Mask every value line so the runner scrubs accidental echoes. The data
    // must be percent-encoded the way the runner expects, since it *unescapes*
    // add-mask data before registering the mask; emitting the raw value would
    // register a different string and leave the true secret unmasked.
    let mut masks = String::new();
    for (_, value) in entries {
        for line in value.split('\n') {
            if !line.is_empty() {
                masks.push_str("::add-mask::");
                masks.push_str(&gha_escape_data(line));
                masks.push('\n');
            }
        }
    }
    out.write_all(masks.as_bytes())
        .map_err(SecretSpecError::Io)?;

    let mut file = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(&github_env)
        .map_err(SecretSpecError::Io)?;

    let mut block = String::new();
    for (key, value) in entries {
        if value.contains('\n') {
            let delimiter = gha_heredoc_delimiter(value);
            block.push_str(key);
            block.push_str("<<");
            block.push_str(&delimiter);
            block.push('\n');
            block.push_str(value);
            block.push('\n');
            block.push_str(&delimiter);
            block.push('\n');
        } else {
            block.push_str(key);
            block.push('=');
            block.push_str(value);
            block.push('\n');
        }
    }

    // Record the length before appending so a partial write can be rolled back:
    // a truncated heredoc opener with no closing delimiter would otherwise
    // corrupt `$GITHUB_ENV` parsing for every later step in the job.
    let start_len = file.metadata().map_err(SecretSpecError::Io)?.len();
    if let Err(e) = file.write_all(block.as_bytes()) {
        let _ = file.set_len(start_len);
        return Err(SecretSpecError::Io(e));
    }

    Ok(())
}

/// Percent-encodes workflow-command data the way the Actions runner expects (it
/// unescapes the data before registering the mask), so the masked string equals
/// the real secret. Mirrors `@actions/core`'s `escapeData`. `%` is escaped first
/// so an embedded `%25`/`%0D`/`%0A` in the value is not later read back as `%`,
/// CR, or LF.
fn gha_escape_data(value: &str) -> String {
    value
        .replace('%', "%25")
        .replace('\r', "%0D")
        .replace('\n', "%0A")
}

/// A heredoc delimiter that does not collide with any line of `value`
fn gha_heredoc_delimiter(value: &str) -> String {
    loop {
        let delimiter = format!("ghadelimiter_{}", uuid::Uuid::new_v4().simple());
        if !value.lines().any(|line| line == delimiter) {
            return delimiter;
        }
    }
}

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

    #[test]
    fn from_spec_uses_explicit_logical_base_directory() {
        let spec = Spec::from_toml(
            r#"
            [project]
            name = "embedded"
            revision = "1.0"
            require_reason = false

            [profiles.default]
            TOKEN = { description = "Embedded token", required = false }
        "#,
        )
        .unwrap();
        let base_dir = PathBuf::from("a-base-directory-that-does-not-exist");

        let secrets = Secrets::from_spec_at(spec, &base_dir).unwrap();

        assert_eq!(secrets.config_dir, base_dir);
    }
}

#[cfg(test)]
mod write_target_tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};

    struct CountingProvider {
        writability_checks: AtomicUsize,
        descriptions: AtomicUsize,
    }

    impl ProviderTrait for CountingProvider {
        fn convention_address(
            &self,
            _project: &str,
            _profile: &str,
            key: &str,
        ) -> Result<NativeAddress> {
            Ok(NativeAddress {
                item: key.to_string(),
                ..Default::default()
            })
        }

        fn get(&self, _addr: Address<'_>) -> Result<Option<SecretString>> {
            Ok(None)
        }

        fn set(&self, _addr: Address<'_>, _value: &SecretString) -> Result<()> {
            Ok(())
        }

        fn check_writable(&self, _addr: Address<'_>) -> Result<()> {
            self.writability_checks.fetch_add(1, Ordering::SeqCst);
            Ok(())
        }

        fn describe_write_target(&self, _addr: Address<'_>) -> Result<String> {
            self.descriptions.fetch_add(1, Ordering::SeqCst);
            Ok("described".to_string())
        }

        fn name(&self) -> &'static str {
            "counting"
        }

        fn uri(&self) -> String {
            "counting".to_string()
        }
    }

    #[test]
    fn library_preflight_skips_target_description_without_a_reporter() {
        let config = crate::tests::resolve_test_config(HashMap::from([(
            "API_KEY".to_string(),
            crate::config::Secret {
                description: Some("API key".to_string()),
                ..Default::default()
            },
        )]));
        let spec = Secrets::new(config, None, None, None);
        let planned = spec
            .plan_secret("API_KEY", "default", None)
            .unwrap()
            .unwrap();
        let provider = CountingProvider {
            writability_checks: AtomicUsize::new(0),
            descriptions: AtomicUsize::new(0),
        };

        spec.preflight_write(&planned, "default", &provider)
            .unwrap();

        assert_eq!(provider.writability_checks.load(Ordering::SeqCst), 1);
        assert_eq!(provider.descriptions.load(Ordering::SeqCst), 0);
    }
}

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

    #[test]
    fn secret_label_emphasizes_the_name_and_deemphasizes_the_description() {
        assert_eq!(
            format_secret_label("DATABASE_URL", Some("PostgreSQL connection string")),
            format!(
                "{} {} {}",
                "DATABASE_URL".cyan().bold(),
                "-".dimmed(),
                "PostgreSQL connection string".dimmed()
            )
        );
    }

    #[test]
    fn secret_label_omits_a_missing_description_without_a_placeholder() {
        let label = format_secret_label("DATABASE_URL", None);

        assert_eq!(label, "DATABASE_URL".cyan().bold().to_string());
        assert!(!label.contains("No description"));
        assert!(!label.contains('-'));
    }
}

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

    /// A POSIX shell evaluating `export K=<quoted>` must read the variable back
    /// as exactly the original value. This round-trip is the real contract that
    /// `shell_single_quote` defends, across quotes, spaces, `$`, `"`, and empty.
    #[cfg(unix)]
    #[test]
    fn shell_single_quote_round_trips_through_sh() {
        let cases = ["abc'123", "a b c", "pa$$word", "he said \"hi\"", "", "'"];

        for value in cases {
            let script = format!("export K={}; printf '%s' \"$K\"", shell_single_quote(value));

            let output = std::process::Command::new("sh")
                .arg("-c")
                .arg(&script)
                .output()
                .expect("sh should be available in the test environment");

            assert!(
                output.status.success(),
                "sh failed for {value:?}: {}",
                String::from_utf8_lossy(&output.stderr)
            );

            let read_back = String::from_utf8(output.stdout).expect("sh stdout is utf-8");
            assert_eq!(read_back, value, "round-trip mismatch for {value:?}");
        }
    }

    fn rendered(format: ExportFormat, entries: &[(&str, &str)]) -> String {
        let mut buf = Vec::new();
        write_export(format, entries, &mut buf).expect("write_export should succeed");
        String::from_utf8(buf).expect("export output is utf-8")
    }

    #[test]
    fn shell_format_quotes_each_value() {
        let out = rendered(ExportFormat::Shell, &[("A", "x y"), ("B", "a'b")]);
        assert_eq!(out, "export A='x y'\nexport B='a'\\''b'\n");
    }

    #[test]
    fn json_format_is_compact() {
        let out = rendered(ExportFormat::Json, &[("A", "1"), ("B", "2")]);
        assert_eq!(out, "{\"A\":\"1\",\"B\":\"2\"}\n");
    }

    #[test]
    fn dotenv_format_uses_minimal_round_trip_quoting() {
        let out = rendered(ExportFormat::Dotenv, &[("A", "pa$$"), ("B", "x")]);
        assert_eq!(out, "A=pa$$\nB=x\n");
    }

    /// The runner unescapes add-mask data before registering it, so the data we
    /// emit must be percent-encoded or the true value is left unmasked.
    #[test]
    fn gha_escape_data_encodes_percent_cr_and_lf() {
        assert_eq!(gha_escape_data("plain"), "plain");
        assert_eq!(gha_escape_data("a%b"), "a%25b");
        assert_eq!(gha_escape_data("a\rb"), "a%0Db");
        assert_eq!(gha_escape_data("a\nb"), "a%0Ab");
        // `%` is escaped first, so a literal `%0A` is not decoded back to a newline.
        assert_eq!(gha_escape_data("a%0Ab"), "a%250Ab");
    }
}

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

    #[test]
    fn policy_decision_matrix() {
        use RequireReason::*;
        assert!(!policy_requires_reason(Never, true));
        assert!(!policy_requires_reason(Never, false));
        assert!(policy_requires_reason(Always, false));
        assert!(policy_requires_reason(Always, true));
        assert!(policy_requires_reason(Agents, true));
        assert!(!policy_requires_reason(Agents, false));
    }

    #[test]
    fn normalize_reason_trims_and_blanks_to_none() {
        assert_eq!(
            normalize_reason("  deploy web  "),
            Some("deploy web".to_string())
        );
        assert_eq!(normalize_reason("deploy"), Some("deploy".to_string()));
        assert_eq!(normalize_reason(""), None);
        assert_eq!(normalize_reason("   "), None);
        assert_eq!(normalize_reason("\t\n"), None);
    }

    /// A default reason fills the gap but never overwrites one the caller
    /// already supplied: a wrapper describing itself must not replace the more
    /// specific reason its own caller passed in.
    #[test]
    fn with_default_reason_only_fills_an_absent_reason() {
        let spec = || {
            Secrets::new(
                crate::tests::resolve_test_config(HashMap::new()),
                None,
                None,
                None,
            )
        };

        // No reason yet: the default is adopted, normalized like any other.
        assert_eq!(
            spec().with_default_reason("  nightly export  ").reason,
            Some("nightly export".to_string())
        );

        // A reason already in effect wins, whichever order the calls come in.
        assert_eq!(
            spec()
                .with_reason("running migrations")
                .with_default_reason("nightly export")
                .reason,
            Some("running migrations".to_string())
        );

        // A blank default is no reason at all, so the session stays unreasoned
        // rather than storing an empty string that would satisfy nothing.
        assert_eq!(spec().with_default_reason("   ").reason, None);
        // ...and a blank default cannot clear a real reason either.
        assert_eq!(
            spec().with_reason("deploy").with_default_reason("").reason,
            Some("deploy".to_string())
        );
    }

    #[test]
    fn caller_context_is_normalized_but_never_counts_as_a_reason() {
        let mut spec = Secrets::new(
            crate::tests::resolve_test_config(HashMap::new()),
            None,
            None,
            None,
        )
        .with_caller(
            CallerContext::new("  git  ")
                .with_operation(" credential_get ")
                .with_resource(" github.com "),
        );

        assert_eq!(
            spec.caller,
            Some(
                CallerContext::new("git")
                    .with_operation("credential_get")
                    .with_resource("github.com")
            )
        );
        spec.require_reason = RequireReason::Always;
        assert!(matches!(
            spec.ensure_reason(),
            Err(SecretSpecError::ReasonRequired)
        ));

        // A real reason remains independent and satisfies the policy.
        assert!(spec.with_reason("release package").ensure_reason().is_ok());
    }

    #[test]
    fn non_blank_trims_and_blanks_to_none() {
        // A padded-but-nonblank override (e.g. a `$(cat file)` trailing newline)
        // is trimmed, not used verbatim, so it cannot select a nonexistent
        // profile/provider.
        assert_eq!(non_blank("production\n"), Some("production".to_string()));
        assert_eq!(non_blank("  keyring  "), Some("keyring".to_string()));
        // Blank input (empty or whitespace-only) is dropped.
        assert_eq!(non_blank(""), None);
        assert_eq!(non_blank("   "), None);
        assert_eq!(non_blank("\t\n"), None);
    }

    /// A non-UTF-8 environment variable must not crash detection: the offending
    /// entry is dropped and the UTF-8 entries survive. This guards against the
    /// `std::env::vars()` panic in `detect-coding-agent`, which auditing (on by
    /// default) would otherwise trigger on every command.
    #[cfg(unix)]
    #[test]
    fn utf8_env_drops_non_utf8_entries_without_panicking() {
        use std::ffi::OsString;
        use std::os::unix::ffi::OsStringExt;

        let bad_key = OsString::from_vec(vec![0x66, 0x6f, 0xff]); // "fo\xff"
        let bad_val = OsString::from_vec(vec![0xfe, 0xfe]);
        let vars = vec![
            (OsString::from("CLEAN_KEY"), OsString::from("clean_value")),
            (bad_key, OsString::from("value_for_bad_key")),
            (OsString::from("KEY_WITH_BAD_VALUE"), bad_val),
        ];

        let env = utf8_env_from(vars);

        // Only the fully-UTF-8 entry survives; the two non-UTF-8 entries are skipped.
        assert_eq!(
            env.get("CLEAN_KEY").map(String::as_str),
            Some("clean_value")
        );
        assert_eq!(env.len(), 1);
    }

    /// The `run` child environment must tolerate non-UTF-8 parent variables
    /// (`env::vars()` would panic on them — see #140) AND pass them through to
    /// the child untouched, unlike agent detection which drops them. Resolved
    /// secrets are added on top and overwrite same-named parent variables.
    #[cfg(unix)]
    #[test]
    fn child_env_passes_through_non_utf8_and_overlays_secrets() {
        use std::ffi::OsString;
        use std::os::unix::ffi::OsStringExt;

        let bad_val = OsString::from_vec(vec![0x64, 0x61, 0x63, 0xa3]); // "dac\xa3"
        let vars = vec![
            (OsString::from("CLEAN_KEY"), OsString::from("clean_value")),
            (OsString::from("BAD"), bad_val.clone()),
            (OsString::from("OVERRIDDEN"), OsString::from("parent_value")),
        ];
        let secrets = vec![
            ("SECRET_KEY".to_string(), "secret_value".to_string()),
            ("OVERRIDDEN".to_string(), "secret_wins".to_string()),
        ];

        let env = child_env_from(vars, secrets);

        // Non-UTF-8 parent entry survives byte-for-byte instead of panicking.
        assert_eq!(env.get(&OsString::from("BAD")), Some(&bad_val));
        assert_eq!(
            env.get(&OsString::from("CLEAN_KEY")),
            Some(&OsString::from("clean_value"))
        );
        // Secrets are injected and win over same-named parent variables.
        assert_eq!(
            env.get(&OsString::from("SECRET_KEY")),
            Some(&OsString::from("secret_value"))
        );
        assert_eq!(
            env.get(&OsString::from("OVERRIDDEN")),
            Some(&OsString::from("secret_wins"))
        );
        assert_eq!(env.len(), 4);
    }
}

#[cfg(test)]
mod provider_credentials_cache_tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::{Arc, Barrier};
    use std::thread;
    use std::time::Duration;

    #[test]
    fn concurrent_population_for_one_key_is_single_flight() {
        const CALLERS: usize = 8;
        let cache = Arc::new(ProviderCredentialsCache::default());
        let start = Arc::new(Barrier::new(CALLERS));
        let fetches = Arc::new(AtomicUsize::new(0));

        let threads: Vec<_> = (0..CALLERS)
            .map(|_| {
                let cache = Arc::clone(&cache);
                let start = Arc::clone(&start);
                let fetches = Arc::clone(&fetches);
                thread::spawn(move || {
                    start.wait();
                    cache
                        .get_or_try_init(("default".into(), "target".into()), || {
                            fetches.fetch_add(1, Ordering::SeqCst);
                            // Keep the first population in flight long enough for
                            // every caller to contend on the same key.
                            thread::sleep(Duration::from_millis(50));
                            let mut credentials = ProviderCredentials::new();
                            credentials.insert("token".into(), SecretString::new("value".into()));
                            Ok(credentials)
                        })
                        .unwrap()
                })
            })
            .collect();

        for thread in threads {
            let credentials = thread.join().unwrap();
            assert_eq!(
                credentials.get("token").map(|value| value.expose_secret()),
                Some("value")
            );
        }
        assert_eq!(fetches.load(Ordering::SeqCst), 1);
    }
}

#[cfg(test)]
mod provider_cache_tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::{Arc, Barrier};
    use std::thread;
    use std::time::Duration;

    fn env_provider() -> Result<Box<dyn ProviderTrait>> {
        crate::provider::provider_from_spec("env://", ProviderCredentials::new())
    }

    /// A fallback chain is walked per secret, so N secrets sharing one link
    /// must not build N providers.
    #[test]
    fn one_key_builds_once_and_hands_back_the_same_instance() {
        let cache = ProviderCache::default();
        let builds = AtomicUsize::new(0);
        let key = ("default".to_string(), "env://".to_string());

        let first = cache
            .get_or_try_init(key.clone(), || {
                builds.fetch_add(1, Ordering::SeqCst);
                env_provider()
            })
            .unwrap();
        let second = cache
            .get_or_try_init(key, || {
                builds.fetch_add(1, Ordering::SeqCst);
                env_provider()
            })
            .unwrap();

        assert_eq!(builds.load(Ordering::SeqCst), 1);
        assert!(Arc::ptr_eq(&first, &second));
    }

    /// The profile is part of the key: a provider carries the credentials of
    /// the profile it was built under.
    #[test]
    fn distinct_keys_build_independently() {
        let cache = ProviderCache::default();
        let builds = AtomicUsize::new(0);

        let build_under = |profile: &str| {
            cache
                .get_or_try_init((profile.to_string(), "env://".to_string()), || {
                    builds.fetch_add(1, Ordering::SeqCst);
                    env_provider()
                })
                .unwrap()
        };
        let default = build_under("default");
        let production = build_under("production");

        assert_eq!(builds.load(Ordering::SeqCst), 2);
        assert!(!Arc::ptr_eq(&default, &production));
    }

    /// Failures are not memoized, so a provider that was unavailable can be
    /// built by a later operation in the same session.
    #[test]
    fn failures_are_not_memoized() {
        let cache = ProviderCache::default();
        let key = ("default".to_string(), "env://".to_string());

        let failed = cache.get_or_try_init(key.clone(), || {
            Err(SecretSpecError::ProviderOperationFailed("nope".into()))
        });
        assert!(failed.is_err());

        assert!(cache.get_or_try_init(key, env_provider).is_ok());
    }

    #[test]
    fn concurrent_construction_for_one_key_is_single_flight() {
        const CALLERS: usize = 8;
        let cache = Arc::new(ProviderCache::default());
        let start = Arc::new(Barrier::new(CALLERS));
        let builds = Arc::new(AtomicUsize::new(0));

        let threads: Vec<_> = (0..CALLERS)
            .map(|_| {
                let cache = Arc::clone(&cache);
                let start = Arc::clone(&start);
                let builds = Arc::clone(&builds);
                thread::spawn(move || {
                    start.wait();
                    cache
                        .get_or_try_init(("default".into(), "env://".into()), || {
                            builds.fetch_add(1, Ordering::SeqCst);
                            // Hold the first construction in flight long enough
                            // for every caller to contend on the same key.
                            thread::sleep(Duration::from_millis(50));
                            env_provider()
                        })
                        .unwrap()
                })
            })
            .collect();

        let providers: Vec<_> = threads
            .into_iter()
            .map(|thread| thread.join().unwrap())
            .collect();

        assert_eq!(builds.load(Ordering::SeqCst), 1);
        for provider in &providers {
            assert!(Arc::ptr_eq(provider, &providers[0]));
        }
    }
}

#[cfg(test)]
mod provider_credential_scope_tests {
    use super::*;
    use crate::config::{CredentialSource, Profile, ProviderAlias, Secret};
    use crate::tests::{resolve_test_config, scrub_resolution_env};
    use tempfile::TempDir;

    /// A provider's authentication credential belongs to the alias, not to any
    /// one profile: `config provider login` stores under the session profile,
    /// but the same credential must resolve when the provider is used under a
    /// different profile. Before the fix the convention path embedded the active
    /// profile, so a credential stored under `default` was invisible to
    /// `production` and resolution hard-errored "credential not found".
    #[test]
    fn provider_credentials_resolve_under_any_profile() {
        let _env = scrub_resolution_env();
        let _cwd = crate::secrets::lock_cwd();
        let _store = TempDir::new().unwrap();

        // `access_token` is sourced from a writable, profile-namespacing store.
        let providers = HashMap::from([(
            "bws".to_string(),
            ProviderAlias::leaf(
                "bws://proj",
                HashMap::from([(
                    "access_token".to_string(),
                    CredentialSource::from("memtest://"),
                )]),
            ),
        )]);

        let mut config =
            resolve_test_config(HashMap::from([("API_KEY".to_string(), Secret::default())]));
        config.profiles.insert(
            "production".to_string(),
            Profile {
                defaults: None,
                secrets: HashMap::new(),
            },
        );
        config.providers = Some(providers);

        // `login` runs under the session/default profile.
        let logged_in = Secrets::new(config.clone(), None, None, None);
        let source = logged_in
            .declared_provider_credentials("bws")
            .unwrap()
            .into_iter()
            .next()
            .expect("alias declares one credential")
            .1;
        logged_in
            .store_provider_credential(
                &source,
                "access_token",
                &SecretString::new("tok-123".into()),
            )
            .unwrap();

        // Resolving the same alias under `production` must still find it.
        let resolver = Secrets::new(config, None, None, Some("production".to_string()));
        let resolved = resolver
            .resolve_provider_credentials("bws", "production")
            .expect("a stored provider credential must resolve under any profile");
        assert_eq!(
            resolved
                .get("access_token")
                .map(|value| value.expose_secret()),
            Some("tok-123"),
        );
    }
}

/// Serializes tests that mutate the process-global current directory. The current
/// directory is shared across all threads, so two `set_current_dir` tests running
/// concurrently (the default under `cargo test`) would corrupt each other. Any test
/// that calls `set_current_dir` must hold this guard for its whole body. Poisoning
/// is recovered from (a panicking test leaves the lock poisoned but the data — unit
/// — is meaningless), so one failing test does not cascade into the others.
#[cfg(test)]
pub(crate) static CWD_GUARD: std::sync::Mutex<()> = std::sync::Mutex::new(());

/// Locks [`CWD_GUARD`], recovering from a previous test's poison.
#[cfg(test)]
pub(crate) fn lock_cwd() -> std::sync::MutexGuard<'static, ()> {
    CWD_GUARD.lock().unwrap_or_else(|e| e.into_inner())
}

#[cfg(test)]
mod config_discovery_tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    /// Walking up from a nested subdirectory finds the nearest ancestor
    /// `secretspec.toml`. This is the library half of "run secretspec from a
    /// subdirectory" (issue #59). It exercises `find_config_file_from` directly so
    /// no current-directory mutation is needed — the walk is fully deterministic.
    #[test]
    fn find_config_file_walks_up_to_nearest_ancestor() {
        let root = TempDir::new().unwrap();
        let manifest = root.path().join("secretspec.toml");
        fs::write(&manifest, "[project]\nname=\"x\"\nrevision=\"1.0\"\n").unwrap();

        let nested = root.path().join("a").join("b").join("c");
        fs::create_dir_all(&nested).unwrap();

        let found = find_config_file_from(nested).unwrap();
        // Compare canonicalized paths: on macOS the temp dir lives under a
        // `/var -> /private/var` symlink, so the raw paths differ.
        assert_eq!(
            found.canonicalize().unwrap(),
            manifest.canonicalize().unwrap()
        );
    }

    /// With no `secretspec.toml` anywhere up the tree, the walk reports a missing
    /// manifest rather than looping or panicking. (Assumes the temp dir's ancestors
    /// contain no `secretspec.toml`, which holds for the OS temp directory.)
    #[test]
    fn find_config_file_reports_missing_manifest() {
        let empty = TempDir::new().unwrap();
        assert!(matches!(
            find_config_file_from(empty.path().to_path_buf()),
            Err(SecretSpecError::NoManifest)
        ));
    }

    /// Loading via an explicit **relative** path resolves against the current
    /// directory — both a bare filename and a `../`-relative parent path. This is
    /// the `-f ../secretspec.toml` form from issue #59, and it is the case that
    /// regressed on Windows: `Config::try_from` calls `Path::canonicalize`, whose
    /// behavior on relative paths differs from Unix. Mutates the current directory,
    /// so it holds [`CWD_GUARD`].
    #[test]
    fn try_from_resolves_relative_paths_against_cwd() {
        let _cwd = lock_cwd();

        let root = TempDir::new().unwrap();
        fs::write(
            root.path().join("secretspec.toml"),
            "[project]\nname=\"x\"\nrevision=\"1.0\"\n\n[profiles.default]\n",
        )
        .unwrap();
        let sub = root.path().join("sub");
        fs::create_dir_all(&sub).unwrap();

        let original = env::current_dir().unwrap();

        // Bare filename from the manifest's own directory (the working case).
        env::set_current_dir(root.path()).unwrap();
        let from_cwd = Config::try_from(Path::new("secretspec.toml"));

        // `../`-relative path from a subdirectory (the case that failed on Windows).
        env::set_current_dir(&sub).unwrap();
        let from_parent = Config::try_from(Path::new("../secretspec.toml"));

        // Restore the current directory before any assertion (and before the
        // TempDir is dropped) so a failure cannot leave the process — or TempDir
        // cleanup, which cannot remove the current directory on Windows — wedged.
        env::set_current_dir(&original).unwrap();

        assert!(from_cwd.is_ok(), "bare filename: {:?}", from_cwd.err());
        assert!(
            from_parent.is_ok(),
            "../ relative path: {:?}",
            from_parent.err()
        );
    }
}

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

    #[test]
    fn decoding_accepts_exactly_one_trailing_line_ending() {
        for encoded in ["Zg==\n", "Zg==\r\n"] {
            let value = SecretString::new(encoded.to_string().into());
            let decoded =
                Secrets::decode_stored_value(SecretEncoding::Base64, "VALUE", &value).unwrap();
            assert_eq!(decoded.expose_secret(), b"f");
        }

        let value = SecretString::new("Zg==\n\n".to_string().into());
        let error =
            Secrets::decode_stored_value(SecretEncoding::Base64, "VALUE", &value).unwrap_err();
        assert_eq!(error.kind(), "decode_failed");
    }

    #[test]
    fn encoding_uses_canonical_storage_representations() {
        let cases = [
            (SecretEncoding::Base64, "value", "dmFsdWU="),
            (SecretEncoding::Base64Url, "hello?", "aGVsbG8_"),
            (SecretEncoding::Hex, "value", "76616c7565"),
        ];

        for (encoding, logical, expected) in cases {
            let logical = SecretString::new(logical.to_string().into());
            let stored = Secrets::encode_logical_value(encoding, &logical);
            assert_eq!(stored.expose_secret(), expected);
        }
    }
}

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

    /// The `provider` field of the resolution report / resolve response must not
    /// echo a credential embedded in a user-authored override or alias URI. That
    /// field is shown by `check --explain`, emitted by `--json`, and crosses the
    /// SDK boundary, so `validation_report_provider_uri` runs raw URIs through
    /// `redact_uri_strict` (the `provider.uri()` paths are already credential-free).
    #[test]
    fn report_provider_uri_redacts_credentials() {
        let spec = Secrets::new(
            Config {
                project: crate::config::Project {
                    name: "redact-test".to_string(),
                    ..Default::default()
                },
                profiles: HashMap::new(),
                providers: None,
                scopes: None,
            },
            None,
            None,
            None,
        );

        // Override branch: userinfo and query token are stripped.
        let got = spec
            .validation_report_provider_uri(
                Some("vault+token:s3cr3t@host/db?token=abc"),
                std::iter::empty(),
                None,
            )
            .unwrap();
        assert_eq!(got, "vault+token:host/db");
        assert!(!got.contains("s3cr3t") && !got.contains("abc"));

        // Per-secret alias branch: the first sorted primary URI is redacted too.
        let got = spec
            .validation_report_provider_uri(
                None,
                [Some("vault://host?token=zzz")].into_iter(),
                None,
            )
            .unwrap();
        assert_eq!(got, "vault://host");
        assert!(!got.contains("zzz"));
    }
}

#[cfg(test)]
mod run_prompt_tests {
    use super::*;
    use crate::config::Secret;
    use secrecy::ExposeSecret;
    use std::sync::atomic::{AtomicUsize, Ordering};

    fn prompted_spec() -> Secrets {
        let config = crate::tests::resolve_test_config(HashMap::from([(
            "DEPLOY_PASSWORD".to_string(),
            Secret {
                description: Some("One-time deployment password".to_string()),
                required: Some(true),
                providers: Some(vec!["null".to_string()]),
                prompt: Some(true),
                ..Default::default()
            },
        )]));
        Secrets::new(config, None, None, None)
    }

    fn prompted_dotenv_spec(path: &std::path::Path) -> Secrets {
        let config = crate::tests::resolve_test_config(HashMap::from([(
            "DEPLOY_PASSWORD".to_string(),
            Secret {
                description: Some("Deployment password".to_string()),
                required: Some(true),
                providers: Some(vec![format!("dotenv://{}", path.display())]),
                prompt: Some(true),
                ..Default::default()
            },
        )]));
        Secrets::new(config, None, None, None)
    }

    #[test]
    fn run_prompts_again_for_each_resolution_without_storing() {
        let _env = crate::tests::scrub_resolution_env();
        let prompts = Arc::new(AtomicUsize::new(0));
        let observed = Arc::clone(&prompts);
        let mut spec = prompted_spec();
        spec.set_prompt_reader(move |name, profile| {
            assert_eq!(name, "DEPLOY_PASSWORD");
            assert_eq!(profile, "default");
            observed.fetch_add(1, Ordering::SeqCst);
            Ok(SecretString::new("entered-once".into()))
        });

        for expected_prompts in 1..=2 {
            let validated = spec
                .validate_audited(false, Materialize::Run)
                .unwrap()
                .unwrap();
            assert_eq!(
                validated.resolved.secrets["DEPLOY_PASSWORD"].expose_secret(),
                "entered-once"
            );
            assert_eq!(prompts.load(Ordering::SeqCst), expected_prompts);
        }

        // Ordinary library/SDK resolution never opens an interactive prompt.
        assert!(
            spec.validate_audited(false, Materialize::Values)
                .unwrap()
                .is_err()
        );
    }

    #[test]
    fn writable_provider_persists_the_prompted_value() {
        let _env = crate::tests::scrub_resolution_env();
        let temp_dir = tempfile::TempDir::new().unwrap();
        let dotenv_path = temp_dir.path().join("prompt.env");
        let prompts = Arc::new(AtomicUsize::new(0));
        let observed = Arc::clone(&prompts);
        let mut spec = prompted_dotenv_spec(&dotenv_path);
        spec.set_prompt_reader(move |name, profile| {
            assert_eq!(name, "DEPLOY_PASSWORD");
            assert_eq!(profile, "default");
            observed.fetch_add(1, Ordering::SeqCst);
            Ok(SecretString::new("persisted-answer".into()))
        });

        for _ in 0..2 {
            let validated = spec
                .validate_audited(false, Materialize::Run)
                .unwrap()
                .unwrap();
            assert_eq!(
                validated.resolved.secrets["DEPLOY_PASSWORD"].expose_secret(),
                "persisted-answer"
            );
        }

        assert_eq!(prompts.load(Ordering::SeqCst), 1);
        assert_eq!(
            std::fs::read_to_string(dotenv_path).unwrap(),
            "DEPLOY_PASSWORD=persisted-answer\n"
        );
    }

    #[test]
    fn run_surfaces_an_unavailable_controlling_terminal() {
        let _env = crate::tests::scrub_resolution_env();
        let mut spec = prompted_spec();
        spec.set_prompt_reader(|name, _| Err(SecretSpecError::PromptUnavailable(name.to_string())));

        let error = match spec.validate_audited(false, Materialize::Run) {
            Err(error) => error,
            Ok(_) => panic!("run resolution should fail without a controlling terminal"),
        };
        assert!(matches!(
            error,
            SecretSpecError::PromptUnavailable(name) if name == "DEPLOY_PASSWORD"
        ));
    }

    #[cfg(unix)]
    #[test]
    fn run_injects_the_prompted_value_into_the_child() {
        let _env = crate::tests::scrub_resolution_env();
        let mut spec = prompted_spec();
        spec.set_prompt_reader(|_, _| Ok(SecretString::new("entered-once".into())));

        let exit = spec
            .run_command(vec![
                "sh".to_string(),
                "-c".to_string(),
                "test \"$DEPLOY_PASSWORD\" = entered-once".to_string(),
            ])
            .unwrap();
        assert_eq!(exit, 0);
    }
}

#[cfg(test)]
mod reference_routing_tests {
    use super::*;
    use crate::config::Secret;

    fn spec_with_provider(provider: Option<&str>) -> Secrets {
        Secrets::new(
            Config {
                project: crate::config::Project {
                    name: "ref-test".to_string(),
                    ..Default::default()
                },
                profiles: HashMap::new(),
                providers: None,
                scopes: None,
            },
            None,
            provider.map(String::from),
            None,
        )
    }

    fn ref_secret(providers: Option<Vec<&str>>) -> Secret {
        Secret {
            description: Some("Sentry DSN".to_string()),
            reference: Some(crate::config::NativeAddress {
                item: "shared".to_string(),
                field: Some("SENTRY_DSN".to_string()),
                ..Default::default()
            }),
            providers: providers.map(|p| p.into_iter().map(String::from).collect()),
            ..Default::default()
        }
    }

    /// The read chain the shared router resolves for a secret, in the shape the
    /// read path consumes (`None` = default provider). Exercises the same
    /// `route_for` that the plan, `get`, and `set` route through.
    fn read_uris(
        spec: &Secrets,
        config: &Secret,
        override_arg: Option<&str>,
    ) -> Option<Vec<String>> {
        let override_spec = spec.explicit_provider_spec(override_arg);
        spec.route_for(config, &override_spec).unwrap().specs()
    }

    /// A `ref` supplies naming only: it never contributes to the read chain,
    /// which stays whatever routing (here: nothing, so the default provider)
    /// resolves.
    #[test]
    fn reference_does_not_affect_read_routing() {
        let _env = crate::tests::scrub_resolution_env();
        let spec = spec_with_provider(None);
        let uris = read_uris(&spec, &ref_secret(None), None);
        assert_eq!(uris, None, "no routing configured, default store applies");
    }

    /// Uniform precedence: an explicit `--provider` override redirects ref
    /// secrets exactly like convention secrets, e.g. at a fixtures store
    /// during tests.
    #[test]
    fn override_redirects_reference() {
        let _env = crate::tests::scrub_resolution_env();
        let spec = spec_with_provider(Some("keyring"));
        let uris = read_uris(&spec, &ref_secret(None), Some("dotenv://.env.mock"));
        assert_eq!(uris, Some(vec!["dotenv://.env.mock".to_string()]));
    }

    /// Routing for a ref secret follows its `providers` chain; inline
    /// `scheme://` entries pass through without an alias declaration.
    #[test]
    fn reference_routes_through_providers_chain() {
        let _env = crate::tests::scrub_resolution_env();
        let spec = spec_with_provider(None);
        let uris = read_uris(
            &spec,
            &ref_secret(Some(vec!["onepassword://Production", "keyring://"])),
            None,
        );
        assert_eq!(
            uris,
            Some(vec![
                "onepassword://Production".to_string(),
                "keyring://".to_string()
            ])
        );
    }

    /// The write path follows the same routing: first chain entry without an
    /// override, the override when present.
    #[test]
    fn write_provider_follows_routing() {
        let _env = crate::tests::scrub_resolution_env();
        let spec = spec_with_provider(None);
        let write_provider = |override_arg: Option<&str>| {
            let override_spec = spec.explicit_provider_spec(override_arg);
            let route = spec
                .route_for(
                    &ref_secret(Some(vec!["onepassword://Production"])),
                    &override_spec,
                )
                .unwrap();
            spec.write_provider_for_route(&route, None).unwrap()
        };

        assert_eq!(write_provider(None).name(), "onepassword");
        assert_eq!(write_provider(Some("dotenv://.env.mock")).name(), "dotenv");
    }

    /// Run the executor's pre-fetch coordinate check over a plan holding a
    /// single `default`-profile secret, exactly as `execute_plan` runs it: one
    /// built provider per primary-store group.
    fn check_ref_coords_of(secret: Secret) -> Result<()> {
        let mut secrets = HashMap::new();
        secrets.insert("SECRET".to_string(), secret);
        let spec = Secrets::new(crate::tests::resolve_test_config(secrets), None, None, None);
        let plan = spec.build_plan(None).unwrap();
        for (primary, group) in plan.groups() {
            let provider = spec.get_route_provider(primary, None).unwrap();
            spec.check_single_store_ref_coords(
                primary,
                &group,
                provider.as_ref(),
                &spec.config.project.name,
                "default",
            )?;
        }
        Ok(())
    }

    /// A `ref` routed at a single store that cannot honor its coordinates is
    /// rejected up front: dotenv keys have no `field`, so a `field` ref fails.
    #[test]
    fn single_store_ref_with_unsupported_coord_is_rejected() {
        let _env = crate::tests::scrub_resolution_env();
        assert!(
            check_ref_coords_of(ref_secret(Some(vec!["dotenv:///tmp/x"]))).is_err(),
            "a single-store ref with an unsupported coordinate must be rejected"
        );
    }

    /// The same unsupported `ref` on a multi-store chain is NOT rejected up
    /// front: coordinate checking defers to per-store read-time, so a later
    /// store that cannot express the coordinate never blocks a primary that can.
    #[test]
    fn multi_store_ref_defers_coord_validation() {
        let _env = crate::tests::scrub_resolution_env();
        assert!(
            check_ref_coords_of(ref_secret(Some(vec!["dotenv:///tmp/a", "dotenv:///tmp/b"])))
                .is_ok(),
            "a multi-store ref must defer coordinate checking to read time"
        );
    }
}