pitchfork-cli 2.27.0

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

// Re-export config value types so existing `use crate::pitchfork_toml::X` paths keep working.
pub use crate::config_types::{
    CpuLimit, CronRetrigger, Dir, HealthCmd, HealthHttp, HealthPort, MemoryLimit, OnOutputHook,
    PitchforkTomlAuto, PitchforkTomlCron, PitchforkTomlHooks, PortBump, PortConfig, ProxyConfig,
    ProxyIdleTimeout, ProxyTlsMode, ReadyCmd, ReadyHttp, ReadyOutput, ReadyPort, Retry, StopConfig,
    StopSignal, WatchMode,
};

/// Raw slug entry as read from TOML (uses String for dir path).
/// Format in global config:
/// ```toml
/// [slugs]
/// api = { dir = "/home/user/my-api", daemon = "server" }
/// docs = { dir = "/home/user/docs-site" }  # daemon defaults to slug name
/// ```
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, JsonSchema)]
pub struct SlugEntryRaw {
    /// Project directory containing the pitchfork.toml
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dir: Option<String>,
    /// Namespace reference (alternative to dir)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<String>,
    /// Daemon name within that project (defaults to slug name if omitted)
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub daemon: Option<String>,
}

/// Resolved slug entry with PathBuf.
#[derive(Debug, Clone)]
pub struct SlugEntry {
    /// Project directory containing the pitchfork.toml
    pub dir: Option<PathBuf>,
    /// Namespace reference (alternative to dir)
    pub namespace: Option<String>,
    /// Daemon name within that project (defaults to slug name if omitted)
    pub daemon: Option<String>,
}

impl SlugEntry {
    /// Resolve the project directory.
    /// If `dir` is set, use it. Otherwise look up `namespace` in the global namespace registry.
    pub fn resolve_dir(&self) -> Option<PathBuf> {
        self.dir.clone().or_else(|| {
            self.namespace.as_ref().and_then(|ns| {
                let namespaces = PitchforkToml::read_global_namespaces();
                namespaces.get(ns).map(|entry| entry.dir.clone())
            })
        })
    }

    /// Resolve the namespace name.
    /// If `namespace` is set, use it. Otherwise derive from `dir` via `namespace_for_dir`.
    pub fn resolve_namespace(&self) -> Option<String> {
        self.namespace.clone().or_else(|| {
            self.resolve_dir()
                .and_then(|dir| PitchforkToml::namespace_for_dir(&dir).ok())
        })
    }
}

/// Raw group entry as read from TOML.
/// ```toml
/// [groups.backend]
/// daemons = ["api", "worker"]
/// ```
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, JsonSchema)]
pub struct GroupEntryRaw {
    #[schemars(with = "Vec<DaemonId>")]
    pub daemons: Vec<String>,
}

/// Resolved group entry with qualified DaemonIds.
#[derive(Debug, Clone)]
pub struct GroupEntry {
    pub daemons: Vec<DaemonId>,
}

/// Raw namespace entry as read from TOML.
/// ```toml
/// [namespaces.myproject]
/// dir = "/home/user/projects/myproject"
/// ```
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, JsonSchema)]
pub struct NamespaceEntryRaw {
    /// Project directory containing the pitchfork.toml
    pub dir: String,
    /// Additional configuration files, relative to dir or absolute.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub config: Vec<String>,
}

/// Resolved namespace entry with PathBuf.
#[derive(Debug, Clone)]
pub struct NamespaceEntry {
    /// Project directory containing the pitchfork.toml
    pub dir: PathBuf,
    pub config: Vec<PathBuf>,
}

/// Internal structure for reading config files (uses String keys for short daemon names)
#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
struct PitchforkTomlRaw {
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub namespace: Option<String>,
    /// Hostname label for this checkout when it is a linked git worktree.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub worktree_label: Option<String>,
    #[serde(default)]
    pub daemons: IndexMap<String, PitchforkTomlDaemonRaw>,
    /// Top-level environment variables applied to all daemons as defaults.
    /// Per-daemon `env` overrides these. Values support Tera templates.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub env: Option<IndexMap<String, String>>,
    #[serde(default)]
    pub settings: Option<SettingsPartial>,
    /// Slug registry (only meaningful in global config).
    /// Maps slug names to their configuration (dir + optional daemon name).
    #[serde(skip_serializing_if = "IndexMap::is_empty", default)]
    pub slugs: IndexMap<String, SlugEntryRaw>,
    /// Named groups of daemons for batch operations.
    #[serde(skip_serializing_if = "IndexMap::is_empty", default)]
    pub groups: IndexMap<String, GroupEntryRaw>,
    /// Namespace registry (only meaningful in global config).
    /// Maps namespace names to their project directory.
    #[serde(skip_serializing_if = "IndexMap::is_empty", default)]
    pub namespaces: IndexMap<String, NamespaceEntryRaw>,
}

/// Per-daemon log configuration sub-table `[daemons.<name>.logs]`.
///
/// Fields here override the top-level daemon fields (`time_retention`,
/// `line_retention`, `archive_hook`) and the global `[settings.logs]` defaults.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
pub struct PitchforkTomlDaemonLogs {
    /// Log line format: `json`, `logfmt`, or `text`.
    /// Defaults to `text` (no parsing).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub log_format: Option<String>,
    /// Maximum age of log entries to keep (e.g. "7d", "30d").
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub time_retention: Option<String>,
    /// Maximum number of log entries to keep per daemon.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub line_retention: Option<i64>,
    /// Archive hook command invoked before retention prunes this daemon's logs.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub archive_hook: Option<String>,
}

/// Internal daemon config for reading (uses String for depends).
///
/// Note: This struct mirrors `PitchforkTomlDaemon` but uses `Vec<String>` for `depends`
/// (before namespace resolution) and has serde attributes for TOML serialization.
/// When adding new fields, remember to update both structs and the conversion code
/// in `read()` and `write()`.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct PitchforkTomlDaemonRaw {
    pub run: String,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub auto: Vec<PitchforkTomlAuto>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub oneshot: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub cron: Option<PitchforkTomlCron>,
    #[serde(default)]
    pub retry: Retry,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub ready_delay: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub ready_output: Option<ReadyOutput>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub ready_http: Option<ReadyHttp>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub ready_port: Option<ReadyPort>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub ready_cmd: Option<ReadyCmd>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub health_cmd: Option<HealthCmd>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub health_http: Option<HealthHttp>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub health_port: Option<HealthPort>,
    /// New port configuration (preferred)
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub port: Option<PortConfig>,
    /// Proxy routing: `false` opts out, a string overrides the daemon's hostname label.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub proxy: Option<ProxyConfig>,
    /// Deprecated: use `port` instead
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub expected_port: Vec<u16>,
    /// Deprecated: use `port.bump` instead
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub auto_bump_port: Option<bool>,
    /// Deprecated: use `port.bump` instead
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub port_bump_attempts: Option<u32>,
    /// TLS handling for this daemon's proxy hostname: `terminate` or `passthrough`.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub proxy_tls: Option<ProxyTlsMode>,
    /// Which of the daemon's ports the proxy hostname maps to.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub proxy_tls_port: Option<u16>,
    /// Shorter spelling of `proxy_tls_port`. Never written back out, so a
    /// config that used it keeps one spelling rather than gaining both.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub proxy_port: Option<u16>,
    /// Stop after this long without proxy activity when the proxy started it.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub proxy_idle_timeout: Option<ProxyIdleTimeout>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub boot_start: Option<bool>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub depends: Vec<String>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub watch: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub watch_mode: Option<WatchMode>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub dir: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub env: Option<IndexMap<String, String>>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub hooks: Option<PitchforkTomlHooks>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub mise: Option<bool>,
    /// Unix user to run this daemon as.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub user: Option<String>,
    /// Memory limit for the daemon process (e.g. "50MB", "1GiB")
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub memory_limit: Option<MemoryLimit>,
    /// CPU usage limit as a percentage (e.g. 80 for 80%, 200 for 2 cores)
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub cpu_limit: Option<CpuLimit>,
    /// Unix signal to send for graceful shutdown (default: SIGTERM)
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub stop_signal: Option<StopConfig>,
    /// Allocate a pseudo-terminal for the daemon process.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub pty: Option<bool>,
    /// Maximum age of log entries to keep (e.g. "7d", "30d").
    /// Overrides the global `settings.logs.time_retention` when set.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub time_retention: Option<String>,
    /// Maximum number of log entries to keep per daemon.
    /// Overrides the global `settings.logs.line_retention` when set.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub line_retention: Option<i64>,
    /// Archive hook command invoked before retention prunes this daemon's logs.
    /// Overrides the global `settings.logs.archive_hook.command` when set.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub archive_hook: Option<String>,
    /// Per-daemon log configuration sub-table.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub logs: Option<PitchforkTomlDaemonLogs>,
}

/// Configuration schema for pitchfork.toml daemon supervisor configuration files.
///
/// Note: When read from a file, daemon keys are short names (e.g., "api").
/// After merging, keys become qualified DaemonIds (e.g., "project/api").
#[derive(Debug, Clone, Default, JsonSchema)]
#[schemars(title = "Pitchfork Configuration")]
pub struct PitchforkToml {
    /// Map of daemon IDs to their configurations
    #[serde(default)]
    pub daemons: IndexMap<DaemonId, PitchforkTomlDaemon>,
    /// Top-level environment variables applied to all daemons as defaults.
    /// Per-daemon `env` overrides these on key conflicts. Values support Tera
    /// templates (e.g. `{{ daemons.api.port }}`, `{{ settings.proxy.tld }}`).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub env: Option<IndexMap<String, String>>,
    /// Optional explicit namespace declared in this file.
    ///
    /// This applies to per-file read/write flows. Merged configs may contain
    /// daemons from multiple namespaces and leave this as `None`.
    pub namespace: Option<String>,
    /// Hostname label for this checkout when it is a linked git worktree.
    ///
    /// Overrides the worktree directory's name in proxy hostnames.
    #[schemars(default, with = "Option<String>")]
    pub worktree_label: Option<String>,
    /// Settings configuration (merged from all config files).
    ///
    /// **Note:** This field exists for serialization round-trips and for
    /// `PitchforkToml::merge()` to collect per-file overrides.  It is **not**
    /// consumed by the global `settings()` singleton, which is populated
    /// independently by `Settings::load()` to avoid a circular dependency
    /// between `PitchforkToml` and `Settings`.  Do not rely on mutations to
    /// this field being reflected in `settings()`.
    #[serde(default)]
    pub(crate) settings: SettingsPartial,
    /// Slug registry (merged from global config files).
    /// Maps slug names to their project directory and optional daemon name.
    /// Only populated from global config files (`~/.config/pitchfork/config.toml`
    /// or `/etc/pitchfork/config.toml`).
    #[schemars(default, with = "IndexMap<String, SlugEntryRaw>")]
    pub slugs: IndexMap<String, SlugEntry>,
    /// Named groups of daemons for batch operations.
    #[schemars(default, with = "IndexMap<String, GroupEntryRaw>")]
    pub groups: IndexMap<String, GroupEntry>,
    /// Namespace registry (merged from global config files).
    /// Maps namespace names to their project directory.
    #[schemars(default, with = "IndexMap<String, NamespaceEntryRaw>")]
    pub namespaces: IndexMap<String, NamespaceEntry>,
    #[schemars(skip)]
    pub path: Option<PathBuf>,
    /// Top-level `[env]` of the registered project each daemon merged in from
    /// another namespace came from, keyed by that daemon.
    ///
    /// Such a daemon renders against its own project's defaults, not those of
    /// the checkout that requested it. Daemons from the requesting checkout's
    /// own config chain are absent and use [`Self::env`], which carries every
    /// override along that chain.
    #[schemars(skip)]
    pub(crate) foreign_env: IndexMap<DaemonId, Option<IndexMap<String, String>>>,
}

impl PitchforkToml {
    /// The top-level `[env]` defaults `id` renders against: its own project's
    /// when it came from another registered project, otherwise this config's.
    pub(crate) fn env_for(&self, id: &DaemonId) -> Option<&IndexMap<String, String>> {
        self.foreign_env
            .get(id)
            .map_or(self.env.as_ref(), |env| env.as_ref())
    }
}

pub fn is_global_config(path: &Path) -> bool {
    path == *env::PITCHFORK_GLOBAL_CONFIG_USER || path == *env::PITCHFORK_GLOBAL_CONFIG_SYSTEM
}

pub(crate) fn is_dot_config_pitchfork(path: &Path) -> bool {
    path.ends_with(".config/pitchfork.toml") || path.ends_with(".config/pitchfork.local.toml")
}

fn parse_namespace_override_from_content(path: &Path, content: &str) -> Result<Option<String>> {
    use toml::Value;

    let doc: Value = toml::from_str(content)
        .map_err(|e| ConfigParseError::from_toml_error(path, content.to_string(), e))?;
    let Some(value) = doc.get("namespace") else {
        return Ok(None);
    };

    match value {
        Value::String(s) => Ok(Some(s.clone())),
        _ => Err(ConfigParseError::InvalidNamespace {
            path: path.to_path_buf(),
            namespace: value.to_string(),
            reason: "top-level 'namespace' must be a string".to_string(),
        }
        .into()),
    }
}

fn read_namespace_override_from_file(path: &Path) -> Result<Option<String>> {
    if !path.exists() {
        return Ok(None);
    }
    let content = std::fs::read_to_string(path).map_err(|e| FileError::ReadError {
        path: path.to_path_buf(),
        source: e,
    })?;
    parse_namespace_override_from_content(path, &content)
}

pub fn project_dir_for_config(path: &Path) -> Option<PathBuf> {
    crate::extra_configs::project_dir(path).or_else(|| {
        if is_dot_config_pitchfork(path) {
            path.parent().and_then(Path::parent).map(Path::to_path_buf)
        } else {
            path.parent().map(Path::to_path_buf)
        }
    })
}

fn project_config_family(path: &Path) -> Vec<PathBuf> {
    let Some(dir) = project_dir_for_config(path) else {
        return vec![path.to_path_buf()];
    };
    vec![
        dir.join(".config/pitchfork.toml"),
        dir.join(".config/pitchfork.local.toml"),
        dir.join("pitchfork.toml"),
        dir.join("pitchfork.local.toml"),
    ]
}

/// Resolve one namespace override shared by all project config files in a
/// directory. `content_override` represents unsaved content for `path`.
fn directory_namespace_override(
    path: &Path,
    content_override: Option<&str>,
) -> Result<Option<String>> {
    if is_global_config(path) {
        return match content_override {
            Some(content) => parse_namespace_override_from_content(path, content),
            None => read_namespace_override_from_file(path),
        };
    }

    let mut selected: Option<(String, PathBuf)> = None;
    for candidate in project_config_family(path) {
        let explicit = if candidate == path {
            match content_override {
                Some(content) => parse_namespace_override_from_content(&candidate, content)?,
                None => read_namespace_override_from_file(&candidate)?,
            }
        } else {
            read_namespace_override_from_file(&candidate)?
        };
        let Some(namespace) = explicit else { continue };
        if let Some((selected_namespace, selected_path)) = &selected
            && selected_namespace != &namespace
        {
            return Err(ConfigParseError::InvalidNamespace {
                path: candidate,
                namespace,
                reason: format!(
                    "namespace does not match directory-level namespace '{}' declared in {}",
                    selected_namespace,
                    selected_path.display()
                ),
            }
            .into());
        }
        selected = Some((namespace, candidate));
    }
    Ok(selected.map(|(namespace, _)| namespace))
}

fn validate_namespace(path: &Path, namespace: &str) -> Result<String> {
    if let Err(e) = DaemonId::try_new(namespace, "probe") {
        return Err(ConfigParseError::InvalidNamespace {
            path: path.to_path_buf(),
            namespace: namespace.to_string(),
            reason: e.to_string(),
        }
        .into());
    }
    Ok(namespace.to_string())
}

fn derive_namespace_from_dir(path: &Path) -> Result<String> {
    let dir_for_namespace = project_dir_for_config(path);
    if let Some(namespace) = dir_for_namespace
        .as_deref()
        .and_then(crate::extra_configs::namespace_for_dir)
    {
        return validate_namespace(path, &namespace);
    }
    let raw_namespace = dir_for_namespace
        .as_deref()
        .and_then(|p| p.file_name())
        .and_then(|n| n.to_str())
        .ok_or_else(|| miette::miette!("cannot derive namespace from path '{}'", path.display()))?
        .to_string();

    validate_namespace(path, &raw_namespace).map_err(|e| {
        ConfigParseError::InvalidNamespace {
            path: path.to_path_buf(),
            namespace: raw_namespace,
            reason: format!(
                "{e}. Set a valid top-level namespace, e.g. namespace = \"my-project\""
            ),
        }
        .into()
    })
}

fn namespace_from_path_with_override(path: &Path, explicit: Option<&str>) -> Result<String> {
    if is_global_config(path) {
        if let Some(ns) = explicit
            && ns != "global"
        {
            return Err(ConfigParseError::InvalidNamespace {
                path: path.to_path_buf(),
                namespace: ns.to_string(),
                reason: "global config files must use namespace 'global'".to_string(),
            }
            .into());
        }
        return Ok("global".to_string());
    }

    if let Some(ns) = explicit {
        return validate_namespace(path, ns);
    }

    derive_namespace_from_dir(path)
}

fn namespace_from_file(path: &Path) -> Result<String> {
    let explicit = directory_namespace_override(path, None)?;
    namespace_from_path_with_override(path, explicit.as_deref())
}

/// Extracts a namespace from a config file path.
///
/// - For user global config (`~/.config/pitchfork/config.toml`): returns "global"
/// - For system global config (`/etc/pitchfork/config.toml`): returns "global"
/// - For project configs: uses top-level `namespace` if present, otherwise parent directory name
///
/// Examples:
/// - `~/.config/pitchfork/config.toml` → `"global"`
/// - `/etc/pitchfork/config.toml` → `"global"`
/// - `/home/user/project-a/pitchfork.toml` → `"project-a"`
/// - `/home/user/project-b/sub/pitchfork.toml` → `"sub"`
/// - `/home/user/中文目录/pitchfork.toml` → error unless `namespace = "..."` is set
pub fn namespace_from_path(path: &Path) -> Result<String> {
    namespace_from_file(path)
}

/// Find the nearest ancestor directory of `dir` that contains a `.git` or
/// `.jj` marker (the project root of a git worktree / jj workspace).
///
/// Returns `None` when `dir` is not inside any git/jj project, so callers can
/// fall back to non-worktree behavior. In a linked git worktree, `.git` is a
/// *file* (not a directory) pointing at the common gitdir, so we check
/// existence rather than `is_dir()`.
fn find_project_root(dir: &Path) -> Option<PathBuf> {
    // Canonicalize the start dir so a symlinked path resolves into the
    // repository hierarchy before traversing parents; otherwise `parent()`
    // walks outside the repo and misses `.git`/`.jj`.
    let canonical_dir = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf());
    let mut current = canonical_dir.as_path();
    loop {
        if current.join(".git").exists() || current.join(".jj").exists() {
            return Some(current.to_path_buf());
        }
        current = current.parent()?;
    }
}

/// Cached result of `all_merged_from`, keyed by the cwd used to discover config paths.
///
/// The cache key is the canonical cwd `PathBuf`. The entry stores the merged
/// [`PitchforkToml`] plus a snapshot of every source file's (mtime, size) at
/// cache time. A cache hit requires the same set of paths with identical
/// mtimes **and** sizes.
///
/// Tracking size in addition to mtime catches timestamp-preserving content
/// changes (e.g. `cp --preserve=timestamps`, same-second edits on filesystems
/// with coarse mtime granularity like NFS) that mtime alone would miss.
///
/// **Known limitation**: an equal-size content replacement that also preserves
/// mtime will not be detected. This is an accepted trade-off — fully closing
/// this gap would require hashing file contents on every cache hit, negating
/// the I/O savings the cache exists to provide. In practice, editors and `git
/// pull` always change mtime, and `cp --preserve=timestamps` almost always
/// changes size. The `ReloadConfig` IPC handler (`settings reload`) serves as
/// an explicit escape hatch to force a full re-read when needed.
struct ConfigCacheEntry {
    config: PitchforkToml,
    /// (path, (mtime, size)) snapshot — order matches `list_paths_from` at cache time.
    source_meta: Vec<(PathBuf, Option<(SystemTime, u64)>)>,
}

/// Global config parse cache, keyed by canonical cwd.
///
/// Uses a `std::sync::Mutex` (not tokio) because config parsing is CPU-bound
/// and callers like `spawn_blocking(PitchforkToml::all_merged)` run outside
/// the async runtime. Contention is minimal: the mutex is held only for the
/// metadata comparison and the occasional re-read, not across I/O.
static CONFIG_CACHE: Lazy<StdMutex<HashMap<PathBuf, ConfigCacheEntry>>> =
    Lazy::new(|| StdMutex::new(HashMap::new()));

/// Compare a list of paths' current (mtime, size) against a cached snapshot.
///
/// Returns `true` if every path exists (or not) and has the same mtime and
/// size as when the snapshot was taken. Any difference — a new file, a deleted
/// file, a changed mtime, or a changed size — invalidates the cache.
fn meta_matches(paths: &[PathBuf], snapshot: &[(PathBuf, Option<(SystemTime, u64)>)]) -> bool {
    if paths.len() != snapshot.len() {
        return false;
    }
    paths
        .iter()
        .zip(snapshot.iter())
        .all(|(p, (snap_p, snap_meta))| p == snap_p && current_meta(p) == *snap_meta)
}

/// Best-effort (mtime, size) — `None` if the path doesn't exist or metadata fails.
pub(crate) fn current_meta(path: &Path) -> Option<(SystemTime, u64)> {
    let md = std::fs::metadata(path).ok()?;
    Some((md.modified().ok()?, md.len()))
}

/// Snapshot all (path, (mtime, size)) pairs for a list of paths.
fn snapshot_meta(paths: &[PathBuf]) -> Vec<(PathBuf, Option<(SystemTime, u64)>)> {
    paths.iter().map(|p| (p.clone(), current_meta(p))).collect()
}

/// Invalidate the entire config parse cache.
///
/// Called after any config file write (`write()`, `write_unlocked()`,
/// `add_slug_with_namespace()`, `remove_slug()`, `register_namespace()`,
/// `remove_namespace()`) so that subsequent `all_merged_from` calls re-read
/// from disk.
///
/// Also called by `settings reload` (via IPC `ReloadConfig`) so that external
/// edits to config files are picked up.
///
/// **Cross-process note**: CLI and supervisor are separate processes with
/// independent caches. When the CLI calls this after `write_unlocked()`, it
/// only clears the CLI's own cache (which is about to exit anyway). The
/// supervisor relies on mtime change detection to pick up CLI-written changes.
/// The `ReloadConfig` IPC handler is the one that matters — it clears the
/// supervisor's cache.
pub fn invalidate_config_cache() {
    crate::extra_configs::invalidate();
    // The web project pages keep their own parsed-group cache, validated the
    // same way, so it must be dropped here too.
    crate::web::routes::api::projects::invalidate_group_cache();
    if let Ok(mut cache) = CONFIG_CACHE.lock() {
        cache.clear();
    }
}

impl PitchforkToml {
    /// Resolves a user-provided daemon ID to qualified DaemonIds.
    ///
    /// If the ID is already qualified (contains '/'), parses and returns it.
    /// Otherwise, looks up the short ID in the config and returns
    /// matching qualified IDs.
    ///
    /// # Arguments
    /// * `user_id` - The daemon ID provided by the user
    ///
    /// # Returns
    /// A Result containing a vector of matching DaemonIds (usually one, but could be multiple
    /// if the same short ID exists in multiple namespaces), or an error if the ID is invalid.
    pub fn resolve_daemon_id(&self, user_id: &str) -> Result<Vec<DaemonId>> {
        // If already qualified, parse and return
        if user_id.contains('/') {
            return match DaemonId::parse(user_id) {
                Ok(id) => Ok(vec![id]),
                Err(e) => Err(e), // Invalid format - propagate error
            };
        }

        // Check for slug match in global slugs registry
        let global_slugs = Self::read_global_slugs();
        if let Some(entry) = global_slugs.get(user_id) {
            // Load the project's config from the slug's dir to find the daemon ID
            let daemon_name = entry.daemon.as_deref().unwrap_or(user_id);
            if let Some(dir) = entry.resolve_dir()
                && let Ok(project_config) = Self::all_merged_from(&dir)
            {
                // Find daemon by short name in that project
                let matches: Vec<DaemonId> = project_config
                    .daemons
                    .keys()
                    .filter(|id| id.name() == daemon_name)
                    .cloned()
                    .collect();
                match matches.as_slice() {
                    [] => {}
                    [id] => return Ok(vec![id.clone()]),
                    _ => {
                        let mut candidates: Vec<String> =
                            matches.iter().map(|id| id.qualified()).collect();
                        candidates.sort();
                        return Err(miette::miette!(
                            "slug '{}' maps to daemon '{}' which matches multiple daemons: {}",
                            user_id,
                            daemon_name,
                            candidates.join(", ")
                        ));
                    }
                }
            }
        }

        // Look for matching qualified IDs in the config
        let matches: Vec<DaemonId> = self
            .daemons
            .keys()
            .filter(|id| id.name() == user_id)
            .cloned()
            .collect();

        if matches.is_empty() {
            // No config matches. Search state file for any daemon with matching short name.
            let state_matches = Self::find_in_state_file(user_id);
            match state_matches.as_slice() {
                [] => {}
                [id] => return Ok(vec![id.clone()]),
                _ => {
                    let mut candidates: Vec<String> =
                        state_matches.iter().map(|id| id.qualified()).collect();
                    candidates.sort();
                    return Err(miette::miette!(
                        "daemon '{}' is ambiguous; matches: {}. Use a qualified daemon ID (namespace/name)",
                        user_id,
                        candidates.join(", ")
                    ));
                }
            }
            // No config or state matches. Validate short ID format and return no matches.
            let _ = DaemonId::try_new("global", user_id)?;
        }
        Ok(matches)
    }

    /// Finds all daemons in the persisted state file whose short name matches `short_name`.
    ///
    /// Logs a warning if the state file exists but cannot be read or parsed.
    ///
    /// Returns the matching `DaemonId`s. The caller must handle zero / one / many cases.
    fn find_in_state_file(short_name: &str) -> Vec<DaemonId> {
        match StateFile::read(&*env::PITCHFORK_STATE_FILE) {
            Ok(state) => state
                .daemons
                .keys()
                .filter(|id| id.name() == short_name)
                .cloned()
                .collect(),
            Err(e) => {
                warn!("cannot read state file: {e}");
                Vec::new()
            }
        }
    }

    /// Resolves a user-provided daemon ID to a qualified DaemonId, preferring the current directory's namespace.
    ///
    /// If the ID is already qualified (contains '/'), parses and returns it.
    /// Otherwise, tries to find a daemon in the current directory's namespace first.
    /// Falls back to any matching daemon if not found in current namespace.
    ///
    /// # Arguments
    /// * `user_id` - The daemon ID provided by the user
    /// * `current_dir` - The current working directory (used to determine namespace preference)
    ///
    /// # Returns
    /// The resolved DaemonId, or an error if the ID format is invalid
    ///
    /// # Errors
    /// Returns an error if `user_id` contains '/' but is not a valid qualified ID
    /// (e.g., "foo/bar/baz" with multiple slashes), or if `user_id` contains invalid characters.
    ///
    /// # Warnings
    /// If multiple daemons match the short name and none is in the current namespace,
    /// a warning is logged to stderr indicating the ambiguity.
    #[allow(dead_code)]
    pub fn resolve_daemon_id_prefer_local(
        &self,
        user_id: &str,
        current_dir: &Path,
    ) -> Result<DaemonId> {
        // If already qualified, parse and return (or error if invalid)
        if user_id.contains('/') {
            return DaemonId::parse(user_id);
        }

        // Determine the current directory's namespace by finding the nearest
        // pitchfork.toml. Cache the namespace in the caller when resolving
        // multiple IDs to avoid repeated filesystem traversal.
        let current_namespace = Self::namespace_for_dir(current_dir)?;

        self.resolve_daemon_id_with_namespace(user_id, &current_namespace)
    }

    /// Like `resolve_daemon_id_prefer_local` but accepts a pre-computed namespace,
    /// avoiding redundant filesystem traversal when resolving multiple IDs.
    fn resolve_daemon_id_with_namespace(
        &self,
        user_id: &str,
        current_namespace: &str,
    ) -> Result<DaemonId> {
        // Check for slug match in global slugs registry
        let global_slugs = Self::read_global_slugs();
        if let Some(entry) = global_slugs.get(user_id) {
            let daemon_name = entry.daemon.as_deref().unwrap_or(user_id);
            if let Some(dir) = entry.resolve_dir()
                && let Ok(project_config) = Self::all_merged_from(&dir)
            {
                let matches: Vec<DaemonId> = project_config
                    .daemons
                    .keys()
                    .filter(|id| id.name() == daemon_name)
                    .cloned()
                    .collect();
                match matches.as_slice() {
                    [] => {}
                    [id] => return Ok(id.clone()),
                    _ => {
                        let mut candidates: Vec<String> =
                            matches.iter().map(|id| id.qualified()).collect();
                        candidates.sort();
                        return Err(miette::miette!(
                            "slug '{}' maps to daemon '{}' which matches multiple daemons: {}",
                            user_id,
                            daemon_name,
                            candidates.join(", ")
                        ));
                    }
                }
            }
        }

        // Try to find the daemon in the current namespace first
        // Use try_new to validate user input
        let preferred_id = DaemonId::try_new(current_namespace, user_id)?;
        if self.daemons.contains_key(&preferred_id) {
            return Ok(preferred_id);
        }

        // Fall back to any matching daemon
        let matches = self.resolve_daemon_id(user_id)?;

        // Error on ambiguity instead of implicitly preferring global.
        if matches.len() > 1 {
            let mut candidates: Vec<String> = matches.iter().map(|id| id.qualified()).collect();
            candidates.sort();
            return Err(miette::miette!(
                "daemon '{}' is ambiguous; matches: {}. Use a qualified daemon ID (namespace/name)",
                user_id,
                candidates.join(", ")
            ));
        }

        if let Some(id) = matches.into_iter().next() {
            return Ok(id);
        }

        // If not found in current namespace or merged config matches, only fall back
        // to global when it is explicitly configured.
        let global_id = DaemonId::try_new("global", user_id)?;
        if self.daemons.contains_key(&global_id) {
            return Ok(global_id);
        }

        let suggestion = find_similar_daemon(user_id, self.daemons.keys().map(|id| id.name()));
        Err(DependencyError::DaemonNotFound {
            name: user_id.to_string(),
            suggestion,
        }
        .into())
    }

    /// Resolve a project's namespace even when it has no ordinary config file.
    pub fn namespace_for_project_dir(dir: &Path) -> Result<String> {
        namespace_from_path(&dir.join("pitchfork.toml"))
    }

    /// Return the `worktree_label` declared for this project, ignoring configs
    /// inherited from parent directories.
    ///
    /// This covers the project's own four config files and any external file
    /// registered to this directory with `pitchfork config add --dir`, which is
    /// where a generator such as mise writes its configuration. Later files win,
    /// matching the ordinary configuration precedence.
    pub fn project_worktree_label(dir: &Path) -> Option<String> {
        let mut label = None;
        let candidates = project_config_family(&dir.join("pitchfork.toml"))
            .into_iter()
            .chain(crate::extra_configs::configs_for_dir(dir));
        for candidate in candidates {
            if !candidate.exists() {
                continue;
            }
            if let Ok(pt) = Self::read(&candidate)
                && let Some(found) = pt.worktree_label
            {
                label = Some(found);
            }
        }
        label
    }

    /// Return the explicit namespace shared by this project's own configuration files.
    pub fn project_namespace_override(dir: &Path) -> Result<Option<String>> {
        directory_namespace_override(&dir.join("pitchfork.toml"), None)
    }

    /// Find the effective namespace from the nearest configuration file.
    pub fn namespace_for_dir(dir: &Path) -> Result<String> {
        Ok(Self::list_paths_from(dir)
            .iter()
            .filter(|p| p.exists())
            .max_by_key(|p| {
                if is_global_config(p) {
                    0
                } else {
                    project_dir_for_config(p).map_or(0, |dir| dir.components().count())
                }
            })
            .map(|p| namespace_from_path(p))
            .transpose()?
            .unwrap_or_else(|| "global".to_string()))
    }

    /// Convenience method: resolves a single user ID using the merged config and current directory.
    ///
    /// Equivalent to:
    /// ```ignore
    /// PitchforkToml::all_merged().resolve_daemon_id_prefer_local(user_id, &env::CWD)
    /// ```
    ///
    /// # Errors
    /// Returns an error if `user_id` contains '/' but is not a valid qualified ID
    pub fn resolve_id(user_id: &str) -> Result<DaemonId> {
        if user_id.contains('/') {
            return DaemonId::parse(user_id);
        }

        // Compute the namespace once and reuse it — avoids a second traversal
        // inside resolve_daemon_id_prefer_local.
        let config = Self::all_merged()?;
        let ns = Self::namespace_for_dir(&env::CWD)?;
        config.resolve_daemon_id_with_namespace(user_id, &ns)
    }

    /// Like `resolve_id`, but allows ad-hoc short IDs in the current directory's
    /// derived namespace.
    ///
    /// This is intended for commands such as `pitchfork run` that create
    /// managed daemons without requiring prior config entries.
    pub fn resolve_id_allow_adhoc(user_id: &str) -> Result<DaemonId> {
        Self::resolve_id_allow_adhoc_from(user_id, &env::CWD)
    }

    fn resolve_id_allow_adhoc_from(user_id: &str, dir: &Path) -> Result<DaemonId> {
        if user_id.contains('/') {
            return DaemonId::parse(user_id);
        }

        let ns = Self::namespace_for_dir(dir)?;
        DaemonId::try_new(ns, user_id)
    }

    /// Convenience method: resolves multiple user IDs using the merged config and current directory.
    ///
    /// Equivalent to:
    /// ```ignore
    /// let config = PitchforkToml::all_merged();
    /// ids.iter().map(|s| config.resolve_daemon_id_prefer_local(s, &env::CWD)).collect()
    /// ```
    ///
    /// # Errors
    /// Returns an error if any ID is malformed
    pub fn resolve_ids<S: AsRef<str>>(user_ids: &[S]) -> Result<Vec<DaemonId>> {
        // Fast path: all IDs are already qualified and can be parsed directly.
        if user_ids.iter().all(|s| s.as_ref().contains('/')) {
            return user_ids
                .iter()
                .map(|s| DaemonId::parse(s.as_ref()))
                .collect();
        }

        let config = Self::all_merged()?;
        // Compute namespace once for all IDs
        let ns = Self::namespace_for_dir(&env::CWD)?;
        user_ids
            .iter()
            .map(|s| {
                let id = s.as_ref();
                if id.contains('/') {
                    DaemonId::parse(id)
                } else {
                    config.resolve_daemon_id_with_namespace(id, &ns)
                }
            })
            .collect()
    }

    /// Resolve explicit daemon IDs and/or a group name into a deduplicated list of DaemonIds.
    ///
    /// This is more efficient than calling `resolve_ids` and `resolve_group` separately
    /// because it reads the merged config only once.
    pub fn resolve_ids_and_group<S: AsRef<str>>(
        user_ids: &[S],
        group_name: Option<&str>,
    ) -> Result<Vec<DaemonId>> {
        let config = Self::all_merged()?;
        let ns = Self::namespace_for_dir(&env::CWD)?;
        let mut ids = Vec::new();
        let mut seen = std::collections::HashSet::new();

        for id in user_ids {
            let id_str = id.as_ref();
            let daemon_id = if id_str.contains('/') {
                DaemonId::parse(id_str)?
            } else {
                config.resolve_daemon_id_with_namespace(id_str, &ns)?
            };
            if seen.insert(daemon_id.clone()) {
                ids.push(daemon_id);
            }
        }

        if let Some(name) = group_name {
            match config.groups.get(name) {
                Some(group) => {
                    let missing: Vec<String> = group
                        .daemons
                        .iter()
                        .filter(|id| !config.daemons.contains_key(*id))
                        .map(|id| id.qualified())
                        .collect();
                    if !missing.is_empty() {
                        return Err(miette::miette!(
                            "group '{}' references undefined daemon{}: {}",
                            name,
                            if missing.len() > 1 { "s" } else { "" },
                            missing.join(", ")
                        ));
                    }
                    for daemon_id in &group.daemons {
                        if seen.insert(daemon_id.clone()) {
                            ids.push(daemon_id.clone());
                        }
                    }
                }
                None => {
                    let suggestion =
                        find_similar_daemon(name, config.groups.keys().map(|s| s.as_str()));
                    return Err(miette::miette!(
                        "group '{}' not found in configuration{}",
                        name,
                        suggestion.map(|s| format!(", {s}")).unwrap_or_default()
                    ));
                }
            }
        }

        Ok(ids)
    }

    /// List all configuration file paths from the current working directory.
    /// See `list_paths_from` for details on the search order.
    pub fn list_paths() -> Vec<PathBuf> {
        Self::list_paths_from(&env::CWD)
    }

    /// List all configuration file paths starting from a given directory.
    ///
    /// Returns paths in order of precedence (lowest to highest):
    /// 1. System-level: /etc/pitchfork/config.toml
    /// 2. User-level: ~/.config/pitchfork/config.toml
    /// 3. Project-level: .config/pitchfork.toml, .config/pitchfork.local.toml, pitchfork.toml and pitchfork.local.toml files
    ///    from filesystem root to the given directory
    ///
    /// Within each directory, .config/ comes before pitchfork.toml,
    /// which comes before pitchfork.local.toml, so local.toml values override base config.
    pub fn list_paths_from(cwd: &Path) -> Vec<PathBuf> {
        let mut paths = Vec::new();
        paths.push(env::PITCHFORK_GLOBAL_CONFIG_SYSTEM.clone());
        paths.push(env::PITCHFORK_GLOBAL_CONFIG_USER.clone());

        // Find all project config files. Order is reversed so after .reverse():
        // - each directory has: .config/pitchfork.toml < .config/pitchfork.local.toml < pitchfork.toml < pitchfork.local.toml
        // - directories go from root to cwd (later configs override earlier)
        let mut project_paths = xx::file::find_up_all(
            cwd,
            &[
                "pitchfork.local.toml",
                "pitchfork.toml",
                ".config/pitchfork.local.toml",
                ".config/pitchfork.toml",
            ],
        );
        project_paths.reverse();
        paths.extend(project_paths);
        paths.extend(crate::extra_configs::paths_for(cwd));

        paths
    }

    /// Merge all configuration files from the current working directory.
    /// See `all_merged_from` for details.
    pub fn all_merged() -> Result<PitchforkToml> {
        Self::all_merged_from(&env::CWD)
    }
    /// Load all merged config including daemons from ALL registered namespaces.
    ///
    /// Unlike `all_merged_from` which only merges configs from the cwd chain,
    /// this also iterates all `[namespaces]` entries and loads their daemon configs.
    /// Use this when you need a complete view (e.g. `start` for a daemon from
    /// another namespace).
    pub fn all_merged_all_namespaces() -> Result<Self> {
        Self::all_merged_all_namespaces_from(&env::CWD)
    }

    /// Core of [`Self::all_merged_all_namespaces`], parameterized by the
    /// starting directory so it is testable without touching the global `CWD`.
    pub(crate) fn all_merged_all_namespaces_from(start_dir: &Path) -> Result<Self> {
        let mut pt = Self::all_merged_from(start_dir)?;

        let namespaces = Self::read_global_namespaces();
        for (ns_name, entry) in namespaces {
            match Self::all_merged_from(&entry.dir) {
                Ok(ns_config) => {
                    for (daemon_id, daemon_config) in ns_config.daemons {
                        if !pt.daemons.contains_key(&daemon_id) {
                            pt.foreign_env
                                .insert(daemon_id.clone(), ns_config.env.clone());
                            pt.daemons.insert(daemon_id, daemon_config);
                        }
                    }
                    // Merge namespace-level settings so daemon-local
                    // overrides (e.g. hooks, env defaults) are available.
                    pt.settings.merge_from(&ns_config.settings);
                }
                Err(e) => {
                    log::warn!(
                        "Failed to load namespace '{ns_name}' from {}: {e}",
                        entry.dir.display()
                    );
                }
            }
        }

        // Auto-discover git worktrees / jj workspaces under the current
        // project, so daemons defined in a worktree are visible to supervisor
        // background tasks (cron registration, boot_start, file watch) even
        // when that worktree's namespace was never registered in
        // `[namespaces]`. Discovery spawns a `git`/`jj` subprocess (<1ms) and
        // the per-worktree config reads are cached by `CONFIG_CACHE`, so no
        // extra caching layer is needed here.
        // Controlled by the global setting so disabling worktrees affects both config
        // discovery and proxy slug routing.
        if crate::settings::settings().general.worktree
            && let Some(project_root) = find_project_root(start_dir)
        {
            let worktrees = crate::proxy::worktree::discover_worktrees(&project_root);
            for wt in &worktrees {
                match Self::all_merged_from(&wt.path) {
                    Ok(wt_config) => {
                        for (daemon_id, daemon_config) in wt_config.daemons {
                            if !pt.daemons.contains_key(&daemon_id) {
                                pt.daemons.insert(daemon_id, daemon_config);
                            }
                        }
                        pt.settings.merge_from(&wt_config.settings);
                    }
                    Err(e) => {
                        log::warn!(
                            "Failed to load worktree '{}' config from {}: {e}",
                            wt.branch,
                            wt.path.display()
                        );
                    }
                }
            }
        }

        Ok(pt)
    }

    /// Merge all configuration files starting from a given directory.
    ///
    /// Reads and merges configuration files in precedence order.
    /// Each daemon ID is qualified with a namespace based on its config file location:
    /// - Global configs (`~/.config/pitchfork/config.toml`) use namespace "global"
    /// - Project configs use the parent directory name as namespace
    ///
    /// This prevents ID conflicts when multiple projects define daemons with the same name.
    ///
    /// Results are cached by cwd and invalidated when any source file's mtime
    /// changes or when [`invalidate_config_cache`] is called (e.g. after a
    /// config write via `write()` / `write_unlocked()`).
    ///
    /// # Errors
    /// Returns an error if any config file fails to parse. Aborts with an error
    /// if two *different* project config files produce the same namespace (e.g. two
    /// `pitchfork.toml` files in separate directories that share the same directory name).
    pub fn all_merged_from(cwd: &Path) -> Result<PitchforkToml> {
        let paths = Self::list_paths_from(cwd);

        // Fast path: check the cache under a short-lived lock.
        // We canonicalize cwd for a stable key. If canonicalization fails
        // (e.g. the directory was just deleted), fall back to the raw path.
        let cache_key = cwd.canonicalize().unwrap_or_else(|_| cwd.to_path_buf());

        {
            let cache = CONFIG_CACHE.lock().unwrap_or_else(|e| e.into_inner());
            if let Some(entry) = cache.get(&cache_key)
                && meta_matches(&paths, &entry.source_meta)
            {
                return Ok(entry.config.clone());
            }
        }

        // Cache miss: snapshot (mtime, size) BEFORE reading.
        // If a file changes during the read, the snapshot (old mtime/size) won't
        // match the current values on the next call, forcing a re-read.
        // Taking the snapshot after the read would store old content with new
        // metadata, serving stale data indefinitely.
        let snapshot = snapshot_meta(&paths);
        let pt = Self::all_merged_from_uncached(&paths)?;

        // Store in cache.
        let mut cache = CONFIG_CACHE.lock().unwrap_or_else(|e| e.into_inner());
        cache.insert(
            cache_key,
            ConfigCacheEntry {
                config: pt.clone(),
                source_meta: snapshot,
            },
        );

        Ok(pt)
    }

    /// Uncached merge of all configuration files from a list of paths.
    ///
    /// This is the original merge logic extracted from `all_merged_from` so that
    /// the cache layer can wrap it without duplicating the algorithm.
    fn all_merged_from_uncached(paths: &[PathBuf]) -> Result<PitchforkToml> {
        use std::collections::HashMap as StdHashMap;

        let mut ns_to_origin: StdHashMap<String, (PathBuf, PathBuf)> = StdHashMap::new();

        let mut pt = Self::default();
        for p in paths {
            match Self::read(p) {
                Ok(pt2) => {
                    // Detect collisions for all existing project configs, including
                    // pitchfork.local.toml. Allow sibling base/local files in the same
                    // directory to share a namespace, including siblings via .config subfolder
                    if p.exists() && !is_global_config(p) {
                        let ns = namespace_from_path(p)?;
                        let origin_dir = project_dir_for_config(p)
                            .map(|dir| dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf()))
                            .unwrap_or_else(|| p.clone());

                        if let Some((other_path, other_dir)) = ns_to_origin.get(ns.as_str())
                            && *other_dir != origin_dir
                        {
                            return Err(crate::error::ConfigParseError::NamespaceCollision {
                                path_a: other_path.clone(),
                                path_b: p.clone(),
                                ns,
                            }
                            .into());
                        }
                        ns_to_origin.insert(ns, (p.clone(), origin_dir));
                    }

                    pt.merge(pt2)
                }
                Err(e) => return Err(e.wrap_err(format!("error reading {}", p.display()))),
            }
        }
        Ok(pt)
    }
}

impl PitchforkToml {
    pub fn new(path: PathBuf) -> Self {
        Self {
            daemons: Default::default(),
            env: None,
            namespace: None,
            worktree_label: None,
            settings: SettingsPartial::default(),
            slugs: IndexMap::new(),
            groups: IndexMap::new(),
            namespaces: IndexMap::new(),
            path: Some(path),
            foreign_env: IndexMap::new(),
        }
    }

    /// Parse TOML content as a [`PitchforkToml`] without touching the filesystem.
    ///
    /// Applies the same namespace derivation and daemon validation as [`read()`] but
    /// uses the provided `content` directly instead of reading from disk.  `path` is
    /// used only for namespace derivation and error messages.
    ///
    /// This is useful for validating user-edited content before saving it.
    pub fn parse_str(content: &str, path: &Path) -> Result<Self> {
        let mut raw_config: PitchforkTomlRaw = toml::from_str(content)
            .map_err(|e| ConfigParseError::from_toml_error(path, content.to_string(), e))?;
        if let Some(settings) = &mut raw_config.settings {
            settings.canonicalize_aliases();
        }

        let explicit = directory_namespace_override(path, Some(content))?;
        let namespace = namespace_from_path_with_override(path, explicit.as_deref())?;
        let mut pt = Self::new(path.to_path_buf());
        pt.namespace = raw_config.namespace.clone();
        pt.worktree_label = raw_config.worktree_label.clone();

        for (short_name, raw_daemon) in raw_config.daemons {
            let id = match DaemonId::try_new(&namespace, &short_name) {
                Ok(id) => id,
                Err(e) => {
                    return Err(ConfigParseError::InvalidDaemonName {
                        name: short_name,
                        path: path.to_path_buf(),
                        reason: e.to_string(),
                    }
                    .into());
                }
            };

            let mut depends = Vec::new();
            for dep in raw_daemon.depends {
                let dep_id = if dep.contains('/') {
                    match DaemonId::parse(&dep) {
                        Ok(id) => id,
                        Err(e) => {
                            return Err(ConfigParseError::InvalidDependency {
                                daemon: short_name.clone(),
                                dependency: dep,
                                path: path.to_path_buf(),
                                reason: e.to_string(),
                            }
                            .into());
                        }
                    }
                } else {
                    match DaemonId::try_new(&namespace, &dep) {
                        Ok(id) => id,
                        Err(e) => {
                            return Err(ConfigParseError::InvalidDependency {
                                daemon: short_name.clone(),
                                dependency: dep,
                                path: path.to_path_buf(),
                                reason: e.to_string(),
                            }
                            .into());
                        }
                    }
                };
                depends.push(dep_id);
            }

            // Resolve port config: prefer new `port` field, fall back to deprecated fields
            let has_deprecated = !raw_daemon.expected_port.is_empty()
                || raw_daemon.auto_bump_port.is_some()
                || raw_daemon.port_bump_attempts.is_some();
            let port = if let Some(port) = raw_daemon.port {
                if has_deprecated {
                    warn!(
                        "daemon {short_name}: both `port` and deprecated expected_port/auto_bump_port/port_bump_attempts are set; ignoring deprecated fields"
                    );
                }
                Some(port)
            } else if has_deprecated {
                warn!(
                    "daemon {short_name}: expected_port/auto_bump_port/port_bump_attempts are deprecated, use [daemons.{short_name}.port] instead"
                );
                let bump = if raw_daemon.auto_bump_port.unwrap_or(false) {
                    PortBump(
                        raw_daemon
                            .port_bump_attempts
                            .unwrap_or_else(|| settings().default_port_bump_attempts()),
                    )
                } else {
                    PortBump(0)
                };
                Some(PortConfig {
                    expect: raw_daemon.expected_port,
                    bump,
                })
            } else {
                None
            };

            // `proxy_port` is the shorter spelling of the same setting.
            if let (Some(explicit), Some(short)) =
                (raw_daemon.proxy_tls_port, raw_daemon.proxy_port)
                && explicit != short
            {
                warn!(
                    "daemon {short_name}: proxy_tls_port ({explicit}) and proxy_port ({short}) \
                     disagree; using proxy_tls_port"
                );
            }
            let proxy_tls_port = raw_daemon.proxy_tls_port.or(raw_daemon.proxy_port);

            // Port 0 asks the operating system to choose, so it names no port
            // a hostname can be sent to.
            for (key, value) in [
                ("proxy_tls_port", raw_daemon.proxy_tls_port),
                ("proxy_port", raw_daemon.proxy_port),
            ] {
                if value == Some(0) {
                    return Err(ConfigParseError::ProxyPortZero {
                        daemon: short_name.clone(),
                        key,
                        path: path.to_path_buf(),
                    }
                    .into());
                }
            }

            // The hostname maps to one of the daemon's own ports, so a port it
            // never declares cannot be routed to.
            if let Some(port_want) = proxy_tls_port {
                let declared = port.as_ref().map(|p| p.expect.clone()).unwrap_or_default();
                if !declared.contains(&port_want) {
                    return Err(ConfigParseError::ProxyPortNotDeclared {
                        daemon: short_name.clone(),
                        port: port_want,
                        declared,
                        path: path.to_path_buf(),
                    }
                    .into());
                }
            }

            // TLS passthrough splices the raw stream to 127.0.0.1:<port>, so a
            // daemon without a known port has nothing to splice to.
            if raw_daemon
                .proxy_tls
                .is_some_and(ProxyTlsMode::is_passthrough)
                && port
                    .as_ref()
                    .is_none_or(|p| p.expect.iter().all(|&port| port == 0))
            {
                return Err(ConfigParseError::PassthroughWithoutPort {
                    daemon: short_name.clone(),
                    path: path.to_path_buf(),
                }
                .into());
            }

            let daemon = PitchforkTomlDaemon {
                run: raw_daemon.run,
                auto: raw_daemon.auto,
                oneshot: raw_daemon.oneshot,
                cron: raw_daemon.cron,
                retry: raw_daemon.retry,
                ready_delay: raw_daemon.ready_delay,
                ready_output: raw_daemon.ready_output,
                ready_http: raw_daemon.ready_http,
                ready_port: raw_daemon.ready_port,
                ready_cmd: raw_daemon.ready_cmd,
                health_cmd: raw_daemon.health_cmd,
                health_http: raw_daemon.health_http,
                health_port: raw_daemon.health_port,
                port,
                proxy: raw_daemon.proxy,
                proxy_tls: raw_daemon.proxy_tls,
                proxy_tls_port: raw_daemon.proxy_tls_port,
                proxy_port: raw_daemon.proxy_port,
                proxy_idle_timeout: raw_daemon.proxy_idle_timeout,
                boot_start: raw_daemon.boot_start,
                depends,
                watch: raw_daemon.watch,
                watch_mode: raw_daemon.watch_mode.unwrap_or_default(),
                dir: raw_daemon.dir,
                env: raw_daemon.env,
                hooks: raw_daemon.hooks,
                mise: raw_daemon.mise,
                user: raw_daemon.user,
                memory_limit: raw_daemon.memory_limit,
                cpu_limit: raw_daemon.cpu_limit,
                stop_signal: raw_daemon.stop_signal,
                pty: raw_daemon.pty,
                time_retention: raw_daemon.time_retention,
                line_retention: raw_daemon.line_retention,
                archive_hook: raw_daemon.archive_hook,
                logs: raw_daemon.logs,
                path: Some(path.to_path_buf()),
            };
            if daemon.is_oneshot() {
                let conflicts = daemon.oneshot_conflicts();
                if !conflicts.is_empty() {
                    return Err(ConfigParseError::OneshotConflict {
                        daemon: short_name.clone(),
                        path: path.to_path_buf(),
                        conflicts: conflicts.into_iter().map(str::to_string).collect(),
                    }
                    .into());
                }
            }
            pt.daemons.insert(id, daemon);
        }

        // Copy settings if present
        if let Some(settings) = raw_config.settings {
            pt.settings = settings;
        }

        // Copy top-level env
        pt.env = raw_config.env;

        // Copy slugs registry (only meaningful in global config files)
        for (slug, entry) in raw_config.slugs {
            pt.slugs.insert(
                slug,
                SlugEntry {
                    dir: entry.dir.map(env::expand_tilde),
                    namespace: entry.namespace,
                    daemon: entry.daemon,
                },
            );
        }

        // Copy namespaces registry (only meaningful in global config files)
        for (name, entry) in raw_config.namespaces {
            pt.namespaces.insert(
                name,
                NamespaceEntry {
                    config: entry
                        .config
                        .iter()
                        .map(|p| {
                            crate::extra_configs::resolve_path(&env::expand_tilde(&entry.dir), p)
                        })
                        .collect(),
                    dir: env::expand_tilde(entry.dir),
                },
            );
        }

        // Resolve group entries: convert short daemon names to qualified DaemonIds
        for (group_name, raw_group) in raw_config.groups {
            let mut daemons = Vec::new();
            for daemon_name in &raw_group.daemons {
                let id = if daemon_name.contains('/') {
                    DaemonId::parse(daemon_name).map_err(|e| {
                        ConfigParseError::InvalidDependency {
                            daemon: group_name.clone(),
                            dependency: daemon_name.clone(),
                            path: path.to_path_buf(),
                            reason: e.to_string(),
                        }
                    })?
                } else {
                    DaemonId::try_new(&namespace, daemon_name).map_err(|e| {
                        ConfigParseError::InvalidDaemonName {
                            name: daemon_name.clone(),
                            path: path.to_path_buf(),
                            reason: e.to_string(),
                        }
                    })?
                };
                daemons.push(id);
            }
            pt.groups.insert(group_name, GroupEntry { daemons });
        }

        Ok(pt)
    }

    pub fn read<P: AsRef<Path>>(path: P) -> Result<Self> {
        let path = path.as_ref();
        if !path.exists() {
            return Ok(Self::new(path.to_path_buf()));
        }
        let _lock = xx::fslock::get(path, false)
            .wrap_err_with(|| format!("failed to acquire lock on {}", path.display()))?;
        let raw = std::fs::read_to_string(path).map_err(|e| FileError::ReadError {
            path: path.to_path_buf(),
            source: e,
        })?;
        Self::parse_str(&raw, path)
    }

    pub fn write(&self) -> Result<()> {
        if let Some(path) = &self.path {
            let _lock = xx::fslock::get(path, false)
                .wrap_err_with(|| format!("failed to acquire lock on {}", path.display()))?;
            self.write_unlocked()
        } else {
            Err(FileError::NoPath.into())
        }
    }

    /// Write the config file without acquiring a file lock.
    ///
    /// The caller MUST hold the file lock (via `xx::fslock::get`) before
    /// calling this method. This is used by `register_slug` which needs to
    /// hold a single lock across a read-modify-write cycle.
    pub(crate) fn write_unlocked(&self) -> Result<()> {
        if let Some(path) = &self.path {
            // Determine the namespace for this config file
            let config_namespace = if path.exists() {
                namespace_from_path(path)?
            } else {
                namespace_from_path_with_override(path, self.namespace.as_deref())?
            };

            // Convert back to raw format for writing (use short names as keys)
            // Preserve settings so read-modify-write (e.g. `settings set`, `proxy add`)
            // doesn't drop `[settings.*]`. Gate on is_empty to avoid a bare `[settings]`.
            let mut raw = PitchforkTomlRaw {
                namespace: self.namespace.clone(),
                worktree_label: self.worktree_label.clone(),
                env: self.env.clone(),
                settings: (!self.settings.is_empty()).then(|| self.settings.clone()),
                ..PitchforkTomlRaw::default()
            };
            for (id, daemon) in &self.daemons {
                if id.namespace() != config_namespace {
                    return Err(miette::miette!(
                        "cannot write daemon '{}' to {}: daemon belongs to namespace '{}' but file namespace is '{}'",
                        id,
                        path.display(),
                        id.namespace(),
                        config_namespace
                    ));
                }
                let port = daemon.port.as_ref();
                let raw_daemon = PitchforkTomlDaemonRaw {
                    run: daemon.run.clone(),
                    auto: daemon.auto.clone(),
                    oneshot: daemon.oneshot,
                    cron: daemon.cron.clone(),
                    retry: daemon.retry,
                    ready_delay: daemon.ready_delay,
                    ready_output: daemon.ready_output.clone(),
                    ready_http: daemon.ready_http.clone(),
                    ready_port: daemon.ready_port.clone(),
                    ready_cmd: daemon.ready_cmd.clone(),
                    health_cmd: daemon.health_cmd.clone(),
                    health_http: daemon.health_http.clone(),
                    health_port: daemon.health_port.clone(),
                    port: port.cloned(),
                    proxy: daemon.proxy.clone(),
                    proxy_tls: daemon.proxy_tls,
                    proxy_tls_port: daemon.proxy_tls_port,
                    proxy_port: daemon.proxy_port,
                    proxy_idle_timeout: daemon.proxy_idle_timeout,
                    // Deprecated fields: written for backward compatibility with older pitchfork versions
                    expected_port: port.map(|p| p.expect.clone()).unwrap_or_default(),
                    auto_bump_port: port.filter(|p| p.auto_bump()).map(|_| true),
                    port_bump_attempts: port
                        .filter(|p| p.auto_bump())
                        .map(|p| p.max_bump_attempts()),
                    boot_start: daemon.boot_start,
                    // Preserve cross-namespace dependencies: use qualified ID if namespace differs,
                    // otherwise use short name
                    depends: daemon
                        .depends
                        .iter()
                        .map(|d| {
                            if d.namespace() == config_namespace {
                                d.name().to_string()
                            } else {
                                d.qualified()
                            }
                        })
                        .collect(),
                    watch: daemon.watch.clone(),
                    watch_mode: match daemon.watch_mode {
                        WatchMode::Native => None,
                        mode => Some(mode),
                    },
                    dir: daemon.dir.clone(),
                    env: daemon.env.clone(),
                    hooks: daemon.hooks.clone(),
                    mise: daemon.mise,
                    user: daemon.user.clone(),
                    memory_limit: daemon.memory_limit,
                    cpu_limit: daemon.cpu_limit,
                    stop_signal: daemon.stop_signal,
                    pty: daemon.pty,
                    time_retention: daemon.time_retention.clone(),
                    line_retention: daemon.line_retention,
                    archive_hook: daemon.archive_hook.clone(),
                    logs: daemon.logs.clone(),
                };
                raw.daemons.insert(id.name().to_string(), raw_daemon);
            }

            // Copy slugs registry to raw format
            for (slug, entry) in &self.slugs {
                raw.slugs.insert(
                    slug.clone(),
                    SlugEntryRaw {
                        dir: entry.dir.as_ref().map(|d| d.to_string_lossy().to_string()),
                        namespace: entry.namespace.clone(),
                        daemon: entry.daemon.clone(),
                    },
                );
            }

            // Serialize groups back to raw format (preserve cross-namespace refs as qualified IDs)
            for (name, group) in &self.groups {
                let raw_daemons: Vec<String> = group
                    .daemons
                    .iter()
                    .map(|id| {
                        if id.namespace() == config_namespace {
                            id.name().to_string()
                        } else {
                            id.qualified()
                        }
                    })
                    .collect();
                raw.groups.insert(
                    name.clone(),
                    GroupEntryRaw {
                        daemons: raw_daemons,
                    },
                );
            }

            // Copy namespaces registry to raw format
            for (name, entry) in &self.namespaces {
                raw.namespaces.insert(
                    name.clone(),
                    NamespaceEntryRaw {
                        dir: entry.dir.to_string_lossy().to_string(),
                        config: entry
                            .config
                            .iter()
                            .map(|p| p.to_string_lossy().into_owned())
                            .collect(),
                    },
                );
            }

            let raw_str = toml::to_string(&raw).map_err(|e| FileError::SerializeError {
                path: path.clone(),
                source: e,
            })?;
            xx::file::write(path, &raw_str).map_err(|e| FileError::WriteError {
                path: path.clone(),
                details: Some(e.to_string()),
            })?;
            invalidate_config_cache();
            Ok(())
        } else {
            Err(FileError::NoPath.into())
        }
    }

    /// Simple merge without namespace re-qualification.
    /// Used primarily for testing or when merging configs from the same namespace.
    /// Since read() already qualifies daemon IDs with namespace, this just inserts them.
    /// Settings are also merged - later values override earlier ones.
    pub fn merge(&mut self, pt: Self) {
        if pt.worktree_label.is_some() {
            self.worktree_label = pt.worktree_label.clone();
        }
        for (id, d) in pt.daemons {
            self.daemons.insert(id, d);
        }
        // Merge top-level env - pt's values override self's values
        if let Some(env) = pt.env {
            let merged = self.env.get_or_insert_with(IndexMap::new);
            for (k, v) in env {
                merged.insert(k, v);
            }
        }
        // Merge slugs - pt's values override self's values
        for (slug, entry) in pt.slugs {
            self.slugs.insert(slug, entry);
        }
        // Merge groups - pt's values override self's values
        for (name, group) in pt.groups {
            self.groups.insert(name, group);
        }
        // Merge namespaces - pt's values override self's values
        for (name, entry) in pt.namespaces {
            self.namespaces.insert(name, entry);
        }
        // Merge settings - pt's values override self's values
        self.settings.merge_from(&pt.settings);
    }

    /// Read the global slug registry from the user-level global config.
    ///
    /// Returns a map of slug → SlugEntry from `[slugs]` in
    /// `~/.config/pitchfork/config.toml`.
    pub fn read_global_slugs() -> IndexMap<String, SlugEntry> {
        match Self::read(&*env::PITCHFORK_GLOBAL_CONFIG_USER) {
            Ok(pt) => pt.slugs,
            Err(_) => IndexMap::new(),
        }
    }

    /// Whether more than one registry key folds to `slug`'s ASCII-lowercased form.
    ///
    /// Host names are case-insensitive (RFC 4343), so the proxy refuses to route
    /// such a slug at all rather than pick one of the spellings.  Callers that
    /// turn a slug into a URL must not advertise an address the proxy will
    /// reject, so they check this first.
    pub fn slug_is_ambiguous(slug: &str, global_slugs: &IndexMap<String, SlugEntry>) -> bool {
        global_slugs
            .keys()
            .filter(|k| k.eq_ignore_ascii_case(slug))
            .count()
            > 1
    }

    /// Find the registered slug for a daemon using a pre-loaded slug registry.
    ///
    /// Returns `None` for a slug the proxy will not route — see
    /// [`Self::slug_is_ambiguous`].
    pub fn find_slug_for_daemon_in_registry(
        daemon_id: &DaemonId,
        global_slugs: &IndexMap<String, SlugEntry>,
    ) -> Option<String> {
        global_slugs
            .iter()
            .find(|(slug, entry)| {
                let daemon_name = entry.daemon.as_deref().unwrap_or(slug);
                if daemon_id.name() != daemon_name {
                    return false;
                }

                // Skipped rather than returned and discarded: another alias for
                // the same daemon may still be routable.
                if Self::slug_is_ambiguous(slug, global_slugs) {
                    return false;
                }

                match entry.resolve_namespace() {
                    Some(namespace) => daemon_id.namespace() == namespace,
                    None => false,
                }
            })
            .map(|(slug, _)| slug.clone())
    }

    /// Check if a slug is registered in the global config's `[slugs]` section.
    #[allow(dead_code)]
    pub fn is_slug_registered(slug: &str) -> bool {
        Self::read_global_slugs().contains_key(slug)
    }

    /// Add a slug entry to the global config's `[slugs]` section using namespace instead of dir.
    ///
    /// Reads the global config, adds/updates the slug entry, and writes it back.
    /// If `namespace` is provided but not yet registered in `[namespaces]`,
    /// also registers it at `dir` (acquired via `resolve_dir()` on the slug entry).
    pub fn add_slug_with_namespace(
        slug: &str,
        namespace: Option<&str>,
        daemon: Option<&str>,
    ) -> Result<()> {
        let global_path = &*env::PITCHFORK_GLOBAL_CONFIG_USER;

        // Ensure the config directory exists
        if let Some(parent) = global_path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| {
                miette::miette!(
                    "Failed to create config directory {}: {e}",
                    parent.display()
                )
            })?;
        }

        let _lock = xx::fslock::get(global_path, false)
            .wrap_err_with(|| format!("failed to acquire lock on {}", global_path.display()))?;

        let mut pt = if global_path.exists() {
            let raw = std::fs::read_to_string(global_path).map_err(|e| FileError::ReadError {
                path: global_path.to_path_buf(),
                source: e,
            })?;
            Self::parse_str(&raw, global_path)?
        } else {
            Self::new(global_path.to_path_buf())
        };

        // If caller provided a namespace that isn't yet registered,
        // auto-register it at the directory we can resolve.
        // Falls back to CWD if the slug dir cannot be resolved.
        if let Some(ns) = namespace
            && !pt.namespaces.contains_key(ns)
        {
            // Resolve against the already-parsed `pt` instead of
            // SlugEntry::resolve_dir(): that re-reads the global config via
            // read(), which would re-acquire the lock held above (flock is per
            // open file description, so the same process deadlocks on itself).
            let dir = pt
                .slugs
                .get(slug)
                .and_then(|e| {
                    e.dir.clone().or_else(|| {
                        e.namespace
                            .as_ref()
                            .and_then(|ns| pt.namespaces.get(ns).map(|entry| entry.dir.clone()))
                    })
                })
                .or_else(|| env::CWD.as_path().canonicalize().ok());
            if let Some(ref d) = dir {
                pt.namespaces.insert(
                    ns.to_string(),
                    NamespaceEntry {
                        dir: d.clone(),
                        config: Vec::new(),
                    },
                );
            }
        }

        pt.slugs.insert(
            slug.to_string(),
            SlugEntry {
                dir: None,
                namespace: namespace.map(str::to_string),
                daemon: daemon.map(str::to_string),
            },
        );
        pt.write_unlocked()?;
        // Sync hosts from the in-memory slug set, not sync_hosts_from_settings():
        // that re-reads the global config via read(), which acquires the lock held
        // above — flock is per open file description, so re-acquiring in the same
        // process deadlocks against our own lock. Staying under the lock also keeps
        // hosts writes ordered with config mutations across concurrent commands.
        let slug_names: Vec<String> = pt.slugs.keys().cloned().collect();
        crate::proxy::hosts::sync_hosts_from_settings_with_slugs(&slug_names);
        Ok(())
    }

    /// Remove a slug from the global config's `[slugs]` section.
    pub fn remove_slug(slug: &str) -> Result<bool> {
        let global_path = &*env::PITCHFORK_GLOBAL_CONFIG_USER;
        if !global_path.exists() {
            return Ok(false);
        }

        let _lock = xx::fslock::get(global_path, false)
            .wrap_err_with(|| format!("failed to acquire lock on {}", global_path.display()))?;

        let raw = std::fs::read_to_string(global_path).map_err(|e| FileError::ReadError {
            path: global_path.to_path_buf(),
            source: e,
        })?;
        let mut pt = Self::parse_str(&raw, global_path)?;

        let removed = pt.slugs.shift_remove(slug).is_some();
        if removed {
            pt.write_unlocked()?;
            // Sync hosts from the in-memory slug set, not sync_hosts_from_settings():
            // that re-reads the global config via read(), which acquires the lock held
            // above — flock is per open file description, so re-acquiring in the same
            // process deadlocks against our own lock. Staying under the lock also keeps
            // hosts writes ordered with config mutations across concurrent commands.
            let slug_names: Vec<String> = pt.slugs.keys().cloned().collect();
            crate::proxy::hosts::sync_hosts_from_settings_with_slugs(&slug_names);
        }
        Ok(removed)
    }
    /// Returns a map of namespace → NamespaceEntry from `[namespaces]` in
    /// `~/.config/pitchfork/config.toml`.
    pub fn read_global_namespaces() -> IndexMap<String, NamespaceEntry> {
        match Self::read(&*env::PITCHFORK_GLOBAL_CONFIG_USER) {
            Ok(pt) => pt.namespaces,
            Err(_) => IndexMap::new(),
        }
    }

    /// Add a namespace entry to the global config's `[namespaces]` section.
    ///
    /// Reads the global config, adds/updates the namespace entry, and writes it back.
    pub fn register_namespace(name: &str, dir: &str) -> crate::Result<()> {
        let global_path = &*crate::env::PITCHFORK_GLOBAL_CONFIG_USER;

        // Ensure the config directory exists
        if let Some(parent) = global_path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| {
                miette::miette!(
                    "Failed to create config directory {}: {e}",
                    parent.display()
                )
            })?;
        }

        let _lock = xx::fslock::get(global_path, false)
            .wrap_err_with(|| format!("failed to acquire lock on {}", global_path.display()))?;

        let mut pt = if global_path.exists() {
            let raw = std::fs::read_to_string(global_path).map_err(|e| {
                crate::error::FileError::ReadError {
                    path: global_path.to_path_buf(),
                    source: e,
                }
            })?;
            Self::parse_str(&raw, global_path)?
        } else {
            Self::new(global_path.to_path_buf())
        };

        let dir = env::expand_tilde(dir);
        if let Some(entry) = pt.namespaces.get_mut(name) {
            if !entry.config.is_empty()
                && crate::extra_configs::normalize(&entry.dir)
                    != crate::extra_configs::normalize(&dir)
            {
                miette::bail!(
                    "namespace '{name}' has external configuration attached to another directory"
                );
            }
            entry.dir = dir;
        } else {
            pt.namespaces.insert(
                name.to_string(),
                NamespaceEntry {
                    dir,
                    config: Vec::new(),
                },
            );
        }
        pt.write_unlocked()?;
        Ok(())
    }

    /// Remove a namespace from the global config's `[namespaces]` section.
    pub fn remove_namespace(name: &str) -> crate::Result<bool> {
        let global_path = &*crate::env::PITCHFORK_GLOBAL_CONFIG_USER;
        if !global_path.exists() {
            return Ok(false);
        }

        let _lock = xx::fslock::get(global_path, false)
            .wrap_err_with(|| format!("failed to acquire lock on {}", global_path.display()))?;

        let raw = std::fs::read_to_string(global_path).map_err(|e| {
            crate::error::FileError::ReadError {
                path: global_path.to_path_buf(),
                source: e,
            }
        })?;
        let mut pt = Self::parse_str(&raw, global_path)?;

        let removed = pt.namespaces.shift_remove(name).is_some();
        if removed {
            pt.write_unlocked()?;
        }
        Ok(removed)
    }
}

/// Configuration for a single daemon (internal representation with DaemonId)
#[derive(Debug, Clone, JsonSchema, Default)]
pub struct PitchforkTomlDaemon {
    /// The command to run. Prepend with 'exec' to avoid shell process overhead.
    #[schemars(example = example_run_command())]
    pub run: String,
    /// Automatic start/stop behavior based on shell hooks
    #[schemars(default)]
    pub auto: Vec<PitchforkTomlAuto>,
    /// Run this daemon as a task that must finish rather than a long-running
    /// service. Readiness means the process exited with code 0, the daemon
    /// then reports the `completed` status, and daemons that `depends` on it
    /// wait for that completion. Cannot be combined with any `ready_*` or
    /// `health_*` field.
    pub oneshot: Option<bool>,
    /// Cron scheduling configuration for periodic execution
    pub cron: Option<PitchforkTomlCron>,
    /// Number of times to retry if the daemon fails.
    /// Can be a number (e.g., `3`) or `true` for infinite retries.
    #[schemars(default)]
    pub retry: Retry,
    /// Delay in seconds before considering the daemon ready
    pub ready_delay: Option<u64>,
    /// Regex pattern to match in ANSI-stripped stdout/stderr to determine readiness
    pub ready_output: Option<ReadyOutput>,
    /// HTTP URL to poll for readiness. Accepts any 2xx response by default, or configured statuses.
    pub ready_http: Option<ReadyHttp>,
    /// TCP port to check for readiness (connection success = ready).
    /// Accepts a port number, a Tera template string that renders to one, or an
    /// object with an optional overall polling timeout.
    pub ready_port: Option<ReadyPort>,
    /// Shell command to poll for readiness (exit code 0 = ready)
    pub ready_cmd: Option<ReadyCmd>,
    /// Shell command to poll for health (exit code 0 = healthy)
    pub health_cmd: Option<HealthCmd>,
    /// HTTP endpoint URL to poll for health
    pub health_http: Option<HealthHttp>,
    /// TCP port to probe for health (connection success = healthy).
    /// Accepts a port number, a Tera template string that renders to one, or an
    /// object with optional per-check `interval`, `retries`, and `timeout`.
    pub health_port: Option<HealthPort>,
    /// Port configuration: expected ports and auto-bump settings
    pub port: Option<PortConfig>,
    /// Proxy routing: `false` opts out of the automatic hostname, a string
    /// overrides the daemon label used in it.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub proxy: Option<ProxyConfig>,
    /// TLS handling for this daemon's proxy hostname.
    ///
    /// - `terminate` (default): the proxy terminates TLS with its own
    ///   certificate and forwards plain HTTP to the daemon.
    /// - `passthrough`: the proxy reads the SNI hostname from the TLS
    ///   ClientHello and splices the raw TCP stream to the daemon, which
    ///   presents its own certificate and can require client certificates.
    ///   Requires `port`.
    pub proxy_tls: Option<ProxyTlsMode>,
    /// Which of the daemon's ports the proxy hostname maps to.
    ///
    /// Must name one of the ports in `port`. Defaults to the daemon's first
    /// port. `proxy_port` is the shorter spelling of the same setting.
    #[schemars(range(min = 1))]
    pub proxy_tls_port: Option<u16>,
    /// Shorter spelling of `proxy_tls_port`. Set one or the other, not both.
    ///
    /// Kept separate rather than folded so that a config keeps the spelling
    /// its author chose when pitchfork rewrites it. Read
    /// [`Self::effective_proxy_tls_port`] rather than either field.
    #[schemars(range(min = 1))]
    pub proxy_port: Option<u16>,
    /// Idle timeout when the proxy auto-starts this daemon, for example `"15m"`.
    /// Accepts a duration string or `false`; `"0"` also disables idle shutdown.
    ///
    /// When omitted, a daemon started through its URL uses
    /// `settings.proxy.idle_timeout`; a dependency inherits the requested
    /// daemon's timeout. An explicit `false` exempts this daemon in either case.
    ///
    /// The timeout is recorded at startup. Explicitly started daemons are
    /// exempt; live dependents, active proxy connections, and tracked shell
    /// sessions prevent idle shutdown.
    pub proxy_idle_timeout: Option<ProxyIdleTimeout>,
    /// Whether to start this daemon automatically on system boot
    pub boot_start: Option<bool>,
    /// List of daemon IDs that must be started before this one
    #[schemars(default)]
    pub depends: Vec<DaemonId>,
    /// File patterns to watch for changes
    #[schemars(default)]
    pub watch: Vec<String>,
    /// File watching backend mode.
    ///
    /// - `native`: use platform-native notifications (default)
    /// - `poll`: use polling-based watcher
    /// - `auto`: prefer native, fall back to polling if native watch fails
    #[schemars(default)]
    pub watch_mode: WatchMode,
    /// Working directory for the daemon. Relative paths are resolved from the pitchfork.toml location.
    pub dir: Option<String>,
    /// Environment variables to set for the daemon process
    pub env: Option<IndexMap<String, String>>,
    /// Lifecycle hooks (on_ready, on_fail, on_retry)
    pub hooks: Option<PitchforkTomlHooks>,
    /// Wrap this daemon's command with `mise x --` for tool/env setup.
    /// Overrides the global `settings.general.mise` when set.
    pub mise: Option<bool>,
    /// Unix user to run this daemon as. Overrides `settings.supervisor.user` when set.
    pub user: Option<String>,
    /// Memory limit for the daemon process (e.g. "50MB", "1GiB").
    /// The supervisor periodically monitors RSS and kills the process if it exceeds the limit.
    pub memory_limit: Option<MemoryLimit>,
    /// CPU usage limit as a percentage (e.g. 80 for 80%, 200 for 2 cores).
    /// The supervisor periodically monitors CPU usage and kills the process if it exceeds the limit.
    pub cpu_limit: Option<CpuLimit>,
    /// Stop signal and optional per-daemon timeout. Accepts a signal name string
    /// or `{ signal = "...", timeout = "..." }` object.
    pub stop_signal: Option<StopConfig>,
    /// Allocate a pseudo-terminal for the daemon process.
    pub pty: Option<bool>,
    /// Maximum age of log entries to keep (e.g. "7d", "30d").
    /// Overrides the global `settings.logs.time_retention` when set.
    pub time_retention: Option<String>,
    /// Maximum number of log entries to keep per daemon.
    /// Overrides the global `settings.logs.line_retention` when set.
    pub line_retention: Option<i64>,
    /// Archive hook command invoked before retention prunes this daemon's logs.
    /// Overrides the global `settings.logs.archive_hook.command` when set.
    pub archive_hook: Option<String>,
    /// Per-daemon log configuration sub-table.
    pub logs: Option<PitchforkTomlDaemonLogs>,
    #[schemars(skip)]
    pub path: Option<PathBuf>,
}

impl PitchforkTomlDaemon {
    /// Which of the daemon's ports its proxy hostname maps to, from either
    /// spelling of the setting.
    ///
    /// `proxy_tls_port` wins when both are set; parsing has already warned
    /// about that combination.
    pub fn effective_proxy_tls_port(&self) -> Option<u16> {
        self.proxy_tls_port.or(self.proxy_port)
    }

    /// Whether this daemon is a oneshot task (`oneshot = true`).
    pub fn is_oneshot(&self) -> bool {
        self.oneshot.unwrap_or(false)
    }

    /// Names of the readiness and health fields that are set on this daemon
    /// and cannot be combined with `oneshot`. Empty when there is no conflict.
    pub(crate) fn oneshot_conflicts(&self) -> Vec<&'static str> {
        [
            ("ready_delay", self.ready_delay.is_some()),
            ("ready_output", self.ready_output.is_some()),
            ("ready_http", self.ready_http.is_some()),
            ("ready_port", self.ready_port.is_some()),
            ("ready_cmd", self.ready_cmd.is_some()),
            ("health_cmd", self.health_cmd.is_some()),
            ("health_http", self.health_http.is_some()),
            ("health_port", self.health_port.is_some()),
        ]
        .into_iter()
        .filter(|(_, set)| *set)
        .map(|(name, _)| name)
        .collect()
    }

    /// Effective user for this daemon: per-daemon `user` overrides `settings.supervisor.user`.
    ///
    /// Returns `None` when neither is set (inherit the supervisor's user).
    pub fn effective_user(&self) -> Option<String> {
        let daemon_user = self
            .user
            .as_deref()
            .map(str::trim)
            .filter(|u| !u.is_empty());
        daemon_user.map(str::to_owned).or_else(|| {
            let s = crate::settings::settings();
            let su = s.supervisor.user.trim();
            (!su.is_empty()).then(|| su.to_owned())
        })
    }

    /// Build RunOptions from this daemon configuration.
    ///
    /// Carries over all config fields and resolves the working directory.
    /// Callers can override specific fields on the returned value.
    pub fn to_run_options(
        &self,
        id: &crate::daemon_id::DaemonId,
        cmd: Vec<String>,
    ) -> crate::daemon::RunOptions {
        use crate::daemon::RunOptions;

        let effective_user = self.effective_user();
        let dir = crate::ipc::batch::resolve_daemon_dir(
            self.dir.as_deref(),
            self.path.as_deref(),
            effective_user.as_deref(),
        );
        // The same lookup the proxy and the CLI use, so a slug the proxy
        // refuses to route as ambiguous is not handed to the daemon either.
        let slug = PitchforkToml::find_slug_for_daemon_in_registry(
            id,
            &PitchforkToml::read_global_slugs(),
        );

        RunOptions {
            id: id.clone(),
            cmd,
            run: Some(self.run.clone()),
            force: false,
            shell_pid: None,
            dir: Dir(dir),
            autostop: self.auto.contains(&PitchforkTomlAuto::Stop),
            oneshot: self.is_oneshot(),
            // Filled in by `build_run_options`, which resolves it against the
            // daemon's own project rather than whatever directory this process
            // happens to be in.
            oneshot_wait: None,
            on_directory_enter: false,
            cron_schedule: self.cron.as_ref().map(|c| c.schedule.clone()),
            cron_retrigger: self.cron.as_ref().map(|c| c.retrigger),
            cron_immediate: self.cron.as_ref().map(|c| c.immediate),
            retry: self.retry,
            retry_count: 0,
            ready_delay: self.ready_delay,
            ready_output: self.ready_output.clone(),
            ready_http: self.ready_http.clone(),
            ready_port: self.ready_port.clone(),
            ready_cmd: self.ready_cmd.clone(),
            health_cmd: self.health_cmd.clone(),
            health_http: self.health_http.clone(),
            health_port: self.health_port.clone(),
            port: self.port.clone(),
            wait_ready: false,
            depends: self.depends.clone(),
            env: self.env.clone(),
            watch: self.watch.clone(),
            watch_mode: self.watch_mode,
            watch_base_dir: Some(crate::ipc::batch::resolve_config_base_dir(
                self.path.as_deref(),
            )),
            mise: self.mise,
            slug,
            proxy: None,
            user: self.user.clone(),
            memory_limit: self.memory_limit,
            cpu_limit: self.cpu_limit,
            stop_signal: self.stop_signal,
            archive_hook: self
                .logs
                .as_ref()
                .and_then(|l| l.archive_hook.clone())
                .or_else(|| self.archive_hook.clone()),
            log_format: self.logs.as_ref().and_then(|l| l.log_format.clone()),
            on_output_hook: self.hooks.as_ref().and_then(|h| h.on_output.clone()),
            pty: self.pty,
            // Explicit unless the proxy's start marks it otherwise.
            proxy_idle_timeout_ms: None,
        }
    }
}
fn example_run_command() -> &'static str {
    "exec node server.js"
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::Path;

    #[test]
    fn test_daemon_user_parses_and_flows_to_run_options() {
        let pt = PitchforkToml::parse_str(
            r#"
[daemons.api]
run = "node server.js"
user = "postgres"
"#,
            Path::new("/tmp/my-project/pitchfork.toml"),
        )
        .unwrap();

        let id = DaemonId::new("my-project", "api");
        let daemon = pt.daemons.get(&id).unwrap();
        assert_eq!(daemon.user.as_deref(), Some("postgres"));

        let opts = daemon.to_run_options(&id, vec!["node".to_string(), "server.js".to_string()]);
        assert_eq!(opts.user.as_deref(), Some("postgres"));
    }

    #[test]
    fn test_daemon_user_write_roundtrip() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("pitchfork.toml");
        let mut pt = PitchforkToml::new(path.clone());
        pt.namespace = Some("test-project".to_string());
        pt.daemons.insert(
            DaemonId::new("test-project", "api"),
            PitchforkTomlDaemon {
                run: "node server.js".to_string(),
                user: Some("postgres".to_string()),
                ..PitchforkTomlDaemon::default()
            },
        );

        pt.write().unwrap();

        let raw = std::fs::read_to_string(&path).unwrap();
        assert!(raw.contains("user = \"postgres\""));

        let parsed = PitchforkToml::read(&path).unwrap();
        let daemon = parsed
            .daemons
            .get(&DaemonId::new("test-project", "api"))
            .unwrap();
        assert_eq!(daemon.user.as_deref(), Some("postgres"));
    }

    #[test]
    fn test_registry_dirs_expand_tilde() {
        let pt = PitchforkToml::parse_str(
            r#"
[slugs.api]
dir = "~/projects/api"

[namespaces.web]
dir = "~/projects/web"
"#,
            Path::new("/tmp/config.toml"),
        )
        .unwrap();

        assert_eq!(
            pt.slugs["api"].dir,
            Some(crate::env::HOME_DIR.join("projects/api"))
        );
        assert_eq!(
            pt.namespaces["web"].dir,
            crate::env::HOME_DIR.join("projects/web")
        );
    }

    #[test]
    fn test_settings_write_roundtrip() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("pitchfork.toml");
        let mut pt = PitchforkToml::new(path.clone());
        pt.namespace = Some("test-project".to_string());
        pt.settings.web.auto_start = Some(true);
        pt.settings.general.log_level = Some("debug".to_string());

        pt.write().unwrap();

        let raw = std::fs::read_to_string(&path).unwrap();
        assert!(
            raw.contains("[settings.web]"),
            "settings.web section should be written, got:\n{raw}"
        );
        assert!(raw.contains("auto_start = true"));
        assert!(raw.contains("log_level = \"debug\""));

        let parsed = PitchforkToml::read(&path).unwrap();
        assert_eq!(parsed.settings.web.auto_start, Some(true));
        assert_eq!(parsed.settings.general.log_level.as_deref(), Some("debug"));
    }

    fn slug_entry(namespace: &str, daemon: Option<&str>) -> SlugEntry {
        SlugEntry {
            dir: None,
            namespace: Some(namespace.to_string()),
            daemon: daemon.map(str::to_string),
        }
    }

    #[test]
    fn test_slug_is_ambiguous() {
        let mut slugs = IndexMap::new();
        slugs.insert("api".to_string(), slug_entry("my-project", None));
        assert!(!PitchforkToml::slug_is_ambiguous("api", &slugs));

        slugs.insert("API".to_string(), slug_entry("other-project", None));
        // Host names are case-insensitive, so both spellings are ambiguous.
        assert!(PitchforkToml::slug_is_ambiguous("api", &slugs));
        assert!(PitchforkToml::slug_is_ambiguous("API", &slugs));
    }

    #[test]
    fn test_find_slug_for_daemon_skips_case_collisions() {
        let id = DaemonId::new("my-project", "api");
        let mut slugs = IndexMap::new();
        slugs.insert("api".to_string(), slug_entry("my-project", None));
        assert_eq!(
            PitchforkToml::find_slug_for_daemon_in_registry(&id, &slugs),
            Some("api".to_string())
        );

        // The proxy refuses to route either spelling, so no URL may be
        // advertised for this daemon.
        slugs.insert("API".to_string(), slug_entry("other-project", None));
        assert_eq!(
            PitchforkToml::find_slug_for_daemon_in_registry(&id, &slugs),
            None
        );
    }

    #[test]
    fn test_find_slug_for_daemon_prefers_a_routable_alias() {
        let id = DaemonId::new("my-project", "api");
        let mut slugs = IndexMap::new();
        // A colliding pair comes first in config order, then a routable alias
        // for the same daemon.
        slugs.insert("api".to_string(), slug_entry("my-project", None));
        slugs.insert("API".to_string(), slug_entry("my-project", None));
        slugs.insert("my-api".to_string(), slug_entry("my-project", Some("api")));

        assert_eq!(
            PitchforkToml::find_slug_for_daemon_in_registry(&id, &slugs),
            Some("my-api".to_string())
        );
    }

    #[test]
    fn test_settings_preserved_on_unrelated_write() {
        // Regression test for https://github.com/jdx/pitchfork/discussions/574
        // A read-modify-write of slugs/namespaces must not drop existing [settings].
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("pitchfork.toml");
        std::fs::write(&path, "[settings.web]\nauto_start = true\n").unwrap();

        let mut pt = PitchforkToml::read(&path).unwrap();
        pt.slugs.insert(
            "api".to_string(),
            SlugEntry {
                dir: None,
                namespace: Some("myproject".to_string()),
                daemon: None,
            },
        );
        pt.namespaces.insert(
            "myproject".to_string(),
            NamespaceEntry {
                dir: PathBuf::from("/tmp/myproject"),
                config: Vec::new(),
            },
        );
        pt.write().unwrap();

        let raw = std::fs::read_to_string(&path).unwrap();
        assert!(
            raw.contains("[settings.web]"),
            "existing settings must be preserved, got:\n{raw}"
        );
        assert!(raw.contains("auto_start = true"));
        assert!(raw.contains("[slugs.api]"));

        let parsed = PitchforkToml::read(&path).unwrap();
        assert_eq!(parsed.settings.web.auto_start, Some(true));
        assert!(parsed.slugs.contains_key("api"));
    }

    #[tokio::test]
    async fn test_proxy_worktree_alias_is_canonicalized_on_rewrite() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("pitchfork.toml");
        tokio::fs::write(&path, "[settings.proxy]\nworktree = false\n")
            .await
            .unwrap();

        let read_path = path.clone();
        let pt = tokio::task::spawn_blocking(move || PitchforkToml::read(&read_path))
            .await
            .unwrap()
            .unwrap();
        assert_eq!(pt.settings.general.worktree, Some(false));
        assert_eq!(pt.settings.proxy.worktree, None);
        tokio::task::spawn_blocking(move || pt.write())
            .await
            .unwrap()
            .unwrap();

        let raw = tokio::fs::read_to_string(&path).await.unwrap();
        assert!(raw.contains("[settings.general]"), "{raw}");
        assert!(raw.contains("worktree = false"), "{raw}");
        assert!(!raw.contains("[settings.proxy]"), "{raw}");

        let parsed = tokio::task::spawn_blocking(move || PitchforkToml::read(&path))
            .await
            .unwrap()
            .unwrap();
        assert_eq!(parsed.settings.general.worktree, Some(false));
    }

    #[test]
    fn test_config_cache_hit_and_invalidation() {
        let temp = tempfile::tempdir().unwrap();
        let dir = temp.path();
        let config_path = dir.join("pitchfork.toml");
        std::fs::write(&config_path, "[daemons.api]\nrun = \"echo v1\"\n").unwrap();

        // Clear any pre-existing cache entries for this directory.
        super::invalidate_config_cache();

        // First call: cache miss, reads from disk.
        let pt1 = PitchforkToml::all_merged_from(dir).unwrap();
        let daemon_id = DaemonId::new(namespace_from_path(&config_path).unwrap(), "api");
        assert_eq!(pt1.daemons[&daemon_id].run, "echo v1");

        // Second call: should be a cache hit (same mtime).
        let pt2 = PitchforkToml::all_merged_from(dir).unwrap();
        assert_eq!(pt2.daemons[&daemon_id].run, "echo v1");

        // Modify the config file — mtime changes, cache should miss.
        // Sleep briefly to ensure mtime resolution differs.
        std::thread::sleep(std::time::Duration::from_millis(50));
        std::fs::write(&config_path, "[daemons.api]\nrun = \"echo v2\"\n").unwrap();

        let pt3 = PitchforkToml::all_merged_from(dir).unwrap();
        assert_eq!(pt3.daemons[&daemon_id].run, "echo v2");

        // Explicit invalidation should also force a re-read.
        super::invalidate_config_cache();
        let pt4 = PitchforkToml::all_merged_from(dir).unwrap();
        assert_eq!(pt4.daemons[&daemon_id].run, "echo v2");

        // Clean up.
        super::invalidate_config_cache();
    }

    #[test]
    fn test_config_cache_invalidation_on_write() {
        let temp = tempfile::tempdir().unwrap();
        let dir = temp.path();
        let config_path = dir.join("pitchfork.toml");
        std::fs::write(&config_path, "[daemons.api]\nrun = \"echo v1\"\n").unwrap();

        super::invalidate_config_cache();

        // Populate cache.
        let pt1 = PitchforkToml::all_merged_from(dir).unwrap();
        let daemon_id = DaemonId::new(namespace_from_path(&config_path).unwrap(), "api");
        assert_eq!(pt1.daemons[&daemon_id].run, "echo v1");

        // Write via PitchforkToml::write() — should invalidate cache.
        let mut pt = PitchforkToml::read(&config_path).unwrap();
        pt.daemons.get_mut(&daemon_id).unwrap().run = "echo v3".to_string();
        // write() needs the path set and namespace match
        let _ = pt.write();

        // Next read should see the updated value, not the cached one.
        let pt2 = PitchforkToml::all_merged_from(dir).unwrap();
        assert_eq!(pt2.daemons[&daemon_id].run, "echo v3");

        super::invalidate_config_cache();
    }

    #[test]
    fn test_config_cache_size_invalidation() {
        let temp = tempfile::tempdir().unwrap();
        let dir = temp.path();
        let config_path = dir.join("pitchfork.toml");
        std::fs::write(&config_path, "[daemons.api]\nrun = \"echo v1\"\n").unwrap();

        super::invalidate_config_cache();

        // Populate cache.
        let pt1 = PitchforkToml::all_merged_from(dir).unwrap();
        let daemon_id = DaemonId::new(namespace_from_path(&config_path).unwrap(), "api");
        assert_eq!(pt1.daemons[&daemon_id].run, "echo v1");

        // Capture the original mtime, then write different-size content and
        // restore the *same* mtime — simulating `cp --preserve=timestamps`
        // or a same-second edit on a coarse-grained filesystem.
        let original_mtime = std::fs::metadata(&config_path).unwrap().modified().unwrap();
        std::fs::write(&config_path, "[daemons.api]\nrun = \"echo different\"\n").unwrap();
        // On Windows, set_times requires the file handle to be opened with
        // write access; File::open is read-only.
        let file = std::fs::OpenOptions::new()
            .write(true)
            .open(&config_path)
            .unwrap();
        let times = std::fs::FileTimes::new().set_modified(original_mtime);
        file.set_times(times).unwrap();

        // Size changed (shorter run string), so cache should miss even though
        // mtime is identical.
        let pt2 = PitchforkToml::all_merged_from(dir).unwrap();
        assert_eq!(
            pt2.daemons[&daemon_id].run, "echo different",
            "cache should invalidate on size change even with identical mtime"
        );

        super::invalidate_config_cache();
    }

    #[test]
    fn test_find_project_root_in_plain_dir_returns_none() {
        let temp = tempfile::tempdir().unwrap();
        assert_eq!(find_project_root(temp.path()), None);
    }

    #[test]
    fn test_find_project_root_finds_git_marker() {
        let temp = tempfile::tempdir().unwrap();
        let repo = temp.path().join("my-repo");
        std::fs::create_dir(&repo).unwrap();
        std::fs::create_dir(repo.join(".git")).unwrap();

        let sub = repo.join("sub/dir");
        std::fs::create_dir_all(&sub).unwrap();

        // `find_project_root` canonicalizes, so compare against the canonical
        // path (on Windows this differs by the `\\?\` verbatim prefix).
        assert_eq!(find_project_root(&sub), Some(repo.canonicalize().unwrap()));
    }

    #[test]
    fn test_find_project_root_accepts_git_file_marker() {
        // Linked git worktrees store `.git` as a *file* pointing at the
        // common gitdir, so `exists()` (not `is_dir()`) is the right check.
        let temp = tempfile::tempdir().unwrap();
        let wt = temp.path().join("my-worktree");
        std::fs::create_dir(&wt).unwrap();
        std::fs::write(wt.join(".git"), "gitdir: /tmp/some-common-gitdir\n").unwrap();

        assert_eq!(find_project_root(&wt), Some(wt.canonicalize().unwrap()));
    }

    /// A symlinked start dir must resolve into the repository hierarchy so
    /// `parent()` traversal does not walk out of the repo.
    #[cfg(unix)]
    #[test]
    fn test_find_project_root_resolves_symlinked_start_dir() {
        use std::os::unix::fs::symlink;

        let temp = tempfile::tempdir().unwrap();
        let repo = temp.path().join("real-repo");
        std::fs::create_dir(&repo).unwrap();
        std::fs::create_dir(repo.join(".git")).unwrap();

        let sub = repo.join("sub/dir");
        std::fs::create_dir_all(&sub).unwrap();
        let link = temp.path().join("link-to-sub");
        symlink(&sub, &link).unwrap();

        assert_eq!(find_project_root(&link), Some(repo.canonicalize().unwrap()));
    }

    /// Build a real git repository with a linked worktree and assert that
    /// `all_merged_all_namespaces_from` picks up daemons from both.
    #[test]
    fn test_all_merged_all_namespaces_discovers_worktrees() {
        let temp = tempfile::tempdir().unwrap();
        let repo = temp.path().join("my-repo");
        std::fs::create_dir(&repo).unwrap();

        // git worktree add requires at least one commit.
        let git_init = std::process::Command::new("git")
            .args(["init", "-b", "main"])
            .current_dir(&repo)
            .output()
            .expect("git init");
        assert!(git_init.status.success(), "git init failed: {:?}", git_init);

        std::fs::write(repo.join("main.toml"), "hello\n").unwrap();

        let git_commit = std::process::Command::new("git")
            .args([
                "-c",
                "user.name=pitchfork-test",
                "-c",
                "user.email=pitchfork-test@example.com",
                "add",
                "-A",
            ])
            .current_dir(&repo)
            .output()
            .expect("git add");
        assert!(git_commit.status.success());

        let git_commit = std::process::Command::new("git")
            .args([
                "-c",
                "user.name=pitchfork-test",
                "-c",
                "user.email=pitchfork-test@example.com",
                "commit",
                "-m",
                "init",
            ])
            .current_dir(&repo)
            .output()
            .expect("git commit");
        assert!(
            git_commit.status.success(),
            "git commit failed: {:?}",
            git_commit
        );

        let wt = temp.path().join("my-repo-feature");
        let git_wt = std::process::Command::new("git")
            .args(["worktree", "add", "-b", "feature-x", wt.to_str().unwrap()])
            .current_dir(&repo)
            .output()
            .expect("git worktree add");
        assert!(
            git_wt.status.success(),
            "git worktree add failed: {:?}",
            git_wt
        );

        // Config in the main checkout.
        std::fs::write(
            repo.join("pitchfork.toml"),
            "[daemons.api]\nrun = \"echo main\"\n",
        )
        .unwrap();
        // Config in the linked worktree (different namespace: dir name).
        std::fs::write(
            wt.join("pitchfork.toml"),
            "[daemons.worker]\nrun = \"echo wt\"\n",
        )
        .unwrap();

        super::invalidate_config_cache();

        // Resolve from inside the worktree: both namespaces must be visible.
        let pt = PitchforkToml::all_merged_all_namespaces_from(&wt).unwrap();

        let main_id = DaemonId::new("my-repo", "api");
        let wt_id = DaemonId::new("my-repo-feature", "worker");
        assert!(
            pt.daemons.contains_key(&main_id),
            "main checkout daemon missing"
        );
        assert!(pt.daemons.contains_key(&wt_id), "worktree daemon missing");

        // Resolving from the main checkout must also see the worktree daemon.
        let pt_from_main = PitchforkToml::all_merged_all_namespaces_from(&repo).unwrap();
        assert!(pt_from_main.daemons.contains_key(&wt_id));

        // Clean up.
        let _ = std::process::Command::new("git")
            .args(["worktree", "remove", "--force", wt.to_str().unwrap()])
            .current_dir(&repo)
            .output();
        super::invalidate_config_cache();
    }

    #[test]
    fn test_adhoc_id_uses_invocation_directory_namespace() {
        let temp = tempfile::tempdir().unwrap();
        let project = temp.path().join("feature-tree");
        std::fs::create_dir(&project).unwrap();
        std::fs::write(
            project.join("pitchfork.toml"),
            "[daemons.other]\nrun = \"true\"\n",
        )
        .unwrap();

        let id = PitchforkToml::resolve_id_allow_adhoc_from("api", &project).unwrap();
        assert_eq!(id, DaemonId::new("feature-tree", "api"));
        let qualified =
            PitchforkToml::resolve_id_allow_adhoc_from("explicit/api", &project).unwrap();
        assert_eq!(qualified, DaemonId::new("explicit", "api"));
    }

    #[test]
    fn test_adhoc_id_falls_back_to_global_without_project_config() {
        let temp = tempfile::tempdir().unwrap();
        let id = PitchforkToml::resolve_id_allow_adhoc_from("api", temp.path()).unwrap();
        assert_eq!(id, DaemonId::new("global", "api"));
    }
}