worktrunk 0.49.0

A CLI for Git worktree management, designed for parallel AI agent workflows
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
//! Template expansion utilities for worktrunk
//!
//! Uses minijinja for template rendering. Single generic function with escaping flag:
//! - `shell_escape: true` — Shell-escaped for safe command execution
//! - `shell_escape: false` — Literal values for filesystem paths
//!
//! All templates support Jinja2 syntax including filters, conditionals, and loops.
//!
//! See `wt hook --help` for available filters and functions.

use std::borrow::Cow;
use std::collections::{BTreeSet, HashMap};
use std::fmt;
use std::hash::{Hash, Hasher};
use std::sync::Arc;

use anyhow::Context;
use color_print::cformat;
use minijinja::value::{Enumerator, Object, ObjectRepr};
use minijinja::{Environment, ErrorKind, UndefinedBehavior, Value};
use regex::Regex;
use sha2::{Digest, Sha256};
use shell_escape::escape;

use crate::git::{Diagnostic, HookType, Repository};
use crate::path::to_posix_path;
use crate::styling::{
    eprintln, error_message, format_bash_with_gutter, format_with_gutter, hint_message,
    info_message, verbosity,
};

/// Active-context vars: point at the branch the operation acts on.
///
/// `upstream` is conditional on branch tracking configuration but is listed
/// here so templates may reference it in any context (guarded by
/// `{% if upstream %}`).
pub const ACTIVE_VARS: &[&str] = &[
    "branch",
    "worktree_path",
    "worktree_name",
    "commit",
    "short_commit",
    "upstream",
];

/// Repo/remote-metadata vars: describe the repository hosting the operation.
pub const REPO_VARS: &[&str] = &[
    "repo",
    "repo_path",
    "owner",
    "primary_worktree_path",
    "default_branch",
    "remote",
    "remote_url",
];

/// Exec-context vars always available outside hook infrastructure.
///
/// `cwd` is populated for every template expansion; `hook_type`/`hook_name`
/// are added by the hook runner itself (`HOOK_INFRASTRUCTURE_VARS`).
pub const EXEC_BASE_VARS: &[&str] = &["cwd"];

/// Template variables available in every context: the concatenation of
/// [`ACTIVE_VARS`], [`REPO_VARS`], and [`EXEC_BASE_VARS`].
///
/// Populated by `build_hook_context()` in `command_executor.rs`. Operation-
/// context vars (`base`, `target`, `pr_*`) and infrastructure vars
/// (`hook_type`, `hook_name`) are not in the base set — they're added per-
/// scope by `hook_extras` and the hook runner itself.
pub fn base_vars() -> Vec<&'static str> {
    let mut v = Vec::with_capacity(ACTIVE_VARS.len() + REPO_VARS.len() + EXEC_BASE_VARS.len());
    v.extend_from_slice(ACTIVE_VARS);
    v.extend_from_slice(REPO_VARS);
    v.extend_from_slice(EXEC_BASE_VARS);
    v
}

/// Reserved context key carrying a JSON-encoded `Vec<String>` of positional
/// CLI args forwarded to an alias. The key flows through
/// `HashMap<String, String>` — stable for stdin JSON — and
/// [`expand_template`] rehydrates it as a `ShellArgs` object so bare
/// `{{ args }}` renders as a space-joined, shell-escaped string while
/// indexing, iteration, and `length` behave like a sequence.
pub const ALIAS_ARGS_KEY: &str = "args";

/// Deprecated template variable aliases (still valid for backward compatibility).
///
/// These map to current variables and are available in every scope:
/// - `main_worktree` → `repo`
/// - `repo_root` → `repo_path`
/// - `worktree` → `worktree_path`
/// - `main_worktree_path` → `primary_worktree_path`
pub const DEPRECATED_TEMPLATE_VARS: &[&str] = &[
    "main_worktree",
    "repo_root",
    "worktree",
    "main_worktree_path",
];

/// The context in which a template will be expanded.
///
/// Validation uses this to answer "which variables are available here?" —
/// the single source of truth for hook-type-specific vars, alias-only vars,
/// and the `--execute` context. Each hook type gets the base set plus its
/// own extras (e.g., `target` for merge/remove, `base` for create/switch).
#[derive(Debug, Clone, Copy)]
pub enum ValidationScope {
    /// A hook of the given type. Adds hook infrastructure vars (`hook_type`,
    /// `hook_name`) plus hook-specific vars (`base`, `target`, etc.).
    Hook(HookType),
    /// The `--execute` template or trailing args for `wt switch --create`.
    /// Adds `base` / `base_worktree_path` for the source worktree.
    SwitchExecute,
    /// An alias body. Adds `args` for positional CLI forwarding.
    Alias,
}

/// Hook-type-specific extras that sit on top of [`base_vars`].
///
/// These are the vars injected by callers via `extra_vars` when running a
/// hook. Keeping the mapping in one place means "which vars work in a
/// `post-merge` hook?" is answerable without chasing inline comments.
///
/// Each arm's order must be a prefix-ordered subset of the operation-context
/// block in the user-facing help table (`src/cli/mod.rs`, `## Template
/// variables`): `base, base_worktree_path, target, target_worktree_path,
/// pr_number, pr_url`.
fn hook_extras(hook_type: HookType) -> &'static [&'static str] {
    use HookType::*;
    match hook_type {
        // Switch: source branch (`base`) and destination (`target`).
        // `pr_number`/`pr_url` are populated for `post-switch` when creating
        // via `pr:N` / `mr:N`; pre-switch fires before the PR/MR API call,
        // so they're never set there but remain accepted for portability.
        PreSwitch | PostSwitch => &[
            "base",
            "base_worktree_path",
            "target",
            "target_worktree_path",
            "pr_number",
            "pr_url",
        ],
        // Create/start: source worktree (`base`) and newly-created destination
        // (`target`). On create, the destination branch equals the bare `branch`
        // var — `target` is accepted for template portability with switch hooks.
        // `pr_number`/`pr_url` are populated when creating via `pr:N` / `mr:N`
        // (GitLab MRs reuse the same `pr_*` names).
        PreStart | PostStart => &[
            "base",
            "base_worktree_path",
            "target",
            "target_worktree_path",
            "pr_number",
            "pr_url",
        ],
        // Commit: integration target for the pre-commit squash.
        PreCommit | PostCommit => &["target"],
        // Merge: where the feature is being merged into.
        PreMerge | PostMerge => &["target", "target_worktree_path"],
        // Remove: where the user ends up after removal.
        PreRemove | PostRemove => &["target", "target_worktree_path"],
    }
}

/// Vars added by the hook execution infrastructure itself (`expand_commands`
/// / `expand_command_template`), regardless of hook type.
const HOOK_INFRASTRUCTURE_VARS: &[&str] = &["hook_type", "hook_name"];

/// All template variables available in a given scope.
///
/// The returned list is [`base_vars`] + scope-specific extras + deprecated
/// aliases. Used by [`validate_template`] to build the placeholder context
/// and by error messages to list what the user could have typed.
pub fn vars_available_in(scope: ValidationScope) -> Vec<&'static str> {
    let mut vars: Vec<&'static str> = base_vars();
    match scope {
        ValidationScope::Hook(hook_type) => {
            vars.extend(HOOK_INFRASTRUCTURE_VARS);
            vars.extend(hook_extras(hook_type));
            vars.push(ALIAS_ARGS_KEY);
        }
        ValidationScope::SwitchExecute => {
            vars.extend(["base", "base_worktree_path"]);
        }
        ValidationScope::Alias => {
            vars.push(ALIAS_ARGS_KEY);
        }
    }
    vars.extend(DEPRECATED_TEMPLATE_VARS);
    vars
}

/// Shared formatter for [`format_hook_variables`] and [`format_alias_variables`].
///
/// Renders `vars` as an aligned `name = value` block — no heading, no indent,
/// caller wraps. Values come from `ctx`; vars absent from `ctx` render as
/// `(unset)`, surfacing operation-specific gaps (e.g., `target_worktree_path`
/// during `wt switch -`, `upstream` when the branch doesn't track a remote).
///
/// When `referenced` is `Some`, vars absent from `ctx` *and* not in the set
/// render as dim `(unused)` — `build_hook_context` only skips computation for
/// expensive vars, so this fires precisely when the gate saved real work.
/// Cheap vars are populated unconditionally and always show their value, even
/// when the body doesn't reference them. `(unset)` is reserved for the
/// distinct case of a referenced var the operation couldn't supply.
///
/// `(unset)` relies on an invariant in `build_hook_context`: optional vars
/// are omitted from the map rather than inserted as empty strings. If a
/// future caller starts inserting `""`, revisit the empty-vs-absent
/// distinction here.
fn format_variables_table(
    vars: &[&'static str],
    ctx: &HashMap<String, String>,
    referenced: Option<&BTreeSet<String>>,
) -> String {
    let max_name = vars.iter().map(|v| v.len()).max().unwrap_or(0);
    vars.iter()
        .map(|var| match ctx.get(*var) {
            Some(value) => format!("{var:<max_name$} = {value}"),
            None if referenced.is_some_and(|r| !r.contains(*var)) => {
                cformat!("<dim>{var:<max_name$} = (unused)</>")
            }
            None => format!("{var:<max_name$} = (unset)"),
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// Format the resolved template variables for a hook invocation.
///
/// Ordered per the `## Template variables` help table in `src/cli/mod.rs`:
/// active, operation, repo, exec, infrastructure.
///
/// Deprecated aliases and `vars.*` (user state) are intentionally omitted.
pub fn format_hook_variables(hook_type: HookType, ctx: &HashMap<String, String>) -> String {
    let vars: Vec<&'static str> = ACTIVE_VARS
        .iter()
        .chain(hook_extras(hook_type))
        .chain(REPO_VARS)
        .chain(EXEC_BASE_VARS)
        .chain(HOOK_INFRASTRUCTURE_VARS)
        .copied()
        .collect();
    format_variables_table(&vars, ctx, None)
}

/// Format the resolved template variables for an alias invocation.
///
/// Ordering mirrors [`format_hook_variables`]; alias scope has no operation
/// or infrastructure vars, and `args` lives in the exec group per the help
/// table in `src/cli/mod.rs` (alongside `cwd`).
///
/// `args` is stored as a JSON-encoded `Vec<String>` per the [`ALIAS_ARGS_KEY`]
/// contract; the table displays it space-joined and shell-escaped so it
/// matches what `{{ args }}` substitutes in templates.
///
/// `referenced` (the set of vars the body actually substitutes) controls
/// the dim `(unused)` marker for vars the operation skipped computing —
/// the reader sees what's reachable without paying for values the body
/// won't substitute.
pub fn format_alias_variables(
    ctx: &HashMap<String, String>,
    referenced: Option<&BTreeSet<String>>,
) -> String {
    let vars: Vec<&'static str> = ACTIVE_VARS
        .iter()
        .copied()
        .chain(REPO_VARS.iter().copied())
        .chain(EXEC_BASE_VARS.iter().copied())
        .chain(std::iter::once(ALIAS_ARGS_KEY))
        .collect();
    let mut display_ctx = ctx.clone();
    if let Some(json) = ctx.get(ALIAS_ARGS_KEY) {
        let args: Vec<String> = serde_json::from_str(json)
            .expect("ALIAS_ARGS_KEY is always serialized from a Vec<String>");
        display_ctx.insert(ALIAS_ARGS_KEY.into(), shell_join(&args));
    }
    format_variables_table(&vars, &display_ctx, referenced)
}

/// Extend `referenced` with the implicit context-map keys an alias dispatch
/// needs:
///
/// - [`ALIAS_ARGS_KEY`] (`args`) — always present in alias scope (`run_alias`
///   inserts it after `build_hook_context`), so include it so the verbose
///   table renders the row.
/// - `branch` when the body references `vars` — `expand_template` reads
///   `branch` out of the context map to look up `{{ vars.X }}` from git
///   config at execution time. Bare `{{ vars }}`, `{{ vars.X }}`, and
///   `{{ vars["X"] }}` all surface `vars` in `undeclared_variables`.
///
/// New implicit dependencies (template-level reads from the context map that
/// `undeclared_variables` doesn't see) belong here, not at each call site.
pub fn alias_context_filter(mut referenced: BTreeSet<String>) -> BTreeSet<String> {
    let needs_branch = referenced.contains("vars");
    referenced.insert(ALIAS_ARGS_KEY.to_string());
    if needs_branch {
        referenced.insert("branch".to_string());
    }
    referenced
}

/// Positional CLI args forwarded from `wt <alias> a b c` into the alias's
/// template context. Bare `{{ args }}` renders as a space-joined,
/// shell-escaped string ready to append to a command line; `{{ args[0] }}`
/// and `{% for a in args %}…{% endfor %}` and `{{ args | length }}` all
/// behave as expected because the object reports as an
/// [`ObjectRepr::Seq`].
///
/// Shell escaping happens at render time via `shell_escape::unix::escape`
/// rather than through the template environment's formatter — the formatter
/// would otherwise quote the already-escaped joined string as a whole. The
/// formatter installed by `expand_template` detects `ShellArgs` and writes
/// it through unmodified.
#[derive(Debug)]
struct ShellArgs(Vec<String>);

impl ShellArgs {
    fn new(args: Vec<String>) -> Self {
        Self(args)
    }
}

impl Object for ShellArgs {
    fn repr(self: &Arc<Self>) -> ObjectRepr {
        ObjectRepr::Seq
    }

    fn get_value(self: &Arc<Self>, key: &Value) -> Option<Value> {
        let idx = key.as_usize()?;
        self.0.get(idx).cloned().map(Value::from)
    }

    fn enumerate(self: &Arc<Self>) -> Enumerator {
        Enumerator::Seq(self.0.len())
    }

    fn render(self: &Arc<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&shell_join(&self.0))
    }
}

/// Space-join shell-escaped args — the canonical rendering of `{{ args }}`
/// used by both `ShellArgs::render` (template expansion) and the alias
/// `-v` variable table.
fn shell_join(args: &[String]) -> String {
    args.iter()
        .map(|a| escape(Cow::Borrowed(a)).into_owned())
        .collect::<Vec<_>>()
        .join(" ")
}

/// Hash a string to a port in range 10000-19999.
fn string_to_port(s: &str) -> u16 {
    let mut h = std::collections::hash_map::DefaultHasher::new();
    s.hash(&mut h);
    10000 + (h.finish() % 10000) as u16
}

const CODENAME_MAX_WORDS: usize = 8;

/// Wordlists used by [`codename`].
///
/// Sourced from `petname::Petnames::medium()` (1198 adjectives, 1052 nouns —
/// ~1.26M `codename(2)` combinations, ~1.5B for `codename(3)`). The pin in
/// `Cargo.toml` is `=3.0.0`; bumping it may change, add, or remove words and
/// would silently shift every existing user's `worktree-path` output. Treat
/// any upgrade as a breaking change — see `test_codename_outputs_are_stable`.
///
/// `petname::Petnames::medium()` is effectively free — its `Cow::Borrowed`
/// fields point at static slices embedded by the `petnames!` macro — so
/// re-constructing per call is cheaper than reaching for a `OnceLock`.
fn codename_words() -> petname::Petnames<'static> {
    petname::Petnames::medium()
}

/// Sanitize a branch name for use in filesystem paths.
///
/// Replaces path separators (`/` and `\`) with dashes to prevent directory traversal
/// and ensure the branch name is a single path component.
///
/// # Examples
/// ```
/// use worktrunk::config::sanitize_branch_name;
///
/// assert_eq!(sanitize_branch_name("feature/foo"), "feature-foo");
/// assert_eq!(sanitize_branch_name("user\\task"), "user-task");
/// assert_eq!(sanitize_branch_name("simple-branch"), "simple-branch");
/// ```
pub fn sanitize_branch_name(branch: &str) -> String {
    branch.replace(['/', '\\'], "-")
}

/// Sanitize a string for use as a database identifier.
///
/// Transforms input into an identifier compatible with most SQL databases
/// (PostgreSQL, MySQL, SQL Server). The transformation is more aggressive than
/// `sanitize_branch_name` to ensure compatibility with database identifier rules.
///
/// # Transformation Rules (applied in order)
/// 1. Convert to lowercase (ensures portability across case-sensitive systems)
/// 2. Replace non-alphanumeric characters with `_` (only `[a-z0-9_]` are safe)
/// 3. Collapse consecutive underscores into single underscore
/// 4. Add `_` prefix if identifier starts with a digit (SQL prohibits leading digits)
/// 5. Append 3-character hash suffix for uniqueness (avoids reserved words and collisions)
/// 6. Truncate to 48 characters total (well within PostgreSQL's 63-char identifier
///    limit, leaving room for prefixes/suffixes when composing paths or identifiers)
///
/// The hash suffix ensures that:
/// - SQL reserved words are avoided (e.g., `user` → `user_abc`, not a reserved word)
/// - Different inputs don't collide (e.g., `a-b` and `a_b` get different suffixes)
///
/// # Limitations
/// - Empty input produces empty output (not a valid identifier in most DBs)
///
/// # Examples
/// ```
/// use worktrunk::config::sanitize_db;
///
/// // Hash suffix ensures uniqueness
/// assert!(sanitize_db("feature/auth").starts_with("feature_auth_"));
/// assert!(sanitize_db("123-bug-fix").starts_with("_123_bug_fix_"));
/// assert!(sanitize_db("UPPERCASE.Branch").starts_with("uppercase_branch_"));
///
/// // Different inputs get different suffixes even if base transforms are identical
/// assert_ne!(sanitize_db("a-b"), sanitize_db("a_b"));
/// ```
pub fn sanitize_db(s: &str) -> String {
    if s.is_empty() {
        return String::new();
    }

    // Single pass: lowercase, replace non-alphanumeric with underscore, collapse consecutive
    let mut result = String::with_capacity(s.len() + 4); // +4 for _xxx suffix
    let mut prev_underscore = false;
    for c in s.chars() {
        if c.is_ascii_alphanumeric() {
            result.push(c.to_ascii_lowercase());
            prev_underscore = false;
        } else if !prev_underscore {
            result.push('_');
            prev_underscore = true;
        }
    }

    // Prefix with underscore if starts with digit
    if result.starts_with(|c: char| c.is_ascii_digit()) {
        result.insert(0, '_');
    }

    // Truncate base to leave room for hash suffix (4 chars: _ + 3 hash chars).
    // Total cap is 48 chars (well within PostgreSQL's 63-char identifier limit),
    // so max base is 44.
    if result.len() > 44 {
        result.truncate(44);
    }

    // Append 3-character hash suffix for collision avoidance and reserved word safety
    // Hash is computed from original input, ensuring unique suffixes for colliding transforms
    if !result.ends_with('_') {
        result.push('_');
    }
    result.push_str(&short_hash(s));

    result
}

/// Generate a 3-character hash suffix from a string.
///
/// Uses base36 (0-9, a-z) for a compact representation with 46,656 unique values.
/// Used by `sanitize_db` and `sanitize_for_filename` to avoid collisions.
pub fn short_hash(s: &str) -> String {
    let mut h = std::collections::hash_map::DefaultHasher::new();
    s.hash(&mut h);
    let hash = h.finish();

    // Convert to base36 and take 3 characters
    const CHARS: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";
    let c0 = CHARS[(hash % 36) as usize];
    let c1 = CHARS[((hash / 36) % 36) as usize];
    let c2 = CHARS[((hash / 1296) % 36) as usize];
    String::from_utf8(vec![c0, c1, c2]).unwrap()
}

fn codename_index(input: &str, position: usize, salt: usize, pool: &str, len: usize) -> usize {
    // Cast to a fixed-width type so the hash is identical across 32-bit and
    // 64-bit builds. `usize::to_le_bytes` is architecture-dependent and would
    // change the on-disk codename for the same branch when users move between
    // architectures.
    let mut hasher = Sha256::new();
    hasher.update(input.as_bytes());
    hasher.update([0]);
    hasher.update((position as u64).to_le_bytes());
    hasher.update((salt as u64).to_le_bytes());
    hasher.update(pool.as_bytes());
    let digest = hasher.finalize();
    let mut bytes = [0_u8; 8];
    bytes.copy_from_slice(&digest[..8]);
    (u64::from_le_bytes(bytes) as usize) % len
}

fn codename(input: &str, words: usize) -> String {
    let lists = codename_words();
    let adjectives: &[&str] = lists.adjectives.as_ref();
    let nouns: &[&str] = lists.nouns.as_ref();

    let mut parts = Vec::with_capacity(words);
    let adjective_count = words.saturating_sub(1);

    for position in 0..adjective_count {
        let mut salt = 0;
        loop {
            let index = codename_index(input, position, salt, "adjective", adjectives.len());
            let word = adjectives[index];
            if !parts.contains(&word) || salt >= adjectives.len() {
                parts.push(word);
                break;
            }
            salt += 1;
        }
    }

    let index = codename_index(input, adjective_count, 0, "noun", nouns.len());
    parts.push(nouns[index]);
    parts.join("-")
}

fn invalid_filter_arg(message: impl Into<String>) -> minijinja::Error {
    minijinja::Error::new(ErrorKind::InvalidOperation, message.into())
}

fn codename_filter(value: Value, words: Option<usize>) -> Result<String, minijinja::Error> {
    let words = words.unwrap_or(2);
    if words == 0 || words > CODENAME_MAX_WORDS {
        return Err(invalid_filter_arg(format!(
            "codename word count must be between 1 and {CODENAME_MAX_WORDS}"
        )));
    }
    Ok(codename(value.as_str().unwrap_or_default(), words))
}

/// Redact credentials from URLs for safe logging.
///
/// URLs with embedded credentials (e.g., `https://token@github.com/...`) have
/// the credential portion replaced with `[REDACTED]`.
///
/// # Examples
/// ```
/// use worktrunk::config::redact_credentials;
///
/// // URLs with credentials are redacted
/// assert_eq!(
///     redact_credentials("https://ghp_token123@github.com/owner/repo"),
///     "https://[REDACTED]@github.com/owner/repo"
/// );
///
/// // URLs without credentials are unchanged
/// assert_eq!(
///     redact_credentials("https://github.com/owner/repo"),
///     "https://github.com/owner/repo"
/// );
///
/// // Non-URL values pass through unchanged
/// assert_eq!(redact_credentials("main"), "main");
/// ```
pub fn redact_credentials(s: &str) -> String {
    // Pattern: scheme://credentials@host where credentials don't contain @
    // This matches URLs like https://token@github.com or https://user:pass@host.com
    thread_local! {
        static CREDENTIAL_URL: Regex = Regex::new(r"^([a-z][a-z0-9+.-]*://)([^@/]+)@").unwrap();
    }
    CREDENTIAL_URL.with(|re| re.replace(s, "${1}[REDACTED]@").into_owned())
}

/// Error from template expansion with rich context for diagnostics.
///
/// Produced by [`expand_template`] when a template fails to parse or render.
/// Contains structured data for styled display in `main.rs` (via downcast)
/// and a `message` field for callers that embed errors in other output.
#[derive(Debug)]
pub struct TemplateExpandError {
    /// Plain-text error summary for callers that embed errors in styled messages.
    pub message: String,
    /// The failing template line (if identifiable).
    pub source_line: Option<String>,
    /// Variable names available in this template context.
    pub available_vars: Vec<String>,
}

impl std::fmt::Display for TemplateExpandError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.message)
    }
}

impl Diagnostic for TemplateExpandError {
    fn render(&self) -> String {
        let mut parts = vec![error_message(&self.message).to_string()];
        if let Some(ref line) = self.source_line {
            parts.push(format_with_gutter(line, None));
        }
        if !self.available_vars.is_empty() {
            let underlined_vars: Vec<String> = self
                .available_vars
                .iter()
                .map(|v| cformat!("<underline>{}</>", v))
                .collect();
            parts.push(
                hint_message(cformat!(
                    "Available variables: {}",
                    underlined_vars.join(", ")
                ))
                .to_string(),
            );
        }
        parts.join("\n")
    }
}

impl std::error::Error for TemplateExpandError {}

/// Build a [`TemplateExpandError`] from a minijinja error, the original template
/// source, the template name (for error messages), and the available variable names.
///
/// Message format: `Failed to expand {name}: {kind}[: {detail}] [@ line {n}]`
///
/// ```text
/// Failed to expand {name}: {kind}[: {detail}] [@ line {n}]
/// │                 │        │       │              │
/// │                 │        │       │              └─ e.line() from minijinja
/// │                 │        │       └─ e.detail() from minijinja (None for UndefinedError)
/// │                 │        └─ e.kind() from minijinja ("undefined value", "syntax error")
/// │                 └─ `name` param passed by caller
/// └─ hardcoded prefix
/// ```
fn build_template_error(
    e: &minijinja::Error,
    template: &str,
    name: &str,
    available_vars: Vec<String>,
) -> TemplateExpandError {
    let lines: Vec<&str> = template.lines().collect();
    let line_num = e.line();
    let source_line =
        line_num.and_then(|n| lines.get(n.saturating_sub(1)).copied().map(String::from));

    // Build message: "Failed to expand {name}: {kind}[: {detail}] [@ line {n}]"
    // e.g. "Failed to expand --execute command: undefined value @ line 1"
    let detail = match e.detail() {
        Some(detail) => format!("{}: {detail}", e.kind()),
        None => e.kind().to_string(),
    };
    let is_undefined = e.kind() == ErrorKind::UndefinedError;

    // minijinja always provides a line number for syntax and render errors
    let message = match line_num {
        Some(n) => format!("Failed to expand {name}: {detail} @ line {n}"),
        None => format!("Failed to expand {name}: {detail}"),
    };

    TemplateExpandError {
        message,
        source_line,
        // Only show available vars for undefined errors (actionable hint)
        available_vars: if is_undefined {
            available_vars
        } else {
            Vec::new()
        },
    }
}

/// Set up a minijinja environment with worktrunk's custom filters and functions.
///
/// Shared by [`expand_template`] and [`validate_template`] to ensure both use
/// the same filters, functions, and undefined-behavior settings.
fn setup_template_env(repo: &Repository) -> Environment<'static> {
    let mut env = Environment::new();
    // SemiStrict: errors on undefined variable use (printing, iteration) but allows
    // truthiness checks ({% if var %}). This catches typos while supporting optional vars.
    env.set_undefined_behavior(UndefinedBehavior::SemiStrict);

    // Register custom filters
    env.add_filter("sanitize", |value: Value| -> String {
        sanitize_branch_name(value.as_str().unwrap_or_default())
    });
    env.add_filter("sanitize_db", |value: Value| -> String {
        sanitize_db(value.as_str().unwrap_or_default())
    });
    env.add_filter("sanitize_hash", |value: Value| -> String {
        crate::path::sanitize_for_filename(value.as_str().unwrap_or_default())
    });
    env.add_filter("hash", |value: Value| -> String {
        short_hash(value.as_str().unwrap_or_default())
    });
    env.add_filter("hash_port", |value: String| string_to_port(&value));
    env.add_filter("dirname", |value: Value| -> String {
        std::path::Path::new(value.as_str().unwrap_or_default())
            .parent()
            .map(|p| to_posix_path(&p.to_string_lossy()))
            .unwrap_or_default()
    });
    env.add_filter("basename", |value: Value| -> String {
        std::path::Path::new(value.as_str().unwrap_or_default())
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_default()
    });
    env.add_filter("codename", codename_filter);

    // Register worktree_path_of_branch function for looking up branch worktree paths.
    // Returns raw paths — shell escaping is applied by the formatter at output time.
    let repo_clone = repo.clone();
    env.add_function("worktree_path_of_branch", move |branch: String| -> String {
        repo_clone
            .worktree_for_branch(&branch)
            .ok()
            .flatten()
            .map(|p| to_posix_path(&p.to_string_lossy()))
            .unwrap_or_default()
    });

    env
}

/// Top-level variables referenced by a single template.
///
/// Uses minijinja's AST analysis rather than string matching, avoiding false
/// positives from literal text like `template_vars.txt`. Templates that fail
/// to parse contribute nothing — a syntax error surfaces later at expansion
/// time with a richer message.
fn referenced_vars(template: &str) -> std::collections::HashSet<String> {
    minijinja::Environment::new()
        .template_from_str(template)
        .map(|tmpl| tmpl.undeclared_variables(false))
        .unwrap_or_default()
}

/// Check if a template references a specific top-level variable.
pub fn template_references_var(template: &str, var: &str) -> bool {
    referenced_vars(template).contains(var)
}

/// Union of top-level variables referenced across every command in `cfg`.
///
/// Drives alias-arg routing in `AliasOptions::parse`: a `--KEY=VALUE` token
/// binds to `{{ KEY }}` only when KEY appears in this set; otherwise it
/// forwards as a positional. A var referenced in any step of a pipeline is
/// a binding candidate for the whole invocation. A syntax error in any
/// template fails here so the user sees it before flags are routed — a
/// silent skip could mask a typo and change how subsequent CLI args bind.
pub fn referenced_vars_for_config(cfg: &super::CommandConfig) -> anyhow::Result<BTreeSet<String>> {
    let env = minijinja::Environment::new();
    let mut out = BTreeSet::new();
    for cmd in cfg.commands() {
        let tmpl = env
            .template_from_str(&cmd.template)
            .with_context(|| format!("Failed to parse template: {:?}", cmd.template))?;
        out.extend(tmpl.undeclared_variables(false));
    }
    Ok(out)
}

/// Parse-only syntax check for a template.
///
/// Used on lazy-expansion paths (hooks + aliases) where rendering would fail
/// because `vars.*` values are only known at execution time — we still want
/// to catch typos like `{{ vars..foo }}` upfront.
pub fn validate_template_syntax(template: &str, name: &str) -> Result<(), minijinja::Error> {
    minijinja::Environment::new()
        .template_from_named_str(name, template)
        .map(|_| ())
}

/// Validate that a template can be expanded without errors in the given scope.
///
/// Performs a trial expansion with placeholder values for exactly the variables
/// available in `scope` (see [`vars_available_in`]). Catches syntax errors and
/// undefined variable references *before* irreversible operations like worktree
/// creation — including context-mismatch typos like `{{ args }}` in a hook or
/// `{{ target }}` in a `pre-start` hook.
///
/// This is deliberately more permissive than real expansion: conditional vars
/// like `upstream` are provided even when they may be absent at runtime. A
/// template like `{{ upstream }}` passes validation but could fail later if
/// tracking isn't configured — the alternative (predicting which optional
/// variables will be available) would be fragile and context-dependent.
///
/// No verbose logging is performed — this is a pre-flight check, not the real expansion.
pub fn validate_template(
    template: &str,
    scope: ValidationScope,
    repo: &Repository,
    name: &str,
) -> Result<(), TemplateExpandError> {
    let available = vars_available_in(scope);
    let mut context: HashMap<String, minijinja::Value> = available
        .iter()
        .filter(|&&k| k != ALIAS_ARGS_KEY)
        .map(|&k| (k.to_string(), minijinja::Value::from("PLACEHOLDER")))
        .collect();
    // Inject vars as empty map so {{ vars.key | default(...) }} doesn't error
    context.insert(
        "vars".to_string(),
        minijinja::Value::from_serialize(std::collections::BTreeMap::<String, String>::new()),
    );
    // In alias and hook scopes, inject `args` as an empty sequence so
    // `{{ args }}`, `{{ args[0] | default(...) }}`, `{{ args | length }}`,
    // and `{% for a in args %}…{% endfor %}` all validate.
    if matches!(scope, ValidationScope::Alias | ValidationScope::Hook(_)) {
        context.insert(
            ALIAS_ARGS_KEY.to_string(),
            Value::from_object(ShellArgs::new(Vec::new())),
        );
    }

    let env = setup_template_env(repo);

    let tmpl = env
        .template_from_named_str(name, template)
        .map_err(|e| build_template_error(&e, template, name, Vec::new()))?;

    tmpl.render(minijinja::Value::from_object(context))
        .map_err(|e| {
            let mut keys: Vec<String> = available.iter().map(|k| k.to_string()).collect();
            keys.sort();
            build_template_error(&e, template, name, keys)
        })?;

    Ok(())
}

/// Expand a template with variable substitution.
///
/// # Arguments
/// * `template` - Template string using Jinja2 syntax (e.g., `{{ branch }}`)
/// * `vars` - Variables to substitute
/// * `shell_escape` - If true, shell-escape all values for safe command execution.
///   If false, substitute values literally (for filesystem paths).
/// * `repo` - Repository for looking up worktree paths
///
/// # Filters
/// - `sanitize` — Replace `/` and `\` with `-` for filesystem-safe paths
/// - `sanitize_db` — Transform to database-safe identifier (`[a-z0-9_]`, max 48 chars)
/// - `sanitize_hash` — Filesystem-safe name with hash suffix so distinct inputs never collide
/// - `hash` — 3-character base36 hash digest of the input
/// - `hash_port` — Hash to deterministic port number (10000-19999)
/// - `dirname` — Strip the last path component (e.g., `/a/b/c` → `/a/b`)
/// - `basename` — Keep only the last path component (e.g., `/a/b/c` → `c`)
/// - `codename(n)` — deterministic friendly words, e.g. `malleable-opah`
///
/// # Functions
/// - `worktree_path_of_branch(branch)` — Look up the filesystem path of a branch's worktree
///   Returns empty string if branch has no worktree.
///
/// The `name` parameter appears in error messages to help identify which template failed.
pub fn expand_template(
    template: &str,
    vars: &HashMap<&str, &str>,
    shell_escape: bool,
    repo: &Repository,
    name: &str,
) -> Result<String, TemplateExpandError> {
    // Build context map with raw values (shell escaping is applied at output time via formatter).
    // The `args` key is reserved: run_alias encodes positional CLI args as a JSON list string,
    // and we rehydrate it here as a `ShellArgs` object so `{{ args }}` behaves sequence-like.
    let mut context = HashMap::new();
    for (key, value) in vars {
        if *key == ALIAS_ARGS_KEY {
            let parsed: Vec<String> = serde_json::from_str(value).unwrap_or_default();
            context.insert(key.to_string(), Value::from_object(ShellArgs::new(parsed)));
        } else {
            context.insert(
                key.to_string(),
                minijinja::Value::from((*value).to_string()),
            );
        }
    }

    // Inject vars data as a nested object: {{ vars.env }}, {{ vars.config.port }}
    // When branch is present, always inject (even if empty map) so {{ vars.key | default(...) }}
    // works in SemiStrict mode. Only look up vars data if the template references it (avoids a
    // git process spawn per expansion). JSON objects/arrays are parsed so dot access works
    // ({{ vars.config.port }}); plain strings and numbers stay as-is.
    //
    // Use "vars." to avoid false positives from branch names or URLs containing "vars"
    // (e.g., "envvars.internal"). Template access is always `vars.<key>`.
    if template.contains("vars.")
        && let Some(branch) = vars.get("branch")
    {
        let entries = repo.vars_entries(branch);
        let vars_map: std::collections::BTreeMap<String, Value> = entries
            .into_iter()
            .map(|(k, v)| {
                let value = serde_json::from_str::<serde_json::Value>(&v)
                    .ok()
                    .filter(|j| j.is_object() || j.is_array())
                    .map(|j| Value::from_serialize(&j))
                    .unwrap_or_else(|| Value::from(v));
                (k, value)
            })
            .collect();
        context.insert("vars".to_string(), Value::from_serialize(&vars_map));
    }

    let mut env = setup_template_env(repo);
    if shell_escape {
        // Preserve trailing newlines in templates (important for multiline shell commands)
        env.set_keep_trailing_newline(true);

        // Shell-escape values at output time, not before template rendering.
        // This ensures filters (sanitize, sanitize_db, etc.) operate on raw values
        // and the escaping is applied to the final output, preventing corruption
        // when filters modify already-escaped strings.
        env.set_formatter(|out, _state, value| {
            if value.is_none() {
                return Ok(());
            }
            // ShellArgs renders each element pre-escaped and space-joined
            // (see [`ShellArgs::render`]); passing through its Display
            // output avoids re-escaping the whole joined string as one
            // opaque token. Iteration and indexing yield plain string
            // values that still flow through the generic escape branch.
            if value.downcast_object_ref::<ShellArgs>().is_some() {
                write!(out, "{value}")?;
                return Ok(());
            }
            let s = value.to_string();
            let escaped = escape(Cow::Borrowed(&s));
            write!(out, "{escaped}")?;
            Ok(())
        });
    }

    // Cache verbosity level for consistent behavior within this call
    let verbose = verbosity();

    // -vv: Full debug logging with vars
    // Redact credentials from values to prevent leaking tokens in logs
    if verbose >= 2 {
        log::debug!("[template:{name}] template={template:?}");
        // Sort keys for deterministic output in tests
        let mut sorted_vars: Vec<_> = vars.iter().collect();
        sorted_vars.sort_by_key(|(k, _)| *k);
        log::debug!(
            "[template:{name}] vars={{{}}}",
            sorted_vars
                .iter()
                .map(|(k, v)| format!("{k}={:?}", redact_credentials(v)))
                .collect::<Vec<_>>()
                .join(", ")
        );
    }

    // Parse errors are always SyntaxError, never UndefinedError — no need for available_vars
    let tmpl = env
        .template_from_named_str(name, template)
        .map_err(|e| build_template_error(&e, template, name, Vec::new()))?;

    let result = tmpl
        .render(minijinja::Value::from_object(context))
        .map_err(|e| {
            let mut keys: Vec<String> = vars.keys().map(|k| k.to_string()).collect();
            keys.sort();
            build_template_error(&e, template, name, keys)
        })?;

    // -vv: Full debug logging with result
    // Redact credentials from result to prevent leaking tokens in logs
    if verbose >= 2 {
        log::debug!("[template:{name}] result={:?}", redact_credentials(&result));
    }

    // -v: Nice styled output showing template expansion
    // Info message for header, gutter for quoted content (template → result)
    // Single atomic write to avoid interleaving in multi-threaded execution
    if verbose == 1 {
        let header = info_message(cformat!("Expanding <bold>{name}</>"));
        // Format template and result as bash (dim + syntax highlighting),
        // with a dim → separator that bypasses the syntax highlighter
        let template_gutter = format_bash_with_gutter(template);
        let arrow = format_with_gutter(&cformat!("<dim>→</>"), None);
        let result_gutter = format_bash_with_gutter(&result);
        eprintln!("{header}\n{template_gutter}\n{arrow}\n{result_gutter}");
    }
    Ok(result)
}

#[cfg(test)]
mod tests {
    use insta::assert_snapshot;

    use super::*;
    use crate::shell_exec::Cmd;
    use crate::testing::TestRepo;

    fn test_repo() -> TestRepo {
        TestRepo::new()
    }

    #[test]
    fn test_sanitize_branch_name() {
        let cases = [
            ("feature/foo", "feature-foo"),
            (r"user\task", "user-task"),
            ("feature/user/task", "feature-user-task"),
            (r"feature/user\task", "feature-user-task"),
            ("simple-branch", "simple-branch"),
            ("", ""),
            ("///", "---"),
            ("/feature", "-feature"),
            ("feature/", "feature-"),
        ];
        for (input, expected) in cases {
            assert_eq!(sanitize_branch_name(input), expected, "input: {input}");
        }
    }

    #[test]
    fn test_sanitize_db() {
        // Test that base transformations are correct (ignore hash suffix)
        let cases = [
            // Examples from spec
            ("feature/auth-oauth2", "feature_auth_oauth2_"),
            ("123-bug-fix", "_123_bug_fix_"),
            ("UPPERCASE.Branch", "uppercase_branch_"),
            // Lowercase conversion
            ("MyBranch", "mybranch_"),
            ("ALLCAPS", "allcaps_"),
            // Non-alphanumeric replacement
            ("feature/foo", "feature_foo_"),
            ("feature-bar", "feature_bar_"),
            ("feature.baz", "feature_baz_"),
            ("feature@qux", "feature_qux_"),
            // Consecutive underscore collapse
            ("a--b", "a_b_"),
            ("a///b", "a_b_"),
            ("a...b", "a_b_"),
            ("a-/-b", "a_b_"),
            // Leading digit prefix
            ("1branch", "_1branch_"),
            ("123", "_123_"),
            ("0test", "_0test_"),
            // No prefix needed
            ("branch1", "branch1_"),
            ("_already", "_already_"),
            // Edge cases (non-empty)
            ("a", "a_"),
            // Mixed cases
            ("Feature/Auth-OAuth2", "feature_auth_oauth2_"),
            ("user/TASK/123", "user_task_123_"),
            // Non-ASCII characters become underscores
            ("naïve-impl", "na_ve_impl_"),
            ("über-feature", "_ber_feature_"),
        ];
        for (input, expected_prefix) in cases {
            let result = sanitize_db(input);
            assert!(
                result.starts_with(expected_prefix),
                "input: {input}, expected prefix: {expected_prefix}, got: {result}"
            );
            // Result should be prefix + 3-char hash
            assert_eq!(
                result.len(),
                expected_prefix.len() + 3,
                "input: {input}, result: {result}"
            );
        }

        // Empty input stays empty (no hash suffix)
        assert_eq!(sanitize_db(""), "");

        // Special cases that collapse to just underscore + hash
        for input in ["_", "-", "---", "日本語"] {
            let result = sanitize_db(input);
            assert!(result.starts_with('_'), "input: {input}, got: {result}");
            assert_eq!(result.len(), 4, "input: {input}, got: {result}"); // _xxx
        }
    }

    #[test]
    fn test_sanitize_db_collision_avoidance() {
        // Different inputs that would collide without hash suffix now differ
        assert_ne!(sanitize_db("a-b"), sanitize_db("a_b"));
        assert_ne!(sanitize_db("feature/auth"), sanitize_db("feature-auth"));
        assert_ne!(sanitize_db("UPPERCASE"), sanitize_db("uppercase"));

        // Same input always produces same output (deterministic)
        assert_eq!(sanitize_db("test"), sanitize_db("test"));
        assert_eq!(sanitize_db("feature/foo"), sanitize_db("feature/foo"));
    }

    #[test]
    fn test_sanitize_db_reserved_words() {
        // Reserved words get hash suffix, making them safe
        let user = sanitize_db("user");
        assert!(user.starts_with("user_"), "got: {user}");
        assert_ne!(user, "user"); // Not a bare reserved word

        let select = sanitize_db("select");
        assert!(select.starts_with("select_"), "got: {select}");
        assert_ne!(select, "select");
    }

    #[test]
    fn test_sanitize_db_truncation() {
        // Total output is always max 48 characters
        // Base is truncated to 44 chars, then _xxx suffix (4 chars) is added

        // Very long input: base truncated to 44, + 4 = 48
        let long_input = "a".repeat(100);
        let result = sanitize_db(&long_input);
        assert_eq!(result.len(), 48, "result: {result}");
        assert!(result.starts_with(&"a".repeat(43)), "result: {result}");
        assert!(!result.ends_with('_'), "should end with hash chars");

        // Short input: base + _ + hash
        let short = "test";
        let result = sanitize_db(short);
        assert!(result.starts_with("test_"), "result: {result}");
        assert_eq!(result.len(), 8, "result: {result}"); // test_ + 3 hash chars

        // Truncation happens after prefix is added for digit-starting inputs
        let digit_start = format!("1{}", "x".repeat(100));
        let result = sanitize_db(&digit_start);
        assert_eq!(result.len(), 48, "result: {result}");
        assert!(result.starts_with("_1"), "result: {result}");
    }

    #[test]
    fn test_expand_template_basic() {
        let test = test_repo();

        // Single variable
        let mut vars = HashMap::new();
        vars.insert("name", "world");
        assert_eq!(
            expand_template("Hello {{ name }}", &vars, false, &test.repo, "test").unwrap(),
            "Hello world"
        );

        // Multiple variables
        vars.insert("repo", "myrepo");
        assert_eq!(
            expand_template("{{ repo }}/{{ name }}", &vars, false, &test.repo, "test").unwrap(),
            "myrepo/world"
        );

        // Empty/static cases
        let empty: HashMap<&str, &str> = HashMap::new();
        assert_eq!(
            expand_template("", &empty, false, &test.repo, "test").unwrap(),
            ""
        );
        assert_eq!(
            expand_template("static text", &empty, false, &test.repo, "test").unwrap(),
            "static text"
        );
        // Undefined variables now error in SemiStrict mode
        let err = expand_template("no {{ variables }} here", &empty, false, &test.repo, "test")
            .unwrap_err();
        assert!(
            err.message.contains("undefined value"),
            "got: {}",
            err.message
        );
    }

    #[test]
    fn test_expand_template_shell_escape() {
        let test = test_repo();
        let mut vars = HashMap::new();
        vars.insert("path", "my path");
        let expanded = expand_template("cd {{ path }}", &vars, true, &test.repo, "test").unwrap();
        assert!(expanded.contains("'my path'") || expanded.contains(r"my\ path"));

        // Command injection prevention
        vars.insert("arg", "test;rm -rf");
        let expanded = expand_template("echo {{ arg }}", &vars, true, &test.repo, "test").unwrap();
        assert!(!expanded.contains(";rm") || expanded.contains("'"));

        // No escape for literal mode
        vars.insert("branch", "feature/foo");
        assert_eq!(
            expand_template("{{ branch }}", &vars, false, &test.repo, "test").unwrap(),
            "feature/foo"
        );
    }

    #[test]
    fn test_expand_template_errors() {
        let test = test_repo();
        let vars = HashMap::new();
        let err = expand_template("{{ unclosed", &vars, false, &test.repo, "test").unwrap_err();
        assert!(err.message.contains("syntax error"), "got: {}", err.message);
        assert!(expand_template("{{ 1 + }}", &vars, false, &test.repo, "test").is_err());

        // Diagnostic::render produces source line but no available vars hint for syntax errors
        assert_snapshot!(crate::git::Diagnostic::render(&err), @"
        ✗ Failed to expand test: syntax error: unexpected end of input, expected end of variable block @ line 1
          {{ unclosed
        ");
    }

    #[test]
    fn test_expand_template_undefined_var_details() {
        let test = test_repo();
        let mut vars = HashMap::new();
        vars.insert("branch", "main");
        vars.insert("remote", "origin");

        let err =
            expand_template("echo {{ target }}", &vars, false, &test.repo, "test").unwrap_err();
        assert!(
            err.message.contains("undefined value"),
            "should mention undefined value: {}",
            err.message
        );
        assert!(err.available_vars.contains(&"branch".to_string()));
        assert!(err.available_vars.contains(&"remote".to_string()));
        assert_eq!(err.source_line.as_deref(), Some("echo {{ target }}"));

        // Diagnostic::render produces source line and available vars hint
        assert_snapshot!(crate::git::Diagnostic::render(&err), @"
        ✗ Failed to expand test: undefined value @ line 1
          echo {{ target }}
        ↳ Available variables: branch, remote
        ");
    }

    #[test]
    fn test_expand_template_jinja_features() {
        let test = test_repo();
        let mut vars = HashMap::new();
        vars.insert("debug", "true");
        assert_eq!(
            expand_template(
                "{% if debug %}DEBUG{% endif %}",
                &vars,
                false,
                &test.repo,
                "test"
            )
            .unwrap(),
            "DEBUG"
        );

        vars.insert("debug", "");
        assert_eq!(
            expand_template(
                "{% if debug %}DEBUG{% endif %}",
                &vars,
                false,
                &test.repo,
                "test"
            )
            .unwrap(),
            ""
        );

        let empty: HashMap<&str, &str> = HashMap::new();
        assert_eq!(
            expand_template(
                "{{ missing | default('fallback') }}",
                &empty,
                false,
                &test.repo,
                "test",
            )
            .unwrap(),
            "fallback"
        );

        vars.insert("name", "hello");
        assert_eq!(
            expand_template("{{ name | upper }}", &vars, false, &test.repo, "test").unwrap(),
            "HELLO"
        );
    }

    #[test]
    fn test_expand_template_strip_prefix() {
        let test = test_repo();
        let mut vars = HashMap::new();

        // Built-in replace filter strips prefix (replaces all occurrences)
        vars.insert("branch", "feature/foo");
        assert_eq!(
            expand_template(
                "{{ branch | replace('feature/', '') }}",
                &vars,
                false,
                &test.repo,
                "test"
            )
            .unwrap(),
            "foo"
        );

        // Replace + sanitize for worktree paths
        assert_eq!(
            expand_template(
                "{{ branch | replace('feature/', '') | sanitize }}",
                &vars,
                false,
                &test.repo,
                "test"
            )
            .unwrap(),
            "foo"
        );

        // Branch without prefix passes through unchanged
        vars.insert("branch", "main");
        assert_eq!(
            expand_template(
                "{{ branch | replace('feature/', '') }}",
                &vars,
                false,
                &test.repo,
                "test"
            )
            .unwrap(),
            "main"
        );

        // Slicing for prefix-only removal (avoids replacing mid-string)
        vars.insert("branch", "feature/nested/feature/deep");
        assert_eq!(
            expand_template("{{ branch[8:] }}", &vars, false, &test.repo, "test").unwrap(),
            "nested/feature/deep"
        );

        // Conditional slicing for safe prefix removal
        assert_eq!(
            expand_template(
                "{% if branch[:8] == 'feature/' %}{{ branch[8:] }}{% else %}{{ branch }}{% endif %}",
                &vars,
                false,
                &test.repo,
                "test"
            )
            .unwrap(),
            "nested/feature/deep"
        );

        // Conditional passes through non-matching branches
        vars.insert("branch", "bugfix/bar");
        assert_eq!(
            expand_template(
                "{% if branch[:8] == 'feature/' %}{{ branch[8:] }}{% else %}{{ branch }}{% endif %}",
                &vars,
                false,
                &test.repo,
                "test"
            )
            .unwrap(),
            "bugfix/bar"
        );
    }

    #[test]
    fn test_expand_template_sanitize_filter() {
        let test = test_repo();
        let mut vars = HashMap::new();
        vars.insert("branch", "feature/foo");
        assert_eq!(
            expand_template("{{ branch | sanitize }}", &vars, false, &test.repo, "test").unwrap(),
            "feature-foo"
        );

        // Backslashes are also sanitized
        vars.insert("branch", r"feature\bar");
        assert_eq!(
            expand_template("{{ branch | sanitize }}", &vars, false, &test.repo, "test").unwrap(),
            "feature-bar"
        );

        // Multiple slashes
        vars.insert("branch", "user/feature/task");
        assert_eq!(
            expand_template("{{ branch | sanitize }}", &vars, false, &test.repo, "test").unwrap(),
            "user-feature-task"
        );

        // Raw branch is unchanged
        vars.insert("branch", "feature/foo");
        assert_eq!(
            expand_template("{{ branch }}", &vars, false, &test.repo, "test").unwrap(),
            "feature/foo"
        );

        // Shell escaping + sanitize: filters operate on raw values, escaping applied at output.
        // Previously, shell escaping was applied BEFORE filters, corrupting the result
        // when values contained shell-special characters (quotes, backslashes).
        vars.insert("branch", "user's/feature");
        let result =
            expand_template("{{ branch | sanitize }}", &vars, true, &test.repo, "test").unwrap();
        // sanitize replaces / with -, producing "user's-feature"
        // shell_escape wraps it: 'user'\''s-feature' (valid shell for user's-feature)
        assert_eq!(result, r"'user'\''s-feature'", "sanitize + shell escape");

        // Without the fix, pre-escaping would produce corrupted output because
        // sanitize would replace the / and \ in the already-escaped value.

        // Shell escaping without filter: raw value with special chars
        let result = expand_template("{{ branch }}", &vars, true, &test.repo, "test").unwrap();
        // shell_escape wraps: 'user'\''s/feature' (valid shell for user's/feature)
        assert_eq!(
            result, r"'user'\''s/feature'",
            "shell escape without filter"
        );

        // Shell-escape formatter handles none values (renders as empty string)
        let result =
            expand_template("prefix-{{ none }}-suffix", &vars, true, &test.repo, "test").unwrap();
        assert_eq!(result, "prefix--suffix", "none renders as empty");
    }

    #[test]
    fn test_expand_template_sanitize_db_filter() {
        let test = test_repo();
        let mut vars = HashMap::new();

        // Basic transformation (with hash suffix)
        vars.insert("branch", "feature/auth-oauth2");
        let result = expand_template(
            "{{ branch | sanitize_db }}",
            &vars,
            false,
            &test.repo,
            "test",
        )
        .unwrap();
        assert!(result.starts_with("feature_auth_oauth2_"), "got: {result}");

        // Leading digit gets underscore prefix
        vars.insert("branch", "123-bug-fix");
        let result = expand_template(
            "{{ branch | sanitize_db }}",
            &vars,
            false,
            &test.repo,
            "test",
        )
        .unwrap();
        assert!(result.starts_with("_123_bug_fix_"), "got: {result}");

        // Uppercase conversion
        vars.insert("branch", "UPPERCASE.Branch");
        let result = expand_template(
            "{{ branch | sanitize_db }}",
            &vars,
            false,
            &test.repo,
            "test",
        )
        .unwrap();
        assert!(result.starts_with("uppercase_branch_"), "got: {result}");

        // Raw branch is unchanged
        vars.insert("branch", "feature/foo");
        assert_eq!(
            expand_template("{{ branch }}", &vars, false, &test.repo, "test").unwrap(),
            "feature/foo"
        );
    }

    #[test]
    fn test_expand_template_trailing_newline() {
        let test = test_repo();
        let mut vars = HashMap::new();
        vars.insert("cmd", "echo hello");
        assert!(
            expand_template("{{ cmd }}\n", &vars, true, &test.repo, "test")
                .unwrap()
                .ends_with('\n')
        );
    }

    #[test]
    fn test_string_to_port_deterministic_and_in_range() {
        for input in ["main", "feature-foo", "", "a", "long-branch-name-123"] {
            let p1 = string_to_port(input);
            let p2 = string_to_port(input);
            assert_eq!(p1, p2, "same input should produce same port");
            assert!((10000..20000).contains(&p1), "port {} out of range", p1);
        }
    }

    #[test]
    fn test_hash_filter() {
        let test = test_repo();
        let mut vars = HashMap::new();
        vars.insert("branch", "feature/very-long-branch-name");

        // Filter produces a 3-char base36 digest
        let result =
            expand_template("{{ branch | hash }}", &vars, false, &test.repo, "test").unwrap();
        assert_eq!(result.len(), 3);
        assert!(
            result
                .chars()
                .all(|c| c.is_ascii_digit() || c.is_ascii_lowercase()),
            "got: {result}"
        );

        // Deterministic: same input produces same hash across calls
        let r1 = expand_template("{{ branch | hash }}", &vars, false, &test.repo, "test").unwrap();
        let r2 = expand_template("{{ branch | hash }}", &vars, false, &test.repo, "test").unwrap();
        assert_eq!(r1, r2);

        // Composable: hash reflects the upstream filter's output
        vars.insert("branch", "feature/auth");
        let raw = expand_template("{{ branch | hash }}", &vars, false, &test.repo, "test").unwrap();
        let sanitized = expand_template(
            "{{ branch | sanitize | hash }}",
            &vars,
            false,
            &test.repo,
            "test",
        )
        .unwrap();
        // `sanitize` rewrites `/` to `-`, so the hashed input differs and the digest does too.
        assert_ne!(raw, sanitized);

        // User-composed truncation + hash recipe (from extending docs)
        let truncated = expand_template(
            "{{ (branch | sanitize)[:8] }}_{{ branch | sanitize | hash }}",
            &vars,
            false,
            &test.repo,
            "test",
        )
        .unwrap();
        assert!(truncated.starts_with("feature-"), "got: {truncated}");
        assert_eq!(truncated.len(), 8 + 1 + 3);

        // Empty input: still produces a 3-char digest (empty-string hash is stable)
        vars.insert("branch", "");
        let empty =
            expand_template("{{ branch | hash }}", &vars, false, &test.repo, "test").unwrap();
        assert_eq!(empty.len(), 3);
    }

    #[test]
    fn test_codename_filter() {
        let test = test_repo();
        let mut vars = HashMap::new();
        vars.insert("branch", "feature/very-long-branch-name");

        let default =
            expand_template("{{ branch | codename }}", &vars, false, &test.repo, "test").unwrap();
        let explicit_default = expand_template(
            "{{ branch | codename(2) }}",
            &vars,
            false,
            &test.repo,
            "test",
        )
        .unwrap();
        assert_eq!(default, explicit_default);
        assert_eq!(default.split('-').count(), 2, "got: {default}");

        let one_word = expand_template(
            "{{ branch | codename(1) }}",
            &vars,
            false,
            &test.repo,
            "test",
        )
        .unwrap();
        assert!(!one_word.contains('-'), "got: {one_word}");
        let lists = codename_words();
        let nouns: &[&str] = lists.nouns.as_ref();
        assert!(nouns.contains(&one_word.as_str()));

        let three_words = expand_template(
            "{{ branch | codename(3) }}",
            &vars,
            false,
            &test.repo,
            "test",
        )
        .unwrap();
        assert_eq!(three_words.split('-').count(), 3, "got: {three_words}");

        let repeat =
            expand_template("{{ branch | codename }}", &vars, false, &test.repo, "test").unwrap();
        assert_eq!(default, repeat);

        vars.insert("branch", "feature/different-name");
        let other =
            expand_template("{{ branch | codename }}", &vars, false, &test.repo, "test").unwrap();
        assert_eq!(other.split('-').count(), 2, "got: {other}");

        vars.insert("branch", "feature/73");
        let ticket_73 = expand_template(
            "{{ branch | codename(3) }}",
            &vars,
            false,
            &test.repo,
            "test",
        )
        .unwrap();
        vars.insert("branch", "feature/149");
        let ticket_149 = expand_template(
            "{{ branch | codename(3) }}",
            &vars,
            false,
            &test.repo,
            "test",
        )
        .unwrap();
        assert_ne!(ticket_73, ticket_149);
    }

    #[test]
    fn test_codename_filter_rejects_invalid_counts() {
        let test = test_repo();
        let mut vars = HashMap::new();
        vars.insert("branch", "feature");

        let zero = expand_template(
            "{{ branch | codename(0) }}",
            &vars,
            false,
            &test.repo,
            "test",
        )
        .unwrap_err()
        .to_string();
        assert!(
            zero.contains("codename word count must be between 1 and 8"),
            "got: {zero}"
        );

        let too_many = expand_template(
            "{{ branch | codename(9) }}",
            &vars,
            false,
            &test.repo,
            "test",
        )
        .unwrap_err()
        .to_string();
        assert!(
            too_many.contains("codename word count must be between 1 and 8"),
            "got: {too_many}"
        );
    }

    #[test]
    fn test_codename_word_lists_are_path_safe() {
        fn assert_word_list(name: &str, words: &[&str]) {
            assert!(words.len() >= 160, "{name} should have enough entries");
            let mut seen = std::collections::HashSet::new();
            for &word in words {
                assert!(seen.insert(word), "duplicate {name} word: {word}");
                assert!(!word.is_empty(), "empty {name} word");
                assert!(
                    word.chars().all(|c| c.is_ascii_lowercase()),
                    "{name} word is not lowercase ASCII: {word}"
                );
                assert!(
                    !word.contains('-') && !word.contains(' '),
                    "{name} word is not a single path component fragment: {word}"
                );
            }
        }

        let lists = codename_words();
        let adjectives: &[&str] = lists.adjectives.as_ref();
        let nouns: &[&str] = lists.nouns.as_ref();
        assert_word_list("adjective", adjectives);
        assert_word_list("noun", nouns);
        // codename(2) cardinality — petname::medium() gives ~1.26M combinations,
        // so a single adjective+noun pair is enough on its own for typical
        // worktree counts.
        assert!(adjectives.len() * nouns.len() >= 1_000_000);
    }

    /// Pins specific `codename(input, n)` outputs so the on-disk contract
    /// is impossible to break by accident. Once a user adopts this filter in
    /// their `worktree-path` template, the petname wordlists (and the
    /// hash-input layout in `codename_index`) become an on-disk identity for
    /// every worktree they own. Anything that shifts the wordlists (a
    /// `petname` version bump that adds, removes, or reorders a word) or
    /// changes how the hash is computed produces a different name for the
    /// same branch on the next `wt switch`, orphaning the existing worktree.
    ///
    /// If this test fails:
    ///
    /// 1. Stop. Do not update the expected values to silence it.
    /// 2. Confirm whether you actually intended to change the wordlists
    ///    (e.g. via a `petname` version bump) or the hash layout. If it was
    ///    unintentional (a refactor, a Cargo update), revert.
    /// 3. If the change is intentional, accept that you are breaking every
    ///    existing user's worktree paths. Coordinate the rollout, document
    ///    it as a breaking change, and only then update the expected values.
    #[test]
    fn test_codename_outputs_are_stable() {
        let cases: &[(&str, usize, &str)] = &[
            ("main", 1, "gorilla"),
            ("feature/auth", 2, "malleable-opah"),
            ("feature/73", 2, "prodigious-shoveler"),
            ("feature/149", 2, "tuneful-vendace"),
            ("release/1.0", 3, "intent-equipped-treefrog"),
            (
                "hotfix/some-very-long-thing",
                4,
                "noteworthy-musical-durable-silkworm",
            ),
        ];

        for (input, n, expected) in cases {
            let actual = codename(input, *n);
            assert_eq!(
                &actual, expected,
                "\n\
                 codename({input:?}, {n}) returned {actual:?}, expected {expected:?}.\n\
                 \n\
                 Changing the petname version, or the codename algorithm,\n\
                 BREAKS every existing user's worktree paths derived from\n\
                 `{{{{ branch | codename(...) }}}}`. See the comment above\n\
                 this test before updating these expectations.\n"
            );
        }
    }

    #[test]
    fn test_validate_template_accepts_codename_filter() {
        let test = test_repo();
        assert!(
            validate_template(
                "{{ branch | codename(2) }}",
                ValidationScope::SwitchExecute,
                &test.repo,
                "test"
            )
            .is_ok()
        );
    }

    #[test]
    fn test_hash_port_filter() {
        let test = test_repo();
        let mut vars = HashMap::new();
        vars.insert("branch", "feature-foo");
        vars.insert("repo", "myrepo");

        // Filter produces a number in range
        let result =
            expand_template("{{ branch | hash_port }}", &vars, false, &test.repo, "test").unwrap();
        let port: u16 = result.parse().expect("should be a number");
        assert!((10000..20000).contains(&port));

        // Concatenation produces different (but deterministic) result
        let r1 = expand_template(
            "{{ (repo ~ '-' ~ branch) | hash_port }}",
            &vars,
            false,
            &test.repo,
            "test",
        )
        .unwrap();
        let r1_port: u16 = r1.parse().expect("should be a number");
        let r2 = expand_template(
            "{{ (repo ~ '-' ~ branch) | hash_port }}",
            &vars,
            false,
            &test.repo,
            "test",
        )
        .unwrap();
        let r2_port: u16 = r2.parse().expect("should be a number");

        assert!((10000..20000).contains(&r1_port));
        assert!((10000..20000).contains(&r2_port));

        assert_eq!(r1, r2);
    }

    #[test]
    fn test_dirname_and_basename_filters() {
        let test = test_repo();
        let mut vars = HashMap::new();

        // Bare repo wrapped in a hidden dir: `dirname | basename` recovers the wrapper name
        // (the case from #1279 — `{{ repo }}` resolves to `.git`, but the user wants `myrepo`)
        vars.insert("repo_path", "/projects/myrepo/.git");
        let result = expand_template(
            "{{ repo_path | dirname | basename }}",
            &vars,
            false,
            &test.repo,
            "test",
        )
        .unwrap();
        assert_eq!(result, "myrepo");

        // Composing into a worktree-path template
        vars.insert("branch", "feature-auth");
        let result = expand_template(
            "{{ repo_path }}/../{{ repo_path | dirname | basename }}.{{ branch | sanitize }}",
            &vars,
            false,
            &test.repo,
            "test",
        )
        .unwrap();
        assert_eq!(result, "/projects/myrepo/.git/../myrepo.feature-auth");

        // `dirname` strips the last component
        vars.insert("repo_path", "/a/b/c");
        let dirname = expand_template(
            "{{ repo_path | dirname }}",
            &vars,
            false,
            &test.repo,
            "test",
        )
        .unwrap();
        assert_eq!(dirname, "/a/b");

        // `basename` keeps only the last component
        let basename = expand_template(
            "{{ repo_path | basename }}",
            &vars,
            false,
            &test.repo,
            "test",
        )
        .unwrap();
        assert_eq!(basename, "c");

        // No separator: dirname is empty, basename is the whole input
        vars.insert("repo_path", "myrepo");
        assert_eq!(
            expand_template(
                "{{ repo_path | dirname }}",
                &vars,
                false,
                &test.repo,
                "test"
            )
            .unwrap(),
            ""
        );
        assert_eq!(
            expand_template(
                "{{ repo_path | basename }}",
                &vars,
                false,
                &test.repo,
                "test"
            )
            .unwrap(),
            "myrepo"
        );
    }

    #[test]
    fn test_redact_credentials_https_token() {
        // GitHub-style personal access token
        assert_eq!(
            redact_credentials("https://ghp_token123@github.com/owner/repo"),
            "https://[REDACTED]@github.com/owner/repo"
        );
        // GitLab-style token
        assert_eq!(
            redact_credentials("https://glpat-xxxxxxxxxxxx@gitlab.com/owner/repo.git"),
            "https://[REDACTED]@gitlab.com/owner/repo.git"
        );
    }

    #[test]
    fn test_redact_credentials_https_user_pass() {
        // Username:password format
        assert_eq!(
            redact_credentials("https://user:password123@github.com/owner/repo"),
            "https://[REDACTED]@github.com/owner/repo"
        );
    }

    #[test]
    fn test_redact_credentials_no_credentials() {
        // Normal HTTPS URL without credentials - unchanged
        assert_eq!(
            redact_credentials("https://github.com/owner/repo"),
            "https://github.com/owner/repo"
        );
        // SSH URL - unchanged (no credentials in URL format)
        assert_eq!(
            redact_credentials("git@github.com:owner/repo.git"),
            "git@github.com:owner/repo.git"
        );
    }

    #[test]
    fn test_redact_credentials_non_url() {
        // Non-URL values pass through unchanged
        assert_eq!(redact_credentials("main"), "main");
        assert_eq!(redact_credentials("feature/auth"), "feature/auth");
        assert_eq!(redact_credentials("/path/to/worktree"), "/path/to/worktree");
        assert_eq!(redact_credentials(""), "");
    }

    #[test]
    fn test_redact_credentials_git_protocol() {
        // git:// protocol with credentials
        assert_eq!(
            redact_credentials("git://token@github.com/owner/repo.git"),
            "git://[REDACTED]@github.com/owner/repo.git"
        );
    }

    #[test]
    fn test_redact_credentials_preserves_path() {
        // Full URL with path and query should preserve everything after host
        assert_eq!(
            redact_credentials("https://token@github.com/owner/repo.git?ref=main"),
            "https://[REDACTED]@github.com/owner/repo.git?ref=main"
        );
    }

    #[test]
    fn test_expand_template_vars_data() {
        let test = test_repo();

        // Set vars data via git config
        Cmd::new("git")
            .args(["config", "worktrunk.state.main.vars.env", "staging"])
            .current_dir(test.path())
            .run()
            .unwrap();
        Cmd::new("git")
            .args(["config", "worktrunk.state.main.vars.port", "3000"])
            .current_dir(test.path())
            .run()
            .unwrap();

        let mut vars = HashMap::new();
        vars.insert("branch", "main");

        // Access vars via dot notation
        assert_eq!(
            expand_template("{{ vars.env }}", &vars, false, &test.repo, "test").unwrap(),
            "staging"
        );
        assert_eq!(
            expand_template("{{ vars.port }}", &vars, false, &test.repo, "test").unwrap(),
            "3000"
        );

        // Default filter for missing vars keys
        assert_eq!(
            expand_template(
                "{{ vars.missing | default('fallback') }}",
                &vars,
                false,
                &test.repo,
                "test"
            )
            .unwrap(),
            "fallback"
        );

        // Conditional on vars
        assert_eq!(
            expand_template(
                "{% if vars.env %}env={{ vars.env }}{% endif %}",
                &vars,
                false,
                &test.repo,
                "test"
            )
            .unwrap(),
            "env=staging"
        );
    }

    #[test]
    fn test_expand_template_vars_json_dot_access() {
        let test = test_repo();

        // Store a JSON object as a vars value
        Cmd::new("git")
            .args([
                "config",
                "worktrunk.state.main.vars.config",
                r#"{"port": 3000, "debug": true}"#,
            ])
            .current_dir(test.path())
            .run()
            .unwrap();

        // Store a JSON array
        Cmd::new("git")
            .args([
                "config",
                "worktrunk.state.main.vars.tags",
                r#"["alpha", "beta"]"#,
            ])
            .current_dir(test.path())
            .run()
            .unwrap();

        // Store a plain string (not JSON)
        Cmd::new("git")
            .args(["config", "worktrunk.state.main.vars.env", "staging"])
            .current_dir(test.path())
            .run()
            .unwrap();

        let mut vars = HashMap::new();
        vars.insert("branch", "main");

        // Dot access into JSON object
        assert_eq!(
            expand_template("{{ vars.config.port }}", &vars, false, &test.repo, "test").unwrap(),
            "3000"
        );
        assert_eq!(
            expand_template("{{ vars.config.debug }}", &vars, false, &test.repo, "test").unwrap(),
            "true"
        );

        // Array index access
        assert_eq!(
            expand_template("{{ vars.tags[0] }}", &vars, false, &test.repo, "test").unwrap(),
            "alpha"
        );

        // Plain string still works
        assert_eq!(
            expand_template("{{ vars.env }}", &vars, false, &test.repo, "test").unwrap(),
            "staging"
        );

        // Default filter on missing nested key
        assert_eq!(
            expand_template(
                "{{ vars.config.missing | default('fallback') }}",
                &vars,
                false,
                &test.repo,
                "test"
            )
            .unwrap(),
            "fallback"
        );
    }

    #[test]
    fn test_expand_template_vars_json_shell_escape() {
        let test = test_repo();

        Cmd::new("git")
            .args([
                "config",
                "worktrunk.state.main.vars.config",
                r#"{"name": "my project", "cmd": "echo hello"}"#,
            ])
            .current_dir(test.path())
            .run()
            .unwrap();

        let mut vars = HashMap::new();
        vars.insert("branch", "main");

        // Shell escaping should work on JSON-parsed nested values
        let result =
            expand_template("{{ vars.config.name }}", &vars, true, &test.repo, "test").unwrap();
        assert_eq!(result, "'my project'");

        let result =
            expand_template("{{ vars.config.cmd }}", &vars, true, &test.repo, "test").unwrap();
        assert_eq!(result, "'echo hello'");
    }

    #[test]
    fn test_expand_template_vars_empty_when_no_branch() {
        let test = test_repo();
        let vars = HashMap::new(); // No branch var

        // vars should be undefined (no branch to look up)
        assert_eq!(
            expand_template(
                "{{ vars | default('none') }}",
                &vars,
                false,
                &test.repo,
                "test"
            )
            .unwrap(),
            "none"
        );
    }

    #[test]
    fn test_expand_template_vars_empty_when_no_data() {
        let test = test_repo();
        let mut vars = HashMap::new();
        vars.insert("branch", "main");

        // vars injected as empty map when no entries exist — use default filter for missing keys
        assert_eq!(
            expand_template(
                "{{ vars.env | default('dev') }}",
                &vars,
                false,
                &test.repo,
                "test"
            )
            .unwrap(),
            "dev"
        );
    }

    #[test]
    fn test_expand_template_args_sequence() {
        let test = test_repo();
        let args_json = serde_json::to_string(&["foo", "bar baz", "qux"]).unwrap();
        let mut vars = HashMap::new();
        vars.insert("args", args_json.as_str());

        // Bare {{ args }} with shell escaping: space-joined, per-element escaped,
        // NOT wrapped in outer quotes as a single token.
        assert_eq!(
            expand_template("wt switch {{ args }}", &vars, true, &test.repo, "test").unwrap(),
            "wt switch foo 'bar baz' qux"
        );

        // Indexing returns a plain string — flows through the shell-escape formatter.
        assert_eq!(
            expand_template("{{ args[0] }}", &vars, true, &test.repo, "test").unwrap(),
            "foo"
        );
        assert_eq!(
            expand_template("{{ args[1] }}", &vars, true, &test.repo, "test").unwrap(),
            "'bar baz'"
        );

        // Length works like any sequence.
        assert_eq!(
            expand_template("{{ args | length }}", &vars, false, &test.repo, "test").unwrap(),
            "3"
        );

        // Iteration yields per-element string values; each escaped by the formatter.
        assert_eq!(
            expand_template(
                "{% for a in args %}[{{ a }}]{% endfor %}",
                &vars,
                true,
                &test.repo,
                "test"
            )
            .unwrap(),
            "[foo]['bar baz'][qux]"
        );
    }

    #[test]
    fn test_expand_template_args_empty() {
        let test = test_repo();
        let args_json = serde_json::to_string(&Vec::<String>::new()).unwrap();
        let mut vars = HashMap::new();
        vars.insert("args", args_json.as_str());

        // Empty args renders empty. No stray whitespace, no error.
        assert_eq!(
            expand_template("wt switch{{ args }}", &vars, true, &test.repo, "test").unwrap(),
            "wt switch"
        );

        // Length still defined for empty.
        assert_eq!(
            expand_template("{{ args | length }}", &vars, false, &test.repo, "test").unwrap(),
            "0"
        );

        // Iteration yields nothing.
        assert_eq!(
            expand_template(
                "{% for a in args %}X{% endfor %}",
                &vars,
                true,
                &test.repo,
                "test"
            )
            .unwrap(),
            ""
        );
    }

    #[test]
    fn test_expand_template_args_shell_metachar_safety() {
        // The point of ShellArgs is that bare {{ args }} is safe to splice into
        // a command line even when args contain shell metacharacters — each
        // element is individually single-quoted by `shell_escape::unix::escape`,
        // and the outer formatter doesn't re-quote the joined result.
        let test = test_repo();
        let args_json = serde_json::to_string(&["; rm -rf /", "$(whoami)", "a'b"]).unwrap();
        let mut vars = HashMap::new();
        vars.insert("args", args_json.as_str());

        let rendered = expand_template("echo {{ args }}", &vars, true, &test.repo, "test").unwrap();
        assert_eq!(rendered, r#"echo '; rm -rf /' '$(whoami)' 'a'\''b'"#);
    }

    #[test]
    fn test_validate_template_valid() {
        let test = test_repo();
        let hook = ValidationScope::Hook(HookType::PostStart);

        // Static text
        assert!(validate_template("echo hello", hook, &test.repo, "test").is_ok());

        // Base variables are available in every scope
        assert!(validate_template("{{ branch }}", hook, &test.repo, "test").is_ok());
        assert!(validate_template("{{ repo }}/{{ branch }}", hook, &test.repo, "test").is_ok());

        // Filters
        assert!(validate_template("{{ branch | sanitize }}", hook, &test.repo, "test").is_ok());
        assert!(validate_template("{{ branch | sanitize_db }}", hook, &test.repo, "test").is_ok());
        assert!(
            validate_template("{{ branch | sanitize_hash }}", hook, &test.repo, "test").is_ok()
        );
        assert!(validate_template("{{ branch | hash }}", hook, &test.repo, "test").is_ok());
        assert!(validate_template("{{ branch | hash_port }}", hook, &test.repo, "test").is_ok());

        // Conditionals with optional vars
        assert!(
            validate_template(
                "{% if upstream %}{{ upstream }}{% endif %}",
                hook,
                &test.repo,
                "test"
            )
            .is_ok()
        );

        // Deprecated vars still valid in every scope
        assert!(validate_template("{{ main_worktree }}", hook, &test.repo, "test").is_ok());

        // `args` validates in both Hook and Alias scopes.
        assert!(validate_template("echo {{ args }}", hook, &test.repo, "test").is_ok());
        let alias = ValidationScope::Alias;
        assert!(validate_template("wt switch {{ args }}", alias, &test.repo, "test").is_ok());
        assert!(validate_template("{{ args | length }}", alias, &test.repo, "test").is_ok());
        assert!(
            validate_template(
                "{% for a in args %}{{ a }}{% endfor %}",
                alias,
                &test.repo,
                "test"
            )
            .is_ok()
        );
    }

    #[test]
    fn test_validate_template_scope_rejects_out_of_scope_vars() {
        let test = test_repo();

        // `base` is unavailable in pre-merge — catch the typo at validation time.
        let err = validate_template(
            "{{ base }}",
            ValidationScope::Hook(HookType::PreMerge),
            &test.repo,
            "test",
        )
        .unwrap_err();
        assert!(
            err.message.contains("undefined value"),
            "got: {}",
            err.message
        );

        // `base` is available in pre-start.
        assert!(
            validate_template(
                "{{ base }}",
                ValidationScope::Hook(HookType::PreStart),
                &test.repo,
                "test"
            )
            .is_ok()
        );

        // `target` is available in pre-merge.
        assert!(
            validate_template(
                "{{ target }}",
                ValidationScope::Hook(HookType::PreMerge),
                &test.repo,
                "test"
            )
            .is_ok()
        );

        // `pr_number`/`pr_url` are available in pre-start (populated when
        // creating via `pr:N` / `mr:N`).
        for var in ["pr_number", "pr_url"] {
            assert!(
                validate_template(
                    &format!("{{{{ {var} }}}}"),
                    ValidationScope::Hook(HookType::PreStart),
                    &test.repo,
                    "test"
                )
                .is_ok(),
                "{var} should validate in pre-start scope"
            );
        }

        // `pr_number` is not available in pre-merge (different hook type).
        let err = validate_template(
            "{{ pr_number }}",
            ValidationScope::Hook(HookType::PreMerge),
            &test.repo,
            "test",
        )
        .unwrap_err();
        assert!(
            err.message.contains("undefined value"),
            "got: {}",
            err.message
        );

        // `args` is available in hook scope (forwarded via smart routing).
        assert!(
            validate_template(
                "{{ args }}",
                ValidationScope::Hook(HookType::PreStart),
                &test.repo,
                "test",
            )
            .is_ok()
        );

        // `args` is not available in SwitchExecute.
        let err = validate_template(
            "{{ args }}",
            ValidationScope::SwitchExecute,
            &test.repo,
            "test",
        )
        .unwrap_err();
        assert!(
            err.message.contains("undefined value"),
            "got: {}",
            err.message
        );
    }

    #[test]
    fn test_validate_template_syntax_error() {
        let test = test_repo();

        let err = validate_template("{{ unclosed", ValidationScope::Alias, &test.repo, "test")
            .unwrap_err();
        assert!(err.message.contains("syntax error"), "got: {}", err.message);
    }

    #[test]
    fn test_referenced_vars_for_config_syntax_error_propagates() {
        let cfg = super::super::CommandConfig::single("echo {{ unclosed");
        let err = referenced_vars_for_config(&cfg).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("Failed to parse template"), "got: {msg}");
        assert!(msg.contains("syntax error"), "got: {msg}");
    }

    #[test]
    fn test_validate_template_undefined_var() {
        let test = test_repo();

        let err = validate_template(
            "{{ nonexistent_var }}",
            ValidationScope::Hook(HookType::PostStart),
            &test.repo,
            "test",
        )
        .unwrap_err();
        assert!(
            err.message.contains("undefined value"),
            "got: {}",
            err.message
        );
        // Should list available vars in hint
        assert!(!err.available_vars.is_empty(), "should list available vars");
        assert!(err.available_vars.contains(&"branch".to_string()));
    }

    #[test]
    fn test_format_hook_variables_groups_and_unset() {
        let mut ctx: HashMap<String, String> = HashMap::new();
        ctx.insert("branch".into(), "feature".into());
        ctx.insert("worktree_path".into(), "/tmp/feature".into());
        ctx.insert("worktree_name".into(), "feature".into());
        ctx.insert("base".into(), "main".into());
        ctx.insert("base_worktree_path".into(), "/tmp/main".into());
        ctx.insert("target".into(), "-".into());
        // target_worktree_path deliberately absent — mimics `wt switch -`
        ctx.insert("repo".into(), "demo".into());
        ctx.insert("repo_path".into(), "/tmp/demo".into());
        ctx.insert("cwd".into(), "/tmp/feature".into());
        ctx.insert("hook_type".into(), "pre-switch".into());
        ctx.insert("hook_name".into(), "show-variables".into());

        assert_snapshot!(format_hook_variables(HookType::PreSwitch, &ctx), @r"
        branch                = feature
        worktree_path         = /tmp/feature
        worktree_name         = feature
        commit                = (unset)
        short_commit          = (unset)
        upstream              = (unset)
        base                  = main
        base_worktree_path    = /tmp/main
        target                = -
        target_worktree_path  = (unset)
        pr_number             = (unset)
        pr_url                = (unset)
        repo                  = demo
        repo_path             = /tmp/demo
        owner                 = (unset)
        primary_worktree_path = (unset)
        default_branch        = (unset)
        remote                = (unset)
        remote_url            = (unset)
        cwd                   = /tmp/feature
        hook_type             = pre-switch
        hook_name             = show-variables
        ");
    }

    #[test]
    fn test_format_hook_variables_filters_operation() {
        // pre-commit only has `target` in operation scope — no base*, pr_*, etc.
        let mut ctx: HashMap<String, String> = HashMap::new();
        ctx.insert("target".into(), "main".into());
        let out = format_hook_variables(HookType::PreCommit, &ctx);
        assert!(out.contains("target                = main"), "got: {out}");
        assert!(
            !out.contains("base "),
            "pre-commit has no `base`; got: {out}"
        );
        assert!(
            !out.contains("pr_number"),
            "pre-commit has no `pr_number`; got: {out}"
        );
    }

    #[test]
    fn test_format_alias_variables_includes_args_no_hook_keys() {
        let mut ctx: HashMap<String, String> = HashMap::new();
        ctx.insert("branch".into(), "feature".into());
        ctx.insert("worktree_path".into(), "/tmp/feature".into());
        ctx.insert("worktree_name".into(), "feature".into());
        ctx.insert("repo".into(), "demo".into());
        ctx.insert("repo_path".into(), "/tmp/demo".into());
        ctx.insert("cwd".into(), "/tmp/feature".into());
        // args is JSON-encoded per `ALIAS_ARGS_KEY` contract; the table
        // decodes and shell-renders it to match `{{ args }}` substitution.
        ctx.insert(ALIAS_ARGS_KEY.into(), r#"["a","b c"]"#.into());

        let out = format_alias_variables(&ctx, None);
        assert!(
            out.contains("args                  = a 'b c'"),
            "got: {out}"
        );
        // No hook-only keys appear in alias scope.
        assert!(!out.contains("hook_type"), "got: {out}");
        assert!(!out.contains("target"), "got: {out}");
        assert!(!out.contains("base "), "got: {out}");
    }

    #[test]
    fn test_format_alias_variables_args_empty() {
        let mut ctx: HashMap<String, String> = HashMap::new();
        ctx.insert(ALIAS_ARGS_KEY.into(), "[]".into());
        let out = format_alias_variables(&ctx, None);
        // Empty args render as an empty string after the `=` — distinct from
        // `(unset)`, which means the key was absent entirely. `args` sits last
        // in alias ordering, so the output ends with it.
        assert!(out.ends_with("args                  = "), "got: {out:?}");
    }
}