mise 2026.4.11

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

static FUZZY_MATCHER: Lazy<SkimMatcherV2> =
    Lazy::new(|| SkimMatcherV2::default().use_cache(true).smart_case());
static TASK_VARS_CACHE: Lazy<std::sync::Mutex<IndexMap<PathBuf, IndexMap<String, String>>>> =
    Lazy::new(|| std::sync::Mutex::new(IndexMap::new()));

pub(crate) fn reset() {
    TASK_VARS_CACHE.lock().unwrap().clear();
}

/// Type alias for tracking failed tasks with their exit codes
pub type FailedTasks = Arc<std::sync::Mutex<Vec<(Task, Option<i32>)>>>;

mod deps;
pub mod task_context_builder;
mod task_dep;
pub mod task_executor;
pub mod task_fetcher;
pub mod task_file_providers;
pub mod task_helpers;
pub mod task_list;
mod task_load_context;
pub mod task_output;
pub mod task_output_handler;
pub mod task_results_display;
pub mod task_scheduler;
mod task_script_parser;
pub mod task_source_checker;
pub mod task_sources;
pub mod task_template;
pub mod task_tool_installer;

pub use task_load_context::{TaskLoadContext, expand_colon_task_syntax};
pub use task_output::TaskOutput;
pub use task_script_parser::{has_any_args_defined, has_any_usage_spec};
pub use task_template::TaskTemplate;

use crate::config::config_file::ConfigFile;
use crate::env_diff::EnvMap;
use crate::file::display_path;
use crate::toolset::Toolset;
use crate::ui::style;
pub use deps::{Deps, TaskKey};
use task_dep::TaskDep;
use task_sources::{RawOutputTemplates, TaskOutputs};

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RunEntry {
    /// Shell script entry
    Script(String),
    /// Run a single task with optional args and env
    SingleTask {
        task: String,
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        args: Vec<String>,
        #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
        env: IndexMap<String, String>,
    },
    /// Run multiple tasks in parallel
    TaskGroup { tasks: Vec<String> },
}

impl std::hash::Hash for RunEntry {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        match self {
            RunEntry::Script(s) => {
                0u8.hash(state);
                s.hash(state);
            }
            RunEntry::SingleTask { task, args, env } => {
                1u8.hash(state);
                task.hash(state);
                args.hash(state);
                let mut pairs: Vec<_> = env.iter().collect();
                pairs.sort_by_key(|(k, _)| k.as_str());
                for (k, v) in pairs {
                    k.hash(state);
                    v.hash(state);
                }
            }
            RunEntry::TaskGroup { tasks } => {
                2u8.hash(state);
                tasks.hash(state);
            }
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub enum Silent {
    #[default]
    Off,
    Bool(bool),
    Stdout,
    Stderr,
}

impl Silent {
    pub fn is_silent(&self) -> bool {
        matches!(self, Silent::Bool(true) | Silent::Stdout | Silent::Stderr)
    }

    pub fn suppresses_stdout(&self) -> bool {
        matches!(self, Silent::Bool(true) | Silent::Stdout)
    }

    pub fn suppresses_stderr(&self) -> bool {
        matches!(self, Silent::Bool(true) | Silent::Stderr)
    }

    pub fn suppresses_both(&self) -> bool {
        matches!(self, Silent::Bool(true))
    }
}

impl Serialize for Silent {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            Silent::Off | Silent::Bool(false) => serializer.serialize_bool(false),
            Silent::Bool(true) => serializer.serialize_bool(true),
            Silent::Stdout => serializer.serialize_str("stdout"),
            Silent::Stderr => serializer.serialize_str("stderr"),
        }
    }
}

impl From<bool> for Silent {
    fn from(b: bool) -> Self {
        if b { Silent::Bool(true) } else { Silent::Off }
    }
}

impl std::str::FromStr for Silent {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "true" => Ok(Silent::Bool(true)),
            "false" => Ok(Silent::Off),
            "stdout" => Ok(Silent::Stdout),
            "stderr" => Ok(Silent::Stderr),
            _ => Err(format!(
                "invalid silent value: {}, expected true, false, 'stdout', or 'stderr'",
                s
            )),
        }
    }
}

impl<'de> Deserialize<'de> for Silent {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct SilentVisitor;

        impl<'de> serde::de::Visitor<'de> for SilentVisitor {
            type Value = Silent;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("a boolean or a string ('stdout' or 'stderr')")
            }

            fn visit_bool<E>(self, value: bool) -> Result<Silent, E>
            where
                E: serde::de::Error,
            {
                Ok(Silent::from(value))
            }

            fn visit_str<E>(self, value: &str) -> Result<Silent, E>
            where
                E: serde::de::Error,
            {
                match value {
                    "stdout" => Ok(Silent::Stdout),
                    "stderr" => Ok(Silent::Stderr),
                    _ => Err(E::custom(format!(
                        "invalid silent value: '{}', expected 'stdout' or 'stderr'",
                        value
                    ))),
                }
            }
        }

        deserializer.deserialize_any(SilentVisitor)
    }
}

impl std::str::FromStr for RunEntry {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(RunEntry::Script(s.to_string()))
    }
}

impl Display for RunEntry {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            RunEntry::Script(s) => write!(f, "{}", s),
            RunEntry::SingleTask { task, args, env } => {
                for (k, v) in env {
                    write!(f, "{}={} ", k, v)?;
                }
                write!(f, "task: {task}")?;
                if !args.is_empty() {
                    write!(f, " {}", args.join(" "))?;
                }
                Ok(())
            }
            RunEntry::TaskGroup { tasks } => write!(f, "tasks: {}", tasks.join(", ")),
        }
    }
}

#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Task {
    #[serde(skip)]
    pub name: String,
    #[serde(skip)]
    pub display_name: String,
    #[serde(default)]
    pub description: String,
    #[serde(default, rename = "alias", deserialize_with = "deserialize_arr")]
    pub aliases: Vec<String>,
    #[serde(skip)]
    pub config_source: PathBuf,
    #[serde(skip)]
    pub cf: Option<Arc<dyn ConfigFile>>,
    #[serde(skip)]
    pub config_root: Option<PathBuf>,
    #[serde(default)]
    pub confirm: Option<String>,
    #[serde(default, deserialize_with = "deserialize_arr")]
    pub depends: Vec<TaskDep>,
    #[serde(default, deserialize_with = "deserialize_arr")]
    pub depends_post: Vec<TaskDep>,
    #[serde(default, deserialize_with = "deserialize_arr")]
    pub wait_for: Vec<TaskDep>,
    #[serde(default)]
    pub env: EnvList,
    #[serde(default)]
    pub vars: EnvList,
    /// Env vars inherited from parent tasks at runtime (not used for task identity/deduplication)
    #[serde(skip)]
    pub inherited_env: EnvList,
    #[serde(default)]
    pub dir: Option<String>,
    #[serde(default)]
    pub hide: bool,
    #[serde(default)]
    pub global: bool,
    #[serde(default)]
    pub raw: bool,
    #[serde(default)]
    pub interactive: bool,
    #[serde(default)]
    pub sources: Vec<String>,
    #[serde(default)]
    pub outputs: TaskOutputs,
    #[serde(skip)]
    pub raw_outputs: RawOutputTemplates,
    #[serde(default)]
    pub shell: Option<String>,
    #[serde(default)]
    pub quiet: bool,
    #[serde(default)]
    pub silent: Silent,
    #[serde(default)]
    pub tools: IndexMap<String, String>,
    #[serde(default)]
    pub usage: String,
    #[serde(default)]
    pub timeout: Option<String>,

    // normal type
    #[serde(default, deserialize_with = "deserialize_arr")]
    pub run: Vec<RunEntry>,

    #[serde(default, deserialize_with = "deserialize_arr")]
    pub run_windows: Vec<RunEntry>,

    // command type
    // pub command: Option<String>,
    #[serde(default)]
    pub args: Vec<String>,

    // script type
    // pub script: Option<String>,

    // file type
    #[serde(default)]
    pub file: Option<PathBuf>,

    // Store the original remote file source (git::/http:/https:) before it's replaced with local path
    // This is used to determine if the task should use monorepo config file context
    #[serde(skip)]
    pub remote_file_source: Option<String>,

    /// Block reads, writes, network, and env vars
    #[serde(default)]
    pub deny_all: bool,
    /// Block filesystem reads
    #[serde(default)]
    pub deny_read: bool,
    /// Block all filesystem writes
    #[serde(default)]
    pub deny_write: bool,
    /// Block all network access
    #[serde(default)]
    pub deny_net: bool,
    /// Block env var inheritance
    #[serde(default)]
    pub deny_env: bool,
    /// Allow reads from specific paths
    #[serde(default)]
    pub allow_read: Vec<std::path::PathBuf>,
    /// Allow writes to specific paths
    #[serde(default)]
    pub allow_write: Vec<std::path::PathBuf>,
    /// Allow network to specific hosts
    #[serde(default)]
    pub allow_net: Vec<String>,
    /// Allow specific env vars through
    #[serde(default)]
    pub allow_env: Vec<String>,

    /// Name of the task template to extend (requires experimental = true)
    #[serde(default)]
    pub extends: Option<String>,

    /// When true, include args in the output prefix to disambiguate tasks
    /// with the same display_name but different arguments.
    #[serde(skip)]
    pub show_args_in_prefix: bool,

    /// Original unrendered dependency templates, preserved so they can be
    /// re-rendered later with parent task args/flags (usage context) available.
    #[serde(skip)]
    pub depends_raw: Option<Vec<TaskDep>>,
    #[serde(skip)]
    pub depends_post_raw: Option<Vec<TaskDep>>,
    #[serde(skip)]
    pub wait_for_raw: Option<Vec<TaskDep>>,
}

impl Task {
    pub fn new(path: &Path, prefix: &Path, config_root: &Path) -> Result<Task> {
        Ok(Self {
            name: name_from_path(prefix, path)?,
            config_source: path.to_path_buf(),
            config_root: Some(config_root.to_path_buf()),
            ..Default::default()
        })
    }

    pub async fn from_path(
        config: &Arc<Config>,
        path: &Path,
        prefix: &Path,
        config_root: &Path,
    ) -> Result<Task> {
        let mut task = Task::new(path, prefix, config_root)?;
        let info = file::read_to_string(path)?
            .lines()
            .filter_map(|line| {
                regex!(r"^(?:#|//|::)(?:MISE| ?\[MISE\]) ([a-z0-9_.-]+\s*=\s*[^\n]+)$")
                    .captures(line)
            })
            .map(|captures| captures.extract().1)
            .map(|[toml]| {
                toml::de::from_str::<toml::Value>(toml)
                    .map_err(|e| eyre::eyre!("failed to parse task header TOML {toml:?}: {e}"))
            })
            .collect::<Result<Vec<_>>>()?
            .into_iter()
            .filter_map(|toml| toml.as_table().cloned())
            .flatten()
            .fold(toml::Table::new(), |mut map, (key, value)| {
                // Deep-merge tables when both existing and new values are tables
                // This allows multiple #MISE lines like:
                //   #MISE tools.terraform="1"
                //   #MISE tools.tflint="0"
                // to be merged into a single tools table
                // See: https://github.com/jdx/mise/discussions/7839
                if let Some(existing) = map.get_mut(&key) {
                    if let (toml::Value::Table(existing_table), toml::Value::Table(new_table)) =
                        (existing, &value)
                    {
                        for (k, v) in new_table {
                            existing_table.insert(k.clone(), v.clone());
                        }
                    } else {
                        map.insert(key, value);
                    }
                } else {
                    map.insert(key, value);
                }
                map
            });
        let info = toml::Value::Table(info);

        let mut p = TrackingTomlParser::new(&info);
        // trace!("task info: {:#?}", info);

        task.description = p.parse_str("description").unwrap_or_default();
        // Check for multiple alias fields before parsing
        let alias_fields: Vec<&str> = ["alias", "aliases"]
            .iter()
            .filter(|&field| info.get(field).is_some())
            .copied()
            .collect();

        if alias_fields.len() > 1 {
            return Err(eyre::eyre!(
                "Cannot define both 'alias' and 'aliases' fields in task file header: {}. Use only one.",
                display_path(path)
            ));
        }

        task.aliases = p
            .parse_array("alias")
            .or(p.parse_array("aliases"))
            .or(p.parse_str("alias").map(|s| vec![s]))
            .or(p.parse_str("aliases").map(|s| vec![s]))
            .unwrap_or_default();
        task.confirm = p.parse_str("confirm");
        task.depends = p.parse_array("depends").unwrap_or_default();
        task.depends_post = p.parse_array("depends_post").unwrap_or_default();
        task.wait_for = p.parse_array("wait_for").unwrap_or_default();
        task.env = p.parse_env("env")?.unwrap_or_default();
        task.dir = p.parse_str("dir");
        task.hide = !file::is_executable(path) || p.parse_bool("hide").unwrap_or_default();
        task.raw = p.parse_bool("raw").unwrap_or_default();
        task.interactive = p.parse_bool("interactive").unwrap_or_default();
        task.sources = p.parse_array("sources").unwrap_or_default();
        task.outputs = p.get_raw("outputs").map(|to| to.into()).unwrap_or_default();
        task.file = Some(path.to_path_buf());
        task.shell = p.parse_str("shell");
        task.quiet = p.parse_bool("quiet").unwrap_or_default();
        task.silent = p
            .get_raw("silent")
            .and_then(|v| Silent::deserialize(v.clone()).ok())
            .unwrap_or_default();
        task.tools = p
            .parse_table("tools")
            .map(|t| {
                t.into_iter()
                    .filter_map(|(k, v)| v.as_str().map(|vs| (k, vs.to_string())))
                    .collect()
            })
            .unwrap_or_default();

        let mut unparsed = p.unparsed_keys();
        unparsed.sort();

        if !unparsed.is_empty() {
            return Err(eyre::eyre!(
                "unknown field(s) {:?} in task file header: {}",
                unparsed,
                display_path(path)
            ));
        }

        #[cfg(test)]
        {
            let fields: Vec<String> = p.parsed_keys().map(|s| s.to_string()).collect();
            tests::capture_parsed_fields(fields);
        }
        task.render(config, config_root).await?;
        Ok(task)
    }

    /// Add env vars that were inherited from parent tasks (e.g., via `run = [{ task = "..." }]`)
    /// These do NOT affect task identity/deduplication
    pub fn derive_env(&self, env_directives: &[EnvDirective]) -> Self {
        let mut new_task = self.clone();
        new_task.inherited_env.0.extend_from_slice(env_directives);
        new_task
    }

    /// Add env vars specified in dependency declarations (e.g., `depends = ["FOO=bar task"]`)
    /// These DO affect task identity/deduplication
    pub fn with_dependency_env(&self, env_directives: &[EnvDirective]) -> Self {
        let mut new_task = self.clone();
        new_task.env.0.extend_from_slice(env_directives);
        new_task
    }

    /// prints the task name without an extension
    pub fn display_name(&self, all_tasks: &BTreeMap<String, Task>) -> String {
        // For task names, only strip extensions after the last colon (:)
        // This handles monorepo task names like "//projects/my.app:build.sh"
        // where we want to strip ".sh" but keep "my.app" intact
        let display_name = if let Some((prefix, task_part)) = self.name.rsplit_once(':') {
            // Has a colon separator (e.g., "//projects/my.app:build.sh")
            // Strip extension from the task part only
            let task_without_ext = task_part.rsplitn(2, '.').last().unwrap_or_default();
            format!("{}:{}", prefix, task_without_ext)
        } else {
            // No colon separator (e.g., "build.sh")
            // Strip extension from the whole name
            self.name
                .rsplitn(2, '.')
                .last()
                .unwrap_or_default()
                .to_string()
        };

        if all_tasks.contains_key(&display_name) {
            // this means another task has the name without an extension so use the full name
            self.name.clone()
        } else {
            display_name
        }
    }

    pub fn is_match(&self, pat: &str) -> bool {
        if self.name == pat || self.aliases.contains(&pat.to_string()) {
            return true;
        }

        // For pattern matching, we need to handle several cases:
        // 1. Simple pattern (e.g., "build") should match monorepo tasks (e.g., "//projects/my.app:build")
        // 2. Full pattern (e.g., "//projects/my.app:build") should only match exact path
        // 3. Extensions should be stripped for comparison

        let matches = if let Some((prefix, task_part)) = self.name.rsplit_once(':') {
            // Task name has a colon (e.g., "//projects/my.app:build.sh")
            let task_stripped = task_part.rsplitn(2, '.').last().unwrap_or_default();

            if let Some((pat_prefix, pat_task)) = pat.rsplit_once(':') {
                // Pattern also has a colon - compare full paths
                let pat_task_stripped = pat_task.rsplitn(2, '.').last().unwrap_or_default();
                prefix == pat_prefix && task_stripped == pat_task_stripped
            } else {
                // Pattern is simple (no colon) - just compare task names
                let pat_stripped = pat.rsplitn(2, '.').last().unwrap_or_default();
                task_stripped == pat_stripped
            }
        } else {
            // Simple task name without colon (e.g., "build.sh")
            let name_stripped = self.name.rsplitn(2, '.').last().unwrap_or_default();
            let pat_stripped = pat.rsplitn(2, '.').last().unwrap_or_default();
            name_stripped == pat_stripped
        };

        matches || self.aliases.contains(&pat.to_string())
    }

    pub async fn task_dir() -> PathBuf {
        let config = Config::get().await.unwrap();
        let cwd = dirs::CWD.clone().unwrap_or_default();
        let project_root = config.project_root.clone().unwrap_or(cwd);
        for dir in config::task_includes_for_dir(&project_root, &config.config_files) {
            if dir.is_dir() && project_root.join(&dir).exists() {
                return project_root.join(dir);
            }
        }
        project_root.join("mise-tasks")
    }

    pub fn with_args(mut self, args: Vec<String>) -> Self {
        self.args = args;
        self
    }

    pub fn prefix(&self) -> String {
        let max_width = 40;
        let inner = if self.show_args_in_prefix && !self.args.is_empty() {
            let s = format!("{} {}", self.display_name, self.args.join(" "));
            s.trim().to_string()
        } else {
            self.display_name.clone()
        };
        format!("[{}]", console::truncate_str(&inner, max_width, "…"))
    }

    pub fn run(&self) -> &Vec<RunEntry> {
        if cfg!(windows) && !self.run_windows.is_empty() {
            &self.run_windows
        } else {
            &self.run
        }
    }

    /// Returns only the script strings from the run entries (without rendering)
    pub fn run_script_strings(&self) -> Vec<String> {
        self.run()
            .iter()
            .filter_map(|e| match e {
                RunEntry::Script(s) => Some(s.clone()),
                _ => None,
            })
            .collect()
    }

    pub fn all_depends(&self, tasks: &BTreeMap<String, Task>) -> Result<Vec<Task>> {
        let tasks_ref = build_task_ref_map(tasks.iter());
        let mut path = vec![self.name.clone()];
        self.all_depends_recursive(&tasks_ref, &mut path)
    }

    fn all_depends_recursive(
        &self,
        tasks: &BTreeMap<String, &Task>,
        path: &mut Vec<String>,
    ) -> Result<Vec<Task>> {
        let mut depends: Vec<Task> = self
            .depends
            .iter()
            .chain(self.depends_post.iter())
            .filter(|td| !dep_has_usage_ref(td))
            .map(|td| match_tasks_with_context(tasks, td, Some(self)))
            .flatten_ok()
            .filter_ok(|t| t.name != self.name)
            .collect::<Result<Vec<_>>>()?;

        // Collect transitive dependencies with cycle detection
        for dep in depends.clone() {
            if path.contains(&dep.name) {
                // Circular dependency detected - build path string for error message
                let cycle_path = path
                    .iter()
                    .skip_while(|&name| name != &dep.name)
                    .chain(std::iter::once(&dep.name))
                    .join(" -> ");
                return Err(eyre!("circular dependency detected: {}", cycle_path));
            }
            path.push(dep.name.clone());
            let mut extra = dep.all_depends_recursive(tasks, path)?;
            path.pop(); // Remove from path after processing this branch
            extra.retain(|t| t.name != self.name); // prevent depending on ourself
            depends.extend(extra);
        }
        let depends = depends.into_iter().unique().collect();
        Ok(depends)
    }

    pub async fn resolve_depends(
        &self,
        config: &Arc<Config>,
        tasks_to_run: &[Task],
    ) -> Result<(Vec<Task>, Vec<Task>)> {
        use crate::task::TaskLoadContext;

        let tasks_to_run: HashSet<&Task> = tasks_to_run.iter().collect();

        // Build context with path hints from self, tasks_to_run, and dependency patterns
        // Resolve patterns before extracting paths to handle local deps (e.g., ":A")
        let path_hints: Vec<String> = once(&self.name)
            .chain(tasks_to_run.iter().map(|t| &t.name))
            .filter_map(|name| extract_monorepo_path(name))
            .chain(
                self.depends
                    .iter()
                    .chain(self.wait_for.iter())
                    .chain(self.depends_post.iter())
                    .map(|td| resolve_task_pattern(&td.task, Some(self)))
                    .filter_map(|resolved| extract_monorepo_path(&resolved)),
            )
            .unique()
            .collect();

        let ctx = if !path_hints.is_empty() {
            Some(TaskLoadContext {
                path_hints,
                load_all: false,
            })
        } else {
            None
        };

        let all_tasks = config.tasks_with_context(ctx.as_ref()).await?;
        let tasks = build_task_ref_map(all_tasks.iter());
        // Skip deps with unresolved {{usage.*}} references — they'll be resolved
        // later when render_depends_with_usage() is called with actual arg values.
        let depends = self
            .depends
            .iter()
            .filter(|td| !dep_has_usage_ref(td))
            .map(|td| match_tasks_with_context(&tasks, td, Some(self)))
            .flatten_ok()
            .collect_vec();
        let wait_for = self
            .wait_for
            .iter()
            .filter(|td| !dep_has_usage_ref(td))
            .map(|td| {
                match_tasks_with_context(&tasks, td, Some(self))
                    .map(|tasks| tasks.into_iter().map(|t| (t, td)).collect_vec())
            })
            .flatten_ok()
            .filter_map_ok(|(t, td)| {
                if td.env.is_empty() && td.args.is_empty() {
                    // Name-based matching: wait for any running instance of this task
                    // regardless of env/args variant (e.g., "VERBOSE=1 setup" matches "setup").
                    // Return the actual task from tasks_to_run so the dependency graph
                    // gets the correct env/args-variant node.
                    tasks_to_run
                        .iter()
                        .find(|tr| tr.name == t.name)
                        .map(|tr| (*tr).clone())
                } else {
                    // Full identity matching: user explicitly wants a specific env/args variant
                    tasks_to_run.contains(&t).then_some(t)
                }
            })
            .collect_vec();
        let depends_post = self
            .depends_post
            .iter()
            .filter(|td| !dep_has_usage_ref(td))
            .map(|td| match_tasks_with_context(&tasks, td, Some(self)))
            .flatten_ok()
            .filter_ok(|t| t.name != self.name)
            .collect::<Result<Vec<_>>>()?;
        let depends = depends
            .into_iter()
            .chain(wait_for)
            .filter_ok(|t| t.name != self.name)
            .collect::<Result<_>>()?;
        Ok((depends, depends_post))
    }

    fn populate_spec_metadata(&self, spec: &mut usage::Spec) {
        spec.name = self.display_name.clone();
        spec.bin = self.display_name.clone();
        if spec.cmd.help.is_none() {
            spec.cmd.help = Some(self.description.clone());
        }
        spec.cmd.name = self.display_name.clone();
        spec.cmd.aliases = self.aliases.clone();
        if spec.cmd.before_help.is_none()
            && spec.cmd.before_help_long.is_none()
            && !self.depends.is_empty()
        {
            spec.cmd.before_help_long =
                Some(format!("- Depends: {}", self.depends.iter().join(", ")));
        }
        spec.cmd.usage = spec.cmd.usage();
    }
    pub async fn parse_usage_spec_with_vars(
        &self,
        config: &Arc<Config>,
        cwd: Option<PathBuf>,
        env: &EnvMap,
        extra_vars: Option<IndexMap<String, String>>,
    ) -> Result<(usage::Spec, Vec<String>)> {
        let (mut spec, scripts) = if let Some(file) = self.file_path(config).await? {
            let spec = usage::Spec::parse_script(&file)
                .inspect_err(|e| {
                    warn!(
                        "failed to parse task file {} with usage: {e:?}",
                        file::display_path(&file)
                    )
                })
                .unwrap_or_default();
            (spec, vec![])
        } else {
            let scripts_only = self.run_script_strings();
            let (scripts, spec) = Self::make_script_parser(cwd, extra_vars)
                .parse_run_scripts(config, self, &scripts_only, env)
                .await?;
            (spec, scripts)
        };
        self.populate_spec_metadata(&mut spec);
        Ok((spec, scripts))
    }

    fn make_script_parser(
        cwd: Option<PathBuf>,
        extra_vars: Option<IndexMap<String, String>>,
    ) -> TaskScriptParser {
        let parser = TaskScriptParser::new(cwd);
        match extra_vars {
            Some(vars) => parser.with_extra_vars(vars),
            None => parser,
        }
    }

    /// Parse usage spec for display purposes without expensive environment rendering
    pub async fn parse_usage_spec_for_display(&self, config: &Arc<Config>) -> Result<usage::Spec> {
        let dir = self.dir(config).await?;
        let mut spec = if let Some(file) = self.file_path(config).await? {
            usage::Spec::parse_script(&file)
                .inspect_err(|e| {
                    warn!(
                        "failed to parse task file {} with usage: {e:?}",
                        file::display_path(&file)
                    )
                })
                .unwrap_or_default()
        } else {
            let scripts_only = self.run_script_strings();
            TaskScriptParser::new(dir)
                .parse_run_scripts_for_spec_only(config, self, &scripts_only)
                .await?
        };
        self.populate_spec_metadata(&mut spec);
        Ok(spec)
    }

    pub async fn render_run_scripts_with_args(
        &self,
        config: &Arc<Config>,
        cwd: Option<PathBuf>,
        args: &[String],
        env: &EnvMap,
        extra_vars: Option<IndexMap<String, String>>,
    ) -> Result<Vec<(String, Vec<String>)>> {
        let (spec, scripts) = self
            .parse_usage_spec_with_vars(config, cwd.clone(), env, extra_vars.clone())
            .await?;
        if has_any_args_defined(&spec) {
            let scripts_only = self.run_script_strings();
            let scripts = Self::make_script_parser(cwd, extra_vars)
                .parse_run_scripts_with_args(config, self, &scripts_only, env, args, &spec)
                .await?;
            Ok(scripts.into_iter().map(|s| (s, vec![])).collect())
        } else {
            Ok(scripts
                .iter()
                .enumerate()
                .map(|(i, script)| {
                    // only pass args to the last script if no formal args are defined
                    match i == self.run_script_strings().len() - 1 {
                        true => (script.clone(), args.iter().cloned().collect_vec()),
                        false => (script.clone(), vec![]),
                    }
                })
                .collect())
        }
    }

    pub async fn render_markdown(&self, config: &Arc<Config>) -> Result<String> {
        let spec = self.parse_usage_spec_for_display(config).await?;
        let ctx = usage::docs::markdown::MarkdownRenderer::new(spec)
            .with_replace_pre_with_code_fences(true)
            .with_header_level(2);
        Ok(ctx.render_spec()?)
    }

    pub fn estyled_prefix(&self) -> String {
        static COLORS: Lazy<Vec<Color>> = Lazy::new(|| {
            vec![
                Color::Blue,
                Color::Magenta,
                Color::Cyan,
                Color::Green,
                Color::Yellow,
                Color::Red,
            ]
        });
        let idx = self.display_name.chars().map(|c| c as usize).sum::<usize>() % COLORS.len();

        style::ereset() + &style::estyle(self.prefix()).fg(COLORS[idx]).to_string()
    }

    pub async fn dir(&self, config: &Arc<Config>) -> Result<Option<PathBuf>> {
        if let Some(dir) = self.dir.clone().or_else(|| {
            self.cf(config)
                .as_ref()
                .and_then(|cf| cf.task_config().dir.clone())
        }) {
            let config_root = self.config_root.clone().unwrap_or_default();
            let mut tera = get_tera(Some(&config_root));
            let tera_ctx = self.tera_ctx(config).await?;
            let dir = tera.render_str(&dir, &tera_ctx)?;
            let dir = file::replace_path(&dir);
            if dir.is_absolute() {
                Ok(Some(dir.to_path_buf()))
            } else if let Some(root) = &self.config_root {
                Ok(Some(root.join(dir)))
            } else {
                Ok(Some(dir.clone()))
            }
        } else {
            Ok(self.config_root.clone())
        }
    }

    pub async fn file_path(&self, config: &Arc<Config>) -> Result<Option<PathBuf>> {
        if let Some(file) = &self.file {
            let file_str = file.to_string_lossy().to_string();
            let config_root = self.config_root.clone().unwrap_or_default();
            let mut tera = get_tera(Some(&config_root));
            let tera_ctx = self.tera_ctx(config).await?;
            let rendered = tera.render_str(&file_str, &tera_ctx)?;
            let rendered_path = file::replace_path(&rendered);
            if rendered_path.is_absolute() {
                Ok(Some(rendered_path))
            } else if let Some(root) = &self.config_root {
                Ok(Some(root.join(rendered_path)))
            } else {
                Ok(Some(rendered_path))
            }
        } else {
            Ok(None)
        }
    }

    /// Get file path without templating (for display purposes)
    /// This is a non-async version used when we just need the path for display
    fn file_path_raw(&self) -> Option<PathBuf> {
        self.file.as_ref().map(|file| {
            if file.is_absolute() {
                file.clone()
            } else if let Some(root) = &self.config_root {
                root.join(file)
            } else {
                file.clone()
            }
        })
    }

    pub async fn tera_ctx(&self, config: &Arc<Config>) -> Result<tera::Context> {
        let ts = config.get_toolset().await?;
        let mut tera_ctx = ts.tera_ctx(config).await?.clone();
        let mut vars = self.resolve_base_vars(config).await?;
        // Insert base vars first so that task-level var templates can reference them
        // (e.g. a task var `foo = "{{vars.bar}}"` can read a config-level `bar`).
        tera_ctx.insert("vars", &vars);
        vars.extend(self.resolve_task_vars(config, ts, &tera_ctx).await?);
        // Re-insert with task-level vars merged in so callers see the final combined map,
        // with task-level values taking precedence over config-level ones.
        tera_ctx.insert("vars", &vars);
        tera_ctx.insert("config_root", &self.config_root);
        Ok(tera_ctx)
    }

    async fn resolve_base_vars(&self, config: &Arc<Config>) -> Result<IndexMap<String, String>> {
        let Some(task_cf) = self.cf(config) else {
            return Ok(config.vars.clone());
        };

        if task_cf.project_root() == config.project_root {
            return Ok(config.vars.clone());
        }

        let config_path = task_cf.get_path().to_path_buf();
        if let Some(vars) = TASK_VARS_CACHE.lock().unwrap().get(&config_path) {
            return Ok(vars.clone());
        }

        let task_dir = task_cf.get_path().parent().unwrap_or(task_cf.get_path());
        let (config_paths, idiomatic_filenames) =
            crate::config::load_config_hierarchy_from_dir(task_dir).await?;
        let task_config_files =
            crate::config::load_config_files_from_paths(&config_paths, &idiomatic_filenames)
                .await?;
        let vars_results =
            crate::config::resolve_vars_from_config_files(config, &task_config_files).await?;
        let vars: IndexMap<String, String> = vars_results
            .vars
            .iter()
            .map(|(k, (v, _))| (k.clone(), v.clone()))
            .collect();
        TASK_VARS_CACHE
            .lock()
            .unwrap()
            .insert(config_path, vars.clone());
        Ok(vars)
    }

    async fn resolve_task_vars(
        &self,
        config: &Arc<Config>,
        ts: &Toolset,
        tera_ctx: &tera::Context,
    ) -> Result<IndexMap<String, String>> {
        if self.vars.0.is_empty() {
            return Ok(IndexMap::new());
        }

        let env_map = ts.full_env(config).await?;
        let results = EnvResults::resolve(
            config,
            tera_ctx.clone(),
            &env_map,
            self.vars
                .0
                .iter()
                .cloned()
                .map(|directive| (directive, self.config_source.clone()))
                .collect(),
            EnvResolveOptions {
                vars: true,
                tools: ToolsFilter::NonToolsOnly,
                warn_on_missing_required: false,
            },
        )
        .await?;

        Ok(results
            .vars
            .iter()
            .map(|(k, (v, _))| (k.clone(), v.clone()))
            .collect())
    }

    pub fn cf<'a>(&'a self, config: &'a Config) -> Option<&'a Arc<dyn ConfigFile>> {
        // For monorepo tasks, use the stored config file reference
        if let Some(ref cf) = self.cf {
            return Some(cf);
        }
        // Fallback to looking up in config.config_files
        config.config_files.get(&self.config_source)
    }

    /// Check if this task is a remote task (loaded from git:// or http:// URL)
    /// Remote tasks should not use monorepo config file context because they need
    /// access to tools from the full config hierarchy, not just the local config file
    pub fn is_remote(&self) -> bool {
        // Check the stored remote file source (set before file is replaced with local path)
        if let Some(source) = &self.remote_file_source {
            return source.starts_with("git::")
                || source.starts_with("http://")
                || source.starts_with("https://");
        }
        false
    }

    pub fn shell(&self) -> Option<Vec<String>> {
        self.shell.as_ref().and_then(|shell| {
            let shell_cmd = shell
                .split_whitespace()
                .map(|s| s.to_string())
                .collect::<Vec<_>>();
            if shell_cmd.is_empty() || shell_cmd[0].trim().is_empty() {
                warn!("invalid shell '{shell}', expected '<program> <argument>' (e.g. sh -c)");
                None
            } else {
                Some(shell_cmd)
            }
        })
    }

    pub async fn render(&mut self, config: &Arc<Config>, config_root: &Path) -> Result<()> {
        let mut tera = get_tera(Some(config_root));
        let tera_ctx = self.tera_ctx(config).await?;
        for a in &mut self.aliases {
            *a = tera.render_str(a, &tera_ctx)?;
        }

        self.description = tera.render_str(&self.description, &tera_ctx)?;
        for s in &mut self.sources {
            *s = tera.render_str(s, &tera_ctx)?;
        }
        if !self.sources.is_empty() && self.outputs.is_empty() {
            self.outputs = TaskOutputs::Auto;
        }
        self.raw_outputs = self.outputs.render(&mut tera, &tera_ctx)?;
        // Save unrendered dependency templates so they can be re-rendered later
        // with parent task args available (for passing args to dependencies).
        self.depends_raw = Some(self.depends.clone());
        self.depends_post_raw = Some(self.depends_post.clone());
        self.wait_for_raw = Some(self.wait_for.clone());
        // Render deps that don't contain {{usage.*}} references. Deps with usage
        // references are deferred until render_depends_with_usage() is called with
        // the actual arg values from CLI or parent dependency.
        for d in &mut self.depends {
            if !dep_has_usage_ref(d) {
                d.render(&mut tera, &tera_ctx)?;
            }
        }
        for d in &mut self.depends_post {
            if !dep_has_usage_ref(d) {
                d.render(&mut tera, &tera_ctx)?;
            }
        }
        for d in &mut self.wait_for {
            if !dep_has_usage_ref(d) {
                d.render(&mut tera, &tera_ctx)?;
            }
        }
        if let Some(dir) = &mut self.dir {
            *dir = tera.render_str(dir, &tera_ctx)?;
        }
        if let Some(shell) = &mut self.shell {
            *shell = tera.render_str(shell, &tera_ctx)?;
        }
        for (_, v) in &mut self.tools {
            *v = tera.render_str(v, &tera_ctx)?;
        }
        Ok(())
    }

    /// Re-render dependency templates with usage args/flags from the parent task.
    /// This allows `depends = ["child {{usage.app}}"]` to resolve when the parent
    /// task receives `--app=foo` from the CLI.
    pub async fn render_depends_with_usage(
        &mut self,
        config: &Arc<Config>,
        usage_values: &IndexMap<String, String>,
    ) -> Result<()> {
        if usage_values.is_empty() {
            return Ok(());
        }
        let config_root = self.config_root.clone().unwrap_or_default();
        let mut tera = get_tera(Some(&config_root));
        let mut tera_ctx = self.tera_ctx(config).await?;
        // Insert usage values into the tera context so templates like
        // {{usage.app}} resolve to the actual CLI arg value.
        tera_ctx.insert("usage", usage_values);

        // Re-render from raw templates (not from already-rendered values).
        // Only restore from raw if the field is non-empty — skip_deps clears
        // depends/depends_post/wait_for and we must not undo that.
        if !self.depends.is_empty()
            && let Some(raw) = &self.depends_raw
        {
            self.depends = raw.clone();
            for d in &mut self.depends {
                d.render(&mut tera, &tera_ctx)?;
            }
        }
        if !self.depends_post.is_empty()
            && let Some(raw) = &self.depends_post_raw
        {
            self.depends_post = raw.clone();
            for d in &mut self.depends_post {
                d.render(&mut tera, &tera_ctx)?;
            }
        }
        if !self.wait_for.is_empty()
            && let Some(raw) = &self.wait_for_raw
        {
            self.wait_for = raw.clone();
            for d in &mut self.wait_for {
                d.render(&mut tera, &tera_ctx)?;
            }
        }
        Ok(())
    }

    pub fn name_to_path(&self) -> PathBuf {
        self.name.replace(':', path::MAIN_SEPARATOR_STR).into()
    }

    pub async fn render_env(
        &self,
        config: &Arc<Config>,
        ts: &Toolset,
    ) -> Result<(EnvMap, Vec<(String, String)>)> {
        let mut tera_ctx = ts.tera_ctx(config).await?.clone();
        let mut env = ts.full_env(config).await?;
        if let Some(root) = &config.project_root {
            tera_ctx.insert("config_root", &root);
        }

        // Convert task env directives to (EnvDirective, PathBuf) pairs
        // Use the config file path as source for proper path resolution
        // Include inherited_env first (so task's own env can override it)
        let env_directives: Vec<_> = self
            .inherited_env
            .0
            .iter()
            .chain(self.env.0.iter())
            .map(|directive| (directive.clone(), self.config_source.clone()))
            .collect();

        // Resolve environment directives using the same system as global env
        let env_results = EnvResults::resolve(
            config,
            tera_ctx.clone(),
            &env,
            env_directives,
            EnvResolveOptions {
                vars: false,
                tools: ToolsFilter::Both,
                warn_on_missing_required: false,
            },
        )
        .await?;
        // Register task-specific redactions with the global redactor
        // Include config-level redaction patterns so they also cover task-specific env vars
        let redact_keys = config
            .redaction_keys()
            .into_iter()
            .chain(env_results.redactions.iter().cloned());
        let task_env_map: EnvMap = env_results
            .env
            .iter()
            .map(|(k, (v, _))| (k.clone(), v.clone()))
            .collect();
        config.add_redactions(redact_keys, &task_env_map);

        let task_env = env_results.env.into_iter().map(|(k, (v, _))| (k, v));
        // Apply the resolved environment variables
        env.extend(task_env.clone());

        // Remove environment variables that were explicitly unset
        for key in &env_results.env_remove {
            env.remove(key);
        }

        // Apply path additions from _.path directives
        if !env_results.env_paths.is_empty() {
            let mut path_env = PathEnv::from_iter(env::split_paths(
                &env.get(&*env::PATH_KEY).cloned().unwrap_or_default(),
            ));
            for path in env_results.env_paths {
                path_env.add(path);
            }
            env.insert(env::PATH_KEY.to_string(), path_env.to_string());
        }

        Ok((env, task_env.collect()))
    }
}

fn name_from_path(prefix: impl AsRef<Path>, path: impl AsRef<Path>) -> Result<String> {
    let name = path
        .as_ref()
        .strip_prefix(prefix)
        .map(|p| match p {
            p if p.starts_with("mise-tasks") => p.strip_prefix("mise-tasks"),
            p if p.starts_with(".mise-tasks") => p.strip_prefix(".mise-tasks"),
            p if p.starts_with(".mise/tasks") => p.strip_prefix(".mise/tasks"),
            p if p.starts_with("mise/tasks") => p.strip_prefix("mise/tasks"),
            p if p.starts_with(".config/mise/tasks") => p.strip_prefix(".config/mise/tasks"),
            _ => Ok(p),
        })??
        .components()
        .map(path::Component::as_os_str)
        .map(ffi::OsStr::to_string_lossy)
        .map(|s| s.replace(':', "_"))
        .join(":");
    if let Some((parent, last)) = name.rsplit_once(':')
        && strip_extension(last) == "_default"
    {
        return Ok(parent.to_string());
    }
    Ok(name)
}

/// Extract monorepo path from a task name
/// e.g., "//projects/frontend:test" -> Some("projects/frontend")
/// e.g., "//projects/frontend:test:nested" -> Some("projects/frontend")
/// Returns None if the task name doesn't have monorepo syntax
pub(crate) fn extract_monorepo_path(name: &str) -> Option<String> {
    name.strip_prefix("//").and_then(|stripped| {
        // Find the FIRST colon after "//" prefix to handle task names with colons like "do:item-1"
        stripped.find(':').map(|idx| stripped[..idx].to_string())
    })
}

/// Build a map of task names and aliases to task references
/// For monorepo tasks, creates entries for both prefixed and unprefixed aliases
/// e.g., task "//:format" with alias "fmt" creates both "//:fmt" and "fmt"
pub(crate) fn build_task_ref_map<'a, I>(tasks: I) -> BTreeMap<String, &'a Task>
where
    I: Iterator<Item = (&'a String, &'a Task)> + 'a,
{
    tasks
        .flat_map(|(_, t)| {
            t.aliases
                .iter()
                .flat_map(|a| {
                    // For monorepo tasks, create entries for both prefixed and unprefixed aliases
                    // This allows references like "fmt" to resolve to "//:format"
                    if let Some(path) = extract_monorepo_path(&t.name) {
                        vec![(format!("//{}:{}", path, a), t), (a.to_string(), t)]
                    } else {
                        // Non-monorepo task, use alias as-is
                        vec![(a.to_string(), t)]
                    }
                })
                .chain(once((t.name.clone(), t)))
                .collect::<Vec<_>>()
        })
        .collect()
}

/// Resolve a task dependency pattern, optionally relative to a parent task
/// If pattern starts with ":" and parent_task is provided, resolve relative to parent's path
/// For example: parent "//projects/frontend:test" with pattern ":build" -> "//projects/frontend:build"
pub(crate) fn resolve_task_pattern(pattern: &str, parent_task: Option<&Task>) -> String {
    // Check if this is a bare task name that should be treated as relative
    let is_bare_name =
        !pattern.starts_with("//") && !pattern.starts_with("::") && !pattern.starts_with(':');

    // If pattern starts with ":" or is a bare name in monorepo context, resolve relatively
    let should_resolve_relatively = pattern.starts_with(':') && !pattern.starts_with("::")
        || (is_bare_name && parent_task.is_some_and(|p| p.name.starts_with("//")));

    if should_resolve_relatively && let Some(parent) = parent_task {
        // Extract the path portion from the parent task name
        // For monorepo tasks like "//projects/frontend:test:nested", we need to extract "//projects/frontend"
        // by finding the FIRST colon after the "//" prefix, not the last one
        if let Some(stripped) = parent.name.strip_prefix("//") {
            // Find the first colon after "//" prefix
            if let Some(colon_idx) = stripped.find(':') {
                let path = format!("//{}", &stripped[..colon_idx]);
                // If pattern is a bare name, add the colon prefix
                return if is_bare_name {
                    format!("{}:{}", path, pattern)
                } else {
                    format!("{}{}", path, pattern)
                };
            }
        } else if let Some((path, _)) = parent.name.rsplit_once(':') {
            // For non-monorepo tasks, use the old logic
            return format!("{}{}", path, pattern);
        }
    }
    pattern.to_string()
}

fn match_tasks_with_context(
    tasks: &BTreeMap<String, &Task>,
    td: &TaskDep,
    parent_task: Option<&Task>,
) -> Result<Vec<Task>> {
    let resolved_pattern = resolve_task_pattern(&td.task, parent_task);
    let matches = tasks
        .get_matching(&resolved_pattern)?
        .into_iter()
        .map(|t| {
            let mut t = (*t).clone();
            t.args = td.args.clone();
            // Apply env vars from dependency - these affect task identity/deduplication
            if !td.env.is_empty() {
                let env_directives: Vec<EnvDirective> = td
                    .env
                    .iter()
                    .map(|(k, v)| EnvDirective::Val(k.clone(), v.clone(), Default::default()))
                    .collect();
                t = t.with_dependency_env(&env_directives);
                if let Some(config_root) = &t.config_root {
                    let config_root = config_root.clone();
                    t.outputs
                        .re_render_with_env(&t.raw_outputs.clone(), &td.env, &config_root)?;
                }
            }
            Ok(t)
        })
        .collect::<Result<Vec<_>>>()?;
    if matches.is_empty() {
        let mut err_msg = format!("task not found: {}", td.task);

        // In monorepo mode, suggest similar tasks using fuzzy matching
        if resolved_pattern.starts_with("//") {
            let similar: Vec<String> = tasks
                .keys()
                .filter(|k| k.starts_with("//"))
                .filter_map(|k| {
                    FUZZY_MATCHER
                        .fuzzy_match(&k.to_lowercase(), &resolved_pattern.to_lowercase())
                        .map(|score| (score, k.clone()))
                })
                .sorted_by_key(|(score, _)| -1 * *score)
                .take(5)
                .map(|(_, k)| k)
                .collect();

            if !similar.is_empty() {
                err_msg.push_str("\n\nDid you mean one of these?");
                for task_name in similar {
                    err_msg.push_str(&format!("\n  - {}", task_name));
                }
            }
        }

        return Err(eyre!(err_msg));
    };

    Ok(matches)
}

impl Default for Task {
    fn default() -> Self {
        Task {
            name: "".to_string(),
            display_name: "".to_string(),
            description: "".to_string(),
            aliases: vec![],
            config_source: PathBuf::new(),
            cf: None,
            config_root: None,
            confirm: None,
            depends: vec![],
            depends_post: vec![],
            wait_for: vec![],
            env: Default::default(),
            vars: Default::default(),
            inherited_env: Default::default(),
            dir: None,
            hide: false,
            global: false,
            raw: false,
            interactive: false,
            sources: vec![],
            outputs: Default::default(),
            raw_outputs: Default::default(),
            shell: None,
            silent: Silent::Off,
            run: vec![],
            run_windows: vec![],
            args: vec![],
            file: None,
            quiet: false,
            tools: Default::default(),
            usage: "".to_string(),
            timeout: None,
            remote_file_source: None,
            deny_all: false,
            deny_read: false,
            deny_write: false,
            deny_net: false,
            deny_env: false,
            allow_read: vec![],
            allow_write: vec![],
            allow_net: vec![],
            allow_env: vec![],
            extends: None,
            show_args_in_prefix: false,
            depends_raw: None,
            depends_post_raw: None,
            wait_for_raw: None,
        }
    }
}

impl Display for Task {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let cmd = self
            .run()
            .iter()
            .map(|e| e.to_string())
            .next()
            .or_else(|| self.file_path_raw().as_ref().map(display_path));

        if let Some(cmd) = cmd {
            let cmd = cmd.lines().next().unwrap_or_default();
            let prefix = self.prefix();
            let prefix_len = measure_text_width(&prefix);
            // Ensure we have at least 20 characters for the command, even with very long prefixes
            let available_width = (*env::TERM_WIDTH).saturating_sub(prefix_len + 4); // 4 chars buffer for spacing and ellipsis
            let max_width = available_width.max(20); // Always show at least 20 chars of command
            let truncated_cmd = truncate_str(cmd, max_width, "…");
            write!(f, "{} {}", prefix, truncated_cmd)
        } else {
            write!(f, "{}", self.prefix())
        }
    }
}

impl PartialOrd for Task {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

/// Extract sorted env key-value pairs from task's own env (not inherited_env)
/// Used for consistent comparison/hashing of task identity
fn env_key(task: &Task) -> Vec<(&String, &String)> {
    task.env
        .0
        .iter()
        .filter_map(|d| match d {
            EnvDirective::Val(k, v, _) => Some((k, v)),
            _ => None,
        })
        .sorted()
        .collect()
}

impl Ord for Task {
    fn cmp(&self, other: &Self) -> Ordering {
        match self.name.cmp(&other.name) {
            Ordering::Equal => match self.args.cmp(&other.args) {
                Ordering::Equal => env_key(self).cmp(&env_key(other)),
                o => o,
            },
            o => o,
        }
    }
}

impl Hash for Task {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.name.hash(state);
        self.args.iter().for_each(|arg| arg.hash(state));
        // Include task's own env (not inherited_env) for deduplication
        for (k, v) in env_key(self) {
            k.hash(state);
            v.hash(state);
        }
    }
}

impl Eq for Task {}
impl PartialEq for Task {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name && self.args == other.args && env_key(self) == env_key(other)
    }
}

impl TreeItem for (&Graph<Task, ()>, NodeIndex) {
    type Child = Self;

    fn write_self(&self) -> std::io::Result<()> {
        if let Some(w) = self.0.node_weight(self.1) {
            miseprint!("{}", w.display_name)?;
        }
        Ok(())
    }

    fn children(&self) -> Cow<'_, [Self::Child]> {
        let v: Vec<_> = self.0.neighbors(self.1).map(|i| (self.0, i)).collect();
        Cow::from(v)
    }
}

pub trait GetMatchingExt<T> {
    fn get_matching(&self, pat: &str) -> Result<Vec<&T>>;
}

/// Helper function to strip file extension from a task name
/// e.g., "test.js" -> "test", "build" -> "build"
/// Special case: hidden files like ".hidden" are preserved to avoid empty strings
fn strip_extension(name: &str) -> &str {
    let result = name.rsplitn(2, '.').last().unwrap_or(name);
    // Don't strip extension if it would result in empty string (hidden files)
    if result.is_empty() { name } else { result }
}

impl<T> GetMatchingExt<T> for BTreeMap<String, T>
where
    T: Eq + Hash,
{
    fn get_matching(&self, pat: &str) -> Result<Vec<&T>> {
        // === Monorepo pattern matching ===
        // Only patterns starting with '//' or ':' are monorepo patterns
        // Reject patterns that look like monorepo paths but use wrong syntax (have / and : but don't start with // or :)
        if !pat.starts_with("//") && !pat.starts_with(':') {
            // Check if this looks like an attempt at a monorepo path with wrong syntax
            if pat.contains('/') && pat.contains(':') {
                bail!(
                    "relative path syntax '{}' is not supported, use '//{}'  or ':task' for current directory",
                    pat,
                    pat
                )
            }
            // If it doesn't contain wildcards or ':', it's a simple task name
            if !pat.contains('*') && !pat.contains("...") && !pat.contains(':') {
                return Ok(self
                    .iter()
                    .filter(|(k, _)| {
                        // Check if task name exactly matches, or matches without extension
                        k.as_str() == pat || strip_extension(k) == pat
                    })
                    .map(|(_, v)| v)
                    .collect());
            }
            // Has wildcards or colon but no /, so it's a regular task pattern like "render:*" or "build:linux"
            // Process with glob matching below
        }

        // === Parse monorepo pattern ===
        let normalized_pat = if pat.starts_with("//") {
            pat.to_string()
        } else if pat.starts_with(':') {
            // Special case: :task should have been expanded before calling get_matching
            // If we reach here, it means the expansion didn't happen properly
            bail!("':task' pattern should be expanded before matching")
        } else {
            pat.to_string()
        };

        // Split pattern into path and task parts
        // Pattern format: //path/...:task* or //path:task*
        let parts: Vec<&str> = normalized_pat.splitn(2, ':').collect();
        let has_explicit_task_glob = parts.len() > 1;
        let (path_pattern, task_pattern) = match parts.as_slice() {
            [path, task] => (*path, *task),
            [path] => (*path, "*"),
            _ => (normalized_pat.as_str(), "*"),
        };

        // === Convert ellipsis to glob syntax ===
        // Convert ellipsis (...) to glob pattern (**)
        // //... matches everything, //foo/... matches foo and all subdirs
        let path_glob = path_pattern.replace("...", "**");

        // For task patterns, * only matches within the task name portion (after final :)
        // e.g., test:* matches test:unit, test:integration, etc.
        let task_glob = task_pattern;

        // === Build glob matchers once (performance optimization) ===
        // Build path matcher for absolute patterns
        let path_matcher = GlobBuilder::new(&path_glob)
            .literal_separator(true)
            .build()
            .ok()
            .map(|b| b.compile_matcher());

        // Build task matcher if not wildcard
        let task_matcher = if task_glob != "*" {
            GlobBuilder::new(task_glob)
                .literal_separator(false) // Allow * to match : in task names
                .build()
                .ok()
                .map(|b| b.compile_matcher())
        } else {
            None
        };

        // Build relative pattern matchers if needed
        let (rel_path_matcher, rel_task_matcher) = if !pat.starts_with("//") {
            let rel_path_pattern = path_pattern.strip_prefix("//").unwrap_or(path_pattern);
            let rel_path_glob = rel_path_pattern.replace("...", "**");

            let rel_path = GlobBuilder::new(&rel_path_glob)
                .literal_separator(true)
                .build()
                .ok()
                .map(|b| b.compile_matcher());

            let rel_task = if task_glob != "*" {
                GlobBuilder::new(task_glob)
                    .literal_separator(false)
                    .build()
                    .ok()
                    .map(|b| b.compile_matcher())
            } else {
                None
            };

            (rel_path, rel_task)
        } else {
            (None, None)
        };

        // === Match tasks with extension stripping ===
        Ok(self
            .iter()
            .filter(|(k, _)| {
                // Split task name into path and task parts
                let key_parts: Vec<&str> = k.splitn(2, ':').collect();
                let (key_path, key_task) = match key_parts.as_slice() {
                    [path, task] => (*path, *task),
                    [path] => (*path, ""),
                    _ => (k.as_str(), ""),
                };

                // Match path part with ellipsis support
                let path_matches = if let Some(ref matcher) = path_matcher {
                    matcher.is_match(key_path)
                } else {
                    false
                };

                // Match task part with asterisk support and extension stripping
                // When the pattern explicitly uses a wildcard after `:` (e.g., "test:*"),
                // require the key to actually have a task part (i.e., contain a `:`
                // separator). This prevents "test" from matching "test:*", which would
                // cause circular dependencies. Implicit wildcards (bare names like "test")
                // should still match the exact task.
                let task_matches = if task_glob == "*" {
                    !has_explicit_task_glob || !key_task.is_empty()
                } else if let Some(ref matcher) = task_matcher {
                    // Check exact match OR match without extension
                    matcher.is_match(key_task) || matcher.is_match(strip_extension(key_task))
                } else {
                    false
                };

                // Try matching without // prefix for relative patterns
                let relative_match = if !pat.starts_with("//") {
                    let stripped_key = k.strip_prefix("//").unwrap_or(k);
                    let stripped_parts: Vec<&str> = stripped_key.splitn(2, ':').collect();
                    let (stripped_path, stripped_task) = match stripped_parts.as_slice() {
                        [path, task] => (*path, *task),
                        [path] => (*path, ""),
                        _ => (stripped_key, ""),
                    };

                    let rel_path_matches = if let Some(ref matcher) = rel_path_matcher {
                        matcher.is_match(stripped_path)
                    } else {
                        false
                    };

                    let rel_task_matches = if task_glob == "*" {
                        !has_explicit_task_glob || !stripped_task.is_empty()
                    } else if let Some(ref matcher) = rel_task_matcher {
                        // Check exact match OR match without extension
                        matcher.is_match(stripped_task)
                            || matcher.is_match(strip_extension(stripped_task))
                    } else {
                        false
                    };

                    rel_path_matches && rel_task_matches
                } else {
                    false
                };

                (path_matches && task_matches) || relative_match
            })
            .map(|(_, t)| t)
            .unique()
            .collect())
    }
}

/// Check if a TaskDep contains {{usage.*}} references that need deferred rendering.
/// Strips whitespace before matching to handle Tera's `{{ usage.foo }}` syntax.
pub(crate) fn dep_has_usage_ref(dep: &TaskDep) -> bool {
    let has_ref = |s: &str| {
        let s = s.replace(' ', "");
        s.contains("{{usage.")
    };
    has_ref(&dep.task)
        || dep.args.iter().any(|a| has_ref(a))
        || dep.env.values().any(|v| has_ref(v))
}

/// Parse a task's usage spec against its current args and return a map
/// of named arg/flag values (e.g., {"app": "myapp", "verbose": "true"}).
/// Used to provide `{{usage.*}}` context when rendering dependency templates.
pub async fn parse_usage_values_from_task(
    config: &Arc<Config>,
    task: &Task,
) -> Result<IndexMap<String, String>> {
    let ts = config.get_toolset().await?;
    let env = ts.full_env(config).await?;
    let (spec, _) = task
        .parse_usage_spec_with_vars(config, None, &env, None)
        .await?;
    if spec.cmd.args.is_empty() && spec.cmd.flags.is_empty() {
        return Ok(IndexMap::new());
    }
    // Build args list with empty first element (usage parser expects argv[0] to be the command)
    let args: Vec<String> = once(String::new())
        .chain(task.args.iter().cloned())
        .collect();
    let po = match usage::Parser::new(&spec).parse(&args) {
        Ok(po) => po,
        Err(e) => {
            debug!("usage parse failed for task '{}': {e}", task.name);
            return Ok(IndexMap::new());
        }
    };
    let mut values = IndexMap::new();
    for (k, v) in po.as_env() {
        // Strip "usage_" prefix to get the bare arg/flag name
        if let Some(name) = k.strip_prefix("usage_") {
            values.insert(name.to_string(), v);
        }
    }
    Ok(values)
}

#[cfg(test)]
mod tests {
    #[cfg(unix)]
    use std::os::unix::fs::PermissionsExt;
    use std::path::Path;
    use std::sync::Mutex;

    use crate::task::Task;
    use crate::{config::Config, dirs};
    use pretty_assertions::assert_eq;

    use super::name_from_path;

    // Thread-local storage to capture parser state during tests
    thread_local! {
        static CAPTURED_PARSER_FIELDS: Mutex<Option<Vec<String>>> = const { Mutex::new(None) };
    }

    pub(super) fn capture_parsed_fields(fields: Vec<String>) {
        CAPTURED_PARSER_FIELDS.with(|captured| {
            *captured.lock().unwrap() = Some(fields);
        });
    }

    fn take_captured_fields() -> Option<Vec<String>> {
        CAPTURED_PARSER_FIELDS.with(|captured| captured.lock().unwrap().take())
    }

    #[tokio::test]
    async fn test_from_path() {
        let test_cases = [(".mise/tasks/filetask", "filetask", vec!["ft"])];
        let config = Config::get().await.unwrap();
        for (path, name, aliases) in test_cases {
            let t = Task::from_path(
                &config,
                Path::new(path),
                Path::new(".mise/tasks"),
                Path::new(dirs::CWD.as_ref().unwrap()),
            )
            .await
            .unwrap();
            assert_eq!(t.name, name);
            assert_eq!(t.aliases, aliases);
        }
    }

    #[test]
    #[cfg(unix)]
    fn test_name_from_path() {
        let test_cases = [
            (("/.mise/tasks", "/.mise/tasks/a"), "a"),
            (("/.mise/tasks", "/.mise/tasks/a/b"), "a:b"),
            (("/.mise/tasks", "/.mise/tasks/a/b/c"), "a:b:c"),
            (("/.mise/tasks", "/.mise/tasks/a:b"), "a_b"),
            (("/.mise/tasks", "/.mise/tasks/a:b/c"), "a_b:c"),
            (("/.mise/tasks", "/.mise/tasks/a/_default"), "a"),
            (("/.mise/tasks", "/.mise/tasks/a/_default.sh"), "a"),
            (("/.mise/tasks", "/.mise/tasks/a/_default.js"), "a"),
            (("/.mise/tasks", "/.mise/tasks/a/b/_default"), "a:b"),
            (("/.mise/tasks", "/.mise/tasks/a/b/_default.sh"), "a:b"),
        ];

        for ((root, path), expected) in test_cases {
            assert_eq!(name_from_path(root, path).unwrap(), expected)
        }
    }

    #[test]
    fn test_name_from_path_invalid() {
        let test_cases = [("/some/other/dir", "/.mise/tasks/a")];

        for (root, path) in test_cases {
            assert!(name_from_path(root, path).is_err())
        }
    }

    // This test verifies that resolve_depends correctly uses self.depends_post
    // instead of iterating through all tasks_to_run (which was the bug)
    #[tokio::test]
    async fn test_resolve_depends_post_uses_self_only() {
        use crate::task::task_dep::TaskDep;

        // Create a task with depends_post
        let task_with_post_deps = Task {
            name: "task_with_post".to_string(),
            depends_post: vec![
                TaskDep {
                    task: "post1".to_string(),
                    args: vec![],
                    env: Default::default(),
                },
                TaskDep {
                    task: "post2".to_string(),
                    args: vec![],
                    env: Default::default(),
                },
            ],
            ..Default::default()
        };

        // Create another task with different depends_post
        let other_task = Task {
            name: "other_task".to_string(),
            depends_post: vec![TaskDep {
                task: "other_post".to_string(),
                args: vec![],
                env: Default::default(),
            }],
            ..Default::default()
        };

        // Verify that task_with_post_deps has the expected depends_post
        assert_eq!(task_with_post_deps.depends_post.len(), 2);
        assert_eq!(task_with_post_deps.depends_post[0].task, "post1");
        assert_eq!(task_with_post_deps.depends_post[1].task, "post2");

        // Verify that other_task doesn't interfere (would have before the fix)
        assert_eq!(other_task.depends_post.len(), 1);
        assert_eq!(other_task.depends_post[0].task, "other_post");
    }

    #[tokio::test]
    async fn test_from_path_toml_headers() {
        use std::fs;
        use tempfile::tempdir;

        let config = Config::get().await.unwrap();
        let temp_dir = tempdir().unwrap();
        let task_path = temp_dir.path().join("test_task");

        fs::write(
            &task_path,
            r#"#!/bin/bash
#MISE description="Build the CLI"
# MISE alias="b"
# [MISE] sources=["Cargo.toml", "src/**/*.rs"]
echo "hello world"
"#,
        )
        .unwrap();

        let result = Task::from_path(&config, &task_path, temp_dir.path(), temp_dir.path()).await;
        let mut expected = Task::new(&task_path, temp_dir.path(), temp_dir.path()).unwrap();
        expected.description = "Build the CLI".to_string();
        expected.aliases = vec!["b".to_string()];
        expected.sources = vec!["Cargo.toml".to_string(), "src/**/*.rs".to_string()];
        assert_eq!(result.unwrap(), expected);
    }

    #[tokio::test]
    #[cfg(unix)]
    async fn test_from_path_env_file_with_spaces_around_equals() {
        use std::fs;
        use tempfile::tempdir;

        let config = Config::get().await.unwrap();
        let ts = config.get_toolset().await.unwrap();
        let temp_dir = tempdir().unwrap();
        let task_path = temp_dir.path().join("hello");
        let env_path = temp_dir.path().join("env.yaml");

        fs::write(&env_path, "USR: World!\n").unwrap();
        fs::write(
            &task_path,
            r#"#!/usr/bin/env bash
#MISE env._.file = "env.yaml"
echo "Hello $USR"
"#,
        )
        .unwrap();

        let task = Task::from_path(&config, &task_path, temp_dir.path(), temp_dir.path())
            .await
            .unwrap();
        let (env, task_env) = task.render_env(&config, ts).await.unwrap();

        assert_eq!(task_env, vec![("USR".to_string(), "World!".to_string())]);
        assert_eq!(env.get("USR"), Some(&"World!".to_string()));
    }

    #[tokio::test]
    async fn test_from_path_invalid_toml() {
        use std::fs;
        use tempfile::tempdir;

        let config = Config::get().await.unwrap();
        let temp_dir = tempdir().unwrap();
        let task_path = temp_dir.path().join("test_task");

        // Create a task file with invalid TOML in the header
        fs::write(
            &task_path,
            r#"#!/bin/bash
#MISE description="test task"
#MISE env={invalid=toml=here}
echo "hello world"
"#,
        )
        .unwrap();

        let result = Task::from_path(&config, &task_path, temp_dir.path(), temp_dir.path()).await;

        assert!(result.is_err());
        let error = result.unwrap_err();
        assert!(
            error
                .to_string()
                .contains("failed to parse task header TOML")
        );
    }

    #[test]
    fn test_resolve_task_pattern() {
        use super::resolve_task_pattern;

        // Test 1: Relative pattern with monorepo parent task
        let parent_task = Task {
            name: "//projects/frontend:test".to_string(),
            ..Default::default()
        };
        assert_eq!(
            resolve_task_pattern(":build", Some(&parent_task)),
            "//projects/frontend:build"
        );

        // Test 2: Relative pattern with different parent
        let parent_task = Task {
            name: "//libs/shared:lint".to_string(),
            ..Default::default()
        };
        assert_eq!(
            resolve_task_pattern(":compile", Some(&parent_task)),
            "//libs/shared:compile"
        );

        // Test 3: Absolute pattern should not be modified
        let parent_task = Task {
            name: "//projects/frontend:test".to_string(),
            ..Default::default()
        };
        assert_eq!(
            resolve_task_pattern("//projects/backend:build", Some(&parent_task)),
            "//projects/backend:build"
        );

        // Test 4: Simple task name with monorepo parent should resolve relatively (NEW BEHAVIOR)
        assert_eq!(
            resolve_task_pattern("build", Some(&parent_task)),
            "//projects/frontend:build"
        );

        // Test 5: Relative pattern without parent task (no resolution)
        assert_eq!(resolve_task_pattern(":build", None), ":build");

        // Test 6: Non-monorepo task - colon pattern should not resolve
        let parent_task = Task {
            name: "test".to_string(),
            ..Default::default()
        };
        assert_eq!(resolve_task_pattern(":build", Some(&parent_task)), ":build");

        // Test 6a: Non-monorepo task - bare name should not resolve
        assert_eq!(resolve_task_pattern("build", Some(&parent_task)), "build");

        // Test 7: Root monorepo task (empty path)
        let parent_task = Task {
            name: "//:root-task".to_string(),
            ..Default::default()
        };
        assert_eq!(
            resolve_task_pattern(":other", Some(&parent_task)),
            "//:other"
        );

        // Test 8: Double colon should not be treated as relative
        let parent_task = Task {
            name: "//projects/frontend:test".to_string(),
            ..Default::default()
        };
        assert_eq!(
            resolve_task_pattern("::global", Some(&parent_task)),
            "::global"
        );

        // Test 9: Pattern with wildcards
        let parent_task = Task {
            name: "//projects/frontend:test".to_string(),
            ..Default::default()
        };
        assert_eq!(
            resolve_task_pattern(":test*", Some(&parent_task)),
            "//projects/frontend:test*"
        );

        // Test 10: Deep nested path
        let parent_task = Task {
            name: "//a/b/c/d:task".to_string(),
            ..Default::default()
        };
        assert_eq!(
            resolve_task_pattern(":dep", Some(&parent_task)),
            "//a/b/c/d:dep"
        );

        // Test 11: Task name with colon (e.g., "do:item-1")
        // This is the bug that was fixed - we need to split on the FIRST colon after //
        let parent_task = Task {
            name: "//submodule:do:item-1".to_string(),
            ..Default::default()
        };
        assert_eq!(
            resolve_task_pattern(":before", Some(&parent_task)),
            "//submodule:before"
        );

        // Test 12: Another task name with multiple colons
        let parent_task = Task {
            name: "//project:test:unit:fast".to_string(),
            ..Default::default()
        };
        assert_eq!(
            resolve_task_pattern(":setup", Some(&parent_task)),
            "//project:setup"
        );

        // Test 13: Bare name without parent task (no resolution)
        assert_eq!(resolve_task_pattern("build", None), "build");

        // Test 14: Bare name with different monorepo parent
        let parent_task = Task {
            name: "//libs/shared:lint".to_string(),
            ..Default::default()
        };
        assert_eq!(
            resolve_task_pattern("compile", Some(&parent_task)),
            "//libs/shared:compile"
        );

        // Test 15: Bare name with root monorepo task
        let parent_task = Task {
            name: "//:root-task".to_string(),
            ..Default::default()
        };
        assert_eq!(
            resolve_task_pattern("other", Some(&parent_task)),
            "//:other"
        );

        // Test 16: Bare name with task containing colons
        let parent_task = Task {
            name: "//submodule:do:item-1".to_string(),
            ..Default::default()
        };
        assert_eq!(
            resolve_task_pattern("before", Some(&parent_task)),
            "//submodule:before"
        );

        // Test 17: Absolute path should not be modified even with monorepo parent
        let parent_task = Task {
            name: "//projects/frontend:test".to_string(),
            ..Default::default()
        };
        assert_eq!(
            resolve_task_pattern("//other/module:task", Some(&parent_task)),
            "//other/module:task"
        );

        // Test 18: Global task (::) should not be modified
        assert_eq!(
            resolve_task_pattern("::global", Some(&parent_task)),
            "::global"
        );
    }

    #[test]
    fn test_extract_monorepo_path() {
        use super::extract_monorepo_path;

        // Test 1: Simple monorepo task
        assert_eq!(
            extract_monorepo_path("//projects/frontend:test"),
            Some("projects/frontend".to_string())
        );

        // Test 2: Root level task
        assert_eq!(extract_monorepo_path("//:root-task"), Some("".to_string()));

        // Test 3: Deep nested path
        assert_eq!(
            extract_monorepo_path("//a/b/c/d:task"),
            Some("a/b/c/d".to_string())
        );

        // Test 4: Non-monorepo task (no // prefix)
        assert_eq!(extract_monorepo_path("regular-task"), None);

        // Test 5: Task name with colon (e.g., "do:item-1")
        // This was the bug - we need to extract based on FIRST colon after //
        assert_eq!(
            extract_monorepo_path("//submodule:do:item-1"),
            Some("submodule".to_string())
        );

        // Test 6: Multiple colons in task name
        assert_eq!(
            extract_monorepo_path("//project:test:unit:fast"),
            Some("project".to_string())
        );

        // Test 7: Complex path with colons in task name
        assert_eq!(
            extract_monorepo_path("//apps/backend:build:prod"),
            Some("apps/backend".to_string())
        );
    }

    #[test]
    fn test_strip_extension() {
        use super::strip_extension;

        // Test 1: Single extension
        assert_eq!(strip_extension("task.sh"), "task");
        assert_eq!(strip_extension("build.js"), "build");
        assert_eq!(strip_extension("test.py"), "test");

        // Test 2: Multiple extensions (only strips rightmost one)
        assert_eq!(strip_extension("backup.test.js"), "backup.test");
        assert_eq!(strip_extension("file.tar.gz"), "file.tar");
        assert_eq!(strip_extension("archive.tar.bz2"), "archive.tar");

        // Test 3: No extension
        assert_eq!(strip_extension("task"), "task");
        assert_eq!(strip_extension("build"), "build");

        // Test 4: Hidden files (starting with dot)
        // Now preserved to avoid empty strings
        assert_eq!(strip_extension(".hidden"), ".hidden");
        assert_eq!(strip_extension(".gitignore"), ".gitignore");

        // Test 5: Hidden files with extension
        assert_eq!(strip_extension(".hidden.sh"), ".hidden");
        assert_eq!(strip_extension(".config.json"), ".config");

        // Test 6: Empty string
        assert_eq!(strip_extension(""), "");

        // Test 7: Only extension separator (preserved to avoid empty string)
        assert_eq!(strip_extension("."), ".");

        // Test 8: Multiple dots with extension
        assert_eq!(strip_extension("my.task.name.js"), "my.task.name");

        // Test 9: Path-like names (shouldn't treat / as special)
        assert_eq!(strip_extension("path/to/task.sh"), "path/to/task");
        assert_eq!(strip_extension("path/task"), "path/task");

        // Test 10: Task names with dots in the middle
        assert_eq!(strip_extension("test.unit"), "test");
        assert_eq!(strip_extension("build.prod.js"), "build.prod");
    }

    #[test]
    fn test_circular_dependency_detection() {
        use super::Task;
        use std::collections::BTreeMap;

        let mut tasks = BTreeMap::new();

        // Create circular dependency: task_a -> task_b -> task_a
        let task_a = Task {
            name: "task_a".to_string(),
            depends: vec![crate::task::task_dep::TaskDep {
                task: "task_b".to_string(),
                args: vec![],
                env: Default::default(),
            }],
            ..Default::default()
        };

        let task_b = Task {
            name: "task_b".to_string(),
            depends: vec![crate::task::task_dep::TaskDep {
                task: "task_a".to_string(),
                args: vec![],
                env: Default::default(),
            }],
            ..Default::default()
        };

        tasks.insert("task_a".to_string(), task_a.clone());
        tasks.insert("task_b".to_string(), task_b);

        // Should detect circular dependency
        let result = task_a.all_depends(&tasks);
        assert!(result.is_err());
        let err_msg = format!("{}", result.unwrap_err());
        assert!(err_msg.contains("circular dependency detected"));
    }

    #[test]
    fn test_transitive_circular_dependency_detection() {
        use super::Task;
        use std::collections::BTreeMap;

        let mut tasks = BTreeMap::new();

        // Create transitive circular dependency: a -> b -> c -> a
        let task_a = Task {
            name: "task_a".to_string(),
            depends: vec![crate::task::task_dep::TaskDep {
                task: "task_b".to_string(),
                args: vec![],
                env: Default::default(),
            }],
            ..Default::default()
        };

        let task_b = Task {
            name: "task_b".to_string(),
            depends: vec![crate::task::task_dep::TaskDep {
                task: "task_c".to_string(),
                args: vec![],
                env: Default::default(),
            }],
            ..Default::default()
        };

        let task_c = Task {
            name: "task_c".to_string(),
            depends: vec![crate::task::task_dep::TaskDep {
                task: "task_a".to_string(),
                args: vec![],
                env: Default::default(),
            }],
            ..Default::default()
        };

        tasks.insert("task_a".to_string(), task_a.clone());
        tasks.insert("task_b".to_string(), task_b);
        tasks.insert("task_c".to_string(), task_c);

        // Should detect circular dependency
        let result = task_a.all_depends(&tasks);
        assert!(result.is_err());
        let err_msg = format!("{}", result.unwrap_err());
        assert!(err_msg.contains("circular dependency detected"));
    }

    #[test]
    fn test_no_false_positive_for_diamond_dependency() {
        use super::Task;
        use std::collections::BTreeMap;

        let mut tasks = BTreeMap::new();

        // Create diamond dependency (NOT circular): root -> [a, b] -> common
        let root = Task {
            name: "root".to_string(),
            depends: vec![
                crate::task::task_dep::TaskDep {
                    task: "task_a".to_string(),
                    args: vec![],
                    env: Default::default(),
                },
                crate::task::task_dep::TaskDep {
                    task: "task_b".to_string(),
                    args: vec![],
                    env: Default::default(),
                },
            ],
            ..Default::default()
        };

        let task_a = Task {
            name: "task_a".to_string(),
            depends: vec![crate::task::task_dep::TaskDep {
                task: "common".to_string(),
                args: vec![],
                env: Default::default(),
            }],
            ..Default::default()
        };

        let task_b = Task {
            name: "task_b".to_string(),
            depends: vec![crate::task::task_dep::TaskDep {
                task: "common".to_string(),
                args: vec![],
                env: Default::default(),
            }],
            ..Default::default()
        };

        let common = Task {
            name: "common".to_string(),
            ..Default::default()
        };

        tasks.insert("root".to_string(), root.clone());
        tasks.insert("task_a".to_string(), task_a);
        tasks.insert("task_b".to_string(), task_b);
        tasks.insert("common".to_string(), common);

        // Should NOT detect circular dependency (diamond is OK)
        let result = root.all_depends(&tasks);
        assert!(result.is_ok());
        let deps = result.unwrap();
        // Should have task_a, task_b, and common (deduplicated)
        assert_eq!(deps.len(), 3);
    }

    #[test]
    fn test_file_path_raw_absolute() {
        use std::path::PathBuf;

        let task = Task {
            name: "test".to_string(),
            file: Some(PathBuf::from("/absolute/path/script.sh")),
            config_root: Some(PathBuf::from("/project/root")),
            ..Default::default()
        };

        let result = task.file_path_raw();
        assert_eq!(result, Some(PathBuf::from("/absolute/path/script.sh")));
    }

    #[test]
    fn test_file_path_raw_relative() {
        use std::path::PathBuf;

        let task = Task {
            name: "test".to_string(),
            file: Some(PathBuf::from("scripts/test.sh")),
            config_root: Some(PathBuf::from("/project/root")),
            ..Default::default()
        };

        let result = task.file_path_raw();
        assert_eq!(result, Some(PathBuf::from("/project/root/scripts/test.sh")));
    }

    #[test]
    fn test_file_path_raw_relative_no_config_root() {
        use std::path::PathBuf;

        let task = Task {
            name: "test".to_string(),
            file: Some(PathBuf::from("scripts/test.sh")),
            config_root: None,
            ..Default::default()
        };

        let result = task.file_path_raw();
        assert_eq!(result, Some(PathBuf::from("scripts/test.sh")));
    }

    #[test]
    fn test_file_path_raw_none() {
        let task = Task {
            name: "test".to_string(),
            file: None,
            config_root: None,
            ..Default::default()
        };

        let result = task.file_path_raw();
        assert_eq!(result, None);
    }

    #[tokio::test]
    async fn test_file_path_absolute() {
        use std::path::PathBuf;

        let config = Config::get().await.unwrap();
        let task = Task {
            name: "test".to_string(),
            file: Some(PathBuf::from("/absolute/path/script.sh")),
            config_root: Some(PathBuf::from("/project/root")),
            ..Default::default()
        };

        let result = task.file_path(&config).await.unwrap();
        assert_eq!(result, Some(PathBuf::from("/absolute/path/script.sh")));
    }

    #[tokio::test]
    async fn test_file_path_relative() {
        use std::path::PathBuf;

        let config = Config::get().await.unwrap();
        let task = Task {
            name: "test".to_string(),
            file: Some(PathBuf::from("scripts/test.sh")),
            config_root: Some(PathBuf::from("/project/root")),
            ..Default::default()
        };

        let result = task.file_path(&config).await.unwrap();
        assert_eq!(result, Some(PathBuf::from("/project/root/scripts/test.sh")));
    }

    #[tokio::test]
    async fn test_file_path_none() {
        let config = Config::get().await.unwrap();
        let task = Task {
            name: "test".to_string(),
            file: None,
            config_root: None,
            ..Default::default()
        };

        let result = task.file_path(&config).await.unwrap();
        assert_eq!(result, None);
    }

    #[tokio::test]
    async fn test_file_path_with_templating() {
        use std::path::PathBuf;

        let config = Config::get().await.unwrap();
        let task = Task {
            name: "test".to_string(),
            file: Some(PathBuf::from("scripts/{{config_root}}/test.sh")),
            config_root: Some(PathBuf::from("/project/root")),
            ..Default::default()
        };

        // This test verifies that templating is processed in file_path
        let result = task.file_path(&config).await;
        // Should succeed (not error on template rendering)
        assert!(result.is_ok());
    }

    #[tokio::test]
    #[cfg(unix)]
    async fn test_parses_all_fields() {
        use std::fs;
        use tempfile::tempdir;

        // Create a temporary directory for the test
        let temp_dir = tempdir().unwrap();
        let tasks_dir = temp_dir.path().join("tasks");
        fs::create_dir(&tasks_dir).unwrap();
        let task_file = tasks_dir.join("test-task");

        // Create a file task with ALL possible header fields
        let script_content = r#"#!/usr/bin/env bash
#MISE description="Test task with all fields"
#MISE aliases=["alias1", "alias2"]
#MISE depends=["dep1", "dep2"]
#MISE depends_post=["post1"]
#MISE wait_for=["wait1"]
#MISE env={TEST_VAR="value"}
#MISE dir="/some/dir"
#MISE hide=true
#MISE raw=true
#MISE interactive=true
#MISE sources=["src1.txt", "src2.txt"]
#MISE outputs=["out1.txt"]
#MISE shell="bash -c"
#MISE quiet=true
#MISE silent=true
#MISE tools={node="20", python="3.11"}
#MISE confirm="Are you sure?"
echo "test"
"#;
        fs::write(&task_file, script_content).unwrap();
        fs::set_permissions(&task_file, std::fs::Permissions::from_mode(0o755)).unwrap();

        let config = Config::get().await.unwrap();
        let task = Task::from_path(&config, &task_file, &tasks_dir, temp_dir.path())
            .await
            .unwrap();

        assert_eq!(task.description, "Test task with all fields");
        assert_eq!(task.aliases, vec!["alias1", "alias2"]);
        assert_eq!(task.depends.len(), 2);
        assert_eq!(task.depends_post.len(), 1);
        assert_eq!(task.wait_for.len(), 1);
        assert_eq!(task.dir, Some("/some/dir".to_string()));
        assert_eq!(task.hide, true);
        assert_eq!(task.raw, true);
        assert_eq!(task.interactive, true);
        assert_eq!(task.sources, vec!["src1.txt", "src2.txt"]);
        assert_eq!(task.shell, Some("bash -c".to_string()));
        assert_eq!(task.quiet, true);
        assert!(!task.tools.is_empty());
        assert_eq!(task.confirm, Some("Are you sure?".to_string()));

        let mut parsed_fields =
            take_captured_fields().expect("Parser fields should have been captured");

        // Group "alias" and "aliases" as they are alternate forms (count as 1)
        let has_alias = parsed_fields.iter().any(|k| k == "alias");
        parsed_fields.retain(|k| k != "aliases" || !has_alias);

        // Count property lines in script (exclude shebang and echo command)
        let script_lines = script_content.lines().count() - 2;

        assert_eq!(
            parsed_fields.len(),
            script_lines,
            "Parser looks for {} properties but test script has {} field lines.\n\
             If you added (or removed) parseable fields, add it to the test script.\n\
             Parser fields: {:?}",
            parsed_fields.len(),
            script_lines,
            parsed_fields
        );
    }

    #[tokio::test]
    #[cfg(unix)]
    async fn test_multi_line_tools_merge() {
        // Regression test for https://github.com/jdx/mise/discussions/7839
        // Multiple #MISE tools.X=Y lines should be merged into a single tools table
        use std::fs;
        use std::os::unix::fs::PermissionsExt;
        use tempfile::tempdir;

        let temp_dir = tempdir().unwrap();
        let tasks_dir = temp_dir.path().join("tasks");
        fs::create_dir(&tasks_dir).unwrap();
        let task_file = tasks_dir.join("multi-tools-task");

        // Create a file task with multiple tools on separate lines
        let script_content = r#"#!/usr/bin/env bash
#MISE tools.node="20"
#MISE tools.python="3.11"
#MISE tools.ruby="3.2"
echo "test"
"#;
        fs::write(&task_file, script_content).unwrap();
        fs::set_permissions(&task_file, std::fs::Permissions::from_mode(0o755)).unwrap();

        let config = Config::get().await.unwrap();
        let task = Task::from_path(&config, &task_file, &tasks_dir, temp_dir.path())
            .await
            .unwrap();

        // All three tools should be present
        assert_eq!(
            task.tools.len(),
            3,
            "Expected 3 tools, got: {:?}",
            task.tools
        );
        assert!(
            task.tools.contains_key("node"),
            "Expected 'node' in tools: {:?}",
            task.tools
        );
        assert!(
            task.tools.contains_key("python"),
            "Expected 'python' in tools: {:?}",
            task.tools
        );
        assert!(
            task.tools.contains_key("ruby"),
            "Expected 'ruby' in tools: {:?}",
            task.tools
        );
        assert_eq!(task.tools.get("node").unwrap(), "20");
        assert_eq!(task.tools.get("python").unwrap(), "3.11");
        assert_eq!(task.tools.get("ruby").unwrap(), "3.2");
    }

    #[tokio::test]
    #[cfg(unix)]
    async fn test_hyphenated_and_numeric_tool_names() {
        // Test that tool names with hyphens and numbers are parsed correctly
        // e.g., git-cliff, 1password
        use std::fs;
        use std::os::unix::fs::PermissionsExt;
        use tempfile::tempdir;

        let temp_dir = tempdir().unwrap();
        let tasks_dir = temp_dir.path().join("tasks");
        fs::create_dir(&tasks_dir).unwrap();
        let task_file = tasks_dir.join("hyphenated-tools-task");

        // Create a file task with hyphenated and numeric tool names
        let script_content = r#"#!/usr/bin/env bash
#MISE tools.git-cliff="1.0"
#MISE tools.1password-cli="2.0"
echo "test"
"#;
        fs::write(&task_file, script_content).unwrap();
        fs::set_permissions(&task_file, std::fs::Permissions::from_mode(0o755)).unwrap();

        let config = Config::get().await.unwrap();
        let task = Task::from_path(&config, &task_file, &tasks_dir, temp_dir.path())
            .await
            .unwrap();

        // Both tools should be present
        assert_eq!(
            task.tools.len(),
            2,
            "Expected 2 tools, got: {:?}",
            task.tools
        );
        assert!(
            task.tools.contains_key("git-cliff"),
            "Expected 'git-cliff' in tools: {:?}",
            task.tools
        );
        assert!(
            task.tools.contains_key("1password-cli"),
            "Expected '1password-cli' in tools: {:?}",
            task.tools
        );
        assert_eq!(task.tools.get("git-cliff").unwrap(), "1.0");
        assert_eq!(task.tools.get("1password-cli").unwrap(), "2.0");
    }

    #[test]
    fn test_get_matching_wildcard_does_not_match_parent() {
        use std::collections::BTreeMap;

        use super::GetMatchingExt;

        let mut tasks: BTreeMap<String, String> = BTreeMap::new();
        tasks.insert("test".to_string(), "test".to_string());
        tasks.insert("test:foo".to_string(), "test:foo".to_string());
        tasks.insert("test:bar".to_string(), "test:bar".to_string());

        // "test:*" should match "test:foo" and "test:bar" but NOT "test" itself
        let matches = tasks.get_matching("test:*").unwrap();
        assert_eq!(
            matches,
            vec![&"test:bar".to_string(), &"test:foo".to_string()]
        );

        // Bare name "test" should still match the "test" task (implicit wildcard)
        let matches = tasks.get_matching("test").unwrap();
        assert!(matches.contains(&&"test".to_string()));
    }

    #[test]
    fn test_get_matching_resolves_aliases() {
        use std::collections::BTreeMap;

        use super::GetMatchingExt;

        let mut tasks: BTreeMap<String, String> = BTreeMap::new();
        tasks.insert("pr:remove".to_string(), "pr:remove".to_string());
        tasks.insert("prr".to_string(), "pr:remove".to_string());

        let matches = tasks.get_matching("prr").unwrap();
        assert_eq!(matches, vec![&"pr:remove".to_string()]);

        let matches = tasks.get_matching("pr:remove").unwrap();
        assert_eq!(matches, vec![&"pr:remove".to_string()]);
    }

    #[test]
    fn test_get_matching_resolves_monorepo_aliases() {
        use std::collections::BTreeMap;

        use super::GetMatchingExt;

        let mut tasks: BTreeMap<String, String> = BTreeMap::new();
        tasks.insert("//:pr:remove".to_string(), "//:pr:remove".to_string());
        tasks.insert("//:prr".to_string(), "//:pr:remove".to_string());
        tasks.insert("prr".to_string(), "//:pr:remove".to_string());

        let matches = tasks.get_matching("//:prr").unwrap();
        assert_eq!(matches, vec![&"//:pr:remove".to_string()]);

        let matches = tasks.get_matching("prr").unwrap();
        assert_eq!(matches, vec![&"//:pr:remove".to_string()]);

        let matches = tasks.get_matching("//:pr:remove").unwrap();
        assert_eq!(matches, vec![&"//:pr:remove".to_string()]);
    }
}