powerliners 0.2.14

1:1 Rust port of powerline/powerline. The ultimate statusline/prompt utility
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
// vim:fileencoding=utf-8:noet
//! Shared render runtime: bin-private orchestration that lives
//! under `src/bin/` (sanctioned non-port location per PORT.md).
//!
//! `powerline-daemon` wires this through the daemon main_loop;
//! `powerline-render` calls `render_once` directly for one-shot
//! rendering. The fn surface here is bin-glue, not a port — no
//! Python source corresponds because Python uses dynamic
//! `__import__` to dispatch segment fns at runtime; the Rust
//! port replaces that with a static `ADAPTERS` registry.

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;

use serde_json::{Map, Value};

use powerliners::ported::colorscheme::Colorscheme;
use powerliners::ported::commands::main::Args;
use powerliners::ported::lib::config::load_json_config;
use powerliners::ported::lib::dict::mergedicts;
use powerliners::ported::renderer::{RenderReturn, Renderer};
use powerliners::ported::renderers::tmux::{ColorSpec, TmuxRenderer};
use powerliners::ported::renderers::vim::{ColorSpec as VimColorSpec, VimRenderer};
use powerliners::ported::segment::gen_segment_getter;
use powerliners::ported::theme::Theme;
use powerliners::ported::{_find_config_files, get_config_paths};

/// Adapter signature for one built-in segment fn.
/// Reads from `args` (segment kwargs) + `segment_info` (runtime env)
/// and returns either a string (single chunk) or list-of-dicts (multi-
/// chunk) as `Value`.
type AdapterFn = fn(&Map<String, Value>, &Map<String, Value>) -> Option<Value>;

fn search_paths() -> Vec<PathBuf> {
    // Mirror upstream `ShellPowerline.get_config_paths`
    // (powerline/shell.py:25-26): `return self.args.config_path or
    // super().get_config_paths()`. When POWERLINE_CONFIG_PATHS is
    // set it REPLACES the default cascade entirely — no bundled
    // fallback. Test fixtures rely on this to pin a self-contained
    // config tree.
    if let Ok(pcp) = std::env::var("POWERLINE_CONFIG_PATHS") {
        let explicit: Vec<PathBuf> = pcp
            .split(':')
            .filter(|s| !s.is_empty())
            .map(PathBuf::from)
            .collect();
        if !explicit.is_empty() {
            return explicit;
        }
    }
    // Default cascade: bundled `plugin_path` FIRST (py:152) so
    // load_cascade uses it as the base, then XDG / user_home come
    // AFTER so mergedicts(base, override) lets the user win.
    //
    // Source-of-truth for the bundled tree is
    // `src/ported/config_files/` baked into the binary via
    // `include_str!` and extracted to `$XDG_CACHE_HOME/powerliners/
    // config_files/` on first call — install-method-agnostic
    // (works for cargo install, brew, release tarball).
    let mut paths: Vec<PathBuf> = Vec::new();
    // Prefer the live checkout when `cargo install --path .` baked
    // a real CARGO_MANIFEST_DIR — dev iteration is faster when edits
    // to `src/ported/config_files/*.json` show up without a
    // rebuild-and-extract cycle.
    if let Some(manifest) = option_env!("CARGO_MANIFEST_DIR") {
        let ported = PathBuf::from(manifest).join("src/ported/config_files");
        if ported.is_dir() {
            paths.push(ported);
        }
    }
    // Fallback: extracted-cache copy of the bundled tree. Always
    // pushed so release-tarball installs (where the manifest path
    // is unreachable, e.g. `/Users/runner/work/...`) still find a
    // valid base layer. Implementation in
    // `src/extensions/bundled_config.rs` so all three bins
    // (daemon, render, config) share the same extraction.
    if let Some(cache) = powerliners::extensions::bundled_config::bundled_config_dir() {
        // Avoid duplicate-load when manifest path === cache path
        // (paranoid; they're never equal in practice).
        if !paths.contains(&cache) {
            paths.push(cache);
        }
    }
    paths.extend(get_config_paths());
    paths
}

fn load_one(name: &str, paths: &[PathBuf]) -> Option<Map<String, Value>> {
    let matches = _find_config_files(paths, name).ok()?;
    let p = matches.first()?;
    let v = load_json_config(p).ok()?;
    v.as_object().cloned()
}

fn load_cascade(levels: &[String], paths: &[PathBuf]) -> Option<Map<String, Value>> {
    // py:191-200  load_config: iterate ALL matches per level and merge
    // them in find-order. Upstream `get_config_paths` puts bundled
    // FIRST and user-config LAST, so later matches override earlier
    // — exactly the user-overrides-bundled semantics. Earlier
    // versions only loaded `matches.first()` which silently dropped
    // bundled fallback groups (e.g. tmux/`window:current` highlight).
    let mut out: Map<String, Value> = Map::new();
    let mut loaded = 0u32;
    for level in levels {
        if let Ok(matches) = _find_config_files(paths, level) {
            for p in &matches {
                if let Ok(v) = load_json_config(p) {
                    if let Some(o) = v.as_object().cloned() {
                        mergedicts(&mut out, o, true);
                        loaded += 1;
                    }
                }
            }
        }
    }
    if loaded == 0 {
        None
    } else {
        Some(out)
    }
}

#[derive(Clone)]
pub struct Configs {
    /// Active ext name (`shell`, `tmux`, `vim`, …). Drives the
    /// markup-format dispatch in `render_once`. Stored as a string
    /// rather than an enum so future exts can be added without
    /// expanding a closed set.
    pub ext: String,
    pub colorscheme: Arc<Colorscheme>,
    pub theme: Arc<Theme>,
    pub tmux: Arc<TmuxRenderer>,
    /// VimRenderer state — populated only when `ext == "vim"`. Held
    /// behind `Mutex` because `VimRenderer::hlstyle()` mutates the
    /// internal `(fg, bg, attrs) -> hl_group` cache. Daemon caches
    /// `Configs` per-ext so the cache persists across requests within
    /// one daemon lifetime, keeping `:hi` redefinitions to a minimum.
    pub vim: Option<Arc<std::sync::Mutex<VimRenderer>>>,
    /// py:265-272 — WM extensions consume `update_interval` to drive
    /// background re-render. tmux daemon path doesn't run a WM thread;
    /// surfaced here so a future WM dispatch can read the configured
    /// value (default 2 seconds per upstream).
    #[allow(dead_code)]
    wm_update_interval: f64,
    /// py:133-141  `reload_config` (default true) — when true, the
    /// daemon polls cached config-file mtimes on each render and
    /// invalidates the cache when any have changed. Mirrors upstream
    /// `ConfigLoader.check` semantics with a per-request stat instead
    /// of a background watcher thread (the
    /// `lib/watcher/{inotify,stat,uv,tree}.rs` ports are ready but
    /// not threaded here to keep the daemon process model simple).
    /// Read by the daemon bin only — render bin doesn't cache.
    #[allow(dead_code)]
    pub reload_config: bool,
    /// Paths whose mtimes are checked when `reload_config` is true.
    /// Read by the daemon bin only — render bin doesn't cache.
    #[allow(dead_code)]
    pub loaded_paths: Vec<(PathBuf, std::time::SystemTime)>,
}

impl Configs {
    /// Returns true if any `loaded_paths` entry has a different mtime
    /// vs load time — mirrors `ConfigLoader.check` at
    /// `lib/config.py:130-141`. Called from the daemon bin only.
    #[allow(dead_code)]
    pub fn is_stale(&self) -> bool {
        if !self.reload_config {
            return false;
        }
        loaded_paths_are_stale(&self.loaded_paths)
    }
}

/// Free-fn extraction of [`Configs::is_stale`]'s mtime-walk so the
/// stale-detection logic can be unit-tested without constructing a
/// full `Configs` (which requires `Arc<Theme>`, `Arc<Colorscheme>`,
/// etc.). `reload_config: false` is handled by the caller — this
/// helper always walks the list.
fn loaded_paths_are_stale(loaded_paths: &[(PathBuf, std::time::SystemTime)]) -> bool {
    for (p, t) in loaded_paths {
        match std::fs::metadata(p).and_then(|m| m.modified()) {
            Ok(now) if now != *t => return true,
            Err(_) => return true,
            _ => {}
        }
    }
    false
}

/// Snapshot mtime of `path` for the `loaded_paths` cache. Returns
/// SystemTime::UNIX_EPOCH when the stat fails so a follow-up
/// `is_stale` check naturally returns true (treats missing as
/// changed).
fn mtime_or_epoch(path: &PathBuf) -> std::time::SystemTime {
    std::fs::metadata(path)
        .and_then(|m| m.modified())
        .unwrap_or(std::time::SystemTime::UNIX_EPOCH)
}

/// Free-fn extraction of `build_configs`'s loaded_paths population
/// so the cascade-iteration logic is unit-testable. Returns one
/// `(path, mtime)` entry per match per level — every layer of the
/// search-path cascade, not just `matches.first()`. See the bug-fix
/// commit message for why this matters.
fn collect_loaded_paths(
    paths: &[PathBuf],
    probe_levels: &[String],
) -> Vec<(PathBuf, std::time::SystemTime)> {
    let mut out: Vec<(PathBuf, std::time::SystemTime)> = Vec::new();
    for level in probe_levels {
        if let Ok(matches) = _find_config_files(paths, level) {
            for p in matches {
                let mt = mtime_or_epoch(&p);
                out.push((p, mt));
            }
        }
    }
    out
}

pub fn build_configs(ext: &str) -> Result<Configs, String> {
    let paths = search_paths();
    let main = load_one("config", &paths).ok_or("config.json not found")?;
    let colors_json = load_one("colors", &paths).ok_or("colors.json not found")?;

    let (cs_name, theme_name) = {
        let mut cs = "default".to_string();
        let mut th = "default".to_string();
        if let Some(ext_block) = main
            .get("ext")
            .and_then(|v| v.as_object())
            .and_then(|o| o.get(ext))
            .and_then(|v| v.as_object())
        {
            if let Some(s) = ext_block.get("colorscheme").and_then(|v| v.as_str()) {
                cs = s.to_string();
            }
            if let Some(s) = ext_block.get("theme").and_then(|v| v.as_str()) {
                th = s.to_string();
            }
        }
        (cs, th)
    };

    let cs_levels = vec![
        format!("colorschemes/{}", cs_name),
        format!("colorschemes/{}/__main__", ext),
        format!("colorschemes/{}/{}", ext, cs_name),
    ];
    let colorscheme_json =
        load_cascade(&cs_levels, &paths).ok_or_else(|| format!("no colorscheme for {}", ext))?;

    // py:324-328  default_top_theme cascade:
    //   1. user `common.default_top_theme` (explicit override)
    //   2. else `get_default_theme(encoding.startswith(utf|ucs))`
    //      → `powerline_terminus` on UTF-8 / `ascii` on legacy
    // Mirrors `finish_common_config` at `powerline/__init__.py:313`.
    use powerliners::ported::get_default_theme;
    use powerliners::ported::lib::encoding::get_preferred_output_encoding;
    let user_top_theme = main
        .get("common")
        .and_then(|c| c.get("default_top_theme"))
        .and_then(|v| v.as_str())
        .map(String::from);
    let computed_top_theme = {
        let enc = get_preferred_output_encoding().to_lowercase();
        get_default_theme(enc.starts_with("utf") || enc.starts_with("ucs"))
    };
    let top_theme: String = user_top_theme.unwrap_or_else(|| computed_top_theme.to_string());
    let top_theme = top_theme.as_str();
    // py:806-810 / py:821-823  Theme cascade has THREE layers:
    // 1. `themes/<top_theme>` (cross-ext defaults: dividers, spaces)
    // 2. `themes/<ext>/__main__` (per-ext defaults: segment_data,
    //    division of segments, …)
    // 3. `themes/<ext>/<theme_name>` (the user's specific theme)
    // Each later layer overrides earlier ones via `mergedicts`. Most
    // shipped exts have a `__main__.json` so dropping the middle
    // layer loses per-ext defaults.
    let theme_levels = vec![
        format!("themes/{}", top_theme),
        format!("themes/{}/__main__", ext),
        format!("themes/{}/{}", ext, theme_name),
    ];
    let theme_json =
        load_cascade(&theme_levels, &paths).ok_or_else(|| format!("no theme for {}", ext))?;

    let colorscheme = Colorscheme::new(&colorscheme_json, &colors_json);

    // Build the Theme.segments table from the theme JSON via gen_segment_getter.
    let get_segment = gen_segment_getter(
        &(),
        ext,
        &Map::new(),
        vec![theme_json.clone()],
        theme_json.get("default_module").and_then(|v| v.as_str()),
        |module: &str, name: &str| {
            // Resolve known module.fn pairs to the adapter registry.
            adapter_id(module, name).is_some()
        },
        Some(top_theme),
    );

    let segments_json = theme_json
        .get("segments")
        .and_then(|v| v.as_object())
        .cloned()
        .unwrap_or_default();

    // Mirrors `Theme.__init__` segments-iteration at upstream
    // `powerline/theme.py:91-105`:
    //   `for segdict in itertools.chain((theme_config['segments'],),
    //                                    theme_config['segments'].get('above', ())):`
    //     `self.segments.append(new_empty_segment_line())`
    //     ... fill left + right ...
    // Each segdict = one line. Line 0 = the base render
    // (`segments.{left,right}`); lines 1..=N = `segments.above[0..]`
    // each a `{left, right}` dict in upstream order.
    let prepare_line = |segdict: &Map<String, Value>| -> Map<String, Value> {
        let mut line_map: Map<String, Value> = Map::new();
        for side in ["left", "right"] {
            let mut side_arr: Vec<Value> = Vec::new();
            if let Some(specs) = segdict.get(side).and_then(|v| v.as_array()) {
                for spec in specs {
                    if let Some(spec_obj) = spec.as_object() {
                        let fn_name = spec_obj
                            .get("function")
                            .and_then(|v| v.as_str())
                            .unwrap_or("?");
                        match get_segment(spec_obj, side) {
                            Some(prepared) => {
                                side_arr.push(Value::Object(prepared));
                            }
                            None => {
                                powerliners::extensions::diag_log::log(&format!(
                                    "prepare_line side={} DROP fn={} (get_segment returned None — module lookup failed)",
                                    side, fn_name
                                ));
                            }
                        }
                    }
                }
            }
            line_map.insert(side.to_string(), Value::Array(side_arr));
        }
        line_map
    };

    let mut lines: Vec<Map<String, Value>> = Vec::new();
    // Base line first (theme.py:91 `(theme_config['segments'],)`).
    lines.push(prepare_line(&segments_json));
    // Then each entry under `segments.above`. Python uses tuple()
    // default → empty iter; Rust mirrors with `unwrap_or_default`.
    if let Some(above_list) = segments_json.get("above").and_then(|v| v.as_array()) {
        for above_seg in above_list {
            if let Some(above_obj) = above_seg.as_object() {
                lines.push(prepare_line(above_obj));
            }
        }
    }

    let dividers = theme_json
        .get("dividers")
        .and_then(|v| v.as_object())
        .cloned()
        .unwrap_or_default();
    let spaces = theme_json
        .get("spaces")
        .and_then(|v| v.as_i64())
        .unwrap_or(1);
    let outer_padding = theme_json
        .get("outer_padding")
        .and_then(|v| v.as_i64())
        .unwrap_or(1);

    let mut empty_seg = Map::new();
    empty_seg.insert("contents".to_string(), Value::Null);
    let mut empty_hl = Map::new();
    empty_hl.insert("fg".to_string(), Value::Bool(false));
    empty_hl.insert("bg".to_string(), Value::Bool(false));
    empty_hl.insert("attrs".to_string(), Value::from(0));
    empty_seg.insert("highlight".to_string(), Value::Object(empty_hl));

    // py:67-70  Theme.__init__: cursor_space → 1 - (theme_config['cursor_space'] / 100)
    // when present (KeyError → None); cursor_columns from theme_config.get.
    let cursor_space_multiplier = theme_json
        .get("cursor_space")
        .and_then(|v| v.as_f64())
        .map(|n| 1.0 - (n / 100.0));
    let cursor_columns = theme_json.get("cursor_columns").and_then(|v| v.as_i64());

    let theme = Theme {
        colorscheme: Value::Null,
        dividers,
        cursor_space_multiplier,
        cursor_columns,
        spaces,
        outer_padding,
        segments: lines,
        empty_segment: Value::Object(empty_seg),
        shutdown_called: std::sync::Mutex::new(Vec::new()),
    };

    // Read common.term_truecolor from main config to drive
    // TmuxRenderer.hlstyle's `fg=#RRGGBB` vs `fg=colourN` branch.
    let term_truecolor = main
        .get("common")
        .and_then(|c| c.get("term_truecolor"))
        .and_then(|v| v.as_bool())
        .unwrap_or(false);

    // py:218-223  ext.wm.update_interval (default 2.0). Read from
    // main config so WM-ext requests can honor it once a WM thread
    // dispatcher lands. The tmux ext path is request-driven and
    // ignores it.
    let wm_update_interval = main
        .get("ext")
        .and_then(|v| v.as_object())
        .and_then(|o| o.get("wm"))
        .and_then(|v| v.as_object())
        .and_then(|o| o.get("update_interval"))
        .and_then(|v| v.as_f64())
        .unwrap_or(2.0);

    // py:133-141  reload_config (default true)
    let reload_config = main
        .get("common")
        .and_then(|c| c.get("reload_config"))
        .and_then(|v| v.as_bool())
        .unwrap_or(true);

    // Collect every config file path our cascade actually consumed so
    // `is_stale` can stat them on subsequent renders. Watches EVERY
    // match across the cascade — user-layer files come last in
    // search_paths and would be missed if we only registered
    // `matches.first()`. See `collect_loaded_paths` for the
    // bug-history details.
    let probe_levels: Vec<String> = vec![
        "config".to_string(),
        "colors".to_string(),
        format!("colorschemes/{}", cs_name),
        format!("colorschemes/{}/__main__", ext),
        format!("colorschemes/{}/{}", ext, cs_name),
        format!("themes/{}", top_theme),
        format!("themes/{}/__main__", ext),
        format!("themes/{}/{}", ext, theme_name),
    ];
    let loaded_paths = collect_loaded_paths(&paths, &probe_levels);

    let vim = if ext == "vim" {
        Some(Arc::new(std::sync::Mutex::new(VimRenderer::new())))
    } else {
        None
    };
    Ok(Configs {
        ext: ext.to_string(),
        colorscheme: Arc::new(colorscheme),
        theme: Arc::new(theme),
        tmux: Arc::new(TmuxRenderer::new(term_truecolor)),
        vim,
        wm_update_interval,
        reload_config,
        loaded_paths,
    })
}

/// Look up the segment id (module + name) in the adapter registry.
/// Returns the canonical "module.name" form on match, None on miss.
///
/// Falls back to filesystem-resolved scripts under
/// `<config_path>/segments/<module>/<name>.{sh,py,...}` per
/// `extensions::exec_segment::resolve_dotted_path` semantics. This is
/// what makes user-authored segments work without touching the binary:
/// drop a script in `~/.config/powerline/segments/myseg/cpu_temp.sh`
/// and theme JSON can reference `"function": "myseg.cpu_temp"`.
pub fn adapter_id(module: &str, name: &str) -> Option<String> {
    let full = format!("{}.{}", module, name);
    if ADAPTERS.iter().any(|(k, _)| *k == full.as_str()) {
        return Some(full);
    }
    // Bare-name fallback in ADAPTERS — theme JSON writes
    // `"function": "exec"`, default_module expands to
    // `powerline.segments.exec` which doesn't exist, retry with just
    // `exec` so the short alias hits.
    if ADAPTERS.iter().any(|(k, _)| *k == name) {
        return Some(name.to_string());
    }
    // Fallback: filesystem-resolved script under <config_path>/segments/.
    let paths = search_paths();
    if powerliners::extensions::exec_segment::resolve_dotted_path(&full, &paths).is_some() {
        return Some(full);
    }
    if powerliners::extensions::exec_segment::resolve_dotted_path(name, &paths).is_some() {
        return Some(name.to_string());
    }
    None
}

pub fn invoke_adapter(
    id: &str,
    args: &Map<String, Value>,
    segment_info: &Map<String, Value>,
) -> Option<Value> {
    if let Some(entry) = ADAPTERS.iter().find(|(k, _)| *k == id) {
        return entry.1(args, segment_info);
    }
    // Bare-name fallback in ADAPTERS — `gen_segment_getter` stamps
    // the id as `<default_module>.<function_name>`, so a theme that
    // writes `"function": "exec"` arrives here as
    // `"powerline.segments.tmux.exec"`. Retry with the trailing
    // component so the short-form alias hits.
    if let Some(tail) = id.rsplit('.').next() {
        if tail != id {
            if let Some(entry) = ADAPTERS.iter().find(|(k, _)| *k == tail) {
                return entry.1(args, segment_info);
            }
        }
    }
    // Fallback: dotted-path → script dispatch. Theme can pass `args`,
    // `format`, `highlight_groups` through the segment kwargs (option
    // B) — same surface as the explicit `exec` adapter (option A).
    let script_args: Vec<String> = args
        .get("args")
        .and_then(|v| v.as_array())
        .map(|a| {
            a.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();
    let format = args.get("format").and_then(|v| v.as_str());
    let highlight_groups: Vec<String> = args
        .get("highlight_groups")
        .and_then(|v| v.as_array())
        .map(|a| {
            a.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();
    let hg_slice: Option<&[String]> = if highlight_groups.is_empty() {
        None
    } else {
        Some(&highlight_groups)
    };
    powerliners::extensions::exec_segment::exec_by_dotted_path(
        id,
        &search_paths(),
        &script_args,
        format,
        hg_slice,
    )
    .map(Value::Array)
}

// =============================================================
// Adapters: each maps a built-in Rust segment fn into the
// dispatcher's uniform signature. Lives in the bin (non-port).
// =============================================================

fn ad_hostname(args: &Map<String, Value>, info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::net::hostname;
    let environ = info
        .get("environ")
        .and_then(|v| v.as_object())
        .cloned()
        .unwrap_or_default();
    let only_if_ssh = args
        .get("only_if_ssh")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let exclude_domain = args
        .get("exclude_domain")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let s = hostname(&environ, only_if_ssh, exclude_domain, || {
        std::process::Command::new("hostname")
            .output()
            .ok()
            .and_then(|o| String::from_utf8(o.stdout).ok())
            .map(|s| s.trim().to_string())
            .unwrap_or_default()
    })?;
    Some(Value::String(s))
}

fn ad_date(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::time::date;
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or("%Y-%m-%d");
    let istime = args
        .get("istime")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let timezone = args.get("timezone").and_then(|v| v.as_str());
    let chunks = date(&(), format, istime, timezone);
    Some(Value::Array(chunks))
}

fn read_cpu_percent() -> f64 {
    // `top -l 1 -s 0 -n 0` takes ~300ms on macOS — too slow for a
    // per-tick segment with tmux's `#()` ready threshold. Cache the
    // last reading for 2 seconds (matches the typical
    // `status-interval`); subsequent renders reuse the value.
    use std::sync::Mutex;
    use std::time::{Duration, Instant};
    static CACHE: std::sync::OnceLock<Mutex<Option<(Instant, f64)>>> = std::sync::OnceLock::new();
    let cell = CACHE.get_or_init(|| Mutex::new(None));
    if let Ok(guard) = cell.lock() {
        if let Some((t, v)) = *guard {
            if t.elapsed() < Duration::from_millis(1900) {
                return v;
            }
        }
    }
    let pct = read_cpu_percent_uncached();
    if let Ok(mut guard) = cell.lock() {
        *guard = Some((Instant::now(), pct));
    }
    pct
}

fn read_cpu_percent_uncached() -> f64 {
    #[cfg(target_os = "macos")]
    {
        if let Ok(out) = std::process::Command::new("top")
            .args(["-l", "1", "-s", "0", "-n", "0"])
            .output()
        {
            let text = String::from_utf8_lossy(&out.stdout);
            for line in text.lines() {
                if let Some(rest) = line.strip_prefix("CPU usage: ") {
                    let mut user = 0.0f64;
                    let mut sys = 0.0f64;
                    for part in rest.split(',') {
                        let part = part.trim();
                        if let Some(p) = part.strip_suffix("% user") {
                            user = p.trim().parse().unwrap_or(0.0);
                        } else if let Some(p) = part.strip_suffix("% sys") {
                            sys = p.trim().parse().unwrap_or(0.0);
                        }
                    }
                    return user + sys;
                }
            }
        }
    }
    #[cfg(target_os = "linux")]
    {
        let read = || -> Option<(u64, u64)> {
            let s = std::fs::read_to_string("/proc/stat").ok()?;
            let line = s.lines().next()?;
            let parts: Vec<u64> = line
                .split_whitespace()
                .skip(1)
                .filter_map(|p| p.parse().ok())
                .collect();
            let total: u64 = parts.iter().sum();
            let idle = *parts.get(3)?;
            Some((total, idle))
        };
        if let (Some((t1, i1)), _) = (
            read(),
            std::thread::sleep(std::time::Duration::from_millis(100)),
        ) {
            if let Some((t2, i2)) = read() {
                let dt = t2.saturating_sub(t1) as f64;
                let di = i2.saturating_sub(i1) as f64;
                if dt > 0.0 {
                    return 100.0 * (1.0 - di / dt);
                }
            }
        }
    }
    0.0
}

fn ad_cpu_load_percent(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::extensions::icons;
    use powerliners::ported::segments::common::sys::render as cpu_render;
    // Default format leads with the cpu glyph from the active tier
    // (NF → Unicode → ASCII per `POWERLINERS_ICONS`). Themes can
    // still override `format` per-segment.
    let default = format!("{} {{0:.0f}}%", icons::cpu());
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or(&default);
    let pct = read_cpu_percent();
    let chunks = cpu_render(pct, format);
    Some(Value::Array(chunks))
}

fn ad_mem_usage(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::extensions::icons;
    use powerliners::extensions::mem_usage::mem_usage;
    let default = format!("{} %s/%s", icons::memory());
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or(&default);
    let mem_type = args
        .get("mem_type")
        .and_then(|v| v.as_str())
        .unwrap_or("used");
    let short = args.get("short").and_then(|v| v.as_bool()).unwrap_or(false);
    Some(Value::Array(mem_usage(format, mem_type, short)))
}

fn ad_mem_usage_percent(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::extensions::icons;
    use powerliners::extensions::mem_usage::mem_usage_percent;
    let default = format!("{} %d%%", icons::memory());
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or(&default);
    let mem_type = args
        .get("mem_type")
        .and_then(|v| v.as_str())
        .unwrap_or("used");
    Some(Value::Array(mem_usage_percent(format, mem_type)))
}

fn ad_mem_swap(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::extensions::icons;
    use powerliners::extensions::mem_usage::mem_swap;
    let default = format!("{} %s/%s", icons::swap());
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or(&default);
    let mem_type = args
        .get("mem_type")
        .and_then(|v| v.as_str())
        .unwrap_or("used");
    let short = args.get("short").and_then(|v| v.as_bool()).unwrap_or(false);
    Some(Value::Array(mem_swap(format, mem_type, short)))
}

fn ad_gpu_usage_percent(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::extensions::gpu::gpu_usage_percent;
    use powerliners::extensions::icons;
    let default = format!("{} {{0:d}}%", icons::gpu());
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or(&default);
    Some(Value::Array(gpu_usage_percent(format)))
}

fn ad_gpu_vram(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::extensions::gpu::gpu_vram;
    use powerliners::extensions::icons;
    let default = format!("{}{} %s/%s", icons::gpu(), icons::memory());
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or(&default);
    let short = args.get("short").and_then(|v| v.as_bool()).unwrap_or(false);
    Some(Value::Array(gpu_vram(format, short)))
}

fn ad_disk_usage(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::extensions::disk::disk_usage;
    use powerliners::extensions::icons;
    let mount = args.get("mount").and_then(|v| v.as_str()).unwrap_or("/");
    let default = format!("{} %s/%s", icons::disk());
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or(&default);
    let short = args.get("short").and_then(|v| v.as_bool()).unwrap_or(false);
    Some(Value::Array(disk_usage(mount, format, short)))
}

fn ad_disk_usage_percent(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::extensions::disk::disk_usage_percent;
    use powerliners::extensions::icons;
    let mount = args.get("mount").and_then(|v| v.as_str()).unwrap_or("/");
    let default = format!("{} {{0:d}}%", icons::disk());
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or(&default);
    Some(Value::Array(disk_usage_percent(mount, format)))
}

fn ad_disk_io(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::extensions::disk::disk_io;
    use powerliners::extensions::icons;
    let device = args
        .get("device")
        .and_then(|v| v.as_str())
        .unwrap_or("auto");
    let default = format!("{} {} R %s W %s", icons::disk(), icons::io());
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or(&default);
    let short = args.get("short").and_then(|v| v.as_bool()).unwrap_or(true);
    let recv_max = args
        .get("recv_max")
        .and_then(|v| v.as_f64())
        .unwrap_or(100.0 * 1024.0 * 1024.0);
    let sent_max = args
        .get("sent_max")
        .and_then(|v| v.as_f64())
        .unwrap_or(100.0 * 1024.0 * 1024.0);
    Some(Value::Array(disk_io(
        device, format, short, recv_max, sent_max,
    )))
}

fn ad_git_status(args: &Map<String, Value>, info: &Map<String, Value>) -> Option<Value> {
    use powerliners::extensions::git_status::git_status;
    let cwd = info.get("getcwd").and_then(|v| v.as_str()).unwrap_or("/");
    let pick = |key: &str, default: &str| -> String {
        args.get(key)
            .and_then(|v| v.as_str())
            .unwrap_or(default)
            .to_string()
    };
    // Defaults mirror p10k-lean.zsh symbols + the Powerline branch
    // glyph (U+E0A0). `github_icon` defaults to Nerd Font's
    // nf-fa-github_alt (U+F09B) — empty string in the theme JSON
    // disables the prefix for non-NF fonts.
    use powerliners::extensions::icons;
    let branch_icon = pick("branch_icon", icons::branch());
    let github_icon = pick("github_icon", icons::github());
    let tag_icon = pick("tag_icon", icons::tag());
    let unstaged_icon = pick("unstaged_icon", "!");
    let untracked_icon = pick("untracked_icon", "?");
    let staged_icon = pick("staged_icon", "+");
    let conflict_icon = pick("conflict_icon", "~");
    let ahead_icon = pick("ahead_icon", "");
    let behind_icon = pick("behind_icon", "");
    let stash_icon = pick("stash_icon", "*");
    let status_colors = args
        .get("status_colors")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    git_status(
        cwd,
        &branch_icon,
        &github_icon,
        &tag_icon,
        &unstaged_icon,
        &untracked_icon,
        &staged_icon,
        &conflict_icon,
        &ahead_icon,
        &behind_icon,
        &stash_icon,
        status_colors,
    )
    .map(Value::Array)
}

fn ad_thermal(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::extensions::icons;
    use powerliners::extensions::thermal::thermal;
    let family = args.get("family").and_then(|v| v.as_str()).unwrap_or("cpu");
    // Pick the family-matching glyph by default so a single template
    // serves both `family=cpu` and `family=gpu`. GPU has no usable
    // fan RPM probe (Apple SMC kext is entitled), so the gpu default
    // drops the `%sRPM` tail.
    let default = match family {
        "gpu" => format!("{} %s°C", icons::gpu()),
        _ => format!("{} %s°C %sRPM", icons::cpu()),
    };
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or(&default);
    let temp_max = args
        .get("temp_max")
        .and_then(|v| v.as_f64())
        .unwrap_or(95.0);
    Some(Value::Array(thermal(family, format, temp_max)))
}

fn ad_mem_swap_percentage(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::extensions::icons;
    use powerliners::extensions::mem_usage::mem_swap_percentage;
    let default = format!("{} %d%%", icons::swap());
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or(&default);
    let mem_type = args
        .get("mem_type")
        .and_then(|v| v.as_str())
        .unwrap_or("used");
    Some(Value::Array(mem_swap_percentage(format, mem_type)))
}

fn ad_docker_containers(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::extensions::docker::containers;
    use powerliners::extensions::icons;
    let default = format!("{} {{running}}/{{total}}", icons::docker());
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or(&default);
    let cli = args.get("cli").and_then(|v| v.as_str()).unwrap_or("docker");
    let show_when_zero = args
        .get("show_when_zero")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    containers(cli, format, show_when_zero).map(Value::Array)
}

fn ad_kubecontext(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::extensions::icons;
    use powerliners::extensions::k8s::kubecontext;
    let default = format!("{} {{context}}:{{namespace}}", icons::kubernetes());
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or(&default);
    let cli = args
        .get("cli")
        .and_then(|v| v.as_str())
        .unwrap_or("kubectl");
    let default_namespace = args
        .get("default_namespace")
        .and_then(|v| v.as_str())
        .unwrap_or("default");
    let hide_default = args
        .get("hide_default")
        .and_then(|v| v.as_bool())
        .unwrap_or(true);
    kubecontext(cli, format, default_namespace, hide_default).map(Value::Array)
}

fn ad_github_ci(args: &Map<String, Value>, info: &Map<String, Value>) -> Option<Value> {
    use powerliners::extensions::github_ci::ci_status;
    use powerliners::extensions::icons;
    let cwd = info.get("getcwd").and_then(|v| v.as_str()).unwrap_or("/");
    // Default template: github prefix + state-picked CI glyph + passed/total.
    // The `{icon}` token is the check_circle / x_circle / sync glyph
    // picked by `ci_status()` so the user sees " ✓ 5/5" / " ✗ 2/5" /
    // " ⟳ 3/5" — no "ok"/"fail" text word to decode.
    // Unicode tier returns an empty github glyph (no canonical text
    // equivalent exists); skip the leading prefix in that case to
    // avoid a stray leading space.
    let gh = icons::github();
    let default = if gh.is_empty() {
        "{icon} {passed}/{total}".to_string()
    } else {
        format!("{gh} {{icon}} {{passed}}/{{total}}")
    };
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or(&default);
    let cli = args.get("cli").and_then(|v| v.as_str()).unwrap_or("gh");
    let ttl_secs = args.get("ttl_secs").and_then(|v| v.as_u64()).unwrap_or(30);
    let ok_icon = args
        .get("ok_icon")
        .and_then(|v| v.as_str())
        .unwrap_or(icons::ci_ok());
    let fail_icon = args
        .get("fail_icon")
        .and_then(|v| v.as_str())
        .unwrap_or(icons::ci_fail());
    let run_icon = args
        .get("run_icon")
        .and_then(|v| v.as_str())
        .unwrap_or(icons::ci_run());
    ci_status(cwd, cli, format, ttl_secs, ok_icon, fail_icon, run_icon).map(Value::Array)
}

fn ad_aws_context(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::extensions::aws_ctx::context;
    use powerliners::extensions::icons;
    let default = format!("{} {{profile}}@{{region}}", icons::aws());
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or(&default);
    let hide_default_profile = args
        .get("hide_default_profile")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    // Honor the AWS icon override the same way k8s lets themes pin a
    // custom glyph — strips the leading `{icon}` swap once if present.
    let format = if let Some(custom) = args.get("icon").and_then(|v| v.as_str()) {
        format.replacen(icons::aws(), custom, 1)
    } else {
        format.to_string()
    };
    context(&format, hide_default_profile).map(Value::Array)
}

fn ad_gcp_context(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::extensions::gcp_ctx::context;
    use powerliners::extensions::icons;
    let default = format!("{} {{project}}:{{account}}", icons::gcp());
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or(&default);
    let hide_account = args
        .get("hide_account")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let format = if let Some(custom) = args.get("icon").and_then(|v| v.as_str()) {
        format.replacen(icons::gcp(), custom, 1)
    } else {
        format.to_string()
    };
    context(&format, hide_account).map(Value::Array)
}

fn ad_zshrs_version(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::extensions::icons;
    use powerliners::extensions::zshrs_version::version;
    let default = format!("{} {{version}}", icons::zshrs());
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or(&default);
    let bin = args.get("bin").and_then(|v| v.as_str()).unwrap_or("zshrs");
    let ttl_secs = args.get("ttl_secs").and_then(|v| v.as_u64()).unwrap_or(300);
    version(bin, format, ttl_secs).map(Value::Array)
}

fn ad_stryke_version(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::extensions::icons;
    use powerliners::extensions::stryke_version::version;
    let default = format!("{} {{version}}", icons::stryke());
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or(&default);
    let bin = args.get("bin").and_then(|v| v.as_str()).unwrap_or("stryke");
    let ttl_secs = args.get("ttl_secs").and_then(|v| v.as_u64()).unwrap_or(300);
    version(bin, format, ttl_secs).map(Value::Array)
}

fn ad_awkrs_version(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::extensions::awkrs_version::version;
    use powerliners::extensions::icons;
    let default = format!("{} {{version}}", icons::awkrs());
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or(&default);
    let bin = args.get("bin").and_then(|v| v.as_str()).unwrap_or("awkrs");
    let ttl_secs = args.get("ttl_secs").and_then(|v| v.as_u64()).unwrap_or(300);
    version(bin, format, ttl_secs).map(Value::Array)
}

fn ad_awkrs_rkyv_cache(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::extensions::awkrs_rkyv::rkyv_cache;
    use powerliners::extensions::icons;
    let default = format!("{} {{size}}", icons::awkrs());
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or(&default);
    let path = args.get("path").and_then(|v| v.as_str()).unwrap_or("");
    let show_when_empty = args
        .get("show_when_empty")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    rkyv_cache(path, format, show_when_empty).map(Value::Array)
}

fn ad_zshrs_rkyv_cache(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::extensions::icons;
    use powerliners::extensions::zshrs_rkyv::rkyv_cache;
    let default = format!("{} {{size}}", icons::zshrs());
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or(&default);
    let path = args.get("path").and_then(|v| v.as_str()).unwrap_or("");
    let show_when_empty = args
        .get("show_when_empty")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    rkyv_cache(path, format, show_when_empty).map(Value::Array)
}

fn ad_stryke_rkyv_cache(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::extensions::icons;
    use powerliners::extensions::stryke_rkyv::rkyv_cache;
    let default = format!("{} {{size}}", icons::stryke());
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or(&default);
    let path = args.get("path").and_then(|v| v.as_str()).unwrap_or("");
    let show_when_empty = args
        .get("show_when_empty")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    rkyv_cache(path, format, show_when_empty).map(Value::Array)
}

fn ad_fusevm_jit_cache(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::extensions::fusevm_jit::jit_cache;
    use powerliners::extensions::icons;
    // Prefix each number with a label-glyph so "142" is clearly an
    // entry count and "18.4M" is clearly on-disk size. Without these
    // prefixes the segment renders as " 142 18.4M" — unreadable.
    let default = format!(
        "{} {} {{entries}} {} {{size}}",
        icons::fusevm(),
        icons::count(),
        icons::harddisk(),
    );
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or(&default);
    let path = args.get("path").and_then(|v| v.as_str()).unwrap_or("");
    let show_when_empty = args
        .get("show_when_empty")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    jit_cache(path, format, show_when_empty).map(Value::Array)
}

fn ad_process_count(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::extensions::icons;
    use powerliners::extensions::proc_count::process_count;
    let default = format!("{} {{total}}", icons::process());
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or(&default);
    let warn_zombie = args
        .get("warn_zombie")
        .and_then(|v| v.as_bool())
        .unwrap_or(true);
    process_count(format, warn_zombie).map(Value::Array)
}

fn ad_exec(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    // Option A — explicit `exec` adapter. Theme JSON:
    //   { "function": "exec",
    //     "args": { "command": "/path/to/script.sh",
    //               "args": ["arg1", "arg2"],
    //               "format": "cpu: %s%%",
    //               "highlight_groups": ["cpu_load"] } }
    use powerliners::extensions::exec_segment::exec_segment;
    let command = args.get("command").and_then(|v| v.as_str())?;
    let script_args: Vec<String> = args
        .get("args")
        .and_then(|v| v.as_array())
        .map(|a| {
            a.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();
    let format = args.get("format").and_then(|v| v.as_str());
    let highlight_groups: Vec<String> = args
        .get("highlight_groups")
        .and_then(|v| v.as_array())
        .map(|a| {
            a.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();
    let hg_slice: Option<&[String]> = if highlight_groups.is_empty() {
        None
    } else {
        Some(&highlight_groups)
    };
    exec_segment(command, &script_args, format, None, None, hg_slice).map(Value::Array)
}

fn ad_system_load(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::sys::system_load;
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or("{avg:.1f}");
    let threshold_good = args
        .get("threshold_good")
        .and_then(|v| v.as_f64())
        .unwrap_or(1.0);
    let threshold_bad = args
        .get("threshold_bad")
        .and_then(|v| v.as_f64())
        .unwrap_or(2.0);
    let track_cpu_count = args
        .get("track_cpu_count")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let short = args.get("short").and_then(|v| v.as_bool()).unwrap_or(false);
    let _ = (threshold_good, threshold_bad, track_cpu_count, short);
    Some(Value::Array(system_load(
        &(),
        format,
        threshold_good,
        threshold_bad,
        track_cpu_count,
        short,
    )?))
}

fn ad_uptime(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::sys::uptime;
    let days_format = args
        .get("days_format")
        .and_then(|v| v.as_str())
        .unwrap_or("{days:d}d ");
    let hours_format = args
        .get("hours_format")
        .and_then(|v| v.as_str())
        .unwrap_or("{hours:d}h ");
    let minutes_format = args
        .get("minutes_format")
        .and_then(|v| v.as_str())
        .unwrap_or("{minutes:d}m ");
    let seconds_format = args
        .get("seconds_format")
        .and_then(|v| v.as_str())
        .unwrap_or("{seconds:d}s");
    let shorten_len = args
        .get("shorten_len")
        .and_then(|v| v.as_u64())
        .unwrap_or(3) as usize;
    let s = uptime(
        &(),
        days_format,
        hours_format,
        minutes_format,
        seconds_format,
        shorten_len,
    )?;
    Some(Value::String(s))
}

fn ad_external_ip(_args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::net::{_external_ip, external_ip_render};
    let ip = _external_ip(|| {
        std::process::Command::new("curl")
            .args(["-s", "https://ipv4.icanhazip.com"])
            .output()
            .ok()
            .and_then(|o| String::from_utf8(o.stdout).ok())
            .map(|s| s.trim().to_string())
    });
    let chunks = external_ip_render(ip.as_deref())?;
    Some(Value::Array(chunks))
}

fn ad_internal_ip(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    let interface = args
        .get("interface")
        .and_then(|v| v.as_str())
        .unwrap_or("auto");
    let ipv = args
        .get("ipv")
        .and_then(|v| v.as_u64())
        .map(|n| n as u8)
        .unwrap_or(4);
    let iface = if interface == "auto" {
        // Resolve default route's interface via netstat -rn on darwin /
        // ip route on linux.
        #[cfg(target_os = "macos")]
        {
            let out = std::process::Command::new("netstat")
                .args(["-rn", "-f", "inet"])
                .output()
                .ok()?;
            let text = String::from_utf8_lossy(&out.stdout);
            let mut found: Option<String> = None;
            for line in text.lines() {
                if line.starts_with("default ") {
                    let cols: Vec<&str> = line.split_whitespace().collect();
                    if let Some(name) = cols.get(3) {
                        found = Some(name.to_string());
                        break;
                    }
                }
            }
            found?
        }
        #[cfg(not(target_os = "macos"))]
        {
            let out = std::process::Command::new("ip")
                .args(["route", "show", "default"])
                .output()
                .ok()?;
            let text = String::from_utf8_lossy(&out.stdout);
            text.split_whitespace()
                .skip_while(|s| *s != "dev")
                .nth(1)?
                .to_string()
        }
    } else {
        interface.to_string()
    };

    let out = std::process::Command::new("ifconfig")
        .arg(&iface)
        .output()
        .ok()?;
    let text = String::from_utf8_lossy(&out.stdout);
    let needle = if ipv == 6 { "inet6 " } else { "inet " };
    for line in text.lines() {
        let trimmed = line.trim();
        if let Some(after) = trimmed.strip_prefix(needle) {
            let ip = after.split_whitespace().next()?.to_string();
            if ipv == 4 && ip == "127.0.0.1" {
                continue;
            }
            return Some(Value::String(ip));
        }
    }
    None
}

fn ad_network_load(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::net::render_one;
    let interface = args
        .get("interface")
        .and_then(|v| v.as_str())
        .unwrap_or("auto")
        .to_string();
    // Darwin: netstat -ib gives per-interface byte counters.
    // Linux: /sys/class/net/<iface>/statistics/{rx,tx}_bytes via _get_bytes_sysfs.
    // Stateful per-interface cache: snap1 = prior call's snapshot,
    // snap2 = right now. Delta over the actual elapsed time. Avoids a
    // 500ms snap-sleep-snap window per render — that alone blows
    // through tmux's `#()` ready threshold and triggers <command 'not
    // ready'> across the whole bar.
    use std::sync::Mutex;
    use std::time::Instant;
    #[allow(clippy::type_complexity)]
    static LAST_NET: std::sync::OnceLock<
        Mutex<std::collections::HashMap<String, (Instant, u64, u64)>>,
    > = std::sync::OnceLock::new();
    #[cfg(target_os = "macos")]
    let read = || -> Option<(u64, u64)> {
        let out = std::process::Command::new("netstat")
            .args(["-ibn"])
            .output()
            .ok()?;
        let text = String::from_utf8_lossy(&out.stdout);
        for line in text.lines().skip(1) {
            let cols: Vec<&str> = line.split_whitespace().collect();
            if cols.first().map(|c| *c == interface).unwrap_or(false) {
                let rx: u64 = cols.get(6).and_then(|c| c.parse().ok())?;
                let tx: u64 = cols.get(9).and_then(|c| c.parse().ok())?;
                return Some((rx, tx));
            }
        }
        None
    };
    #[cfg(target_os = "linux")]
    let read = || -> Option<(u64, u64)> {
        let rx =
            std::fs::read_to_string(format!("/sys/class/net/{}/statistics/rx_bytes", interface))
                .ok()?;
        let tx =
            std::fs::read_to_string(format!("/sys/class/net/{}/statistics/tx_bytes", interface))
                .ok()?;
        Some((rx.trim().parse().ok()?, tx.trim().parse().ok()?))
    };
    let bytes = {
        let (rx, tx) = read()?;
        let now = Instant::now();
        let cell = LAST_NET.get_or_init(|| Mutex::new(std::collections::HashMap::new()));
        let mut guard = cell.lock().ok()?;
        let rate = match guard.get(&interface).copied() {
            Some((t0, rx0, tx0)) => {
                let dt = now.duration_since(t0).as_secs_f64();
                if dt > 0.0 {
                    (
                        rx.saturating_sub(rx0) as f64 / dt,
                        tx.saturating_sub(tx0) as f64 / dt,
                    )
                } else {
                    (0.0, 0.0)
                }
            }
            None => (0.0, 0.0),
        };
        guard.insert(interface.clone(), (now, rx, tx));
        (rate.0, rate.1)
    };
    let recv_format = args
        .get("recv_format")
        .and_then(|v| v.as_str())
        .unwrap_or("DL {value:>8}");
    let sent_format = args
        .get("sent_format")
        .and_then(|v| v.as_str())
        .unwrap_or("UL {value:>8}");
    let suffix = args.get("suffix").and_then(|v| v.as_str()).unwrap_or("B/s");
    let si_prefix = args
        .get("si_prefix")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let recv_max = args
        .get("recv_max")
        .and_then(|v| v.as_f64())
        .unwrap_or(1_000_000.0);
    let sent_max = args
        .get("sent_max")
        .and_then(|v| v.as_f64())
        .unwrap_or(1_000_000.0);
    let _ = bytes; // already-rate values; render_one wants raw snapshots
                   // Re-snapshot to feed render_one: it needs (t1, (rx1,tx1)) and (t2, (rx2,tx2)).
    #[cfg(target_os = "macos")]
    let (prev, last) = {
        let read = || -> Option<(f64, (u64, u64))> {
            let out = std::process::Command::new("netstat")
                .args(["-ibn"])
                .output()
                .ok()?;
            let text = String::from_utf8_lossy(&out.stdout);
            for line in text.lines().skip(1) {
                let cols: Vec<&str> = line.split_whitespace().collect();
                if cols.first().map(|c| *c == interface).unwrap_or(false) {
                    let rx: u64 = cols.get(6).and_then(|c| c.parse().ok())?;
                    let tx: u64 = cols.get(9).and_then(|c| c.parse().ok())?;
                    let t = std::time::SystemTime::now()
                        .duration_since(std::time::UNIX_EPOCH)
                        .ok()?
                        .as_secs_f64();
                    return Some((t, (rx, tx)));
                }
            }
            None
        };
        let p = read()?;
        std::thread::sleep(std::time::Duration::from_millis(500));
        let l = read()?;
        (p, l)
    };
    #[cfg(target_os = "linux")]
    let (prev, last) = {
        let read = || -> Option<(f64, (u64, u64))> {
            let rx = std::fs::read_to_string(format!(
                "/sys/class/net/{}/statistics/rx_bytes",
                interface
            ))
            .ok()?
            .trim()
            .parse::<u64>()
            .ok()?;
            let tx = std::fs::read_to_string(format!(
                "/sys/class/net/{}/statistics/tx_bytes",
                interface
            ))
            .ok()?
            .trim()
            .parse::<u64>()
            .ok()?;
            let t = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .ok()?
                .as_secs_f64();
            Some((t, (rx, tx)))
        };
        let p = read()?;
        std::thread::sleep(std::time::Duration::from_millis(500));
        let l = read()?;
        (p, l)
    };
    let chunks = render_one(
        Some(prev),
        Some(last),
        recv_format,
        sent_format,
        suffix,
        si_prefix,
        Some(recv_max),
        Some(sent_max),
    )?;
    Some(Value::Array(chunks))
}

// `needless_return` allowed: the `return` keeps the macOS branch readable
// alongside the `#[cfg(not(target_os = "macos"))] None` tail without
// restructuring around the cfg gate.
#[allow(clippy::needless_return)]
fn ad_spotify(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    // Faithful port path: defer to SpotifyAppleScriptPlayerSegment
    // (Darwin) / spotify_dbus (Linux), then PlayerSegment.__call__
    // formatting, which emits highlight_groups
    // ['player_<state>', 'player'] — upstream players.py:56.
    use powerliners::ported::segments::common::players::{player_segment_call, state_symbols};
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or("{state_symbol} {artist} - {title} ({total})");

    #[cfg(target_os = "macos")]
    let func_stats = {
        use powerliners::ported::segments::common::players::{
            SpotifyAppleScriptPlayerSegment, APPLESCRIPT_STATUS_DELIMITER,
        };
        // py:374-396 — the full 6-field delimited AppleScript.
        // Status order: state | album | artist | title | track_length | player_position
        let script = format!(
            "tell application \"System Events\"\n\
             set process_list to (name of every process)\n\
             end tell\n\
             if process_list contains \"Spotify\" then\n\
             tell application \"Spotify\"\n\
             if player state is playing or player state is paused then\n\
             set track_name to name of current track\n\
             set artist_name to artist of current track\n\
             set album_name to album of current track\n\
             set track_length to duration of current track\n\
             set now_playing to \"\" & player state & \"{0}\" & album_name & \"{0}\" & artist_name & \"{0}\" & track_name & \"{0}\" & track_length & \"{0}\" & player position\n\
             return now_playing\n\
             else\n\
             return player state\n\
             end if\n\
             end tell\n\
             else\n\
             return \"stopped\"\n\
             end if",
            APPLESCRIPT_STATUS_DELIMITER
        );
        let out = std::process::Command::new("osascript")
            .args(["-e", &script])
            .output()
            .ok()?;
        if !out.status.success() {
            return None;
        }
        let s = String::from_utf8(out.stdout).ok()?.trim().to_string();
        SpotifyAppleScriptPlayerSegment.get_player_status(&s)
    };

    #[cfg(not(target_os = "macos"))]
    let func_stats: Option<powerliners::ported::segments::common::players::PlayerStats> = None;

    // py:40  state_symbols=STATE_SYMBOLS — overridable via segment_data
    // ["player"]["args"]["state_symbols"], which the segment_data cascade
    // in gen_segment_getter merges into `args` for us. Falls back to
    // upstream's hardcoded Python defaults (`>` / `~` / `X` / `''`).
    let symbols = match args.get("state_symbols").and_then(|v| v.as_object()) {
        Some(obj) => obj.clone(),
        None => state_symbols(),
    };
    let chunks = player_segment_call(func_stats, format, &symbols)?;
    Some(Value::Array(chunks))
}

fn ad_branch(args: &Map<String, Value>, info: &Map<String, Value>) -> Option<Value> {
    // py:18-39  BranchSegment.__call__:
    //   name = segment_info['getcwd']()
    //   if name: repo = guess(path=name, ...); if repo:
    //     branch = repo.branch(); scol = ['branch']
    //     if status_colors: status = tree_status(repo, pl) (or '?' on Exc);
    //         if status in ignore_statuses: status = None
    //         scol.insert(0, 'branch_dirty' if status else 'branch_clean')
    //     return [{'contents': branch, 'highlight_groups': scol,
    //              'divider_highlight_group': None}]
    let cwd = info
        .get("getcwd")
        .and_then(|v| v.as_str())
        .unwrap_or("/")
        .to_string();
    let status_colors = args
        .get("status_colors")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let ignore_statuses: Vec<String> = args
        .get("ignore_statuses")
        .and_then(|v| v.as_array())
        .map(|a| {
            a.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();

    let (branch, status) = git_branch(&cwd)
        .or_else(|| hg_branch(&cwd))
        .or_else(|| bzr_branch(&cwd))?;
    if branch.is_empty() {
        return None;
    }
    let mut groups: Vec<Value> = vec![Value::String("branch".to_string())];
    if status_colors {
        // py:32-35: a None status means probe errored (== '?'), else
        // trim and compare against ignore_statuses; if in ignore set,
        // treat as clean.
        let effective = status.as_deref().map(str::trim).map(String::from);
        let is_dirty = match &effective {
            Some(s) if s.is_empty() => false,
            Some(s) if ignore_statuses.iter().any(|i| i == s) => false,
            Some(_) => true,
            None => true, // '?' fallback at py:30 — treated as truthy
        };
        groups.insert(
            0,
            Value::String(
                if is_dirty {
                    "branch_dirty"
                } else {
                    "branch_clean"
                }
                .to_string(),
            ),
        );
    }
    Some(Value::Array(vec![serde_json::json!({
        "contents": branch,
        "highlight_groups": groups,
        "divider_highlight_group": Value::Null,
    })]))
}

/// Probe git for current branch + working-tree status string.
/// Status is the porcelain output (`M `, `??`, etc.) flattened to
/// a single status letter string; empty when working tree is clean.
/// Returns None when the cwd isn't a git repo.
fn git_branch(cwd: &str) -> Option<(String, Option<String>)> {
    let out = std::process::Command::new("git")
        .args(["-C", cwd, "rev-parse", "--abbrev-ref", "HEAD"])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let branch = String::from_utf8(out.stdout).ok()?.trim().to_string();
    let status = std::process::Command::new("git")
        .args(["-C", cwd, "status", "--porcelain"])
        .output()
        .ok()
        .map(|o| String::from_utf8_lossy(&o.stdout).to_string());
    Some((branch, status))
}

/// Probe mercurial. `hg branch` prints the active branch (default
/// "default"); `hg status` reports working-copy changes.
fn hg_branch(cwd: &str) -> Option<(String, Option<String>)> {
    let out = std::process::Command::new("hg")
        .args(["--cwd", cwd, "branch"])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let branch = String::from_utf8(out.stdout).ok()?.trim().to_string();
    let status = std::process::Command::new("hg")
        .args(["--cwd", cwd, "status"])
        .output()
        .ok()
        .map(|o| String::from_utf8_lossy(&o.stdout).to_string());
    Some((branch, status))
}

/// Probe bazaar. `bzr nick` prints the nick of the current branch;
/// `bzr status` reports working-tree changes.
fn bzr_branch(cwd: &str) -> Option<(String, Option<String>)> {
    let out = std::process::Command::new("bzr")
        .args(["--directory", cwd, "nick"])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let branch = String::from_utf8(out.stdout).ok()?.trim().to_string();
    let status = std::process::Command::new("bzr")
        .args(["--directory", cwd, "status"])
        .output()
        .ok()
        .map(|o| String::from_utf8_lossy(&o.stdout).to_string());
    Some((branch, status))
}

fn ad_stash(_args: &Map<String, Value>, info: &Map<String, Value>) -> Option<Value> {
    let cwd = info
        .get("getcwd")
        .and_then(|v| v.as_str())
        .unwrap_or("/")
        .to_string();
    let out = std::process::Command::new("git")
        .args(["-C", &cwd, "stash", "list"])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let count = String::from_utf8(out.stdout)
        .ok()?
        .lines()
        .filter(|l| !l.is_empty())
        .count();
    if count == 0 {
        return None;
    }
    Some(Value::Array(vec![serde_json::json!({
        "contents": format!("{}", count),
        "highlight_groups": ["stash"],
        "divider_highlight_group": Value::Null,
    })]))
}

fn ad_battery(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::bat::{battery, parse_pmset_output};
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or("{ac_state} {capacity:3.0%}");
    let steps = args.get("steps").and_then(|v| v.as_u64()).unwrap_or(5) as u32;
    let gamify = args
        .get("gamify")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let full_heart = args
        .get("full_heart")
        .and_then(|v| v.as_str())
        .unwrap_or("O");
    let empty_heart = args
        .get("empty_heart")
        .and_then(|v| v.as_str())
        .unwrap_or("O");
    let online = args.get("online").and_then(|v| v.as_str()).unwrap_or("C");
    let offline = args.get("offline").and_then(|v| v.as_str()).unwrap_or(" ");
    let result = battery(
        || {
            let out = std::process::Command::new("pmset")
                .args(["-g", "batt"])
                .output()
                .ok()?;
            let text = String::from_utf8(out.stdout).ok()?;
            let (pct, ac) = parse_pmset_output(&text)?;
            Some((pct as f64, ac))
        },
        format,
        steps,
        gamify,
        full_heart,
        empty_heart,
        online,
        offline,
    )?;
    Some(Value::Array(result))
}

fn ad_environment(args: &Map<String, Value>, info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::env::environment;
    let environ = info
        .get("environ")
        .and_then(|v| v.as_object())
        .cloned()
        .unwrap_or_default();
    let variable = args.get("variable").and_then(|v| v.as_str())?;
    let v = environment(&environ, variable)?;
    Some(Value::String(v))
}

fn ad_jobnum(args: &Map<String, Value>, info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::shell::jobnum;
    use powerliners::ported::segments::shell::ShellSegmentInfo;
    let show_zero = args
        .get("show_zero")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let seg_info = ShellSegmentInfo {
        jobnum: info
            .get("args")
            .and_then(|v| v.as_object())
            .and_then(|o| o.get("jobnum"))
            .and_then(|v| v.as_i64())
            .map(|n| n as i32),
        ..Default::default()
    };
    let s = jobnum(&(), &seg_info, show_zero)?;
    Some(Value::String(s))
}

fn ad_last_status(args: &Map<String, Value>, info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::shell::last_status;
    use powerliners::ported::segments::shell::ShellSegmentInfo;
    let signal_names = args
        .get("signal_names")
        .and_then(|v| v.as_bool())
        .unwrap_or(true);
    // ShellSegmentInfo uses i32 for last_exit_code. Signal-name strings
    // (e.g. "sigINT") aren't carried through the i32 path — that's a
    // structural divergence from upstream (Python IntOrSig union) which
    // we surface by treating signal names as exit-code 0 here. Real
    // shell-prompt drivers should switch to IntOrSig once
    // ShellSegmentInfo gains a union field.
    let last_exit_code = info
        .get("args")
        .and_then(|v| v.as_object())
        .and_then(|o| o.get("last_exit_code"))
        .and_then(|v| v.as_i64())
        .map(|n| n as i32);
    let seg_info = ShellSegmentInfo {
        last_exit_code,
        ..Default::default()
    };
    let chunks = last_status(&(), &seg_info, signal_names)?;
    Some(Value::Array(chunks))
}

fn ad_last_pipe_status(args: &Map<String, Value>, info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::shell::last_pipe_status as lps_fn;
    use powerliners::ported::segments::shell::ShellSegmentInfo;
    let signal_names = args
        .get("signal_names")
        .and_then(|v| v.as_bool())
        .unwrap_or(true);
    let lps_vec: Vec<i32> = info
        .get("args")
        .and_then(|v| v.as_object())
        .and_then(|o| o.get("last_pipe_status"))
        .and_then(|v| v.as_array())
        .map(|arr| arr.iter().map(|v| v.as_i64().unwrap_or(0) as i32).collect())
        .unwrap_or_default();
    let seg_info = ShellSegmentInfo {
        last_pipe_status: lps_vec,
        ..Default::default()
    };
    let chunks = lps_fn(&(), &seg_info, signal_names)?;
    Some(Value::Array(chunks))
}

fn ad_cwd(args: &Map<String, Value>, info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::env::cwd_segments;
    let cwd = info
        .get("getcwd")
        .and_then(|v| v.as_str())
        .unwrap_or("/")
        .to_string();
    let dir_shorten_len = args
        .get("dir_shorten_len")
        .and_then(|v| v.as_u64())
        .map(|n| n as usize);
    let dir_limit_depth = args
        .get("dir_limit_depth")
        .and_then(|v| v.as_u64())
        .map(|n| n as usize);
    let use_path_separator = args
        .get("use_path_separator")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let ellipsis = args.get("ellipsis").and_then(|v| v.as_str());
    let chunks = cwd_segments(
        &cwd,
        dir_shorten_len,
        dir_limit_depth,
        use_path_separator,
        ellipsis,
    );
    if chunks.is_empty() {
        return None;
    }
    Some(Value::Array(chunks))
}

fn ad_virtualenv(args: &Map<String, Value>, info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::env::virtualenv;
    let environ = info
        .get("environ")
        .and_then(|v| v.as_object())
        .cloned()
        .unwrap_or_default();
    let ignore_venv = args
        .get("ignore_venv")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let ignore_conda = args
        .get("ignore_conda")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let ignored: Vec<String> = args
        .get("ignored_names")
        .and_then(|v| v.as_array())
        .map(|a| {
            a.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_else(|| vec!["venv".to_string(), ".venv".to_string()]);
    let ignored_refs: Vec<&str> = ignored.iter().map(String::as_str).collect();
    let v = virtualenv(&environ, ignore_venv, ignore_conda, &ignored_refs)?;
    Some(Value::String(v))
}

fn ad_fuzzy_time(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::time::{
        fuzzy_time, fuzzy_time_default_hour_str, fuzzy_time_default_minute_str,
        fuzzy_time_default_special_cases,
    };
    let format = args.get("format").and_then(|v| v.as_str());
    let unicode_text = args
        .get("unicode_text")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let timezone = args.get("timezone").and_then(|v| v.as_str());

    // py:46  hour_str=[...], minute_str={...}, special_case_str={...}
    // User-supplied overrides come in via theme args; build the
    // owned String buffers, then take &str slices for the fuzzy_time
    // call. Defaults fill in any keys the user omits.
    let hour_str_default = fuzzy_time_default_hour_str();
    let hour_str_owned: Vec<String> = match args.get("hour_str").and_then(|v| v.as_array()) {
        Some(arr) => arr
            .iter()
            .filter_map(|v| v.as_str().map(String::from))
            .collect(),
        None => hour_str_default.iter().map(|s| s.to_string()).collect(),
    };
    let hour_str: Vec<&str> = hour_str_owned.iter().map(String::as_str).collect();

    let minute_str_default = fuzzy_time_default_minute_str();
    let minute_str_owned: std::collections::HashMap<u32, String> =
        match args.get("minute_str").and_then(|v| v.as_object()) {
            Some(obj) => obj
                .iter()
                .filter_map(|(k, v)| {
                    let key: u32 = k.parse().ok()?;
                    let val = v.as_str()?.to_string();
                    Some((key, val))
                })
                .collect(),
            None => minute_str_default
                .iter()
                .map(|(k, v)| (*k, v.to_string()))
                .collect(),
        };
    let minute_str: std::collections::HashMap<u32, &str> = minute_str_owned
        .iter()
        .map(|(k, v)| (*k, v.as_str()))
        .collect();

    let special_cases = fuzzy_time_default_special_cases();
    let s = fuzzy_time(
        format,
        unicode_text,
        timezone,
        Some(&hour_str),
        Some(&minute_str),
        Some(&special_cases),
    );
    if s.is_empty() {
        return None;
    }
    Some(Value::String(s))
}

fn ad_weather(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::wthr::{compute_state, render_one, weather_key};
    let location_query = args
        .get("location_query")
        .and_then(|v| v.as_str())
        .map(String::from);
    let api_key = args
        .get("weather_api_key")
        .and_then(|v| v.as_str())
        .map(String::from);
    let key = weather_key(location_query, api_key);
    let weather = compute_state(&key)?;
    let unit = args.get("unit").and_then(|v| v.as_str()).unwrap_or("C");
    let temp_format = args.get("temp_format").and_then(|v| v.as_str());
    // Upstream defaults (-30..40) are °C — the human cold-to-hot
    // envelope. When the user picks F or K, convert those same
    // semantic bounds into their unit so the blue→red gradient
    // tracks perceived temperature instead of forcing every F-reading
    // ≥40 (a chilly 40°F) into the red end.
    let (default_cold, default_hot) = match unit {
        "F" => (-22.0, 104.0),
        "K" => (243.15, 313.15),
        _ => (-30.0, 40.0),
    };
    let temp_coldest = args
        .get("temp_coldest")
        .and_then(|v| v.as_f64())
        .unwrap_or(default_cold);
    let temp_hottest = args
        .get("temp_hottest")
        .and_then(|v| v.as_f64())
        .unwrap_or(default_hot);
    // Default weather glyphs from the active icon tier
    // (`POWERLINERS_ICONS=nerdfont|unicode|ascii`). The adapter
    // substitutes these when the theme doesn't pin its own.
    use powerliners::extensions::icons;
    // Build the defaults from the active icon tier.
    let mut merged_icons: Map<String, Value> = Map::new();
    merged_icons.insert("day".into(), Value::String(icons::weather_sunny().into()));
    merged_icons.insert("sunny".into(), Value::String(icons::weather_sunny().into()));
    merged_icons.insert("night".into(), Value::String(icons::weather_night().into()));
    merged_icons.insert("rainy".into(), Value::String(icons::weather_rainy().into()));
    merged_icons.insert(
        "cloudy".into(),
        Value::String(icons::weather_cloudy().into()),
    );
    merged_icons.insert("snowy".into(), Value::String(icons::weather_snowy().into()));
    merged_icons.insert(
        "stormy".into(),
        Value::String(icons::weather_stormy().into()),
    );
    merged_icons.insert("foggy".into(), Value::String(icons::weather_foggy().into()));
    merged_icons.insert("windy".into(), Value::String(icons::weather_windy().into()));
    merged_icons.insert(
        "blustery".into(),
        Value::String(icons::weather_windy().into()),
    );
    merged_icons.insert(
        "not_available".into(),
        Value::String(icons::weather_unknown().into()),
    );
    merged_icons.insert(
        "unknown".into(),
        Value::String(icons::weather_unknown().into()),
    );
    // Layer user-explicit icons on top, BUT skip values that exactly
    // match upstream's ASCII fallback set — those are cascade noise
    // from the bundled `themes/<top_theme>.json` segment_data, not
    // intentional user customization. Anything else (Unicode glyph,
    // different NF, etc.) wins over the code default.
    let upstream_ascii: &[(&str, &str)] = &[
        ("day", "DAY"),
        ("blustery", "WIND"),
        ("rainy", "RAIN"),
        ("cloudy", "CLOUDS"),
        ("snowy", "SNOW"),
        ("stormy", "STORM"),
        ("foggy", "FOG"),
        ("sunny", "SUN"),
        ("night", "NIGHT"),
        ("windy", "WINDY"),
        ("not_available", "NA"),
        ("unknown", "UKN"),
    ];
    if let Some(user_icons) = args.get("icons").and_then(|v| v.as_object()) {
        for (k, v) in user_icons {
            let val_str = v.as_str().unwrap_or("");
            let is_cascade_noise = upstream_ascii
                .iter()
                .any(|(uk, uv)| uk == k && *uv == val_str);
            if !is_cascade_noise {
                merged_icons.insert(k.clone(), v.clone());
            }
        }
    }
    let chunks = render_one(
        Some(weather),
        Some(&merged_icons),
        unit,
        temp_format,
        temp_coldest,
        temp_hottest,
    )?;
    Some(Value::Array(chunks))
}

fn ad_email_imap_alert(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    // py:43-138  EmailIMAPSegment — full IMAP probe would need a
    // TLS imap crate (not in deps). Surface a configured-username
    // placeholder so the segment is visible; faithful imap probe
    // is a follow-up dep choice.
    let username = args.get("username").and_then(|v| v.as_str())?;
    Some(Value::Array(vec![serde_json::json!({
        "contents": format!("{}: 0", username),
        "highlight_groups": ["email_alert"],
    })]))
}

fn ad_cmus(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::players::{
        player_segment_call, state_symbols, CmusPlayerSegment,
    };
    let out = std::process::Command::new("cmus-remote")
        .arg("-Q")
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let s = String::from_utf8(out.stdout).ok()?;
    let stats = CmusPlayerSegment.get_player_status(&s);
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or("{state_symbol} {artist} - {title} ({total})");
    let symbols = match args.get("state_symbols").and_then(|v| v.as_object()) {
        Some(obj) => obj.clone(),
        None => state_symbols(),
    };
    let chunks = player_segment_call(stats, format, &symbols)?;
    Some(Value::Array(chunks))
}

fn ad_rhythmbox(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::players::{
        player_segment_call, state_symbols, RhythmboxPlayerSegment,
    };
    // py:458-473  rhythmbox-client probe
    let out = std::process::Command::new("rhythmbox-client")
        .args([
            "--no-start",
            "--print-playing-format",
            "%at\n%aa\n%tt\n%te\n%td",
        ])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let s = String::from_utf8(out.stdout).ok()?;
    let stats = RhythmboxPlayerSegment.get_player_status(&s);
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or("{state_symbol} {artist} - {title} ({total})");
    let symbols = match args.get("state_symbols").and_then(|v| v.as_object()) {
        Some(obj) => obj.clone(),
        None => state_symbols(),
    };
    let chunks = player_segment_call(stats, format, &symbols)?;
    Some(Value::Array(chunks))
}

fn ad_itunes(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::players::{player_segment_call, state_symbols};
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or("{state_symbol} {artist} - {title} ({total})");

    #[cfg(target_os = "macos")]
    let stats = {
        use powerliners::ported::segments::common::players::{
            ITunesPlayerSegment, APPLESCRIPT_STATUS_DELIMITER,
        };
        // py:534-554 — 6-field delimited AppleScript (title|artist|album|elapsed|duration|state)
        let script = format!(
            "tell application \"System Events\"\n\
             set process_list to (name of every process)\n\
             end tell\n\
             if process_list contains \"iTunes\" then\n\
             tell application \"iTunes\"\n\
             if player state is playing then\n\
             set t_title to name of current track\n\
             set t_artist to artist of current track\n\
             set t_album to album of current track\n\
             set t_duration to duration of current track\n\
             set t_elapsed to player position\n\
             set t_state to player state\n\
             return t_title & \"{0}\" & t_artist & \"{0}\" & t_album & \"{0}\" & t_elapsed & \"{0}\" & t_duration & \"{0}\" & t_state\n\
             end if\n\
             end tell\n\
             end if",
            APPLESCRIPT_STATUS_DELIMITER
        );
        let out = std::process::Command::new("osascript")
            .args(["-e", &script])
            .output()
            .ok()?;
        if !out.status.success() {
            return None;
        }
        let s = String::from_utf8(out.stdout).ok()?.trim().to_string();
        ITunesPlayerSegment.get_player_status(&s)
    };

    #[cfg(not(target_os = "macos"))]
    let stats: Option<powerliners::ported::segments::common::players::PlayerStats> = None;

    let symbols = match args.get("state_symbols").and_then(|v| v.as_object()) {
        Some(obj) => obj.clone(),
        None => state_symbols(),
    };
    let chunks = player_segment_call(stats, format, &symbols)?;
    Some(Value::Array(chunks))
}

fn ad_dbus_player(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    // py:241-312  generic MPRIS probe parameterized by player_name.
    use powerliners::ported::segments::common::players::{
        player_segment_call, state_symbols, PlayerStats,
    };
    let player = args.get("player_name").and_then(|v| v.as_str())?;
    let service = format!("org.mpris.MediaPlayer2.{}", player);
    let metadata = std::process::Command::new("qdbus")
        .args([
            &service,
            "/Player",
            "org.freedesktop.MediaPlayer.GetMetadata",
        ])
        .output()
        .ok()?;
    if !metadata.status.success() {
        return None;
    }
    let text = String::from_utf8(metadata.stdout).ok()?;
    let mut artist = String::new();
    let mut title = String::new();
    let mut album = String::new();
    for line in text.lines() {
        if let Some(rest) = line.strip_prefix("artist: ") {
            artist = rest.to_string();
        } else if let Some(rest) = line.strip_prefix("title: ") {
            title = rest.to_string();
        } else if let Some(rest) = line.strip_prefix("album: ") {
            album = rest.to_string();
        }
    }
    if title.is_empty() {
        return None;
    }
    let stats = Some(PlayerStats {
        state: Some("play".to_string()),
        album: Some(album).filter(|s| !s.is_empty()),
        artist: Some(artist).filter(|s| !s.is_empty()),
        title: Some(title),
        total: None,
        elapsed: None,
    });
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or("{state_symbol} {artist} - {title} ({total})");
    let symbols = match args.get("state_symbols").and_then(|v| v.as_object()) {
        Some(obj) => obj.clone(),
        None => state_symbols(),
    };
    let chunks = player_segment_call(stats, format, &symbols)?;
    Some(Value::Array(chunks))
}

fn ad_clementine(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    // py:436-449  Clementine via MPRIS dbus. `qdbus` shells the
    // method calls; on systems without qdbus we silently skip.
    use powerliners::ported::segments::common::players::{
        player_segment_call, state_symbols, PlayerStats,
    };
    let metadata = std::process::Command::new("qdbus")
        .args([
            "org.mpris.MediaPlayer2.clementine",
            "/Player",
            "org.freedesktop.MediaPlayer.GetMetadata",
        ])
        .output()
        .ok()?;
    if !metadata.status.success() {
        return None;
    }
    let text = String::from_utf8(metadata.stdout).ok()?;
    // qdbus prints `key: value` lines for the dict. Extract artist + title.
    let mut artist = String::new();
    let mut title = String::new();
    let mut album = String::new();
    for line in text.lines() {
        if let Some(rest) = line.strip_prefix("artist: ") {
            artist = rest.to_string();
        } else if let Some(rest) = line.strip_prefix("title: ") {
            title = rest.to_string();
        } else if let Some(rest) = line.strip_prefix("album: ") {
            album = rest.to_string();
        }
    }
    if title.is_empty() {
        return None;
    }
    let stats = Some(PlayerStats {
        state: Some("play".to_string()),
        album: Some(album).filter(|s| !s.is_empty()),
        artist: Some(artist).filter(|s| !s.is_empty()),
        title: Some(title),
        total: None,
        elapsed: None,
    });
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or("{state_symbol} {artist} - {title} ({total})");
    let symbols = match args.get("state_symbols").and_then(|v| v.as_object()) {
        Some(obj) => obj.clone(),
        None => state_symbols(),
    };
    let chunks = player_segment_call(stats, format, &symbols)?;
    Some(Value::Array(chunks))
}

fn ad_mocp(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::players::{
        player_segment_call, state_symbols, MocPlayerSegment,
    };
    let out = std::process::Command::new("mocp").arg("-i").output().ok()?;
    if !out.status.success() {
        return None;
    }
    let s = String::from_utf8(out.stdout).ok()?;
    let stats = MocPlayerSegment.get_player_status(&s);
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or("{state_symbol} {artist} - {title} ({total})");
    let symbols = match args.get("state_symbols").and_then(|v| v.as_object()) {
        Some(obj) => obj.clone(),
        None => state_symbols(),
    };
    let chunks = player_segment_call(stats, format, &symbols)?;
    Some(Value::Array(chunks))
}

fn ad_mpd(args: &Map<String, Value>, _info: &Map<String, Value>) -> Option<Value> {
    // py:172-202  MpdPlayerSegment.get_player_status — CLI branch:
    // probes `mpc` for the now-playing line + `mpc current -f %album%`
    // for the album field. Routes through player_segment_call for the
    // full {state_symbol}{artist}-{title}({total}) contract.
    use powerliners::ported::segments::common::players::{
        player_segment_call, state_symbols, MpdPlayerSegment,
    };
    let host = args.get("host").and_then(|v| v.as_str());
    let port = args.get("port").and_then(|v| v.as_u64());
    let password = args.get("password").and_then(|v| v.as_str());
    let build_cmd = || {
        let mut cmd = std::process::Command::new("mpc");
        if let (Some(pw), Some(h)) = (password, host) {
            cmd.env("MPD_HOST", format!("{}@{}", pw, h));
        } else if let Some(h) = host {
            cmd.env("MPD_HOST", h);
        }
        if let Some(p) = port {
            cmd.arg("-p").arg(p.to_string());
        }
        cmd
    };
    let np_out = build_cmd().output().ok()?;
    if !np_out.status.success() {
        return None;
    }
    let np = String::from_utf8(np_out.stdout).ok()?;
    let mut album_cmd = build_cmd();
    album_cmd.args(["current", "-f", "%album%"]);
    let album = album_cmd
        .output()
        .ok()
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .map(|s| s.trim().to_string());
    let stats = MpdPlayerSegment.get_player_status(&np, album.as_deref());
    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or("{state_symbol} {artist} - {title} ({total})");
    let symbols = match args.get("state_symbols").and_then(|v| v.as_object()) {
        Some(obj) => obj.clone(),
        None => state_symbols(),
    };
    let chunks = player_segment_call(stats, format, &symbols)?;
    Some(Value::Array(chunks))
}

fn ad_user(args: &Map<String, Value>, info: &Map<String, Value>) -> Option<Value> {
    use powerliners::ported::segments::common::env::user;
    let environ = info
        .get("environ")
        .and_then(|v| v.as_object())
        .cloned()
        .unwrap_or_default();
    let hide_user = args.get("hide_user").and_then(|v| v.as_str());
    let hide_domain = args
        .get("hide_domain")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    // SAFETY: geteuid() is async-signal-safe POSIX.
    let euid = unsafe { libc::geteuid() };
    let chunks = user(&environ, hide_user, hide_domain, euid)?;
    Some(Value::Array(chunks))
}

pub const ADAPTERS: &[(&str, AdapterFn)] = &[
    ("powerline.segments.common.net.hostname", ad_hostname),
    ("powerline.segments.common.time.date", ad_date),
    ("powerline.segments.common.time.fuzzy_time", ad_fuzzy_time),
    ("powerline.segments.common.env.environment", ad_environment),
    ("powerline.segments.common.env.virtualenv", ad_virtualenv),
    ("powerline.segments.common.env.cwd", ad_cwd),
    ("powerline.segments.shell.jobnum", ad_jobnum),
    ("powerline.segments.shell.last_status", ad_last_status),
    (
        "powerline.segments.shell.last_pipe_status",
        ad_last_pipe_status,
    ),
    ("powerline.segments.common.env.user", ad_user),
    ("powerline.segments.common.players.mpd", ad_mpd),
    (
        "powerline.segments.common.sys.cpu_load_percent",
        ad_cpu_load_percent,
    ),
    ("powerline.segments.common.sys.system_load", ad_system_load),
    ("powerline.segments.common.sys.uptime", ad_uptime),
    ("powerline.segments.common.net.external_ip", ad_external_ip),
    ("powerline.segments.common.net.internal_ip", ad_internal_ip),
    ("powerline.segments.common.vcs.branch", ad_branch),
    ("powerline.segments.common.vcs.stash", ad_stash),
    ("powerline.segments.common.bat.battery", ad_battery),
    ("powerlinemem.mem_usage.mem_usage", ad_mem_usage),
    (
        "powerlinemem.mem_usage.mem_usage_percent",
        ad_mem_usage_percent,
    ),
    ("powerlinemem.mem_usage.mem_swap", ad_mem_swap),
    (
        "powerlinemem.mem_usage.mem_swap_percentage",
        ad_mem_swap_percentage,
    ),
    // GPU / Disk / Thermal extensions (src/extensions/{gpu,disk,thermal}.rs).
    ("powerliners.gpu.gpu_usage_percent", ad_gpu_usage_percent),
    ("powerliners.gpu.gpu_vram", ad_gpu_vram),
    ("powerliners.disk.disk_usage", ad_disk_usage),
    ("powerliners.disk.disk_usage_percent", ad_disk_usage_percent),
    ("powerliners.disk.disk_io", ad_disk_io),
    ("powerliners.thermal.thermal", ad_thermal),
    ("powerliners.vcs.git_status", ad_git_status),
    // Docker / OCI containers — src/extensions/docker.rs
    ("powerliners.docker.containers", ad_docker_containers),
    // Kubernetes context — src/extensions/k8s.rs
    ("powerliners.k8s.kubecontext", ad_kubecontext),
    // POSIX process tally — src/extensions/proc_count.rs
    ("powerliners.proc.process_count", ad_process_count),
    // GitHub CI status — src/extensions/github_ci.rs
    ("powerliners.github.ci_status", ad_github_ci),
    // AWS active profile + region — src/extensions/aws_ctx.rs
    ("powerliners.aws.context", ad_aws_context),
    // GCP active configuration — src/extensions/gcp_ctx.rs
    ("powerliners.gcp.context", ad_gcp_context),
    // fusevm Cranelift JIT cache stats — src/extensions/fusevm_jit.rs
    ("powerliners.fusevm.jit_cache", ad_fusevm_jit_cache),
    // zshrs rkyv cache stats — src/extensions/zshrs_rkyv.rs
    ("powerliners.zshrs.rkyv_cache", ad_zshrs_rkyv_cache),
    // stryke rkyv cache stats — src/extensions/stryke_rkyv.rs
    ("powerliners.stryke.rkyv_cache", ad_stryke_rkyv_cache),
    // awkrs rkyv cache stats — src/extensions/awkrs_rkyv.rs
    ("powerliners.awkrs.rkyv_cache", ad_awkrs_rkyv_cache),
    // zshrs version — src/extensions/zshrs_version.rs
    ("powerliners.zshrs.version", ad_zshrs_version),
    // stryke version — src/extensions/stryke_version.rs
    ("powerliners.stryke.version", ad_stryke_version),
    // awkrs version — src/extensions/awkrs_version.rs
    ("powerliners.awkrs.version", ad_awkrs_version),
    // User-extensibility (`src/extensions/exec_segment.rs`):
    //   Option A — explicit `exec` adapter spawns args.command + parses
    //   stdout. Theme JSON references `"function": "exec"`.
    ("powerliners.exec.exec", ad_exec),
    // Short-form alias so theme authors can write `"function": "exec"`
    // without the dotted-path prefix — gen_segment_getter's
    // default-module lookup expands the bare name through every level
    // of the resolver, but stamping the short form here makes the
    // direct lookup hit succeed without the cascade.
    ("exec", ad_exec),
    (
        "powerline.segments.common.net.network_load",
        ad_network_load,
    ),
    ("powerline.segments.common.players.spotify", ad_spotify),
    ("powerline.segments.common.players.cmus", ad_cmus),
    ("powerline.segments.common.players.mocp", ad_mocp),
    ("powerline.segments.common.players.rhythmbox", ad_rhythmbox),
    ("powerline.segments.common.players.itunes", ad_itunes),
    (
        "powerline.segments.common.players.clementine",
        ad_clementine,
    ),
    (
        "powerline.segments.common.players.dbus_player",
        ad_dbus_player,
    ),
    ("powerline.segments.common.wthr.weather", ad_weather),
    (
        "powerline.segments.common.mail.email_imap_alert",
        ad_email_imap_alert,
    ),
];

/// Python-faithful color encoding for the hlstyle directive builder.
/// Python passes `fg`/`bg` as one of:
///   - `None` → don't emit the channel directive at all
///   - `False` or `(False, ...)` → emit `<channel>=default`
///   - `(cterm_int, hex_int_or_None)` → emit `<channel>=colourN` (or `=#hex` truecolor)
enum ColorChoice {
    /// Python `None` — no directive.
    None,
    /// Python `False` (or `[False, …]`) — `<channel>=default`.
    Default,
    /// Python `[cterm, hex]` tuple.
    Spec(ColorSpec),
}

fn classify_color(v: &Value) -> ColorChoice {
    match v {
        Value::Null => ColorChoice::None,
        Value::Bool(false) => ColorChoice::Default,
        Value::Bool(true) => ColorChoice::Default,
        Value::Array(arr) => {
            // Python `[False, …]` is the array form of the default sentinel.
            if matches!(arr.first(), Some(Value::Bool(false))) {
                return ColorChoice::Default;
            }
            let cterm = arr.first().and_then(|x| x.as_u64()).unwrap_or(0) as u16;
            let truecolor = arr.get(1).and_then(|x| x.as_u64()).map(|n| n as u32);
            ColorChoice::Spec(ColorSpec { cterm, truecolor })
        }
        _ => ColorChoice::None,
    }
}

/// Classify a `Value`-encoded `attrs` field.
/// - `Value::Null` → no `attrs` directive (Python `attrs is None`)
/// - `Value::Bool(_)` → Python `False` sentinel: emit all "no-" resets
/// - integer → standard bit field
enum AttrsChoice {
    /// Python `None` — no attrs directive at all.
    None,
    /// Python `False` — all-off ("nobold,noitalics,nounderscore").
    AllOff,
    /// Standard bit field (matches `get_attrs_flag` output).
    Flag(u32),
}

fn classify_attrs(v: &Value) -> AttrsChoice {
    match v {
        Value::Null => AttrsChoice::None,
        Value::Bool(_) => AttrsChoice::AllOff,
        _ => match v.as_u64() {
            Some(n) => AttrsChoice::Flag(n as u32),
            None => AttrsChoice::None,
        },
    }
}

/// Build the Python-faithful `#[…]` tag for the given fg/bg/attrs.
/// Mirrors `TmuxRenderer.hlstyle` at `powerline/renderers/tmux.py:40`
/// exactly, including the early-exit "if not attrs and not bg and not
/// fg: return ''" check and the three-state fg/bg semantics. Used by
/// both the `hl_fn` and `hlstyle_fn` closures so the bin shim emits
/// byte-for-byte parity with upstream Python.
pub fn render_hlstyle(tmux: &TmuxRenderer, fg: &Value, bg: &Value, attrs: &Value) -> String {
    let fc = classify_color(fg);
    let bc = classify_color(bg);
    let ac = classify_attrs(attrs);

    // py:44  if not attrs and not bg and not fg: return ''
    let attrs_empty = matches!(ac, AttrsChoice::None);
    let bg_empty = matches!(bc, ColorChoice::None);
    let fg_empty = matches!(fc, ColorChoice::None);
    if attrs_empty && bg_empty && fg_empty {
        return String::new();
    }

    let mut parts: Vec<String> = Vec::new();
    // py:47-54  fg branch — Python `if term_truecolor and fg[1]:`
    // includes the implicit truthiness check on the hex value, so
    // `hex == 0` (e.g. pure black 0x000000) falls back to cterm.
    match fc {
        ColorChoice::None => {}
        ColorChoice::Default => parts.push("fg=default".into()),
        ColorChoice::Spec(spec) => {
            if tmux.term_truecolor && spec.truecolor.filter(|&n| n != 0).is_some() {
                parts.push(format!("fg=#{:06x}", spec.truecolor.unwrap()));
            } else {
                parts.push(format!("fg=colour{}", spec.cterm));
            }
        }
    }
    // py:55-62  bg branch — same truthiness rule on bg[1].
    match bc {
        ColorChoice::None => {}
        ColorChoice::Default => parts.push("bg=default".into()),
        ColorChoice::Spec(spec) => {
            if tmux.term_truecolor && spec.truecolor.filter(|&n| n != 0).is_some() {
                parts.push(format!("bg=#{:06x}", spec.truecolor.unwrap()));
            } else {
                parts.push(format!("bg=colour{}", spec.cterm));
            }
        }
    }
    // py:63-64  attrs branch
    match ac {
        AttrsChoice::None => {}
        AttrsChoice::AllOff => parts.extend(
            powerliners::ported::renderers::tmux::attrs_to_tmux_attrs(None),
        ),
        AttrsChoice::Flag(flag) => parts.extend(
            powerliners::ported::renderers::tmux::attrs_to_tmux_attrs(Some(flag)),
        ),
    }
    // py:65  return '#[' + ','.join(tmux_attrs) + ']'
    format!("#[{}]", parts.join(","))
}

/// Build a base `Renderer` with `TmuxRenderer.character_translations`
/// pre-installed so `Renderer::escape` performs the `#` → `##[]`
/// substitution upstream Python `class TmuxRenderer(Renderer):
/// character_translations = Renderer.character_translations.copy();
/// ct[ord('#')] = '##['` (powerline/renderers/tmux.py:30-31) installs
/// at class-load time.
pub fn make_renderer() -> Arc<Renderer> {
    let mut renderer_inner = Renderer::new(Map::new(), Map::new(), 1);
    for (ch, replacement) in TmuxRenderer::character_translations() {
        renderer_inner
            .character_translations
            .insert(ch, replacement.to_string());
    }
    Arc::new(renderer_inner)
}

/// One-shot render: build segment_info from environ + cwd + args,
/// call `Renderer::render`, return the rendered bytes.
///
/// Used by `powerline-daemon` (wrapped with a per-ext Configs cache)
/// and `powerline-render` (called directly per invocation). The
/// closures wired here — `hl_fn`, `hlstyle_fn`, `contents_func` —
/// mirror the upstream Python `Renderer.render` call shape so both
/// drivers produce byte-identical output for the same request.
pub fn render_once(
    args: &Args,
    environ: &HashMap<String, String>,
    cwd: &str,
    configs: &Configs,
    renderer: &Renderer,
) -> Vec<u8> {
    let __render_t0 = std::time::Instant::now();
    let side = args.side.clone().unwrap_or_default();
    powerliners::extensions::diag_log::log(&format!(
        "render_once START ext={} side={} cwd={}",
        configs.ext, side, cwd
    ));

    let mut environ_map: Map<String, Value> = Map::new();
    for (k, v) in environ {
        environ_map.insert(k.clone(), Value::String(v.clone()));
    }
    // py:234-235 (renderer.py) — `Renderer.get_segment_info` resets
    // `getcwd` to `environ['PWD']` if present. That's the powerline
    // *client's* shell PWD, which under tmux is unrelated to the
    // *pane's* cwd. When a `-R pane_current_path=...` arg is in flight
    // it must win over PWD, so rewrite PWD to match before the renderer
    // sees the env. Without this the explicit `getcwd` override below
    // is silently overwritten and `branch` / `stash` run `git rev-parse`
    // in the wrong dir.
    if let Some(pcp) = args
        .renderer_arg_merged
        .as_ref()
        .and_then(|m| m.get("pane_current_path"))
        .and_then(|v| v.as_str())
    {
        environ_map.insert("PWD".to_string(), Value::String(pcp.to_string()));
    }
    let mut segment_info: Map<String, Value> = Map::new();
    segment_info.insert("environ".to_string(), Value::Object(environ_map));
    segment_info.insert(
        "home".to_string(),
        Value::String(environ.get("HOME").cloned().unwrap_or_default()),
    );
    segment_info.insert("getcwd".to_string(), Value::String(cwd.to_string()));

    // py:185 commands/main.py — fold `-R k=v` pairs into segment_info
    // so tmux's `pane_current_path` (and any other renderer arg)
    // reaches the segments. The TmuxRenderer override at
    // `renderers/tmux.rs:233-236` mirrors upstream's
    // `pane_current_path` → `getcwd` rewrite but is never called from
    // `Renderer::render`'s code path, so do the rewrite here. Without
    // it `getcwd` stays pinned to the powerline client's own cwd
    // (HOME under tmux), `branch` / `stash` run `git rev-parse` in
    // the wrong dir, and the segments silently return None.
    if let Some(ra) = args.renderer_arg_merged.as_ref() {
        for (k, v) in ra {
            segment_info.insert(k.clone(), v.clone());
        }
        if let Some(pcp) = ra.get("pane_current_path").and_then(|v| v.as_str()) {
            segment_info.insert("getcwd".to_string(), Value::String(pcp.to_string()));
        } else if let Some(pid) = ra.get("pane_id").and_then(|v| v.as_str()) {
            let varname = format!("TMUX_PWD_{}", pid.trim_start_matches([' ', '%']));
            if let Some(p) = environ.get(&varname) {
                segment_info.insert("getcwd".to_string(), Value::String(p.clone()));
            }
        }
    }

    let mut args_map: Map<String, Value> = Map::new();
    if let Some(j) = args.jobnum {
        args_map.insert("jobnum".to_string(), Value::from(j));
    }
    if let Some(ec) = args.last_exit_code.as_ref() {
        args_map.insert(
            "last_exit_code".to_string(),
            match ec {
                powerliners::ported::commands::main::IntOrSig::Int(n) => Value::from(*n),
                powerliners::ported::commands::main::IntOrSig::Sig(s) => Value::String(s.clone()),
            },
        );
    }
    if !args.last_pipe_status.is_empty() {
        let arr: Vec<Value> = args
            .last_pipe_status
            .iter()
            .map(|v| match v {
                powerliners::ported::commands::main::IntOrSig::Int(n) => Value::from(*n),
                powerliners::ported::commands::main::IntOrSig::Sig(s) => Value::String(s.clone()),
            })
            .collect();
        args_map.insert("last_pipe_status".to_string(), Value::Array(arr));
    }
    segment_info.insert("args".to_string(), Value::Object(args_map));

    // Per-request vim command sink — `VimRenderer::hlstyle()`
    // appends every `:hi GroupName ...` declaration here. After the
    // render loop completes we splice the commands onto the response
    // payload so the vim plugin can run them via `:execute` before
    // applying the statusline. Mutex needed because both `hl_fn` and
    // `hlstyle_fn` close over it and `Renderer::render` invokes them
    // sequentially.
    let vim_commands: Arc<std::sync::Mutex<Vec<String>>> =
        Arc::new(std::sync::Mutex::new(Vec::new()));

    let tmux_for_hl = configs.tmux.clone();
    let tmux_for_hlstyle = configs.tmux.clone();
    let vim_for_hl = configs.vim.clone();
    let vim_for_hlstyle = configs.vim.clone();
    let vim_cmds_for_hl = vim_commands.clone();
    let vim_cmds_for_hlstyle = vim_commands.clone();
    let ext_is_vim = configs.ext == "vim";

    let hl_fn = move |contents: Option<&str>,
                      fg: &Value,
                      bg: &Value,
                      attrs: &Value,
                      _hl_args: &Map<String, Value>|
          -> String {
        // py:600-606  return self.hlstyle(fg, bg, attrs, **kwargs) + (contents or '')
        let style = if ext_is_vim {
            render_hlstyle_vim(vim_for_hl.as_ref(), fg, bg, attrs, &vim_cmds_for_hl)
        } else {
            render_hlstyle(&tmux_for_hl, fg, bg, attrs)
        };
        format!("{}{}", style, contents.unwrap_or(""))
    };
    let hlstyle_fn =
        move |fg: &Value, bg: &Value, attrs: &Value, _hl_args: &Map<String, Value>| -> String {
            if ext_is_vim {
                render_hlstyle_vim(
                    vim_for_hlstyle.as_ref(),
                    fg,
                    bg,
                    attrs,
                    &vim_cmds_for_hlstyle,
                )
            } else {
                render_hlstyle(&tmux_for_hlstyle, fg, bg, attrs)
            }
        };

    let contents_func =
        |id: &str, _pl: &(), si: &Map<String, Value>, args: &Map<String, Value>| -> Option<Value> {
            let t0 = std::time::Instant::now();
            let r = invoke_adapter(id, args, si);
            let dt = t0.elapsed().as_millis();
            let cwd_dbg = si.get("getcwd").and_then(|v| v.as_str()).unwrap_or("?");
            powerliners::extensions::diag_log::log(&format!(
                "adapter id={} dt={}ms result={} cwd={}",
                id,
                dt,
                if r.is_some() { "Some" } else { "None" },
                cwd_dbg
            ));
            r
        };

    // Mode extraction: Python pulls it from `args.renderer_arg["mode"]`
    // before passing to `Renderer.render`. Mirrors
    // `commands/main.py:170-189` `write_output`'s segment_info update
    // and the explicit `mode=segment_info.get('mode', None)` at
    // py:177/188.
    let mode_owned: Option<String> = args
        .renderer_arg_merged
        .as_ref()
        .and_then(|m| m.get("mode"))
        .and_then(|v| v.as_str())
        .map(String::from);
    let mode_ref: Option<&str> = mode_owned.as_deref();
    let result = renderer.render(
        mode_ref,
        args.width.map(|w| w as usize),
        if side.is_empty() { None } else { Some(&side) },
        0,
        false,
        false,
        Some(segment_info),
        None,
        None,
        &configs.theme,
        &configs.colorscheme,
        &contents_func,
        &hlstyle_fn,
        &hl_fn,
    );

    let statusline = match result {
        RenderReturn::Plain(s) => s,
        RenderReturn::Tuple { highlighted, .. } => highlighted,
    };
    powerliners::extensions::diag_log::log(&format!(
        "render_once END ext={} side={} dt={}ms bytes={}",
        configs.ext,
        side,
        __render_t0.elapsed().as_millis(),
        statusline.len()
    ));

    if configs.ext == "vim" {
        // Wire format for vim: every `:hi GroupName ...` command on
        // its own line, then a single empty separator line, then the
        // statusline markup as the last line. The vim plugin reads
        // the full response, executes every line before the empty
        // separator via `:execute`, and assigns the line after to
        // `&statusline`. Empty separator means a missing/empty
        // statusline still parses unambiguously.
        let cmds = vim_commands.lock().unwrap();
        let mut out = String::new();
        for c in cmds.iter() {
            out.push_str(c);
            out.push('\n');
        }
        out.push('\n');
        out.push_str(&statusline);
        return out.into_bytes();
    }

    statusline.into_bytes()
}

/// Vim-flavoured `hlstyle`: emits a `%#PowerLine_…#` reference and
/// appends the matching `:hi PowerLine_… ctermfg=…` command to the
/// per-request command sink. Mirrors `render_hlstyle` for the tmux
/// path but threads through `VimRenderer`'s state.
fn render_hlstyle_vim(
    vim: Option<&Arc<std::sync::Mutex<VimRenderer>>>,
    fg: &Value,
    bg: &Value,
    attrs: &Value,
    commands: &Arc<std::sync::Mutex<Vec<String>>>,
) -> String {
    let Some(vim) = vim else {
        return String::new();
    };
    let fg_spec = json_value_to_colorspec(fg);
    let bg_spec = json_value_to_colorspec(bg);
    let attrs_u: Option<u32> = attrs.as_u64().map(|n| n as u32);
    let mut renderer = vim.lock().unwrap();
    let mut local_cmds: Vec<String> = Vec::new();
    let out = renderer.hlstyle(fg_spec, bg_spec, attrs_u, &mut local_cmds);
    if !local_cmds.is_empty() {
        let mut sink = commands.lock().unwrap();
        sink.extend(local_cmds);
    }
    out
}

/// Decode the JSON shape Theme writes for fg/bg — either a number
/// (cterm-only palette index) or an object
/// `{"cterm": N, "truecolor": "RRGGBB"|null}` — into the
/// `VimColorSpec` the renderer wants. Mirrors the same lookup the
/// tmux side does in `render_hlstyle`.
fn json_value_to_colorspec(v: &Value) -> Option<VimColorSpec> {
    if v.is_null() || v.is_boolean() {
        return None;
    }
    if let Some(n) = v.as_u64() {
        return Some(VimColorSpec {
            cterm: n as u16,
            truecolor: None,
        });
    }
    if let Some(arr) = v.as_array() {
        // Theme palette form: `[cterm, "RRGGBB"]`
        let cterm = arr.first().and_then(|v| v.as_u64())? as u16;
        let truecolor = arr
            .get(1)
            .and_then(|v| v.as_str())
            .and_then(|s| u32::from_str_radix(s.trim_start_matches('#'), 16).ok());
        return Some(VimColorSpec { cterm, truecolor });
    }
    if let Some(obj) = v.as_object() {
        let cterm = obj.get("cterm").and_then(|v| v.as_u64())? as u16;
        let truecolor = obj
            .get("truecolor")
            .and_then(|v| v.as_str())
            .and_then(|s| u32::from_str_radix(s.trim_start_matches('#'), 16).ok());
        return Some(VimColorSpec { cterm, truecolor });
    }
    None
}

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

    // =====================================================================
    // json_value_to_colorspec — vim renderer's theme-color decoder
    // (commit 70f0ea3458, feat(vim): ext dispatch).
    // =====================================================================

    #[test]
    fn colorspec_null_returns_none() {
        assert!(json_value_to_colorspec(&Value::Null).is_none());
    }

    #[test]
    fn colorspec_bool_returns_none() {
        assert!(json_value_to_colorspec(&json!(true)).is_none());
        assert!(json_value_to_colorspec(&json!(false)).is_none());
    }

    #[test]
    fn colorspec_number_yields_cterm_only() {
        let c = json_value_to_colorspec(&json!(42)).expect("u64 → Some");
        assert_eq!(c.cterm, 42);
        assert!(c.truecolor.is_none());
    }

    #[test]
    fn colorspec_palette_array_decodes_cterm_and_truecolor() {
        // Theme JSON `[cterm, "RRGGBB"]` form (no leading '#').
        let c = json_value_to_colorspec(&json!([196, "ff0000"])).expect("[cterm, hex] → Some");
        assert_eq!(c.cterm, 196);
        assert_eq!(c.truecolor, Some(0xff0000));
    }

    #[test]
    fn colorspec_palette_array_accepts_hash_prefix() {
        // trim_start_matches('#') means leading hash is tolerated.
        let c = json_value_to_colorspec(&json!([21, "#0000ff"])).expect("[cterm, #hex] → Some");
        assert_eq!(c.cterm, 21);
        assert_eq!(c.truecolor, Some(0x0000ff));
    }

    #[test]
    fn colorspec_object_form_with_truecolor() {
        let c = json_value_to_colorspec(&json!({"cterm": 76, "truecolor": "33cc66"}))
            .expect("{cterm,truecolor} → Some");
        assert_eq!(c.cterm, 76);
        assert_eq!(c.truecolor, Some(0x33cc66));
    }

    #[test]
    fn colorspec_object_form_truecolor_null_yields_cterm_only() {
        // truecolor: null is a legitimate theme value meaning
        // "no GUI color, cterm only" — must still produce Some.
        let c = json_value_to_colorspec(&json!({"cterm": 7, "truecolor": null}))
            .expect("{cterm, null} → Some");
        assert_eq!(c.cterm, 7);
        assert!(c.truecolor.is_none());
    }

    #[test]
    fn colorspec_object_missing_cterm_returns_none() {
        // Without cterm there's nothing to render against; treat as
        // malformed and return None rather than guess a default.
        assert!(json_value_to_colorspec(&json!({"truecolor": "ffffff"})).is_none());
    }

    #[test]
    fn colorspec_string_value_returns_none() {
        // Strings aren't a valid theme color shape — neither a number
        // nor an array nor an object.
        assert!(json_value_to_colorspec(&json!("red")).is_none());
    }

    #[test]
    fn colorspec_palette_array_invalid_hex_drops_truecolor() {
        // Hex parse failure on the truecolor field doesn't poison the
        // cterm value; the cterm-only spec is still valid.
        let c = json_value_to_colorspec(&json!([10, "nothex"]))
            .expect("[cterm, bad-hex] → Some(cterm-only)");
        assert_eq!(c.cterm, 10);
        assert!(c.truecolor.is_none());
    }

    // =====================================================================
    // adapter_id — theme function string → internal dispatcher key
    // =====================================================================

    #[test]
    fn adapter_id_full_dotted_path_matches() {
        // Exact ADAPTERS entry: powerline.segments.common.net.hostname.
        let id = adapter_id("powerline.segments.common.net", "hostname")
            .expect("hostname adapter must register");
        assert_eq!(id, "powerline.segments.common.net.hostname");
    }

    #[test]
    fn adapter_id_bare_name_fallback_hits_short_alias() {
        // ADAPTERS has the bare "exec" alias for user-defined scripts.
        // Caller supplies a nonsense module that's not in the table,
        // but the bare-name fallback at line 459-461 should hit.
        let id = adapter_id("powerline.segments.nonexistent", "exec")
            .expect("exec bare-name alias must be registered");
        assert_eq!(id, "exec");
    }

    #[test]
    fn adapter_id_unknown_returns_none() {
        // Neither full nor bare match → None (unless the fs fallback
        // resolves it; "definitely_not_a_segment" isn't a real script).
        assert!(adapter_id("does.not.exist", "definitely_not_a_segment").is_none());
    }

    #[test]
    fn adapter_id_extension_segments_register() {
        // powerliners.gpu.gpu_usage_percent, .disk.disk_io, etc. are
        // extension-tier (commit 147a0a4b24) — verify they appear in
        // the dispatch table so theme JSON can reference them.
        for (mod_, name) in [
            ("powerliners.gpu", "gpu_usage_percent"),
            ("powerliners.gpu", "gpu_vram"),
            ("powerliners.disk", "disk_usage"),
            ("powerliners.disk", "disk_io"),
            ("powerliners.thermal", "thermal"),
            ("powerliners.vcs", "git_status"),
            ("powerlinemem.mem_usage", "mem_usage"),
            ("powerlinemem.mem_usage", "mem_swap_percentage"),
            ("powerliners.docker", "containers"),
            ("powerliners.k8s", "kubecontext"),
            ("powerliners.proc", "process_count"),
            ("powerliners.github", "ci_status"),
            ("powerliners.aws", "context"),
            ("powerliners.gcp", "context"),
            ("powerliners.fusevm", "jit_cache"),
            ("powerliners.zshrs", "rkyv_cache"),
            ("powerliners.stryke", "rkyv_cache"),
            ("powerliners.awkrs", "rkyv_cache"),
            ("powerliners.zshrs", "version"),
            ("powerliners.stryke", "version"),
            ("powerliners.awkrs", "version"),
        ] {
            let id = adapter_id(mod_, name)
                .unwrap_or_else(|| panic!("extension adapter {mod_}.{name} missing from ADAPTERS"));
            assert_eq!(id, format!("{mod_}.{name}"));
        }
    }

    // =====================================================================
    // ADAPTERS table — invariants
    // =====================================================================

    #[test]
    fn adapters_table_keys_are_unique() {
        // Duplicate keys would let one mask another silently — surface
        // any future merge that introduces collisions.
        let mut seen = std::collections::HashSet::new();
        for (k, _) in ADAPTERS {
            assert!(seen.insert(*k), "duplicate ADAPTERS key: {k}");
        }
    }

    #[test]
    fn adapters_table_keys_have_no_leading_or_trailing_dots() {
        for (k, _) in ADAPTERS {
            assert!(!k.starts_with('.'), "ADAPTERS key {k:?} starts with '.'");
            assert!(!k.ends_with('.'), "ADAPTERS key {k:?} ends with '.'");
        }
    }

    // =====================================================================
    // Config reload — loaded_paths_are_stale + collect_loaded_paths
    // Pins the user-layer-reload bug fix (commit 6e0252db32). search_paths()
    // puts the bundled fallback FIRST and the user's config LAST so
    // mergedicts() lets user override bundled. The pre-fix code watched
    // `matches.first()` (the bundled, install-time-mtime file) and missed
    // user edits entirely.
    // =====================================================================

    /// Build a unique tempdir for one test. Distinct PID + nanos so
    /// parallel tests don't collide.
    fn reload_test_dir(tag: &str) -> PathBuf {
        let pid = std::process::id();
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let mut p = std::env::temp_dir();
        p.push(format!("powerliners-reload-test-{tag}-{pid}-{nanos}"));
        std::fs::create_dir_all(&p).unwrap();
        p
    }

    fn write_json(path: &PathBuf, body: &str) {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).unwrap();
        }
        std::fs::write(path, body).unwrap();
    }

    /// Bump a file's mtime to "now + 2s" so `is_stale` sees a delta
    /// even on filesystems with 1-second mtime granularity (HFS+,
    /// older ext4 mount options).
    fn touch_forward(path: &PathBuf) {
        // Re-write the file with the same contents; std::fs::write
        // updates mtime. Then sleep ≥1ms to ensure SystemTime ticks
        // forward even on coarse-resolution clocks.
        let body = std::fs::read(path).unwrap_or_default();
        std::thread::sleep(std::time::Duration::from_millis(5));
        std::fs::write(path, &body).unwrap();
    }

    #[test]
    fn loaded_paths_are_stale_empty_vec_is_not_stale() {
        // No watched files → nothing to be stale against.
        assert!(!loaded_paths_are_stale(&[]));
    }

    #[test]
    fn loaded_paths_are_stale_unchanged_file_is_not_stale() {
        let dir = reload_test_dir("unchanged");
        let p = dir.join("a.json");
        write_json(&p, "{}");
        let mt = std::fs::metadata(&p).unwrap().modified().unwrap();
        assert!(!loaded_paths_are_stale(&[(p, mt)]));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn loaded_paths_are_stale_modified_file_is_stale() {
        let dir = reload_test_dir("modified");
        let p = dir.join("a.json");
        write_json(&p, "{}");
        let original_mt = std::fs::metadata(&p).unwrap().modified().unwrap();
        touch_forward(&p);
        assert!(loaded_paths_are_stale(&[(p.clone(), original_mt)]));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn loaded_paths_are_stale_missing_file_is_stale() {
        // A file that vanished between build_configs and the next
        // render — metadata() errors, which the stale-walk treats
        // as a change (return true).
        let dir = reload_test_dir("missing");
        let p = dir.join("doesnt_exist.json");
        let fake_mt = std::time::SystemTime::now();
        assert!(loaded_paths_are_stale(&[(p, fake_mt)]));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn loaded_paths_are_stale_detects_change_in_last_position() {
        // THE BUG-FIX PIN: pre-fix, only the first entry was ever in
        // the list (`matches.first()`). The user's actual edited file
        // — last in cascade order — wasn't watched. Verify a change
        // at the END of a multi-entry list is detected.
        let dir = reload_test_dir("last_pos");
        let bundled = dir.join("bundled/config.json");
        let user = dir.join("user/config.json");
        write_json(&bundled, "{}");
        write_json(&user, "{}");
        let mt_bundled = std::fs::metadata(&bundled).unwrap().modified().unwrap();
        let mt_user = std::fs::metadata(&user).unwrap().modified().unwrap();
        touch_forward(&user); // edit the LAST entry
        assert!(loaded_paths_are_stale(&[
            (bundled, mt_bundled),
            (user.clone(), mt_user),
        ]));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn loaded_paths_are_stale_detects_change_in_first_position() {
        // Symmetric pin: a change at the FIRST entry still trips.
        // Original behavior preserved by the fix.
        let dir = reload_test_dir("first_pos");
        let bundled = dir.join("bundled/config.json");
        let user = dir.join("user/config.json");
        write_json(&bundled, "{}");
        write_json(&user, "{}");
        let mt_bundled = std::fs::metadata(&bundled).unwrap().modified().unwrap();
        let mt_user = std::fs::metadata(&user).unwrap().modified().unwrap();
        touch_forward(&bundled);
        assert!(loaded_paths_are_stale(&[
            (bundled.clone(), mt_bundled),
            (user, mt_user),
        ]));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn collect_loaded_paths_records_every_cascade_match_per_level() {
        // THE STRUCTURAL FIX: build_configs must record EVERY match
        // across the cascade, not just `matches.first()`. Stage two
        // search dirs each containing a `config.json`, probe for
        // "config" — must come back with TWO entries.
        let dir = reload_test_dir("cascade");
        let bundled_dir = dir.join("bundled");
        let user_dir = dir.join("user");
        write_json(&bundled_dir.join("config.json"), "{}");
        write_json(&user_dir.join("config.json"), "{}");
        let out = collect_loaded_paths(
            &[bundled_dir.clone(), user_dir.clone()],
            &["config".to_string()],
        );
        assert_eq!(
            out.len(),
            2,
            "expected one entry per cascade match, got {}: {:?}",
            out.len(),
            out
        );
        // Both layers represented — order matches search_paths order
        // (bundled first, user last).
        assert_eq!(out[0].0, bundled_dir.join("config.json"));
        assert_eq!(out[1].0, user_dir.join("config.json"));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn collect_loaded_paths_skips_levels_with_no_matches() {
        // A probe level that doesn't exist in any search dir should
        // produce zero entries — no spurious paths in loaded_paths.
        let dir = reload_test_dir("skip_missing");
        write_json(&dir.join("config.json"), "{}");
        // Don't write `colors.json`.
        let out = collect_loaded_paths(
            std::slice::from_ref(&dir),
            &["config".to_string(), "colors".to_string()],
        );
        assert_eq!(out.len(), 1, "expected only config entry, got {out:?}");
        assert_eq!(
            out[0].0.file_name().and_then(|s| s.to_str()),
            Some("config.json")
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn collect_loaded_paths_walks_multiple_levels_in_each_dir() {
        // Each level is independent — config + colors at the same
        // search dir should both surface.
        let dir = reload_test_dir("multi_level");
        write_json(&dir.join("config.json"), "{}");
        write_json(&dir.join("colors.json"), "{}");
        let out = collect_loaded_paths(
            std::slice::from_ref(&dir),
            &["config".to_string(), "colors".to_string()],
        );
        assert_eq!(out.len(), 2);
        let names: Vec<&str> = out
            .iter()
            .filter_map(|(p, _)| p.file_name().and_then(|s| s.to_str()))
            .collect();
        assert!(names.contains(&"config.json"));
        assert!(names.contains(&"colors.json"));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn collect_loaded_paths_then_is_stale_round_trip() {
        // End-to-end on the helpers: stage a cascade, capture mtimes
        // via collect_loaded_paths, touch one layer, observe stale.
        // This is the same flow build_configs + Configs::is_stale
        // executes minus the parsing.
        let dir = reload_test_dir("round_trip");
        let bundled = dir.join("bundled/config.json");
        let user = dir.join("user/config.json");
        write_json(&bundled, "{}");
        write_json(&user, "{}");
        let snapshot = collect_loaded_paths(
            &[
                bundled.parent().unwrap().to_path_buf(),
                user.parent().unwrap().to_path_buf(),
            ],
            &["config".to_string()],
        );
        assert_eq!(snapshot.len(), 2);
        assert!(
            !loaded_paths_are_stale(&snapshot),
            "fresh snapshot must not report stale"
        );
        touch_forward(&user);
        assert!(
            loaded_paths_are_stale(&snapshot),
            "touch of user-layer file must trip stale (this is the bug fix)"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }
}