diaryx_core 1.4.4

Core library for Diaryx - a tool to manage markdown files with YAML frontmatter
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
//! Workspace operations module.
//!
//! This module provides functionality for working with Diaryx workspaces:
//! - Tree traversal and building
//! - File operations (move, rename, delete)
//! - Index management (contents, part_of relationships)
//!
//! # Module Structure
//!
//! - `types` - Core data types (IndexFrontmatter, IndexFile, TreeNode)
//!
//! # Async-first Design
//!
//! This module uses `AsyncFileSystem` for all filesystem operations.
//! For synchronous contexts (CLI, tests), wrap a sync filesystem with
//! `SyncToAsyncFs` and use `futures_lite::future::block_on()`.

mod tree_selection;
mod types;

// Re-export types for backwards compatibility
pub use tree_selection::*;
pub use types::{IndexFile, IndexFrontmatter, TreeNode, format_tree_node};

use std::collections::{BTreeSet, HashMap, HashSet};
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::yaml_value::YamlValue;

use crate::config::Config;
use crate::error::{DiaryxError, Result};
use crate::fs::AsyncFileSystem;
use crate::link_parser::{self, LinkFormat};
use crate::path_utils::normalize_sync_path;
use crate::utils::{is_workspace_skip_dir, matches_glob_pattern};

/// How to generate filenames from entry titles.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
#[cfg_attr(feature = "typescript", ts(export, export_to = "bindings/"))]
#[serde(rename_all = "snake_case")]
pub enum FilenameStyle {
    /// Keep the title as-is, stripping only filesystem-illegal characters.
    #[default]
    Preserve,
    /// Lowercase, non-alphanumeric chars replaced with dashes.
    KebabCase,
    /// Lowercase, non-alphanumeric chars replaced with underscores.
    SnakeCase,
    /// Uppercase, non-alphanumeric chars replaced with underscores.
    ScreamingSnakeCase,
}

fn default_true() -> bool {
    true
}

/// Workspace-level configuration stored in the root index file's frontmatter.
///
/// This allows workspace settings to live with the data (local-first philosophy)
/// rather than in separate config files.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
#[cfg_attr(feature = "typescript", ts(export, export_to = "bindings/"))]
pub struct WorkspaceConfig {
    /// Format for `part_of`, `contents`, and `attachments` links.
    /// Defaults to MarkdownRoot if not specified.
    #[serde(default)]
    pub link_format: LinkFormat,

    /// Link to the default template entry for new files (in link_format style).
    /// If absent, uses the built-in "note" template.
    #[cfg_attr(feature = "typescript", ts(optional))]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_template: Option<String>,

    /// When true, setting the `title` frontmatter property also updates the first H1 heading.
    /// Unidirectional: title → heading only.
    #[serde(default)]
    pub sync_title_to_heading: bool,

    /// When true, saving content automatically updates the `updated` timestamp.
    #[serde(default = "default_true")]
    pub auto_update_timestamp: bool,

    /// When true, changing the title automatically renames the file.
    #[serde(default = "default_true")]
    pub auto_rename_to_title: bool,

    /// How to generate filenames from entry titles.
    #[serde(default)]
    pub filename_style: FilenameStyle,

    /// Audience tag assigned to entries with no explicit or inherited audience.
    /// Unset = private (excluded from exports). Entries that have this tag via
    /// the default are included in audience-filtered exports for that tag.
    #[cfg_attr(feature = "typescript", ts(optional))]
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "public_audience"
    )]
    pub default_audience: Option<String>,

    /// Folder used by the Daily plugin for date-based entries.
    #[cfg_attr(feature = "typescript", ts(optional))]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub daily_entry_folder: Option<String>,

    /// When true, show files not linked in the workspace hierarchy.
    #[cfg_attr(feature = "typescript", ts(optional))]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub show_unlinked_files: Option<bool>,

    /// When true, show hidden (dot-prefixed) files in the tree.
    #[cfg_attr(feature = "typescript", ts(optional))]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub show_hidden_files: Option<bool>,

    /// Theme mode preference for this workspace: "light", "dark", or "system".
    #[cfg_attr(feature = "typescript", ts(optional))]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub theme_mode: Option<String>,

    /// Active workspace theme preset ID.
    #[cfg_attr(feature = "typescript", ts(optional))]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub theme_preset: Option<String>,

    /// Accent hue override applied to the active theme preset.
    #[cfg_attr(feature = "typescript", ts(optional))]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub theme_accent_hue: Option<f64>,

    /// Map of audience name → Tailwind color class (e.g., "family" → "bg-indigo-500").
    #[cfg_attr(feature = "typescript", ts(optional))]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub audience_colors: Option<std::collections::HashMap<String, String>>,

    /// List of plugin IDs that are explicitly disabled in this workspace.
    /// Plugins not listed here are enabled by default.
    #[cfg_attr(feature = "typescript", ts(optional))]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub disabled_plugins: Option<Vec<String>>,
}

#[derive(Default)]
struct FilesystemTreeTrace {
    explored_dirs: BTreeSet<String>,
    pruned_excluded_dirs: BTreeSet<String>,
    pruned_skip_dirs: BTreeSet<String>,
}

impl FilesystemTreeTrace {
    fn record_explored(&mut self, path: &Path) {
        self.explored_dirs
            .insert(path.to_string_lossy().to_string());
    }

    fn record_pruned_excluded(&mut self, path: &Path) {
        self.pruned_excluded_dirs
            .insert(path.to_string_lossy().to_string());
    }

    fn record_pruned_skip(&mut self, path: &Path) {
        self.pruned_skip_dirs
            .insert(path.to_string_lossy().to_string());
    }
}

/// Workspace operations (async-first).
///
/// All methods are async and use `AsyncFileSystem` for filesystem access.
pub struct Workspace<FS: AsyncFileSystem> {
    fs: FS,
    /// The workspace root directory path (for computing canonical paths)
    root_path: Option<PathBuf>,
    /// Link format for `part_of`, `contents`, and `attachments` properties
    link_format: LinkFormat,
}

impl<FS: AsyncFileSystem> Workspace<FS> {
    /// Create a new workspace without link formatting (legacy mode).
    /// Links will be written as relative paths.
    pub fn new(fs: FS) -> Self {
        Self {
            fs,
            root_path: None,
            link_format: LinkFormat::PlainRelative,
        }
    }

    /// Create a new workspace with link formatting enabled.
    ///
    /// # Arguments
    /// * `fs` - The filesystem to use
    /// * `root_path` - The workspace root directory (for computing canonical paths)
    /// * `link_format` - How to format `part_of`, `contents`, and `attachments` links
    pub fn with_link_format(fs: FS, root_path: PathBuf, link_format: LinkFormat) -> Self {
        Self {
            fs,
            root_path: Some(root_path),
            link_format,
        }
    }

    /// Get a reference to the underlying filesystem
    pub fn fs_ref(&self) -> &FS {
        &self.fs
    }

    /// Get the canonical path (workspace-relative) for a filesystem path.
    /// Returns the path as-is if no root_path is configured.
    ///
    /// The canonical path:
    /// - Has no leading `/` or `./`
    /// - Uses forward slashes
    /// - Is relative to the workspace root
    fn get_canonical_path(&self, path: &Path) -> String {
        let raw = if let Some(ref root) = self.root_path {
            // Strip the root path prefix to get workspace-relative path
            path.strip_prefix(root)
                .unwrap_or(path)
                .to_string_lossy()
                .replace('\\', "/") // Normalize to forward slashes
        } else {
            path.to_string_lossy().replace('\\', "/")
        };

        normalize_sync_path(&raw)
    }

    /// Resolve a title for a canonical path by reading the file's frontmatter.
    /// Falls back to a formatted filename if the file can't be read.
    async fn resolve_title(&self, canonical_path: &str) -> String {
        if let Some(ref root) = self.root_path {
            let full_path = root.join(canonical_path);
            if let Ok(content) = self.fs.read_to_string(&full_path).await {
                // Try to extract title from frontmatter
                if let Some(title) = Self::extract_title_from_content(&content) {
                    return title;
                }
            }
        }
        // Fallback: convert filename to title
        link_parser::path_to_title(canonical_path)
    }

    /// Extract title from file content's frontmatter
    fn extract_title_from_content(content: &str) -> Option<String> {
        if !content.starts_with("---\n") && !content.starts_with("---\r\n") {
            return None;
        }
        let rest = &content[4..];
        let end_idx = rest.find("\n---\n").or_else(|| rest.find("\n---\r\n"))?;
        let frontmatter_str = &rest[..end_idx];

        // Simple extraction - look for "title: " line
        for line in frontmatter_str.lines() {
            let trimmed = line.trim();
            if let Some(title) = trimmed.strip_prefix("title:") {
                let title = title.trim().trim_matches('"').trim_matches('\'');
                if !title.is_empty() {
                    return Some(title.to_string());
                }
            }
        }
        None
    }

    /// Resolve a file's `part_of` frontmatter to an absolute parent index path.
    ///
    /// Reads the `part_of` property from `file_path`, parses the link, and
    /// resolves it to an absolute path. Falls back to `find_any_index_in_dir`
    /// on `fallback_dir` when `part_of` is absent or unresolvable.
    async fn resolve_part_of_to_path(
        &self,
        file_path: &Path,
        fallback_dir: &Path,
    ) -> Option<PathBuf> {
        self.resolve_part_of_from_dir(file_path, file_path.parent(), fallback_dir)
            .await
    }

    /// Like `resolve_part_of_to_path`, but resolves relative `part_of` links
    /// from `resolve_dir` instead of from `file_path.parent()`.
    ///
    /// This is needed by `sync_move_metadata` where the file has already been
    /// moved to a new location but its `part_of` still contains a relative link
    /// written for the old location.
    async fn resolve_part_of_from_dir(
        &self,
        file_path: &Path,
        resolve_dir: Option<&Path>,
        fallback_dir: &Path,
    ) -> Option<PathBuf> {
        use crate::path_utils::normalize_path;

        if let Ok(Some(YamlValue::String(part_of))) =
            self.get_frontmatter_property(file_path, "part_of").await
        {
            let dir = resolve_dir.unwrap_or_else(|| Path::new(""));
            let parsed = link_parser::parse_link(&part_of);
            let resolved = match parsed.path_type {
                link_parser::PathType::WorkspaceRoot => {
                    if let Some(ref root) = self.root_path {
                        normalize_path(&root.join(&parsed.path))
                    } else {
                        PathBuf::from(&parsed.path)
                    }
                }
                link_parser::PathType::Relative | link_parser::PathType::Ambiguous => {
                    normalize_path(&dir.join(&parsed.path))
                }
            };
            return Some(resolved);
        }

        // Fallback: search for an index in the given directory
        self.find_any_index_in_dir(fallback_dir)
            .await
            .ok()
            .flatten()
    }

    /// Collect direct child file paths from an index's `contents` entries.
    ///
    /// Paths are resolved using the same link parsing rules as other workspace
    /// operations, with `self.link_format` used as the hint for ambiguous paths.
    async fn collect_index_content_children(&self, index_path: &Path) -> Vec<PathBuf> {
        let mut children = Vec::new();
        let mut seen = HashSet::new();

        let index = match self.parse_index(index_path).await {
            Ok(index) => index,
            Err(e) => {
                log::warn!(
                    "collect_index_content_children: failed to parse '{}': {}",
                    index_path.display(),
                    e
                );
                return children;
            }
        };

        let index_canonical = self.get_canonical_path(index_path);
        let index_canonical_path = Path::new(&index_canonical);

        for raw_child in index.frontmatter.contents_list() {
            let parsed = link_parser::parse_link(raw_child);
            let child_canonical = link_parser::to_canonical_with_link_format(
                &parsed,
                index_canonical_path,
                Some(self.link_format),
            );

            if !seen.insert(child_canonical.clone()) {
                continue;
            }

            let child_path = if let Some(root) = &self.root_path {
                root.join(&child_canonical)
            } else {
                PathBuf::from(&child_canonical)
            };
            children.push(child_path);
        }

        children
    }

    /// Format a link for frontmatter based on configured link format.
    ///
    /// # Arguments
    /// * `target_canonical` - The canonical path of the target file
    /// * `from_canonical` - The canonical path of the file containing the link
    #[allow(dead_code)]
    async fn format_link(&self, target_canonical: &str, from_canonical: &str) -> String {
        let title = self.resolve_title(target_canonical).await;
        link_parser::format_link_with_format(
            target_canonical,
            &title,
            self.link_format,
            from_canonical,
        )
    }

    /// Format a link synchronously (when title is already known).
    fn format_link_sync(
        &self,
        target_canonical: &str,
        title: &str,
        from_canonical: &str,
    ) -> String {
        link_parser::format_link_with_format(
            target_canonical,
            title,
            self.link_format,
            from_canonical,
        )
    }

    /// Parse a markdown file and extract index frontmatter
    pub async fn parse_index(&self, path: &Path) -> Result<IndexFile> {
        let content = self
            .fs
            .read_to_string(path)
            .await
            .map_err(|e| DiaryxError::FileRead {
                path: path.to_path_buf(),
                source: e,
            })?;

        // Check if content starts with frontmatter delimiter
        if !content.starts_with("---\n") && !content.starts_with("---\r\n") {
            return Err(DiaryxError::NoFrontmatter(path.to_path_buf()));
        }

        // Find the closing delimiter
        let rest = &content[4..]; // Skip first "---\n"
        let end_idx = rest
            .find("\n---\n")
            .or_else(|| rest.find("\n---\r\n"))
            .ok_or_else(|| DiaryxError::NoFrontmatter(path.to_path_buf()))?;

        let frontmatter_str = &rest[..end_idx];
        let body = &rest[end_idx + 5..]; // Skip "\n---\n"

        let frontmatter: IndexFrontmatter =
            serde_yaml::from_str(frontmatter_str).map_err(|e| DiaryxError::YamlParse {
                path: path.to_path_buf(),
                message: e.to_string(),
            })?;

        Ok(IndexFile {
            path: path.to_path_buf(),
            frontmatter,
            body: body.to_string(),
            link_format_hint: None,
        })
    }

    /// Parse a markdown file and extract index frontmatter, with a link format hint.
    ///
    /// This variant of `parse_index` allows setting the `link_format_hint` field
    /// which affects how ambiguous paths (like `Folder/file.md`) are resolved.
    /// When `link_format` is `Some(PlainCanonical)`, ambiguous paths are resolved
    /// as workspace-root paths instead of relative paths.
    pub async fn parse_index_with_hint(
        &self,
        path: &Path,
        link_format: Option<LinkFormat>,
    ) -> Result<IndexFile> {
        let mut index = self.parse_index(path).await?;
        index.link_format_hint = link_format;
        Ok(index)
    }

    /// Parse a markdown file with caching. Returns a clone from the cache on hit,
    /// or parses and inserts on miss. `None` is cached for non-parseable files.
    async fn parse_index_cached(
        &self,
        path: &Path,
        cache: &mut HashMap<PathBuf, Option<IndexFile>>,
    ) -> Result<IndexFile> {
        let key = path.to_path_buf();
        if let Some(cached) = cache.get(&key) {
            return cached.clone().ok_or(DiaryxError::NoFrontmatter(key));
        }
        match self.parse_index(path).await {
            Ok(index) => {
                cache.insert(key, Some(index.clone()));
                Ok(index)
            }
            Err(e) => {
                cache.insert(key, None);
                Err(e)
            }
        }
    }

    /// Check if a file is an index file (has contents property)
    pub async fn is_index_file(&self, path: &Path) -> bool {
        if path.extension().is_none_or(|ext| ext != "md") {
            return false;
        }

        self.parse_index(path)
            .await
            .map(|idx| idx.frontmatter.is_index())
            .unwrap_or(false)
    }

    /// Check if a file is a root index (has contents but no part_of)
    pub async fn is_root_index(&self, path: &Path) -> bool {
        self.parse_index(path)
            .await
            .map(|idx| idx.frontmatter.is_root())
            .unwrap_or(false)
    }

    /// Find a root index in the given directory
    pub async fn find_root_index_in_dir(&self, dir: &Path) -> Result<Option<PathBuf>> {
        let md_files = self
            .fs
            .list_md_files(dir)
            .await
            .map_err(|e| DiaryxError::FileRead {
                path: dir.to_path_buf(),
                source: e,
            })?;

        for file in md_files {
            if self.is_root_index(&file).await {
                return Ok(Some(file));
            }
        }

        Ok(None)
    }

    /// Find any index file in the given directory (has `contents` property)
    /// Prefers root indexes over non-root indexes
    pub async fn find_any_index_in_dir(&self, dir: &Path) -> Result<Option<PathBuf>> {
        let md_files = self
            .fs
            .list_md_files(dir)
            .await
            .map_err(|e| DiaryxError::FileRead {
                path: dir.to_path_buf(),
                source: e,
            })?;

        let mut found_index: Option<PathBuf> = None;

        for file in md_files {
            if let Ok(index) = self.parse_index(&file).await
                && index.frontmatter.is_index()
            {
                // Prefer root index if found
                if index.frontmatter.is_root() {
                    return Ok(Some(file));
                }
                // Otherwise remember the first index we find
                if found_index.is_none() {
                    found_index = Some(file);
                }
            }
        }

        Ok(found_index)
    }

    /// Cached variant of `find_any_index_in_dir` for use during tree builds.
    async fn find_any_index_in_dir_cached(
        &self,
        dir: &Path,
        cache: &mut HashMap<PathBuf, Option<IndexFile>>,
    ) -> Result<Option<PathBuf>> {
        let md_files = self
            .fs
            .list_md_files(dir)
            .await
            .map_err(|e| DiaryxError::FileRead {
                path: dir.to_path_buf(),
                source: e,
            })?;

        let mut found_index: Option<PathBuf> = None;

        for file in md_files {
            if let Ok(index) = self.parse_index_cached(&file, cache).await
                && index.frontmatter.is_index()
            {
                if index.frontmatter.is_root() {
                    return Ok(Some(file));
                }
                if found_index.is_none() {
                    found_index = Some(file);
                }
            }
        }

        Ok(found_index)
    }

    /// Find the nearest index file by walking up directories from the given path.
    ///
    /// Starting from the parent directory of `path`, searches each directory
    /// for an index file (via `find_any_index_in_dir`), walking up the tree
    /// until one is found or the root is reached.
    pub async fn find_nearest_index(&self, path: &Path) -> Result<Option<PathBuf>> {
        let mut current = path.parent();
        while let Some(dir) = current {
            if let Some(index) = self.find_any_index_in_dir(dir).await? {
                // Don't return the file itself as its own "nearest index"
                if index != path {
                    return Ok(Some(index));
                }
            }
            current = dir.parent();
        }
        Ok(None)
    }

    /// Collect all files reachable from an index via `contents` traversal
    /// Returns a list of all files including the index itself and all nested contents
    pub async fn collect_workspace_files(&self, index_path: &Path) -> Result<Vec<PathBuf>> {
        let mut files = Vec::new();
        let mut visited = HashSet::new();

        // Get link format from workspace config for proper path resolution
        let link_format = self
            .get_workspace_config(index_path)
            .await
            .map(|c| c.link_format)
            .ok();

        // Get the workspace root directory (parent of root index file)
        let workspace_root = index_path.parent().unwrap_or(Path::new(".")).to_path_buf();

        self.collect_workspace_files_recursive(
            index_path,
            &mut files,
            &mut visited,
            link_format,
            &workspace_root,
        )
        .await?;
        files.sort();
        Ok(files)
    }

    /// Given the absolute path of an attachment note, reads its `attachment`
    /// frontmatter field and resolves it to the canonical binary path.
    ///
    /// Returns `None` if the file cannot be parsed or has no `attachment` field.
    pub async fn resolve_attachment_binary(
        &self,
        note_path: &Path,
        workspace_root: &Path,
        link_format: Option<LinkFormat>,
    ) -> Option<String> {
        let index = self
            .parse_index_with_hint(note_path, link_format)
            .await
            .ok()?;
        let attachment_link = index.frontmatter.attachment.as_ref()?;
        let binary_resolved = index.resolve_path(attachment_link);
        let binary_full = resolve_workspace_path(workspace_root, &binary_resolved);
        Some(canonical_workspace_path(&binary_full, workspace_root))
    }

    /// Collect the canonical workspace file set for sync/export operations.
    ///
    /// This includes all markdown files reachable from the logical workspace
    /// tree plus any attachment files declared in reachable entries'
    /// frontmatter.
    pub async fn collect_workspace_file_set(&self, index_path: &Path) -> Result<Vec<String>> {
        let workspace_root = index_path.parent().unwrap_or(Path::new(".")).to_path_buf();
        let link_format = self
            .get_workspace_config(index_path)
            .await
            .map(|c| c.link_format)
            .ok();

        let mut files = BTreeSet::new();
        let mut visited = HashSet::new();
        self.collect_workspace_file_set_recursive(
            index_path,
            &workspace_root,
            link_format,
            &mut files,
            &mut visited,
        )
        .await?;
        Ok(files.into_iter().collect())
    }

    /// Cached variant of `collect_exclude_patterns` for use during tree builds.
    async fn collect_exclude_patterns_cached(
        &self,
        index_path: &Path,
        cache: &mut HashMap<PathBuf, Option<IndexFile>>,
    ) -> Vec<String> {
        let mut patterns = Vec::new();
        let mut current_path = index_path.to_path_buf();
        let link_format = self
            .get_workspace_config(index_path)
            .await
            .ok()
            .map(|c| c.link_format);

        loop {
            // Use parse_index_cached but apply the link_format hint afterward
            let Ok(mut index) = self.parse_index_cached(&current_path, cache).await else {
                break;
            };
            index.link_format_hint = link_format;

            patterns.extend(index.frontmatter.exclude_list().iter().cloned());

            if let Some(part_of_ref) = index.frontmatter.part_of.as_ref() {
                let parent_path = resolve_workspace_path(
                    current_path.parent().unwrap_or(Path::new(".")),
                    &index.resolve_path(part_of_ref),
                );

                if self.fs.exists(&parent_path).await {
                    current_path = parent_path;
                    continue;
                }
            }

            break;
        }

        patterns
    }

    /// Cached variant of `exclude_patterns_for_dir` for use during tree builds.
    async fn exclude_patterns_for_dir_cached(
        &self,
        dir: &Path,
        workspace_root: &Path,
        cache: &mut HashMap<PathBuf, Option<IndexFile>>,
    ) -> Vec<String> {
        let mut current = Some(dir);
        while let Some(candidate) = current {
            if !candidate.starts_with(workspace_root) {
                break;
            }

            if let Ok(Some(index)) = self.find_any_index_in_dir_cached(candidate, cache).await {
                return self.collect_exclude_patterns_cached(&index, cache).await;
            }

            current = candidate.parent();
        }

        Vec::new()
    }

    fn workspace_relative_path(&self, workspace_root: &Path, path: &Path) -> String {
        let relative = path.strip_prefix(workspace_root).unwrap_or(path);
        normalize_sync_path(&relative.to_string_lossy().replace('\\', "/"))
    }

    fn path_matches_exclude(
        &self,
        pattern: &str,
        workspace_root: &Path,
        path: &Path,
        file_name: &str,
    ) -> bool {
        let relative_path = self.workspace_relative_path(workspace_root, path);
        matches_glob_pattern(pattern, file_name) || matches_glob_pattern(pattern, &relative_path)
    }

    async fn collect_workspace_file_set_recursive(
        &self,
        path: &Path,
        workspace_root: &Path,
        link_format: Option<LinkFormat>,
        files: &mut BTreeSet<String>,
        visited: &mut HashSet<String>,
    ) -> Result<()> {
        let canonical_path = canonical_workspace_path(path, workspace_root);
        if !visited.insert(canonical_path.clone()) {
            return Ok(());
        }
        files.insert(canonical_path);

        let index = match self.parse_index_with_hint(path, link_format).await {
            Ok(index) => index,
            Err(_) => return Ok(()),
        };

        for attachment_ref in index.frontmatter.attachments_list() {
            let attachment_full_path =
                resolve_workspace_path(workspace_root, &index.resolve_path(attachment_ref));

            if self.fs.exists(&attachment_full_path).await {
                files.insert(canonical_workspace_path(
                    &attachment_full_path,
                    workspace_root,
                ));

                // Follow the note's `attachment` field to include the actual binary
                if let Some(binary_canonical) = self
                    .resolve_attachment_binary(&attachment_full_path, workspace_root, link_format)
                    .await
                {
                    let binary_full =
                        resolve_workspace_path(workspace_root, Path::new(&binary_canonical));
                    if self.fs.exists(&binary_full).await {
                        files.insert(binary_canonical);
                    }
                }
            }
        }

        if !index.frontmatter.is_index() {
            return Ok(());
        }

        for child_ref in index.frontmatter.contents_list() {
            let child_full_path =
                resolve_workspace_path(workspace_root, &index.resolve_path(child_ref));

            if self.fs.exists(&child_full_path).await {
                Box::pin(self.collect_workspace_file_set_recursive(
                    &child_full_path,
                    workspace_root,
                    link_format,
                    files,
                    visited,
                ))
                .await?;
            }
        }

        Ok(())
    }

    /// Recursive helper for collecting workspace files
    async fn collect_workspace_files_recursive(
        &self,
        path: &Path,
        files: &mut Vec<PathBuf>,
        visited: &mut HashSet<PathBuf>,
        link_format: Option<LinkFormat>,
        workspace_root: &Path,
    ) -> Result<()> {
        // Canonicalize to handle relative paths consistently
        let canonical = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());

        // Avoid cycles
        if visited.contains(&canonical) {
            return Ok(());
        }
        visited.insert(canonical.clone());

        // Add this file to the list
        files.push(path.to_path_buf());

        // If this is an index file, recurse into its contents
        if let Ok(index) = self.parse_index_with_hint(path, link_format).await
            && index.frontmatter.is_index()
        {
            for child_path_str in index.frontmatter.contents_list() {
                let child_path = index.resolve_path(child_path_str);

                // Make path absolute if needed by joining with workspace root
                let absolute_child_path = if child_path.is_absolute() {
                    child_path
                } else {
                    workspace_root.join(&child_path)
                };

                // Only include if the file exists
                if self.fs.exists(&absolute_child_path).await {
                    Box::pin(self.collect_workspace_files_recursive(
                        &absolute_child_path,
                        files,
                        visited,
                        link_format,
                        workspace_root,
                    ))
                    .await?;
                }
            }
        }

        Ok(())
    }

    /// Detect the workspace root from the current directory
    /// Searches current directory for a root index file
    pub async fn detect_workspace(&self, start_dir: &Path) -> Result<Option<PathBuf>> {
        // Look for root index in start directory
        if let Some(root) = self.find_root_index_in_dir(start_dir).await? {
            return Ok(Some(root));
        }

        Ok(None)
    }

    /// Combine two index files by moving contents from source to target and deleting source.
    /// Also appends the body of source to target.
    pub async fn combine_indices(&self, source_path: &Path, target_path: &Path) -> Result<()> {
        // 1. Parse both indices
        let source_index = self.parse_index(source_path).await?;
        let target_index = self.parse_index(target_path).await?;

        // Ensure both are valid indices (though parse_index should error if not valid markdown/frontmatter)
        if !source_index.frontmatter.is_index() {
            return Err(DiaryxError::YamlParse {
                path: source_path.to_path_buf(),
                message: "Source is not an index file (missing contents)".to_string(),
            });
        }
        if !target_index.frontmatter.is_index() {
            return Err(DiaryxError::YamlParse {
                path: target_path.to_path_buf(),
                message: "Target is not an index file (missing contents)".to_string(),
            });
        }

        // 2. Prepare new contents for target
        let mut new_target_contents = target_index
            .frontmatter
            .contents
            .clone()
            .unwrap_or_default();

        // Get workspace root for path formatting
        // (Use configured root if available, else derive from target path)
        let workspace_root = self
            .root_path
            .clone()
            .unwrap_or_else(|| target_path.parent().unwrap_or(Path::new(".")).to_path_buf());

        // Get target's canonical path to format links relative to it
        let target_canonical = self.get_canonical_path(target_path);

        // 3. Process source children
        if let Some(ref source_contents) = source_index.frontmatter.contents {
            for child_ref in source_contents {
                // Resolve child to absolute path
                let child_path = source_index.resolve_path(child_ref);

                // Construct absolute path (resolve_path returns workspace-relative for root paths,
                // or file-relative otherwise. It's inconsistent in return type slightly - see resolve_path docs.
                // Actually resolve_path returns PathBuf. Let's look at resolve_path implementation.
                // It returns a PathBuf. If it's workspace-relative (from /), it's returned as such (relative).
                // If it's relative, it's joined with directory.
                // Wait, resolve_path implementation says:
                // "Returns an absolute path resolved against this index file's location."
                // BUT implementation of WorkspaceRoot case returns `PathBuf::from(&parsed.path)` which is NOT absolute
                // if it's just the string from the link without workspace root.
                // Let's re-read resolve_path carefully.
                // "Returns an absolute path resolved against this index file's location." -> implementation seems to try to do that.
                // BUT for WorkspaceRoot it says "Return as PathBuf directly - callers operate relative to workspace root."
                // So result might be "Folder/file.md" (relative to workspace root).

                let mut absolute_child_path = if child_path.is_absolute() {
                    child_path
                } else {
                    // It's relative to workspace root
                    workspace_root.join(&child_path)
                };

                // Verification: Check if the file exists.
                // If not, it might be because the path resolution logic misidentified a workspace-root path
                // as a relative path (e.g. "Daily/2026/01.md" inside "Daily/2026/index.md" resolves to
                // "Daily/2026/Daily/2026/01.md").
                if !self.fs.exists(&absolute_child_path).await {
                    let fallback_path = workspace_root.join(child_ref);
                    if self.fs.exists(&fallback_path).await {
                        log::info!(
                            "Resolved '{}' using fallback workspace-root strategy to {:?}",
                            child_ref,
                            fallback_path
                        );
                        absolute_child_path = fallback_path;
                    } else {
                        // If it still doesn't exist, we will likely error on write, but let's proceed
                        // to attempt write so the error is consistent (or maybe just warn?)
                        // For now, proceed, but let's log.
                        log::warn!(
                            "Child path '{}' resolved to {:?} which does not exist",
                            child_ref,
                            absolute_child_path
                        );
                    }
                }

                // Now we need to update the child's part_of to point to the target
                // We need to format the link from child to target
                let child_canonical = self.get_canonical_path(&absolute_child_path);

                // Update child's part_of
                // Format link FROM child TO target
                let part_of_link = self.format_link(&target_canonical, &child_canonical).await;

                self.set_frontmatter_property(
                    &absolute_child_path,
                    "part_of",
                    YamlValue::String(part_of_link),
                )
                .await?;

                // Add child to target contents
                // Format link FROM target TO child
                let child_link = self.format_link(&child_canonical, &target_canonical).await;
                new_target_contents.push(child_link);
            }
        }

        // 4. Update target index with new contents and appended body
        let mut target_frontmatter = target_index.frontmatter.clone();
        target_frontmatter.contents = Some(new_target_contents);

        // Append body
        let new_body = if source_index.body.trim().is_empty() {
            target_index.body
        } else if target_index.body.trim().is_empty() {
            source_index.body
        } else {
            format!("{}\n\n{}", target_index.body.trim_end(), source_index.body)
        };

        // We need to write back the target file.
        // We can use reconstruct_file-like logic here,
        // but `Workspace` doesn't have `reconstruct_file` directly exposed or easily reusable
        // without `IndexMap` which `IndexFrontmatter` isn't.
        // `IndexFrontmatter` derives `Serialize` so we can convert it to YAML.

        let yaml_str =
            serde_yaml::to_string(&target_frontmatter).map_err(|e| DiaryxError::YamlParse {
                path: target_path.to_path_buf(),
                message: e.to_string(),
            })?;

        let content = format!("---\n{}---\n{}", yaml_str, new_body);

        self.fs
            .write_file(target_path, &content)
            .await
            .map_err(|e| DiaryxError::FileWrite {
                path: target_path.to_path_buf(),
                source: e,
            })?;

        // 5. Delete source index file
        self.fs
            .delete_file(source_path)
            .await
            .map_err(|e| DiaryxError::FileWrite {
                path: source_path.to_path_buf(),
                source: e,
            })?;

        Ok(())
    }

    // ==================== Workspace Config Methods ====================

    /// Get the workspace configuration from the root index file's frontmatter.
    ///
    /// Reads `link_format` and other workspace-level settings from the root index.
    /// Returns default values if the properties aren't present.
    /// Known workspace config field names, used for migration from top-level
    /// frontmatter to the nested `workspace_config` section.
    const WORKSPACE_CONFIG_FIELDS: &'static [&'static str] = &[
        "link_format",
        "default_template",
        "sync_title_to_heading",
        "auto_update_timestamp",
        "auto_rename_to_title",
        "filename_style",
        "default_audience",
        "public_audience",
        "daily_entry_folder",
        "show_unlinked_files",
        "show_hidden_files",
        "theme_mode",
        "theme_preset",
        "theme_accent_hue",
        "audience_colors",
        "disabled_plugins",
    ];

    /// Resolve the `workspace_config` value from the root index.
    ///
    /// Returns the config source (a HashMap of field→Value) and, if the config
    /// lives in an external file, the resolved path to that file.
    ///
    /// The config source is determined by:
    /// 1. If `workspace_config` is a string → parse as a link, read that file's
    ///    frontmatter extra as the config source.
    /// 2. If `workspace_config` is a mapping → use it inline (nested section).
    /// 3. Otherwise → use the root index's own extra (flat/legacy format).
    async fn resolve_config_source(
        &self,
        root_index_path: &Path,
    ) -> Result<(
        std::collections::HashMap<String, YamlValue>,
        Option<PathBuf>,
    )> {
        let index = self.parse_index(root_index_path).await?;
        let extra = &index.frontmatter.extra;

        match extra.get("workspace_config") {
            // File link: workspace_config points to an external file
            Some(YamlValue::String(link_str)) => {
                let config_path = index.resolve_path(link_str);
                let config_index = self.parse_index(&config_path).await?;
                Ok((config_index.frontmatter.extra, Some(config_path)))
            }
            // Inline nested section: workspace_config is a YAML mapping
            Some(YamlValue::Mapping(map)) => {
                // YamlMapping already uses String keys, convert to HashMap
                let config: std::collections::HashMap<String, YamlValue> =
                    map.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
                Ok((config, None))
            }
            // No workspace_config key, or unexpected type → legacy flat format
            _ => Ok((extra.clone(), None)),
        }
    }

    /// Read workspace configuration from the root index file.
    ///
    /// Supports three storage modes (checked in order):
    /// 1. **File link** — `workspace_config: "[Config](/Meta/Config.md)"`
    /// 2. **Nested section** — `workspace_config:` mapping in frontmatter
    /// 3. **Legacy flat** — config fields at the top level of frontmatter
    pub async fn get_workspace_config(&self, root_index_path: &Path) -> Result<WorkspaceConfig> {
        let (config_extra, _config_path) = self.resolve_config_source(root_index_path).await?;

        // Also load the root index extra for backward-compat fallback
        // (fields that haven't been migrated yet may still be at the top level).
        let index = self.parse_index(root_index_path).await?;
        let root_extra = &index.frontmatter.extra;

        // config_get with nested=None since config_extra IS the resolved source.
        // We look in config_extra first, then fall back to root_extra.
        let get = |key: &str| -> Option<&YamlValue> {
            config_extra.get(key).or_else(|| root_extra.get(key))
        };

        let link_format = get("link_format")
            .and_then(|v| v.as_str())
            .and_then(|s| match s {
                "markdown_root" => Some(LinkFormat::MarkdownRoot),
                "markdown_relative" => Some(LinkFormat::MarkdownRelative),
                "plain_relative" => Some(LinkFormat::PlainRelative),
                "plain_canonical" => Some(LinkFormat::PlainCanonical),
                _ => None,
            })
            .unwrap_or_default();

        let default_template = get("default_template")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        let sync_title_to_heading = get("sync_title_to_heading")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        let auto_update_timestamp = get("auto_update_timestamp")
            .and_then(|v| v.as_bool())
            .unwrap_or(true);

        let auto_rename_to_title = get("auto_rename_to_title")
            .and_then(|v| v.as_bool())
            .unwrap_or(true);

        let filename_style = get("filename_style")
            .and_then(|v| v.as_str())
            .and_then(|s| match s {
                "preserve" => Some(FilenameStyle::Preserve),
                "kebab_case" => Some(FilenameStyle::KebabCase),
                "snake_case" => Some(FilenameStyle::SnakeCase),
                "screaming_snake_case" => Some(FilenameStyle::ScreamingSnakeCase),
                _ => None,
            })
            .unwrap_or_default();

        let default_audience = get("default_audience")
            .or_else(|| get("public_audience"))
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        let daily_entry_folder = get("daily_entry_folder")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        let show_unlinked_files = get("show_unlinked_files").and_then(|v| v.as_bool());

        let show_hidden_files = get("show_hidden_files").and_then(|v| v.as_bool());

        let theme_mode = get("theme_mode")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        let theme_preset = get("theme_preset")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        let theme_accent_hue = get("theme_accent_hue").and_then(|v| v.as_f64());

        let audience_colors = get("audience_colors")
            .and_then(|v| v.as_mapping())
            .map(|m| {
                m.iter()
                    .filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_string())))
                    .collect()
            });

        let disabled_plugins = get("disabled_plugins")
            .and_then(|v| v.as_sequence())
            .map(|seq| {
                seq.iter()
                    .filter_map(|v| v.as_str().map(|s| s.to_string()))
                    .collect()
            });

        Ok(WorkspaceConfig {
            link_format,
            default_template,
            sync_title_to_heading,
            auto_update_timestamp,
            auto_rename_to_title,
            filename_style,
            default_audience,
            daily_entry_folder,
            show_unlinked_files,
            show_hidden_files,
            theme_mode,
            theme_preset,
            theme_accent_hue,
            audience_colors,
            disabled_plugins,
        })
    }

    /// Convert a string value to a YAML Value, handling booleans and JSON.
    fn parse_config_value(value: &str) -> YamlValue {
        match value {
            "true" => YamlValue::Bool(true),
            "false" => YamlValue::Bool(false),
            _ => {
                // Try parsing as JSON for scalars and complex types.
                if let Ok(json) = serde_json::from_str::<serde_json::Value>(value) {
                    match &json {
                        serde_json::Value::String(_) => YamlValue::String(value.to_string()),
                        _ => YamlValue::from(json),
                    }
                } else {
                    YamlValue::String(value.to_string())
                }
            }
        }
    }

    /// Set a workspace configuration field.
    ///
    /// The config destination is determined by `workspace_config` in the root
    /// index frontmatter:
    /// - **String (file link):** resolves to a file; writes the field there.
    /// - **Mapping (inline):** writes into the nested `workspace_config` section.
    /// - **Absent:** creates an inline `workspace_config` section and writes there.
    ///
    /// On the first inline write, any known config fields found at the top level
    /// are migrated into the nested section (opportunistic migration).
    pub async fn set_workspace_config_field(
        &self,
        root_index_path: &Path,
        field: &str,
        value: &str,
    ) -> Result<()> {
        let yaml_value = Self::parse_config_value(value);

        // Check if workspace_config is a file link
        let index = self.parse_index(root_index_path).await?;
        if let Some(YamlValue::String(link_str)) = index.frontmatter.extra.get("workspace_config") {
            // Resolve the link to a file path and write the field there
            let config_path = index.resolve_path(link_str);
            return self
                .set_frontmatter_property(&config_path, field, yaml_value)
                .await;
        }

        // Inline mode: write into the nested workspace_config section
        let content =
            self.fs
                .read_to_string(root_index_path)
                .await
                .map_err(|e| DiaryxError::FileRead {
                    path: root_index_path.to_path_buf(),
                    source: e,
                })?;

        let (mut frontmatter, body) =
            if content.starts_with("---\n") || content.starts_with("---\r\n") {
                let rest = &content[4..];
                if let Some(idx) = rest.find("\n---\n").or_else(|| rest.find("\n---\r\n")) {
                    let frontmatter_str = &rest[..idx];
                    let body = &rest[idx + 5..];
                    let fm: indexmap::IndexMap<String, YamlValue> =
                        serde_yaml::from_str(frontmatter_str)?;
                    (fm, body.to_string())
                } else {
                    (indexmap::IndexMap::new(), content)
                }
            } else {
                (indexmap::IndexMap::new(), content)
            };

        // Opportunistic migration: collect top-level config fields and their
        // values so we can move them into the nested workspace_config section.
        let migrated: Vec<(String, YamlValue)> = frontmatter
            .iter()
            .filter(|(k, _)| {
                *k != "workspace_config" && Self::WORKSPACE_CONFIG_FIELDS.contains(&k.as_str())
            })
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect();

        // Remove migrated keys from top level
        for (key, _) in &migrated {
            frontmatter.shift_remove(key);
        }

        // Get or create the workspace_config sub-map
        let config_section = frontmatter
            .entry("workspace_config".to_string())
            .or_insert_with(|| YamlValue::Mapping(indexmap::IndexMap::new()));

        let config_map = match config_section {
            YamlValue::Mapping(m) => m,
            _ => {
                *config_section = YamlValue::Mapping(indexmap::IndexMap::new());
                config_section.as_mapping_mut().unwrap()
            }
        };

        // Insert migrated values (only if not already present in nested section)
        for (key, val) in migrated {
            if !config_map.contains_key(&key) {
                config_map.insert(key, val);
            }
        }

        // Set the new field value
        config_map.insert(field.to_string(), yaml_value);

        let yaml_str = serde_yaml::to_string(&frontmatter)?;
        let new_content = format!("---\n{}---\n{}", yaml_str, body);

        self.fs
            .write_file(root_index_path, &new_content)
            .await
            .map_err(|e| DiaryxError::FileWrite {
                path: root_index_path.to_path_buf(),
                source: e,
            })
    }

    /// Get the link format configuration from a workspace root index.
    pub async fn get_link_format(&self, root_index_path: &Path) -> Result<LinkFormat> {
        let config = self.get_workspace_config(root_index_path).await?;
        Ok(config.link_format)
    }

    /// Set the link format configuration in a workspace root index.
    pub async fn set_link_format(&self, root_index_path: &Path, format: LinkFormat) -> Result<()> {
        let format_str = match format {
            LinkFormat::MarkdownRoot => "markdown_root",
            LinkFormat::MarkdownRelative => "markdown_relative",
            LinkFormat::PlainRelative => "plain_relative",
            LinkFormat::PlainCanonical => "plain_canonical",
        };
        self.set_workspace_config_field(root_index_path, "link_format", format_str)
            .await
    }

    /// Resolve workspace: check current dir, then fall back to config default
    pub async fn resolve_workspace(&self, current_dir: &Path, config: &Config) -> Result<PathBuf> {
        // First, try to detect workspace in current directory
        if let Some(root) = self.detect_workspace(current_dir).await? {
            return Ok(root);
        }

        // Fall back to config's default_workspace and look for root index there
        if let Some(root) = self
            .find_root_index_in_dir(&config.default_workspace)
            .await?
        {
            return Ok(root);
        }

        // If no root index exists in default_workspace, return the expected README.md path
        // (it may need to be created)
        Ok(config.default_workspace.join("README.md"))
    }

    /// Initialize a new workspace with a root index file
    pub async fn init_workspace(
        &self,
        dir: &Path,
        title: Option<&str>,
        description: Option<&str>,
    ) -> Result<PathBuf> {
        // Check if ANY root index already exists in this directory
        // (not just README.md - could be index.md or any other .md file)
        if let Ok(Some(existing_root)) = self.find_root_index_in_dir(dir).await {
            return Err(DiaryxError::WorkspaceAlreadyExists(existing_root));
        }

        let readme_path = dir.join("README.md");

        // Create directory if needed
        self.fs.create_dir_all(dir).await?;

        let display_title = title.unwrap_or_else(|| {
            dir.file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("Workspace")
        });

        let desc = description.unwrap_or("A diaryx workspace");

        let content = format!(
            "---\ntitle: {}\ndescription: {}\ncontents: []\n---\n\n# {}\n\n{}\n",
            display_title, desc, display_title, desc
        );

        self.fs
            .create_new(&readme_path, &content)
            .await
            .map_err(|e| DiaryxError::FileWrite {
                path: readme_path.clone(),
                source: e,
            })?;

        Ok(readme_path)
    }

    /// Build a tree structure from the workspace hierarchy
    pub async fn build_tree(&self, root_path: &Path) -> Result<TreeNode> {
        self.build_tree_with_depth(root_path, None, &mut HashSet::new())
            .await
    }

    /// Build a tree structure with depth limit and cycle detection
    /// `max_depth` of None means unlimited, Some(0) means just the root node
    pub async fn build_tree_with_depth(
        &self,
        root_path: &Path,
        max_depth: Option<usize>,
        visited: &mut HashSet<PathBuf>,
    ) -> Result<TreeNode> {
        // Get link format from workspace config for proper path resolution
        let link_format = self
            .get_workspace_config(root_path)
            .await
            .map(|c| c.link_format)
            .ok();

        // Get the actual workspace root directory.
        // IMPORTANT: We must use self.root_path (the configured workspace root) rather than
        // deriving from root_path. When loading children for nested paths like
        // ./new-entry/new-entry-1/new-entry-1.md, workspace-root paths in contents
        // (like /new-entry/new-entry-1/new-entry.md) need to be resolved relative to
        // the ACTUAL workspace root, not the parent of the current file.
        let workspace_root = self
            .root_path
            .clone()
            .unwrap_or_else(|| root_path.parent().unwrap_or(Path::new(".")).to_path_buf());

        self.build_tree_with_depth_and_format(
            root_path,
            max_depth,
            visited,
            link_format,
            &workspace_root,
        )
        .await
    }

    /// Build a tree structure with depth limit, cycle detection, and explicit link format.
    ///
    /// This is the internal implementation that handles tree building.
    /// Use `build_tree_with_depth` for public API which auto-detects the link format.
    async fn build_tree_with_depth_and_format(
        &self,
        root_path: &Path,
        max_depth: Option<usize>,
        visited: &mut HashSet<PathBuf>,
        link_format: Option<LinkFormat>,
        workspace_root: &Path,
    ) -> Result<TreeNode> {
        let index = self.parse_index_with_hint(root_path, link_format).await?;

        // Canonicalize path for cycle detection
        let canonical = root_path
            .canonicalize()
            .unwrap_or_else(|_| root_path.to_path_buf());

        // Check for cycles
        if visited.contains(&canonical) {
            return Ok(TreeNode {
                name: format!(
                    "{} (cycle)",
                    root_path.file_name().unwrap_or_default().to_string_lossy()
                ),
                description: None,
                path: root_path.to_path_buf(),
                is_index: false,
                children: Vec::new(),
                properties: std::collections::HashMap::new(),
                audience: Vec::new(),
            });
        }
        visited.insert(canonical);

        let name = index
            .frontmatter
            .display_name()
            .map(String::from)
            .unwrap_or_else(|| {
                // Fall back to filename without extension
                root_path
                    .file_stem()
                    .and_then(|s| s.to_str())
                    .map(String::from)
                    .unwrap_or_else(|| root_path.display().to_string())
            });

        let mut children = Vec::new();
        let contents = index.frontmatter.contents_list();
        let child_count = contents.len();
        let mut seen_child_paths = HashSet::new();

        log::debug!(
            "[build_tree] Processing {}: contents={:?}, workspace_root={:?}",
            root_path.display(),
            contents,
            workspace_root
        );

        // Check if we've hit depth limit
        let at_depth_limit = max_depth.map(|d| d == 0).unwrap_or(false);

        if at_depth_limit && child_count > 0 {
            // Show truncation indicator
            children.push(TreeNode {
                name: format!("... ({} more)", child_count),
                description: None,
                path: root_path.to_path_buf(),
                is_index: false,
                children: Vec::new(),
                properties: std::collections::HashMap::new(),
                audience: Vec::new(),
            });
        } else {
            let next_depth = max_depth.map(|d| d.saturating_sub(1));

            for child_path_str in contents {
                let child_path = index.resolve_path(child_path_str);

                // Make path absolute if needed by joining with workspace root
                let absolute_child_path = if child_path.is_absolute() {
                    child_path.clone()
                } else {
                    workspace_root.join(&child_path)
                };

                let exists = self.fs.exists(&absolute_child_path).await;
                log::debug!(
                    "[build_tree] Child '{}' resolved to {:?}, exists={}",
                    child_path_str,
                    absolute_child_path,
                    exists
                );

                // Guard against duplicate entries in `contents` that resolve to
                // the same path. Duplicates can crash keyed UI rendering and do
                // not add useful information to the tree.
                if !seen_child_paths.insert(absolute_child_path.clone()) {
                    log::debug!(
                        "[build_tree] Skipping duplicate child path: {:?}",
                        absolute_child_path
                    );
                    continue;
                }

                // Only include if the file exists
                if exists {
                    match Box::pin(self.build_tree_with_depth_and_format(
                        &absolute_child_path,
                        next_depth,
                        visited,
                        link_format,
                        workspace_root,
                    ))
                    .await
                    {
                        Ok(child_node) => children.push(child_node),
                        Err(_) => {
                            // If we can't parse a child, include it as a leaf with error indication
                            children.push(TreeNode {
                                name: format!("{} (error)", child_path_str),
                                description: None,
                                path: absolute_child_path,
                                is_index: false,
                                children: Vec::new(),
                                properties: std::collections::HashMap::new(),
                                audience: Vec::new(),
                            });
                        }
                    }
                }
                // Ignore non-existent paths (as per spec: "ignore by default")
            }
        }

        let is_index = index.frontmatter.is_index();
        let audience = index.frontmatter.audience.clone().unwrap_or_default();
        Ok(TreeNode {
            name,
            description: index.frontmatter.description,
            path: root_path.to_path_buf(),
            is_index,
            children,
            properties: std::collections::HashMap::new(),
            audience,
        })
    }

    /// Build a tree structure from the actual filesystem (for "Show All Files" mode)
    /// Unlike build_tree, this scans directories for actual files rather than following contents references
    pub async fn build_filesystem_tree(
        &self,
        root_dir: &Path,
        show_hidden: bool,
    ) -> Result<TreeNode> {
        self.build_filesystem_tree_with_depth(root_dir, show_hidden, None)
            .await
    }

    /// Build a filesystem tree with optional depth limiting for lazy loading.
    /// Reads `exclude` patterns from the root directory's index file and skips
    /// matching entries during traversal.
    pub async fn build_filesystem_tree_with_depth(
        &self,
        root_dir: &Path,
        show_hidden: bool,
        max_depth: Option<usize>,
    ) -> Result<TreeNode> {
        let mut parse_cache: HashMap<PathBuf, Option<IndexFile>> = HashMap::new();
        let exclude_patterns = self
            .exclude_patterns_for_dir_cached(root_dir, root_dir, &mut parse_cache)
            .await;
        let mut trace = FilesystemTreeTrace::default();
        let tree = self
            .build_filesystem_tree_recursive(
                root_dir,
                root_dir,
                show_hidden,
                max_depth,
                &exclude_patterns,
                &mut trace,
                &mut parse_cache,
            )
            .await?;

        log::info!(
            "[Workspace] Filesystem tree explored {} directories, pruned {} excluded dirs and {} built-in skip dirs",
            trace.explored_dirs.len(),
            trace.pruned_excluded_dirs.len(),
            trace.pruned_skip_dirs.len(),
        );
        log::debug!(
            "[Workspace] Filesystem tree explored directories: {:?}",
            trace.explored_dirs
        );
        log::debug!(
            "[Workspace] Filesystem tree pruned excluded directories: {:?}",
            trace.pruned_excluded_dirs
        );
        log::debug!(
            "[Workspace] Filesystem tree pruned built-in skip directories: {:?}",
            trace.pruned_skip_dirs
        );

        Ok(tree)
    }

    #[allow(clippy::too_many_arguments)]
    async fn build_filesystem_tree_recursive(
        &self,
        dir: &Path,
        root_dir: &Path,
        show_hidden: bool,
        max_depth: Option<usize>,
        exclude_patterns: &[String],
        trace: &mut FilesystemTreeTrace,
        parse_cache: &mut HashMap<PathBuf, Option<IndexFile>>,
    ) -> Result<TreeNode> {
        trace.record_explored(dir);
        // Get directory name for display
        let dir_name = dir
            .file_name()
            .map(|n| n.to_string_lossy().to_string())
            .unwrap_or_else(|| dir.to_string_lossy().to_string());

        // Try to find an index file in this directory to get title/description
        let (name, description, index_path) =
            if let Ok(Some(index)) = self.find_any_index_in_dir_cached(dir, parse_cache).await {
                if let Ok(parsed) = self.parse_index_cached(&index, parse_cache).await {
                    let title = parsed.frontmatter.title.unwrap_or_else(|| dir_name.clone());
                    (title, parsed.frontmatter.description, Some(index))
                } else {
                    (dir_name.clone(), None, Some(index))
                }
            } else {
                (dir_name.clone(), None, None)
            };

        // The path to use - if there's an index, use it; otherwise use the directory
        let node_path = index_path.unwrap_or_else(|| dir.to_path_buf());

        // Check if we've hit depth limit
        let at_depth_limit = max_depth.map(|d| d == 0).unwrap_or(false);

        // List all entries in this directory
        let mut children = Vec::new();
        if let Ok(entries) = self.fs.list_files(dir).await {
            let mut entries: Vec<_> = entries.into_iter().collect();
            entries.sort(); // Sort alphabetically

            let mut filtered_entries = Vec::new();
            for entry in entries {
                let file_name = entry
                    .file_name()
                    .map(|n| n.to_string_lossy().to_string())
                    .unwrap_or_default();
                let hidden = !show_hidden && file_name.starts_with('.');
                let temp = crate::fs::is_temp_file(&file_name);
                let excluded = exclude_patterns.iter().any(|pattern| {
                    self.path_matches_exclude(pattern, root_dir, &entry, &file_name)
                });

                if hidden || temp || excluded {
                    if excluded && self.fs.is_dir(&entry).await {
                        trace.record_pruned_excluded(&entry);
                    }
                    continue;
                }

                if self.fs.is_dir(&entry).await && is_workspace_skip_dir(&entry) {
                    trace.record_pruned_skip(&entry);
                    continue;
                }

                filtered_entries.push(entry);
            }

            // If at depth limit, show truncation indicator
            if at_depth_limit && !filtered_entries.is_empty() {
                children.push(TreeNode {
                    name: format!("... ({} more)", filtered_entries.len()),
                    description: None,
                    path: node_path.clone(),
                    is_index: false,
                    children: Vec::new(),
                    properties: std::collections::HashMap::new(),
                    audience: Vec::new(),
                });
            } else {
                let next_depth = max_depth.map(|d| d.saturating_sub(1));

                for entry in filtered_entries {
                    let file_name = entry
                        .file_name()
                        .map(|n| n.to_string_lossy().to_string())
                        .unwrap_or_default();

                    if self.fs.is_dir(&entry).await {
                        let child_exclude_patterns = self
                            .exclude_patterns_for_dir_cached(&entry, root_dir, parse_cache)
                            .await;
                        // Recurse into subdirectory with decremented depth
                        if let Ok(child_tree) = Box::pin(self.build_filesystem_tree_recursive(
                            &entry,
                            root_dir,
                            show_hidden,
                            next_depth,
                            &child_exclude_patterns,
                            trace,
                            parse_cache,
                        ))
                        .await
                        {
                            children.push(child_tree);
                        }
                    } else {
                        // For markdown files, parse once and use for both
                        // index detection and title extraction.
                        if entry.extension().is_some_and(|e| e == "md") {
                            if let Ok(parsed) = self.parse_index_cached(&entry, parse_cache).await {
                                // Skip index files (already represented by parent dir)
                                if parsed.frontmatter.is_index() {
                                    continue;
                                }
                                children.push(TreeNode {
                                    name: parsed.frontmatter.title.unwrap_or(file_name.clone()),
                                    description: parsed.frontmatter.description,
                                    audience: parsed
                                        .frontmatter
                                        .audience
                                        .clone()
                                        .unwrap_or_default(),
                                    path: entry,
                                    is_index: false,
                                    children: Vec::new(),
                                    properties: std::collections::HashMap::new(),
                                });
                            } else {
                                // Non-parseable .md file — show as leaf
                                children.push(TreeNode {
                                    name: file_name.clone(),
                                    description: None,
                                    path: entry,
                                    is_index: false,
                                    children: Vec::new(),
                                    properties: std::collections::HashMap::new(),
                                    audience: Vec::new(),
                                });
                            }
                        } else {
                            // Non-markdown file
                            children.push(TreeNode {
                                name: file_name.clone(),
                                description: None,
                                path: entry,
                                is_index: false,
                                children: Vec::new(),
                                properties: std::collections::HashMap::new(),
                                audience: Vec::new(),
                            });
                        }
                    }
                }
            }
        }

        Ok(TreeNode {
            name,
            description,
            path: node_path,
            is_index: true,
            children,
            properties: std::collections::HashMap::new(),
            audience: Vec::new(),
        })
    }

    /// Format tree for display (like the `tree` command)
    pub fn format_tree(&self, node: &TreeNode, prefix: &str) -> String {
        let mut result = String::new();

        // Add the current node (root has no connector)
        result.push_str(prefix);
        result.push_str(&node.name);

        // Add description if present
        if let Some(ref desc) = node.description {
            result.push_str(" - ");
            result.push_str(desc);
        }

        // Add properties if present (for root node)
        if !node.properties.is_empty() {
            let props: Vec<String> = node
                .properties
                .iter()
                .map(|(k, v)| format!("{}={}", k, v))
                .collect();
            result.push_str(" [");
            result.push_str(&props.join(", "));
            result.push(']');
        }

        result.push('\n');

        // Add children
        let child_count = node.children.len();
        for (i, child) in node.children.iter().enumerate() {
            let is_last_child = i == child_count - 1;
            let connector = if is_last_child {
                "└── "
            } else {
                "├── "
            };
            let child_prefix = if is_last_child { "    " } else { "│   " };

            result.push_str(prefix);
            result.push_str(connector);
            result.push_str(&format_tree_node(
                child,
                &format!("{}{}", prefix, child_prefix),
            ));
        }

        result
    }

    /// Format tree for display with custom delimiter-separated properties.
    ///
    /// Properties are output as values only (not key=value), in the order specified
    /// by the `properties` list, separated by `delimiter`.
    pub fn format_tree_with_delimiter(
        &self,
        node: &TreeNode,
        prefix: &str,
        properties: &[String],
        delimiter: &str,
    ) -> String {
        let mut result = String::new();

        // Add the current node (root has no connector)
        result.push_str(prefix);

        // Collect property values in order specified
        let prop_values: Vec<&str> = properties
            .iter()
            .filter_map(|key| node.properties.get(key).map(|v| v.as_str()))
            .collect();

        // Join with delimiter
        result.push_str(&prop_values.join(delimiter));
        result.push('\n');

        // Add children
        let child_count = node.children.len();
        for (i, child) in node.children.iter().enumerate() {
            let is_last_child = i == child_count - 1;
            let connector = if is_last_child {
                "└── "
            } else {
                "├── "
            };
            let child_prefix = if is_last_child { "    " } else { "│   " };

            result.push_str(prefix);
            result.push_str(connector);
            result.push_str(&self.format_tree_node_with_delimiter(
                child,
                &format!("{}{}", prefix, child_prefix),
                properties,
                delimiter,
            ));
        }

        result
    }

    /// Format a tree node with custom delimiter-separated properties (recursive helper).
    fn format_tree_node_with_delimiter(
        &self,
        node: &TreeNode,
        prefix: &str,
        properties: &[String],
        delimiter: &str,
    ) -> String {
        let mut result = String::new();

        // Collect property values in order specified
        let prop_values: Vec<&str> = properties
            .iter()
            .filter_map(|key| node.properties.get(key).map(|v| v.as_str()))
            .collect();

        // Join with delimiter
        result.push_str(&prop_values.join(delimiter));
        result.push('\n');

        // Add children
        let child_count = node.children.len();
        for (i, child) in node.children.iter().enumerate() {
            let is_last_child = i == child_count - 1;
            let connector = if is_last_child {
                "└── "
            } else {
                "├── "
            };
            let child_prefix = if is_last_child { "    " } else { "│   " };

            result.push_str(prefix);
            result.push_str(connector);
            result.push_str(&self.format_tree_node_with_delimiter(
                child,
                &format!("{}{}", prefix, child_prefix),
                properties,
                delimiter,
            ));
        }

        result
    }

    /// Get workspace info as formatted string
    pub async fn workspace_info(&self, root_path: &Path) -> Result<String> {
        self.workspace_info_with_depth(root_path, None).await
    }

    /// Get workspace info as formatted string with depth limit
    /// `max_depth` of None means unlimited
    pub async fn workspace_info_with_depth(
        &self,
        root_path: &Path,
        max_depth: Option<usize>,
    ) -> Result<String> {
        let mut visited = HashSet::new();
        let tree = self
            .build_tree_with_depth(root_path, max_depth, &mut visited)
            .await?;
        Ok(self.format_tree(&tree, "").trim_end().to_string())
    }

    /// Get workspace info as formatted string with depth limit and property extraction.
    ///
    /// `max_depth` of None means unlimited.
    /// `properties` is a list of frontmatter property names to extract and display.
    /// `delimiter` is the separator between property values (e.g., " - ").
    ///
    /// Special virtual properties:
    /// - `filename`: The actual file name (e.g., `README.md`)
    /// - `path`: Workspace-relative file path
    pub async fn workspace_info_with_properties(
        &self,
        root_path: &Path,
        max_depth: Option<usize>,
        properties: &[String],
        delimiter: &str,
    ) -> Result<String> {
        let mut visited = HashSet::new();
        let mut tree = self
            .build_tree_with_depth(root_path, max_depth, &mut visited)
            .await?;

        // Determine workspace root (parent directory of root index file)
        let workspace_root = root_path.parent().unwrap_or(Path::new("."));

        // Extract properties from frontmatter for each node
        self.populate_tree_properties(&mut tree, properties, workspace_root)
            .await;

        Ok(self
            .format_tree_with_delimiter(&tree, "", properties, delimiter)
            .trim_end()
            .to_string())
    }

    /// Recursively populate properties for a tree node and its children
    async fn populate_tree_properties(
        &self,
        node: &mut TreeNode,
        properties: &[String],
        workspace_root: &Path,
    ) {
        // Extract properties for this node
        node.properties = self
            .extract_properties(&node.path, properties, workspace_root)
            .await;

        // Recursively process children
        for child in &mut node.children {
            Box::pin(self.populate_tree_properties(child, properties, workspace_root)).await;
        }
    }

    /// Extract specified properties from a file's frontmatter.
    ///
    /// Handles virtual properties:
    /// - `filename`: The actual file name
    /// - `path`: Workspace-relative file path
    async fn extract_properties(
        &self,
        path: &Path,
        property_names: &[String],
        workspace_root: &Path,
    ) -> std::collections::HashMap<String, String> {
        let mut result = std::collections::HashMap::new();

        for name in property_names {
            let value = match name.as_str() {
                // Virtual properties
                "filename" => path.file_name().and_then(|n| n.to_str()).map(String::from),
                "path" => {
                    // Get workspace-relative path
                    let rel_path = path
                        .strip_prefix(workspace_root)
                        .unwrap_or(path)
                        .to_string_lossy()
                        .replace('\\', "/");
                    Some(rel_path)
                }

                // Frontmatter properties
                _ => match self.get_frontmatter_property(path, name).await {
                    Ok(Some(YamlValue::String(s))) => Some(s),
                    Ok(Some(YamlValue::Int(n))) => Some(n.to_string()),
                    Ok(Some(YamlValue::Float(f))) => Some(f.to_string()),
                    Ok(Some(YamlValue::Bool(b))) => Some(b.to_string()),
                    Ok(Some(YamlValue::Sequence(seq))) => {
                        // Join sequence values with ", "
                        let strings: Vec<String> = seq
                            .iter()
                            .filter_map(|v| match v {
                                YamlValue::String(s) => Some(s.clone()),
                                YamlValue::Int(n) => Some(n.to_string()),
                                YamlValue::Float(f) => Some(f.to_string()),
                                YamlValue::Bool(b) => Some(b.to_string()),
                                _ => None,
                            })
                            .collect();
                        if strings.is_empty() {
                            None
                        } else {
                            Some(strings.join(", "))
                        }
                    }
                    _ => None,
                },
            };

            if let Some(v) = value {
                result.insert(name.clone(), v);
            }
        }

        result
    }

    // ==================== Frontmatter Helper Methods ====================
    // These are internal helpers for manipulating frontmatter in workspace operations

    /// Get a frontmatter property from a file
    async fn get_frontmatter_property(&self, path: &Path, key: &str) -> Result<Option<YamlValue>> {
        let content = match self.fs.read_to_string(path).await {
            Ok(c) => c,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(e) => {
                return Err(DiaryxError::FileRead {
                    path: path.to_path_buf(),
                    source: e,
                });
            }
        };

        if !content.starts_with("---\n") && !content.starts_with("---\r\n") {
            return Ok(None);
        }

        let rest = &content[4..];
        let end_idx = rest.find("\n---\n").or_else(|| rest.find("\n---\r\n"));

        if let Some(idx) = end_idx {
            let frontmatter_str = &rest[..idx];
            let frontmatter: indexmap::IndexMap<String, YamlValue> =
                serde_yaml::from_str(frontmatter_str)?;
            Ok(frontmatter.get(key).cloned())
        } else {
            Ok(None)
        }
    }

    /// Set a frontmatter property in a file
    pub async fn set_frontmatter_property(
        &self,
        path: &Path,
        key: &str,
        value: YamlValue,
    ) -> Result<()> {
        let content = match self.fs.read_to_string(path).await {
            Ok(c) => c,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                // Create new file with just this property
                let mut frontmatter = indexmap::IndexMap::new();
                frontmatter.insert(key.to_string(), value);
                let yaml_str = serde_yaml::to_string(&frontmatter)?;
                let new_content = format!("---\n{}---\n", yaml_str);
                return self.fs.write_file(path, &new_content).await.map_err(|e| {
                    DiaryxError::FileWrite {
                        path: path.to_path_buf(),
                        source: e,
                    }
                });
            }
            Err(e) => {
                return Err(DiaryxError::FileRead {
                    path: path.to_path_buf(),
                    source: e,
                });
            }
        };

        let (mut frontmatter, body) =
            if content.starts_with("---\n") || content.starts_with("---\r\n") {
                let rest = &content[4..];
                if let Some(idx) = rest.find("\n---\n").or_else(|| rest.find("\n---\r\n")) {
                    let frontmatter_str = &rest[..idx];
                    let body = &rest[idx + 5..];
                    let fm: indexmap::IndexMap<String, YamlValue> =
                        serde_yaml::from_str(frontmatter_str)?;
                    (fm, body.to_string())
                } else {
                    (indexmap::IndexMap::new(), content)
                }
            } else {
                (indexmap::IndexMap::new(), content)
            };

        frontmatter.insert(key.to_string(), value);
        let yaml_str = serde_yaml::to_string(&frontmatter)?;
        let new_content = format!("---\n{}---\n{}", yaml_str, body);

        self.fs
            .write_file(path, &new_content)
            .await
            .map_err(|e| DiaryxError::FileWrite {
                path: path.to_path_buf(),
                source: e,
            })
    }

    /// Remove a frontmatter property from a file
    async fn remove_frontmatter_property(&self, path: &Path, key: &str) -> Result<()> {
        let content = match self.fs.read_to_string(path).await {
            Ok(c) => c,
            Err(_) => return Ok(()), // File doesn't exist, nothing to remove
        };

        if !content.starts_with("---\n") && !content.starts_with("---\r\n") {
            return Ok(()); // No frontmatter
        }

        let rest = &content[4..];
        let end_idx = match rest.find("\n---\n").or_else(|| rest.find("\n---\r\n")) {
            Some(idx) => idx,
            None => return Ok(()), // Malformed frontmatter
        };

        let frontmatter_str = &rest[..end_idx];
        let body = &rest[end_idx + 5..];

        let mut frontmatter: indexmap::IndexMap<String, YamlValue> =
            serde_yaml::from_str(frontmatter_str)?;
        frontmatter.shift_remove(key);

        let yaml_str = serde_yaml::to_string(&frontmatter)?;
        let new_content = format!("---\n{}---\n{}", yaml_str, body);

        self.fs
            .write_file(path, &new_content)
            .await
            .map_err(|e| DiaryxError::FileWrite {
                path: path.to_path_buf(),
                source: e,
            })
    }

    /// Normalize a path string by stripping leading "./" prefix
    fn normalize_contents_path(path: &str) -> &str {
        path.strip_prefix("./").unwrap_or(path)
    }

    /// Add an entry to an index's contents list (using raw entry string).
    /// For formatted links, use `add_to_index_contents_canonical` instead.
    pub async fn add_to_index_contents(&self, index_path: &Path, entry: &str) -> Result<bool> {
        // Normalize the entry path (strip leading ./)
        let normalized_entry = Self::normalize_contents_path(entry);

        // Parse the new entry to get its canonical path for comparison
        let parsed_entry = link_parser::parse_link(normalized_entry);
        let index_canonical = self.get_canonical_path(index_path);
        let entry_canonical = link_parser::to_canonical(&parsed_entry, Path::new(&index_canonical));

        match self.get_frontmatter_property(index_path, "contents").await {
            Ok(Some(YamlValue::Sequence(mut items))) => {
                // Check if entry already exists (comparing canonical paths)
                let already_exists = items.iter().any(|item| {
                    if let Some(s) = item.as_str() {
                        let parsed = link_parser::parse_link(s);
                        let existing_canonical =
                            link_parser::to_canonical(&parsed, Path::new(&index_canonical));
                        existing_canonical == entry_canonical
                    } else {
                        false
                    }
                });

                if !already_exists {
                    items.push(YamlValue::String(normalized_entry.to_string()));
                    // Sort contents for consistent ordering
                    items.sort_by(|a, b| {
                        let a_str = a.as_str().unwrap_or("");
                        let b_str = b.as_str().unwrap_or("");
                        a_str.cmp(b_str)
                    });
                    self.set_frontmatter_property(
                        index_path,
                        "contents",
                        YamlValue::Sequence(items),
                    )
                    .await?;
                    return Ok(true);
                }
                Ok(false)
            }
            Ok(None) => {
                // Create contents with just this entry (normalized)
                let items = vec![YamlValue::String(normalized_entry.to_string())];
                self.set_frontmatter_property(index_path, "contents", YamlValue::Sequence(items))
                    .await?;
                Ok(true)
            }
            _ => {
                // Contents exists but isn't a sequence, or error reading - skip
                Ok(false)
            }
        }
    }

    /// Add an entry to an index's contents list using a canonical path.
    /// This formats the link according to the configured link_format.
    pub async fn add_to_index_contents_canonical(
        &self,
        index_path: &Path,
        entry_canonical: &str,
        title: &str,
    ) -> Result<bool> {
        let index_canonical = self.get_canonical_path(index_path);

        // Format the entry based on link format
        let formatted_entry = if self.root_path.is_some() {
            self.format_link_sync(entry_canonical, title, &index_canonical)
        } else {
            // Fallback: just use the canonical path
            entry_canonical.to_string()
        };

        // Extract canonical path from existing entries for comparison
        let entry_for_comparison = entry_canonical;

        match self.get_frontmatter_property(index_path, "contents").await {
            Ok(Some(YamlValue::Sequence(mut items))) => {
                // Check if entry already exists (comparing canonical paths)
                let already_exists = items.iter().any(|item| {
                    if let Some(s) = item.as_str() {
                        // Parse the existing item to get its canonical path
                        let parsed = link_parser::parse_link(s);
                        let existing_canonical =
                            link_parser::to_canonical(&parsed, Path::new(&index_canonical));
                        existing_canonical == entry_for_comparison
                    } else {
                        false
                    }
                });

                if !already_exists {
                    items.push(YamlValue::String(formatted_entry));
                    // Sort contents for consistent ordering
                    items.sort_by(|a, b| {
                        let a_str = a.as_str().unwrap_or("");
                        let b_str = b.as_str().unwrap_or("");
                        a_str.cmp(b_str)
                    });
                    self.set_frontmatter_property(
                        index_path,
                        "contents",
                        YamlValue::Sequence(items),
                    )
                    .await?;
                    return Ok(true);
                }
                Ok(false)
            }
            Ok(None) => {
                // Create contents with just this entry
                let items = vec![YamlValue::String(formatted_entry)];
                self.set_frontmatter_property(index_path, "contents", YamlValue::Sequence(items))
                    .await?;
                Ok(true)
            }
            _ => {
                // Contents exists but isn't a sequence, or error reading - skip
                Ok(false)
            }
        }
    }

    /// Remove an entry from an index's contents list.
    ///
    /// The `entry` can be:
    /// - A plain filename: `new-entry.md`
    /// - A relative path: `subdir/file.md`
    /// - A markdown link: `[Title](/path/to/file.md)`
    ///
    /// This properly handles markdown links in the contents list by comparing
    /// canonical paths.
    async fn remove_from_index_contents(&self, index_path: &Path, entry: &str) -> Result<bool> {
        // Parse the entry to remove to get its canonical form
        let parsed_entry = link_parser::parse_link(entry);
        let index_canonical = self.get_canonical_path(index_path);
        let entry_canonical = link_parser::to_canonical(&parsed_entry, Path::new(&index_canonical));

        self.remove_from_index_contents_impl(index_path, &index_canonical, &entry_canonical)
            .await
    }

    /// Remove an entry from an index's contents list using a pre-computed
    /// canonical path.
    ///
    /// Use this instead of [`remove_from_index_contents`] when the entry path
    /// is already a workspace-relative canonical path (e.g. from
    /// [`get_canonical_path`]). Passing a canonical path through the regular
    /// method would double-resolve it when the file lives in a subdirectory.
    async fn remove_from_index_contents_canonical(
        &self,
        index_path: &Path,
        entry_canonical: &str,
    ) -> Result<bool> {
        let index_canonical = self.get_canonical_path(index_path);
        self.remove_from_index_contents_impl(index_path, &index_canonical, entry_canonical)
            .await
    }

    async fn remove_from_index_contents_impl(
        &self,
        index_path: &Path,
        index_canonical: &str,
        entry_canonical: &str,
    ) -> Result<bool> {
        match self.get_frontmatter_property(index_path, "contents").await {
            Ok(Some(YamlValue::Sequence(mut items))) => {
                let before_len = items.len();
                // Remove entries that match when comparing canonical paths
                items.retain(|item| {
                    if let Some(s) = item.as_str() {
                        // Parse the existing item to get its canonical path
                        let parsed = link_parser::parse_link(s);
                        let existing_canonical =
                            link_parser::to_canonical(&parsed, Path::new(&index_canonical));
                        existing_canonical != entry_canonical
                    } else {
                        true
                    }
                });

                if items.len() != before_len {
                    // Sort contents for consistent ordering
                    items.sort_by(|a, b| {
                        let a_str = a.as_str().unwrap_or("");
                        let b_str = b.as_str().unwrap_or("");
                        a_str.cmp(b_str)
                    });
                    self.set_frontmatter_property(
                        index_path,
                        "contents",
                        YamlValue::Sequence(items),
                    )
                    .await?;
                    return Ok(true);
                }
                Ok(false)
            }
            Ok(None) | Ok(Some(_)) => {
                // No contents property or not a sequence - nothing to remove
                Ok(false)
            }
            Err(_) => {
                // Error reading - skip
                Ok(false)
            }
        }
    }

    // ==================== Entry Management Methods ====================

    /// Attach an entry to a parent index, creating bidirectional links.
    ///
    /// This method:
    /// - Adds the entry to the parent index's `contents` list (relative to parent's directory)
    /// - Sets the entry's `part_of` property to point to the parent index (relative to entry)
    ///
    /// Both paths must exist.
    pub async fn attach_entry_to_parent(
        &self,
        entry_path: &Path,
        parent_index_path: &Path,
    ) -> Result<()> {
        use crate::path_utils::relative_path_from_file_to_target;

        // Validate both paths exist
        if !self.fs.exists(entry_path).await {
            return Err(DiaryxError::FileRead {
                path: entry_path.to_path_buf(),
                source: std::io::Error::new(std::io::ErrorKind::NotFound, "Entry does not exist"),
            });
        }
        if !self.fs.exists(parent_index_path).await {
            return Err(DiaryxError::FileRead {
                path: parent_index_path.to_path_buf(),
                source: std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "Parent index does not exist",
                ),
            });
        }

        // Resolve old parent before making any changes, so we can remove the
        // entry from its old parent's contents after attaching it to the new one.
        let entry_dir = entry_path.parent();
        let old_index_path = self
            .resolve_part_of_from_dir(entry_path, entry_dir, entry_dir.unwrap_or(Path::new("")))
            .await;

        // Add entry to parent's contents with proper formatting
        let entry_canonical = self.get_canonical_path(entry_path);
        let title = self.resolve_title(&entry_canonical).await;
        self.add_to_index_contents_canonical(parent_index_path, &entry_canonical, &title)
            .await?;

        // Remove entry from old parent's contents (if it had one and it differs from new parent).
        if let Some(old_index_path) = old_index_path.as_ref()
            && old_index_path != parent_index_path
            && let Err(e) = self
                .remove_from_index_contents_canonical(old_index_path, &entry_canonical)
                .await
        {
            log::warn!(
                "attach_entry_to_parent: failed to remove old contents reference '{}' from '{}': {}",
                entry_canonical,
                old_index_path.display(),
                e
            );
        }

        // Set entry's part_of with proper formatting
        let part_of = if self.root_path.is_some() {
            let parent_canonical = self.get_canonical_path(parent_index_path);
            let parent_title = self.resolve_title(&parent_canonical).await;
            self.format_link_sync(&parent_canonical, &parent_title, &entry_canonical)
        } else {
            relative_path_from_file_to_target(entry_path, parent_index_path)
        };
        self.set_frontmatter_property(entry_path, "part_of", YamlValue::String(part_of))
            .await?;

        Ok(())
    }

    /// Move every file under `old_dir` into `new_dir`, preserving subdirectory
    /// structure. Works across every `AsyncFileSystem` backend by only ever
    /// calling `move_file` on leaf files — backends like OPFS/FSA don't
    /// implement directory moves, so we iterate rather than rely on a single
    /// directory rename.
    async fn move_dir_contents_recursive(&self, old_dir: &Path, new_dir: &Path) -> Result<()> {
        self.fs
            .create_dir_all(new_dir)
            .await
            .map_err(|e| DiaryxError::FileWrite {
                path: new_dir.to_path_buf(),
                source: e,
            })?;

        let entries = self
            .fs
            .list_files(old_dir)
            .await
            .map_err(|e| DiaryxError::FileRead {
                path: old_dir.to_path_buf(),
                source: e,
            })?;

        for entry in entries {
            let name = match entry.file_name() {
                Some(n) => n,
                None => continue,
            };
            let target = new_dir.join(name);

            if self.fs.is_dir(&entry).await {
                Box::pin(self.move_dir_contents_recursive(&entry, &target)).await?;
            } else {
                self.fs
                    .move_file(&entry, &target)
                    .await
                    .map_err(|e| DiaryxError::FileWrite {
                        path: target,
                        source: e,
                    })?;
            }
        }

        Ok(())
    }

    /// Walk every markdown file under `tree_root_dir` and rewrite each file's
    /// `part_of` to point at its directory-nearest ancestor index, using the
    /// workspace's link format for the current file location.
    ///
    /// This is how we heal descendants after a folder move: the moved tree
    /// has shifted to a new absolute path, so any `part_of` in `markdown_root`
    /// or other absolute formats still points into the old location. By
    /// re-snapping each descendant to `find_nearest_index`, every
    /// grandchild gets a freshly-formatted link against its (also-moved)
    /// nearest index.
    ///
    /// Only files that already have a `part_of` value are touched — this
    /// preserves detached files and avoids auto-attaching anything that
    /// wasn't already in the hierarchy.
    async fn rewrite_descendants_part_of_in_dir(
        &self,
        tree_root_dir: &Path,
        skip_path: Option<&Path>,
    ) -> Result<()> {
        use crate::path_utils::relative_path_from_file_to_target;

        let md_files = match self.fs.list_md_files_recursive(tree_root_dir).await {
            Ok(f) => f,
            Err(e) => {
                log::warn!(
                    "rewrite_descendants_part_of_in_dir: list failed for '{}': {}",
                    tree_root_dir.display(),
                    e
                );
                return Ok(());
            }
        };

        for file in md_files {
            if let Some(skip) = skip_path
                && file == skip
            {
                continue;
            }

            // Only rewrite files that already have an explicit part_of — we
            // don't want to auto-attach previously-detached files.
            let has_part_of = matches!(
                self.get_frontmatter_property(&file, "part_of").await,
                Ok(Some(_))
            );
            if !has_part_of {
                continue;
            }

            let nearest = match self.find_nearest_index(&file).await {
                Ok(Some(p)) => p,
                _ => continue,
            };
            if nearest == file {
                continue;
            }

            let part_of_value = if self.root_path.is_some() {
                let nearest_canonical = self.get_canonical_path(&nearest);
                let title = self.resolve_title(&nearest_canonical).await;
                let file_canonical = self.get_canonical_path(&file);
                self.format_link_sync(&nearest_canonical, &title, &file_canonical)
            } else {
                relative_path_from_file_to_target(&file, &nearest)
            };

            if let Err(e) = self
                .set_frontmatter_property(&file, "part_of", YamlValue::String(part_of_value))
                .await
            {
                log::warn!(
                    "rewrite_descendants_part_of_in_dir: failed to update '{}': {}",
                    file.display(),
                    e
                );
            }
        }

        Ok(())
    }

    /// Move/rename an entry while updating workspace index references.
    ///
    /// This method:
    /// - Moves the file from `from_path` to `to_path`
    /// - Removes the entry from old parent's `contents` (if parent index exists)
    /// - Adds the entry to new parent's `contents` (if parent index exists)
    /// - Updates the moved file's `part_of` to point to new parent index
    ///
    /// Returns `Ok(())` if successful. Does nothing if source equals destination.
    pub async fn move_entry(&self, from_path: &Path, to_path: &Path) -> Result<()> {
        // No-op if same path
        if from_path == to_path {
            return Ok(());
        }

        // Validate destination has a valid filename
        to_path
            .file_name()
            .and_then(|n| n.to_str())
            .ok_or_else(|| DiaryxError::InvalidPath {
                path: to_path.to_path_buf(),
                message: "Invalid destination file name".to_string(),
            })?;

        // Move the file
        self.fs
            .move_file(from_path, to_path)
            .await
            .map_err(|e| DiaryxError::FileWrite {
                path: to_path.to_path_buf(),
                source: e,
            })?;

        // Update hierarchy metadata (contents/part_of in parent indexes)
        self.sync_move_metadata(from_path, to_path).await
    }

    /// Update workspace hierarchy metadata after a file has been moved.
    ///
    /// Unlike `move_entry`, this does NOT move the file on the filesystem.
    /// The file must already exist at `new_path`. This is useful when an
    /// external tool (e.g., Obsidian, VS Code) has already performed the
    /// move and you need to fix up the `contents`/`part_of` frontmatter.
    ///
    /// This method:
    /// 1. Resolves the old parent index from the file's `part_of` at `new_path`,
    ///    using `old_path`'s directory as context for relative link resolution
    /// 2. Finds the new parent index in `new_path`'s directory
    /// 3. Adds the entry to the new parent's `contents`
    /// 4. Updates the entry's `part_of` if the parent changed
    /// 5. Removes the entry from the old parent's `contents`
    pub async fn sync_move_metadata(&self, old_path: &Path, new_path: &Path) -> Result<()> {
        use crate::path_utils::relative_path_from_file_to_target;

        if old_path == new_path {
            return Ok(());
        }

        let old_parent = old_path.parent().ok_or_else(|| DiaryxError::InvalidPath {
            path: old_path.to_path_buf(),
            message: "No parent directory for source path".to_string(),
        })?;
        new_path.parent().ok_or_else(|| DiaryxError::InvalidPath {
            path: new_path.to_path_buf(),
            message: "No parent directory for destination path".to_string(),
        })?;

        // Find old parent index by following part_of (the moved file still has its
        // original part_of at this point). Resolve relative links from the OLD
        // directory, since the part_of was written for the old location.
        let old_index_path = self
            .resolve_part_of_from_dir(new_path, Some(old_parent), old_parent)
            .await;
        // Use nearest index (not just the immediate directory), matching
        // sync_create_metadata/sync_delete_metadata semantics.
        let new_index_path = self.find_nearest_index(new_path).await?;

        // Add to new parent's contents first. This avoids "disappearing entry" states
        // if a transient write error occurs during index updates.
        if let Some(new_index_path) = new_index_path.as_ref() {
            // Add with proper formatting
            let new_path_canonical = self.get_canonical_path(new_path);
            let title = self.resolve_title(&new_path_canonical).await;
            self.add_to_index_contents_canonical(new_index_path, &new_path_canonical, &title)
                .await?;

            // Always recompute part_of from the new file location. Even when the
            // parent index is unchanged, relative formats can change across moves.
            let part_of_value = if self.root_path.is_some() {
                let new_index_canonical = self.get_canonical_path(new_index_path);
                let parent_title = self.resolve_title(&new_index_canonical).await;
                self.format_link_sync(&new_index_canonical, &parent_title, &new_path_canonical)
            } else {
                relative_path_from_file_to_target(new_path, new_index_path)
            };
            self.set_frontmatter_property(new_path, "part_of", YamlValue::String(part_of_value))
                .await?;
        } else {
            // No reachable parent index in the destination path. Remove stale
            // part_of to avoid broken references after external moves.
            self.remove_frontmatter_property(new_path, "part_of")
                .await?;
        }

        // Remove from old parent's contents after successful add to avoid lossy updates.
        if let Some(old_index_path) = old_index_path.as_ref() {
            let from_canonical = self.get_canonical_path(old_path);
            if let Err(e) = self
                .remove_from_index_contents_canonical(old_index_path, &from_canonical)
                .await
            {
                log::warn!(
                    "sync_move_metadata: failed to remove old contents reference '{}' from '{}': {}",
                    from_canonical,
                    old_index_path.display(),
                    e
                );
            }
        }

        // If the moved file is an index whose containing directory changed,
        // any descendants living in the new directory still have `part_of`
        // values written against the old location. Heal them by re-snapping
        // each one to its directory-nearest index at the new location.
        if old_path.parent() != new_path.parent()
            && self.is_index_file(new_path).await
            && let Some(new_dir) = new_path.parent()
        {
            self.rewrite_descendants_part_of_in_dir(new_dir, Some(new_path))
                .await?;
        }

        Ok(())
    }

    /// Update workspace hierarchy metadata after an external file creation.
    ///
    /// The file must already exist at `path`. This finds the nearest parent
    /// index and adds the file to its `contents`, then sets the file's
    /// `part_of` to point back to that index.
    ///
    /// Skips files that already have `part_of` (already attached) or
    /// `contents` (index files should not be auto-attached).
    pub async fn sync_create_metadata(&self, path: &Path) -> Result<()> {
        use crate::path_utils::relative_path_from_file_to_target;

        // Skip if file already has part_of (already in hierarchy)
        if let Ok(Some(_)) = self.get_frontmatter_property(path, "part_of").await {
            return Ok(());
        }

        // Skip if file is an index (has contents property)
        if self.is_index_file(path).await {
            return Ok(());
        }

        // Find nearest parent index
        let parent_index = match self.find_nearest_index(path).await? {
            Some(idx) => idx,
            None => return Ok(()), // No index found, nothing to do
        };

        // Add to parent index's contents
        let entry_canonical = self.get_canonical_path(path);
        let title = self.resolve_title(&entry_canonical).await;
        self.add_to_index_contents_canonical(&parent_index, &entry_canonical, &title)
            .await?;

        // Set file's part_of
        let part_of = if self.root_path.is_some() {
            let parent_canonical = self.get_canonical_path(&parent_index);
            let parent_title = self.resolve_title(&parent_canonical).await;
            self.format_link_sync(&parent_canonical, &parent_title, &entry_canonical)
        } else {
            relative_path_from_file_to_target(path, &parent_index)
        };
        self.set_frontmatter_property(path, "part_of", YamlValue::String(part_of))
            .await?;

        Ok(())
    }

    /// Update workspace hierarchy metadata after an external file deletion.
    ///
    /// The file at `path` no longer exists on disk. This finds the nearest
    /// parent index (by walking up directories) and removes the file from
    /// its `contents` list.
    pub async fn sync_delete_metadata(&self, path: &Path) -> Result<()> {
        // Find nearest parent index by walking up from the deleted file's directory
        let parent_index = match self.find_nearest_index(path).await? {
            Some(idx) => idx,
            None => return Ok(()), // No index found, nothing to do
        };

        // Remove from parent index's contents
        let entry_canonical = self.get_canonical_path(path);
        let _ = self
            .remove_from_index_contents_canonical(&parent_index, &entry_canonical)
            .await;

        Ok(())
    }

    /// Delete an entry while updating workspace index references.
    ///
    /// This method:
    /// - Fails if the entry is an index with non-empty `contents` (has children)
    /// - Removes the entry from parent's `contents` (if parent index exists)
    /// - Deletes the file
    ///
    /// For index files with directories, only the file is deleted (not the directory).
    pub async fn delete_entry(&self, path: &Path) -> Result<()> {
        // Check if this is an index file with children
        if let Ok(index) = self.parse_index(path).await {
            let contents = index.frontmatter.contents_list();
            if !contents.is_empty() {
                return Err(DiaryxError::InvalidPath {
                    path: path.to_path_buf(),
                    message: format!(
                        "Cannot delete index with {} children. Delete children first.",
                        contents.len()
                    ),
                });
            }
        }

        // Get the filename and parent directory
        let parent = path.parent().ok_or_else(|| DiaryxError::InvalidPath {
            path: path.to_path_buf(),
            message: "No parent directory".to_string(),
        })?;
        let file_name = path
            .file_name()
            .and_then(|n| n.to_str())
            .ok_or_else(|| DiaryxError::InvalidPath {
                path: path.to_path_buf(),
                message: "Invalid file name".to_string(),
            })?
            .to_string();

        // Remove from parent's contents by following the part_of link.
        // This correctly handles both leaf files (parent index in same dir)
        // and index files (parent index in grandparent dir).
        if let Ok(Some(YamlValue::String(part_of))) =
            self.get_frontmatter_property(path, "part_of").await
        {
            use crate::path_utils::normalize_path;

            let parsed = link_parser::parse_link(&part_of);
            let parent_index = match parsed.path_type {
                link_parser::PathType::WorkspaceRoot => {
                    if let Some(ref root) = self.root_path {
                        normalize_path(&root.join(&parsed.path))
                    } else {
                        PathBuf::from(&parsed.path)
                    }
                }
                link_parser::PathType::Relative | link_parser::PathType::Ambiguous => {
                    normalize_path(&parent.join(&parsed.path))
                }
            };

            let entry_canonical = self.get_canonical_path(path);
            let _ = self
                .remove_from_index_contents_canonical(&parent_index, &entry_canonical)
                .await;
        } else if let Ok(Some(index_path)) = self.find_any_index_in_dir(parent).await {
            // No part_of: fall back to finding an index in same directory
            let _ = self
                .remove_from_index_contents(&index_path, &file_name)
                .await;
        }

        // Delete the file
        self.fs
            .delete_file(path)
            .await
            .map_err(|e| DiaryxError::FileWrite {
                path: path.to_path_buf(),
                source: e,
            })?;

        Ok(())
    }

    /// Generate a unique filename for a new child entry in the given directory.
    ///
    /// Returns filenames like "new-entry.md", "new-entry-1.md", "new-entry-2.md", etc.
    pub async fn generate_unique_child_name(&self, parent_dir: &Path) -> String {
        let base_name = "new-entry";
        let mut candidate = format!("{}.md", base_name);
        let mut counter = 1;

        while self.fs.exists(&parent_dir.join(&candidate)).await {
            candidate = format!("{}-{}.md", base_name, counter);
            counter += 1;
        }

        candidate
    }

    /// Create a new child entry under a parent index.
    ///
    /// This method:
    /// - Generates a unique filename if not provided
    /// - Creates the child file with basic frontmatter
    /// - Adds the child to the parent's `contents`
    /// - Sets the child's `part_of` to point to the parent
    ///
    /// Returns the path to the new child entry.
    pub async fn create_child_entry(
        &self,
        parent_index_path: &Path,
        title: Option<&str>,
    ) -> Result<PathBuf> {
        use crate::path_utils::relative_path_from_file_to_target;

        // Parse parent - if it's a leaf (not an index), convert it to an index first
        let effective_parent = if let Ok(parent_index) = self.parse_index(parent_index_path).await {
            if parent_index.frontmatter.is_index() {
                parent_index_path.to_path_buf()
            } else {
                // Parent is a leaf file - convert to index first
                self.convert_to_index(parent_index_path).await?
            }
        } else {
            // Parent doesn't exist or couldn't be parsed - try to convert anyway
            // (convert_to_index will fail with a proper error if file doesn't exist)
            return Err(DiaryxError::FileRead {
                path: parent_index_path.to_path_buf(),
                source: std::io::Error::new(std::io::ErrorKind::NotFound, "Parent file not found"),
            });
        };

        // Determine parent directory (from effective parent, which may have moved)
        let parent_dir = effective_parent
            .parent()
            .ok_or_else(|| DiaryxError::InvalidPath {
                path: effective_parent.clone(),
                message: "Parent index has no directory".to_string(),
            })?;

        // Generate unique filename
        let child_filename = self.generate_unique_child_name(parent_dir).await;
        let child_path = parent_dir.join(&child_filename);

        // Format part_of link based on configured format
        let display_title = title.unwrap_or("New Entry");
        let part_of_value = if self.root_path.is_some() {
            // Use link formatting - resolve parent's title for the link display
            let child_canonical = self.get_canonical_path(&child_path);
            let parent_canonical = self.get_canonical_path(&effective_parent);
            let parent_title = self.resolve_title(&parent_canonical).await;
            self.format_link_sync(&parent_canonical, &parent_title, &child_canonical)
        } else {
            // Fallback: use relative path
            relative_path_from_file_to_target(&child_path, &effective_parent)
        };

        // Create child file with frontmatter
        let content = format!(
            "---\ntitle: \"{}\"\npart_of: \"{}\"\n---\n\n# {}\n\n",
            display_title, part_of_value, display_title
        );

        self.fs
            .create_new(&child_path, &content)
            .await
            .map_err(|e| DiaryxError::FileWrite {
                path: child_path.clone(),
                source: e,
            })?;

        // Add to parent's contents (using formatted link)
        let child_canonical = self.get_canonical_path(&child_path);
        self.add_to_index_contents_canonical(&effective_parent, &child_canonical, display_title)
            .await?;

        Ok(child_path)
    }

    /// Create a new child entry under a parent index, returning detailed result.
    ///
    /// This method provides more information than `create_child_entry`, including
    /// whether the parent was converted to an index and what the new parent path is.
    /// This is essential for the frontend to correctly update the tree when a leaf
    /// is converted to an index (which changes its path).
    ///
    /// Returns a [`CreateChildResult`] with:
    /// - `child_path`: The path to the newly created child
    /// - `parent_path`: The current parent path (may differ from input if converted)
    /// - `parent_converted`: Whether the parent was converted from leaf to index
    /// - `original_parent_path`: The original parent path if conversion occurred
    pub async fn create_child_entry_with_result(
        &self,
        parent_index_path: &Path,
        title: Option<&str>,
    ) -> Result<crate::command::CreateChildResult> {
        use crate::path_utils::relative_path_from_file_to_target;

        let original_parent_str = parent_index_path.to_string_lossy().to_string();

        // Parse parent - if it's a leaf (not an index), convert it to an index first
        let (effective_parent, was_converted) = if let Ok(parent_index) =
            self.parse_index(parent_index_path).await
        {
            if parent_index.frontmatter.is_index() {
                (parent_index_path.to_path_buf(), false)
            } else {
                // Parent is a leaf file - convert to index first
                let new_path = self.convert_to_index(parent_index_path).await?;
                (new_path, true)
            }
        } else {
            // Parent doesn't exist or couldn't be parsed
            return Err(DiaryxError::FileRead {
                path: parent_index_path.to_path_buf(),
                source: std::io::Error::new(std::io::ErrorKind::NotFound, "Parent file not found"),
            });
        };

        // Determine parent directory (from effective parent, which may have moved)
        let parent_dir = effective_parent
            .parent()
            .ok_or_else(|| DiaryxError::InvalidPath {
                path: effective_parent.clone(),
                message: "Parent index has no directory".to_string(),
            })?;

        // Generate unique filename
        let child_filename = self.generate_unique_child_name(parent_dir).await;
        let child_path = parent_dir.join(&child_filename);

        // Format part_of link based on configured format
        let display_title = title.unwrap_or("New Entry");
        let part_of_value = if self.root_path.is_some() {
            // Use link formatting - resolve parent's title for the link display
            let child_canonical = self.get_canonical_path(&child_path);
            let parent_canonical = self.get_canonical_path(&effective_parent);
            let parent_title = self.resolve_title(&parent_canonical).await;
            self.format_link_sync(&parent_canonical, &parent_title, &child_canonical)
        } else {
            // Fallback: use relative path
            relative_path_from_file_to_target(&child_path, &effective_parent)
        };

        // Create child file with frontmatter
        let content = format!(
            "---\ntitle: \"{}\"\npart_of: \"{}\"\n---\n\n# {}\n\n",
            display_title, part_of_value, display_title
        );

        self.fs
            .create_new(&child_path, &content)
            .await
            .map_err(|e| DiaryxError::FileWrite {
                path: child_path.clone(),
                source: e,
            })?;

        // Add to parent's contents (using formatted link)
        let child_canonical = self.get_canonical_path(&child_path);
        self.add_to_index_contents_canonical(&effective_parent, &child_canonical, display_title)
            .await?;

        Ok(crate::command::CreateChildResult {
            child_path: child_path.to_string_lossy().to_string(),
            parent_path: effective_parent.to_string_lossy().to_string(),
            parent_converted: was_converted,
            original_parent_path: if was_converted {
                Some(original_parent_str)
            } else {
                None
            },
        })
    }

    /// Rename an entry file by giving it a new filename.
    ///
    /// This method handles both leaf files and index files:
    /// - Leaf files: renames the file directly and updates parent `contents`
    /// - Root index files: renames the file in place and updates children's `part_of`
    /// - Index files: renames the containing directory AND the file itself, updates grandparent `contents`
    ///
    /// Returns the new path to the renamed file.
    pub async fn rename_entry(&self, path: &Path, new_filename: &str) -> Result<PathBuf> {
        let is_index = self.is_index_file(path).await;
        let is_root = self.is_root_index(path).await;

        if is_index && is_root {
            let children_paths = self.collect_index_content_children(path).await;

            // Root index files live at the workspace root (e.g. README.md).
            // There is no containing subdirectory to rename, so just rename the file in place.
            let parent = path.parent().ok_or_else(|| DiaryxError::InvalidPath {
                path: path.to_path_buf(),
                message: "File has no parent directory".to_string(),
            })?;

            let new_path = parent.join(new_filename);

            if new_path == path {
                return Ok(path.to_path_buf());
            }

            if self.fs.exists(&new_path).await {
                return Err(DiaryxError::InvalidPath {
                    path: new_path,
                    message: "Target file already exists".to_string(),
                });
            }

            self.fs.move_file(path, &new_path).await?;

            // Update children's part_of to point to the renamed root index
            let new_path_canonical = self.get_canonical_path(&new_path);
            let new_title = self.resolve_title(&new_path_canonical).await;
            for child_path in &children_paths {
                if child_path == &new_path || !self.fs.exists(child_path).await {
                    continue;
                }

                let part_of_value = if self.root_path.is_some() {
                    let child_canonical = self.get_canonical_path(child_path);
                    self.format_link_sync(&new_path_canonical, &new_title, &child_canonical)
                } else {
                    use crate::path_utils::relative_path_from_file_to_target;
                    relative_path_from_file_to_target(child_path, &new_path)
                };
                if let Err(e) = self
                    .set_frontmatter_property(
                        child_path,
                        "part_of",
                        YamlValue::String(part_of_value),
                    )
                    .await
                {
                    log::warn!(
                        "rename_entry: failed to update child part_of for '{}': {}",
                        child_path.display(),
                        e
                    );
                }
            }

            // Update contents references to use new self-path
            // (contents entries reference children, not self, so no update needed)

            Ok(new_path)
        } else if is_index {
            // For index files, we rename the containing directory AND the file
            let current_dir = path.parent().ok_or_else(|| DiaryxError::InvalidPath {
                path: path.to_path_buf(),
                message: "Index file has no parent directory".to_string(),
            })?;

            let parent_of_dir = current_dir
                .parent()
                .ok_or_else(|| DiaryxError::InvalidPath {
                    path: path.to_path_buf(),
                    message: "Directory has no parent".to_string(),
                })?;
            let children_paths_before_rename = self.collect_index_content_children(path).await;

            // Get new directory name from the filename (strip .md extension)
            let new_dir_name = new_filename.trim_end_matches(".md");
            let new_dir_path = parent_of_dir.join(new_dir_name);
            // New file will be named {dirname}.md
            let new_file_path = new_dir_path.join(new_filename);

            // Don't rename if same path
            if new_dir_path == current_dir {
                return Ok(path.to_path_buf());
            }

            // Check if target directory already exists
            if self.fs.exists(&new_dir_path).await {
                return Err(DiaryxError::InvalidPath {
                    path: new_dir_path,
                    message: "Target directory already exists".to_string(),
                });
            }

            // Create new directory
            self.fs.create_dir_all(&new_dir_path).await?;

            // Move all files/directories from old directory to new directory.
            if let Ok(files) = self.fs.list_files(current_dir).await {
                for file in files {
                    let file_name = file.file_name().unwrap_or_default();
                    let new_path = new_dir_path.join(file_name);

                    // If this is the index file itself, use the new filename
                    if file == path {
                        self.fs.move_file(&file, &new_file_path).await?;
                    } else {
                        self.fs.move_file(&file, &new_path).await?;
                    }
                }
            }

            // Update part_of for all listed children, including nested entries.
            let new_file_canonical = self.get_canonical_path(&new_file_path);
            let new_file_title = self.resolve_title(&new_file_canonical).await;
            let mut rewritten_child_paths = HashSet::new();
            for child_path_before in &children_paths_before_rename {
                let rewritten_child_path = if child_path_before.starts_with(current_dir) {
                    match child_path_before.strip_prefix(current_dir) {
                        Ok(relative) => new_dir_path.join(relative),
                        Err(_) => child_path_before.clone(),
                    }
                } else {
                    child_path_before.clone()
                };

                if !rewritten_child_paths.insert(rewritten_child_path.clone()) {
                    continue;
                }
                if rewritten_child_path == new_file_path
                    || !self.fs.exists(&rewritten_child_path).await
                {
                    continue;
                }

                let part_of_value = if self.root_path.is_some() {
                    let child_canonical = self.get_canonical_path(&rewritten_child_path);
                    self.format_link_sync(&new_file_canonical, &new_file_title, &child_canonical)
                } else {
                    use crate::path_utils::relative_path_from_file_to_target;
                    relative_path_from_file_to_target(&rewritten_child_path, &new_file_path)
                };
                if let Err(e) = self
                    .set_frontmatter_property(
                        &rewritten_child_path,
                        "part_of",
                        YamlValue::String(part_of_value),
                    )
                    .await
                {
                    log::warn!(
                        "rename_entry: failed to update child part_of for '{}': {}",
                        rewritten_child_path.display(),
                        e
                    );
                }
            }

            // Update parent's contents via part_of (fallback: grandparent directory)
            if let Some(parent_index) = self
                .resolve_part_of_to_path(&new_file_path, parent_of_dir)
                .await
            {
                let old_canonical = self.get_canonical_path(path);
                // Add new entry first to avoid transient "missing child" states.
                self.add_to_index_contents_canonical(
                    &parent_index,
                    &new_file_canonical,
                    &new_file_title,
                )
                .await?;

                if let Err(e) = self
                    .remove_from_index_contents_canonical(&parent_index, &old_canonical)
                    .await
                {
                    log::warn!(
                        "rename_entry: failed to remove old parent contents reference '{}' from '{}': {}",
                        old_canonical,
                        parent_index.display(),
                        e
                    );
                }
            }

            Ok(new_file_path)
        } else {
            // For leaf files, simple rename within the same directory
            let parent = path.parent().ok_or_else(|| DiaryxError::InvalidPath {
                path: path.to_path_buf(),
                message: "File has no parent directory".to_string(),
            })?;

            let new_path = parent.join(new_filename);

            // Don't rename if same path
            if new_path == path {
                return Ok(path.to_path_buf());
            }

            // Check if target already exists
            if self.fs.exists(&new_path).await {
                if !self.fs.exists(path).await {
                    // File was already renamed on disk (e.g. by OS or sync tool)
                    // but parent's contents still references the old name.
                    // Just update the parent's contents reference.
                    if let Some(parent_index) =
                        self.resolve_part_of_to_path(&new_path, parent).await
                    {
                        let new_path_canonical = self.get_canonical_path(&new_path);
                        let old_canonical = self.get_canonical_path(path);
                        let title = self.resolve_title(&new_path_canonical).await;
                        self.add_to_index_contents_canonical(
                            &parent_index,
                            &new_path_canonical,
                            &title,
                        )
                        .await?;

                        if let Err(e) = self
                            .remove_from_index_contents_canonical(&parent_index, &old_canonical)
                            .await
                        {
                            log::warn!(
                                "rename_entry: failed to remove old parent contents reference '{}' from '{}': {}",
                                old_canonical,
                                parent_index.display(),
                                e
                            );
                        }
                    }
                    return Ok(new_path);
                }
                return Err(DiaryxError::InvalidPath {
                    path: new_path,
                    message: "Target file already exists".to_string(),
                });
            }

            // Move the file
            self.fs.move_file(path, &new_path).await?;

            // Update parent's contents via part_of (fallback: same directory)
            if let Some(parent_index) = self.resolve_part_of_to_path(&new_path, parent).await {
                // Add new entry first to avoid transient "missing child" states.
                let new_path_canonical = self.get_canonical_path(&new_path);
                let old_canonical = self.get_canonical_path(path);
                let title = self.resolve_title(&new_path_canonical).await;
                self.add_to_index_contents_canonical(&parent_index, &new_path_canonical, &title)
                    .await?;

                if let Err(e) = self
                    .remove_from_index_contents_canonical(&parent_index, &old_canonical)
                    .await
                {
                    log::warn!(
                        "rename_entry: failed to remove old parent contents reference '{}' from '{}': {}",
                        old_canonical,
                        parent_index.display(),
                        e
                    );
                }
            }

            Ok(new_path)
        }
    }

    /// Duplicate an entry, creating a copy with a unique name.
    ///
    /// This method:
    /// - For leaf files: copies the file with a "-copy" suffix (or "-copy-N" if exists)
    /// - For index files: copies the entire directory structure recursively
    /// - Updates the copy's `part_of` to point to the same parent
    /// - Adds the copy to the parent's `contents`
    ///
    /// Returns the path to the new duplicated entry.
    pub async fn duplicate_entry(&self, source_path: &Path) -> Result<PathBuf> {
        use crate::path_utils::relative_path_from_file_to_target;

        let is_index = self.is_index_file(source_path).await;

        if is_index {
            // For index files, we duplicate the entire directory
            let source_dir = source_path
                .parent()
                .ok_or_else(|| DiaryxError::InvalidPath {
                    path: source_path.to_path_buf(),
                    message: "Index file has no parent directory".to_string(),
                })?;

            let parent_of_dir = source_dir
                .parent()
                .ok_or_else(|| DiaryxError::InvalidPath {
                    path: source_path.to_path_buf(),
                    message: "Directory has no parent".to_string(),
                })?;

            // Get source directory name and generate unique copy name
            let source_dir_name =
                source_dir
                    .file_name()
                    .and_then(|n| n.to_str())
                    .ok_or_else(|| DiaryxError::InvalidPath {
                        path: source_path.to_path_buf(),
                        message: "Invalid directory name".to_string(),
                    })?;

            let new_dir_name = self
                .generate_unique_copy_name(parent_of_dir, source_dir_name, false)
                .await;
            let new_dir_path = parent_of_dir.join(&new_dir_name);
            let new_index_path = new_dir_path.join(format!("{}.md", new_dir_name));

            // Create new directory
            self.fs.create_dir_all(&new_dir_path).await?;

            // Copy all files from source directory to new directory
            if let Ok(files) = self.fs.list_files(source_dir).await {
                for file in files {
                    let file_name = file
                        .file_name()
                        .and_then(|n| n.to_str())
                        .unwrap_or_default();

                    // For the index file, use the new directory name
                    let new_path = if file == source_path {
                        new_index_path.clone()
                    } else {
                        new_dir_path.join(file_name)
                    };

                    // Copy file content
                    let content =
                        self.fs
                            .read_to_string(&file)
                            .await
                            .map_err(|e| DiaryxError::FileRead {
                                path: file.clone(),
                                source: e,
                            })?;
                    self.fs.write_file(&new_path, &content).await.map_err(|e| {
                        DiaryxError::FileWrite {
                            path: new_path.clone(),
                            source: e,
                        }
                    })?;

                    // Update part_of for child files to point to new index
                    if new_path != new_index_path {
                        let new_part_of =
                            relative_path_from_file_to_target(&new_path, &new_index_path);
                        let _ = self
                            .set_frontmatter_property(
                                &new_path,
                                "part_of",
                                YamlValue::String(new_part_of),
                            )
                            .await;
                    }
                }
            }

            // Update the copied index's part_of to point to grandparent (same as source)
            if let Ok(Some(grandparent_index)) = self.find_any_index_in_dir(parent_of_dir).await {
                let new_part_of =
                    relative_path_from_file_to_target(&new_index_path, &grandparent_index);
                let _ = self
                    .set_frontmatter_property(
                        &new_index_path,
                        "part_of",
                        YamlValue::String(new_part_of),
                    )
                    .await;

                // Add to grandparent's contents
                let rel_path = format!("{}/{}.md", new_dir_name, new_dir_name);
                let _ = self
                    .add_to_index_contents(&grandparent_index, &rel_path)
                    .await;
            }

            Ok(new_index_path)
        } else {
            // For leaf files, simple copy in same directory
            let parent = source_path
                .parent()
                .ok_or_else(|| DiaryxError::InvalidPath {
                    path: source_path.to_path_buf(),
                    message: "File has no parent directory".to_string(),
                })?;

            let source_filename = source_path
                .file_name()
                .and_then(|n| n.to_str())
                .ok_or_else(|| DiaryxError::InvalidPath {
                    path: source_path.to_path_buf(),
                    message: "Invalid file name".to_string(),
                })?;

            // Generate unique copy name
            let new_filename = self
                .generate_unique_copy_name(parent, source_filename, true)
                .await;
            let new_path = parent.join(&new_filename);

            // Copy file content
            let content =
                self.fs
                    .read_to_string(source_path)
                    .await
                    .map_err(|e| DiaryxError::FileRead {
                        path: source_path.to_path_buf(),
                        source: e,
                    })?;
            self.fs
                .write_file(&new_path, &content)
                .await
                .map_err(|e| DiaryxError::FileWrite {
                    path: new_path.clone(),
                    source: e,
                })?;

            // Update parent's contents if it exists
            if let Ok(Some(parent_index)) = self.find_any_index_in_dir(parent).await {
                // Update part_of to point to parent
                let new_part_of = relative_path_from_file_to_target(&new_path, &parent_index);
                let _ = self
                    .set_frontmatter_property(&new_path, "part_of", YamlValue::String(new_part_of))
                    .await;

                // Add to parent's contents
                let _ = self
                    .add_to_index_contents(&parent_index, &new_filename)
                    .await;
            }

            Ok(new_path)
        }
    }

    /// Generate a unique copy name for a file or directory.
    ///
    /// For files: "name.md" → "name-copy.md", "name-copy-2.md", etc.
    /// For directories: "name" → "name-copy", "name-copy-2", etc.
    async fn generate_unique_copy_name(
        &self,
        parent_dir: &Path,
        original_name: &str,
        is_file: bool,
    ) -> String {
        let (base_name, extension) = if is_file {
            // Strip .md extension for files
            let base = original_name.trim_end_matches(".md");
            (base.to_string(), ".md".to_string())
        } else {
            (original_name.to_string(), String::new())
        };

        // Try "name-copy" first
        let mut candidate = format!("{}-copy{}", base_name, extension);
        let mut counter = 2;

        while self.fs.exists(&parent_dir.join(&candidate)).await {
            candidate = format!("{}-copy-{}{}", base_name, counter, extension);
            counter += 1;
        }

        candidate
    }

    /// Convert a leaf file into an index file with a directory.
    ///
    /// This method:
    /// - Creates a directory with the same name as the file (without .md)
    /// - Moves the file into the directory as `{dirname}.md`
    /// - Adds empty `contents` property to the file
    ///
    /// Example: `journal/my-note.md` → `journal/my-note/my-note.md`
    ///
    /// Returns the new path to the index file.
    pub async fn convert_to_index(&self, path: &Path) -> Result<PathBuf> {
        // Check if already an index
        if self.is_index_file(path).await {
            return Err(DiaryxError::InvalidPath {
                path: path.to_path_buf(),
                message: "File is already an index".to_string(),
            });
        }

        let parent = path.parent().ok_or_else(|| DiaryxError::InvalidPath {
            path: path.to_path_buf(),
            message: "File has no parent directory".to_string(),
        })?;

        let file_stem =
            path.file_stem()
                .and_then(|s| s.to_str())
                .ok_or_else(|| DiaryxError::InvalidPath {
                    path: path.to_path_buf(),
                    message: "Invalid file name".to_string(),
                })?;

        // Create new directory and file paths
        let new_dir = parent.join(file_stem);
        let new_filename = format!("{}.md", file_stem);
        let new_path = new_dir.join(&new_filename);

        // Create directory
        self.fs.create_dir_all(&new_dir).await?;

        // Move file into directory
        self.fs.move_file(path, &new_path).await?;

        // Add contents property
        self.set_frontmatter_property(&new_path, "contents", YamlValue::Sequence(vec![]))
            .await?;

        // Update part_of path since file moved one level deeper
        if let Ok(Some(YamlValue::String(old_part_of))) =
            self.get_frontmatter_property(&new_path, "part_of").await
        {
            use crate::path_utils::{normalize_path, relative_path_from_file_to_target};

            // Parse the markdown link to get the path and type
            let parsed = link_parser::parse_link(&old_part_of);

            // Resolve target path based on path type
            let target_path = match parsed.path_type {
                link_parser::PathType::WorkspaceRoot => {
                    // Workspace-root path: canonical is already workspace-relative
                    if let Some(ref root) = self.root_path {
                        normalize_path(&root.join(&parsed.path))
                    } else {
                        // No workspace root: path is already workspace-relative
                        PathBuf::from(&parsed.path)
                    }
                }
                link_parser::PathType::Relative | link_parser::PathType::Ambiguous => {
                    // Relative path: resolve against old file's parent directory
                    normalize_path(&parent.join(&parsed.path))
                }
            };

            // Format the new part_of link
            let new_part_of = if self.root_path.is_some() {
                // Use markdown link format
                let target_canonical = self.get_canonical_path(&target_path);
                let new_path_canonical = self.get_canonical_path(&new_path);
                let target_title = self.resolve_title(&target_canonical).await;
                self.format_link_sync(&target_canonical, &target_title, &new_path_canonical)
            } else {
                // Fallback: plain relative path
                relative_path_from_file_to_target(&new_path, &target_path)
            };

            let _ = self
                .set_frontmatter_property(&new_path, "part_of", YamlValue::String(new_part_of))
                .await;
        }

        // Update parent's contents via part_of (fallback: original parent directory)
        if let Some(parent_index) = self.resolve_part_of_to_path(&new_path, parent).await {
            let old_canonical = self.get_canonical_path(path);
            let _ = self
                .remove_from_index_contents_canonical(&parent_index, &old_canonical)
                .await;

            // Add new entry with proper formatting
            let new_path_canonical = self.get_canonical_path(&new_path);
            let title = self.resolve_title(&new_path_canonical).await;
            let _ = self
                .add_to_index_contents_canonical(&parent_index, &new_path_canonical, &title)
                .await;
        }

        Ok(new_path)
    }

    /// Convert an empty index file back to a leaf file.
    ///
    /// This method:
    /// - Fails if the index has non-empty `contents`
    /// - Moves `dir/{name}.md` → `parent/dir.md`
    /// - Removes the now-empty directory
    /// - Removes the `contents` property
    ///
    /// Example: `journal/my-note/my-note.md` → `journal/my-note.md`
    ///
    /// Returns the new path to the leaf file.
    pub async fn convert_to_leaf(&self, path: &Path) -> Result<PathBuf> {
        // Check if this is an index with empty contents
        let index = self.parse_index(path).await?;
        let contents = index.frontmatter.contents_list();
        if !contents.is_empty() {
            return Err(DiaryxError::InvalidPath {
                path: path.to_path_buf(),
                message: format!(
                    "Cannot convert index with {} children to leaf",
                    contents.len()
                ),
            });
        }

        let current_dir = path.parent().ok_or_else(|| DiaryxError::InvalidPath {
            path: path.to_path_buf(),
            message: "File has no parent directory".to_string(),
        })?;

        let parent_of_dir = current_dir
            .parent()
            .ok_or_else(|| DiaryxError::InvalidPath {
                path: path.to_path_buf(),
                message: "Directory has no parent".to_string(),
            })?;

        let dir_name = current_dir
            .file_name()
            .and_then(|n| n.to_str())
            .ok_or_else(|| DiaryxError::InvalidPath {
                path: current_dir.to_path_buf(),
                message: "Invalid directory name".to_string(),
            })?;

        let new_filename = format!("{}.md", dir_name);
        let new_path = parent_of_dir.join(&new_filename);

        // Check if target already exists
        if self.fs.exists(&new_path).await {
            return Err(DiaryxError::InvalidPath {
                path: new_path,
                message: "Target file already exists".to_string(),
            });
        }

        // Move file out of directory
        self.fs.move_file(path, &new_path).await?;

        // Remove contents property
        let _ = self
            .remove_frontmatter_property(&new_path, "contents")
            .await;

        // Update part_of path since file moved one level up
        if let Ok(Some(YamlValue::String(old_part_of))) =
            self.get_frontmatter_property(&new_path, "part_of").await
        {
            use crate::path_utils::{normalize_path, relative_path_from_file_to_target};

            // Parse the markdown link to get the path and type
            let parsed = link_parser::parse_link(&old_part_of);

            // Resolve target path based on path type
            let target_path = match parsed.path_type {
                link_parser::PathType::WorkspaceRoot => {
                    // Workspace-root path: canonical is already workspace-relative
                    if let Some(ref root) = self.root_path {
                        normalize_path(&root.join(&parsed.path))
                    } else {
                        // No workspace root: path is already workspace-relative
                        PathBuf::from(&parsed.path)
                    }
                }
                link_parser::PathType::Relative | link_parser::PathType::Ambiguous => {
                    // Relative path: resolve against old file's directory
                    normalize_path(&current_dir.join(&parsed.path))
                }
            };

            // Format the new part_of link
            let new_part_of = if self.root_path.is_some() {
                // Use markdown link format
                let target_canonical = self.get_canonical_path(&target_path);
                let new_path_canonical = self.get_canonical_path(&new_path);
                let target_title = self.resolve_title(&target_canonical).await;
                self.format_link_sync(&target_canonical, &target_title, &new_path_canonical)
            } else {
                // Fallback: plain relative path
                relative_path_from_file_to_target(&new_path, &target_path)
            };

            let _ = self
                .set_frontmatter_property(&new_path, "part_of", YamlValue::String(new_part_of))
                .await;
        }

        // Update parent's contents via part_of (fallback: grandparent directory)
        if let Some(parent_index) = self.resolve_part_of_to_path(&new_path, parent_of_dir).await {
            let old_canonical = self.get_canonical_path(path);
            let _ = self
                .remove_from_index_contents_canonical(&parent_index, &old_canonical)
                .await;

            // Add new entry with proper formatting
            let new_path_canonical = self.get_canonical_path(&new_path);
            let title = self.resolve_title(&new_path_canonical).await;
            let _ = self
                .add_to_index_contents_canonical(&parent_index, &new_path_canonical, &title)
                .await;
        }

        Ok(new_path)
    }

    /// Attach an entry to a parent, converting the parent to an index if needed,
    /// and moving the entry file into the parent's directory.
    ///
    /// This is a higher-level operation that combines:
    /// 1. Convert parent to index if it's a leaf
    /// 2. Move entry into parent's directory
    /// 3. Create bidirectional links (contents and part_of)
    ///
    /// Returns the new path to the entry after any moves.
    pub async fn attach_and_move_entry_to_parent(
        &self,
        entry: &Path,
        parent: &Path,
    ) -> Result<PathBuf> {
        // Check if parent needs to be converted to index
        let parent_is_index = self.is_index_file(parent).await;

        let effective_parent = if parent_is_index {
            parent.to_path_buf()
        } else {
            // Convert parent to index first
            self.convert_to_index(parent).await?
        };

        // Get parent directory
        let parent_dir = effective_parent
            .parent()
            .ok_or_else(|| DiaryxError::InvalidPath {
                path: effective_parent.clone(),
                message: "Parent index has no directory".to_string(),
            })?;

        // If the entry being moved is itself a non-root index (i.e. a folder
        // represented by a directory + its index file), we need to move the
        // entire containing directory — not just the .md file. Moving just
        // the index would strand every descendant at the old path with stale
        // `part_of` links. The root index lives at the workspace root and has
        // no containing subfolder to move, so it falls through to leaf-style
        // handling below.
        let entry_is_index = self.is_index_file(entry).await;
        let entry_is_root = entry_is_index && self.is_root_index(entry).await;
        if entry_is_index && !entry_is_root {
            let old_dir = entry.parent().ok_or_else(|| DiaryxError::InvalidPath {
                path: entry.to_path_buf(),
                message: "Index file has no parent directory".to_string(),
            })?;

            // If the folder is already directly inside the new parent's
            // directory, there's nothing to move — just make sure the index
            // is attached to the correct parent.
            if old_dir.parent() == Some(parent_dir) {
                self.attach_entry_to_parent(entry, &effective_parent)
                    .await?;
                return Ok(entry.to_path_buf());
            }

            let dir_name = old_dir
                .file_name()
                .ok_or_else(|| DiaryxError::InvalidPath {
                    path: old_dir.to_path_buf(),
                    message: "Index directory has no name".to_string(),
                })?;
            let new_dir = parent_dir.join(dir_name);

            // Refuse to move a folder into itself or into one of its own
            // descendants — that would create a cycle on disk.
            if new_dir == old_dir || new_dir.starts_with(old_dir) {
                return Err(DiaryxError::InvalidPath {
                    path: new_dir,
                    message: "Cannot move a folder into itself or its descendants".to_string(),
                });
            }

            if self.fs.exists(&new_dir).await {
                return Err(DiaryxError::InvalidPath {
                    path: new_dir,
                    message: "Target directory already exists".to_string(),
                });
            }

            let entry_filename = entry.file_name().and_then(|n| n.to_str()).ok_or_else(|| {
                DiaryxError::InvalidPath {
                    path: entry.to_path_buf(),
                    message: "Invalid entry filename".to_string(),
                }
            })?;
            let new_entry_path = new_dir.join(entry_filename);

            // Physically move the whole directory tree.
            self.move_dir_contents_recursive(old_dir, &new_dir).await?;

            // sync_move_metadata updates the moved index's own part_of and,
            // because it's an index whose directory changed, also walks the
            // new subtree and rewrites every descendant's part_of against
            // its directory-nearest index at the new location.
            self.sync_move_metadata(entry, &new_entry_path).await?;

            return Ok(new_entry_path);
        }

        // Get entry filename
        let entry_filename =
            entry
                .file_name()
                .and_then(|n| n.to_str())
                .ok_or_else(|| DiaryxError::InvalidPath {
                    path: entry.to_path_buf(),
                    message: "Invalid entry filename".to_string(),
                })?;

        // Calculate new path for entry
        let new_entry_path = parent_dir.join(entry_filename);

        // Move entry if not already in parent directory.
        // move_entry already updates contents and part_of when it discovers the
        // target directory's index, so we only need attach_entry_to_parent when
        // the file didn't actually move.
        if entry.parent() != Some(parent_dir) {
            self.move_entry(entry, &new_entry_path).await?;
        } else {
            self.attach_entry_to_parent(&new_entry_path, &effective_parent)
                .await?;
        }

        Ok(new_entry_path)
    }
}

fn canonical_workspace_path(path: &Path, workspace_root: &Path) -> String {
    let relative = path.strip_prefix(workspace_root).unwrap_or(path);
    let raw = relative.to_string_lossy().replace('\\', "/");
    normalize_sync_path(&raw)
}

fn resolve_workspace_path(workspace_root: &Path, resolved_path: &Path) -> PathBuf {
    if resolved_path.is_absolute() || resolved_path.starts_with(workspace_root) {
        resolved_path.to_path_buf()
    } else {
        workspace_root.join(resolved_path)
    }
}

// ---------------------------------------------------------------------------
// Sync helpers — usable without an async runtime.
// ---------------------------------------------------------------------------

/// Find the root index file in a directory using a synchronous filesystem.
///
/// A root index is a markdown file whose frontmatter has a `contents` key but
/// no `part_of` key.  This is the sync equivalent of
/// [`Workspace::find_root_index_in_dir`].
pub fn find_root_index_in_dir_sync(
    fs: &dyn crate::fs::FileSystem,
    dir: &Path,
) -> Result<Option<PathBuf>> {
    let md_files = fs.list_md_files(dir).map_err(|e| DiaryxError::FileRead {
        path: dir.to_path_buf(),
        source: e,
    })?;

    for file in md_files {
        if is_root_index_sync(fs, &file) {
            return Ok(Some(file));
        }
    }

    Ok(None)
}

/// Check whether `path` is a root index using a synchronous filesystem.
fn is_root_index_sync(fs: &dyn crate::fs::FileSystem, path: &Path) -> bool {
    let content = match fs.read_to_string(path) {
        Ok(c) => c,
        Err(_) => return false,
    };

    // Quick check: must have frontmatter delimiters.
    if !content.starts_with("---\n") && !content.starts_with("---\r\n") {
        return false;
    }

    let rest = &content[4..];
    let end_idx = match rest.find("\n---\n").or_else(|| rest.find("\n---\r\n")) {
        Some(i) => i,
        None => return false,
    };

    let frontmatter_str = &rest[..end_idx];
    match serde_yaml::from_str::<IndexFrontmatter>(frontmatter_str) {
        Ok(fm) => fm.is_root(),
        Err(_) => false,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fs::{FileSystem, InMemoryFileSystem, SyncToAsyncFs, block_on_test};

    type TestFs = SyncToAsyncFs<InMemoryFileSystem>;

    fn make_test_fs() -> TestFs {
        SyncToAsyncFs::new(InMemoryFileSystem::new())
    }

    #[test]
    fn test_index_frontmatter_is_root() {
        let root_fm = IndexFrontmatter {
            title: Some("Root".to_string()),
            link: None,
            description: None,
            contents: Some(vec![]),
            links: None,
            link_of: None,
            part_of: None,
            audience: None,
            attachments: None,
            attachment: None,
            attachment_of: None,
            exclude: None,
            plugins: None,
            extra: std::collections::HashMap::new(),
        };
        assert!(root_fm.is_root());
        assert!(root_fm.is_index());

        let non_root_fm = IndexFrontmatter {
            title: Some("Non-root".to_string()),
            link: None,
            description: None,
            contents: Some(vec![]),
            links: None,
            link_of: None,
            part_of: Some("../parent.md".to_string()),
            audience: None,
            attachments: None,
            attachment: None,
            attachment_of: None,
            exclude: None,
            plugins: None,
            extra: std::collections::HashMap::new(),
        };
        assert!(!non_root_fm.is_root());
        assert!(non_root_fm.is_index());
    }

    #[test]
    fn test_tree_node_formatting() {
        let tree = TreeNode {
            name: "Root".to_string(),
            description: Some("Root description".to_string()),
            path: PathBuf::from("root.md"),
            is_index: true,
            children: vec![
                TreeNode {
                    name: "Child 1".to_string(),
                    description: None,
                    path: PathBuf::from("child1.md"),
                    is_index: false,
                    children: vec![],
                    properties: std::collections::HashMap::new(),
                    audience: Vec::new(),
                },
                TreeNode {
                    name: "Child 2".to_string(),
                    description: Some("Child desc".to_string()),
                    path: PathBuf::from("child2.md"),
                    is_index: false,
                    children: vec![],
                    properties: std::collections::HashMap::new(),
                    audience: Vec::new(),
                },
            ],
            properties: std::collections::HashMap::new(),
            audience: Vec::new(),
        };

        let fs = make_test_fs();
        let ws = Workspace::new(fs);
        let output = ws.format_tree(&tree, "");

        assert!(output.contains("Root - Root description"));
        assert!(output.contains("Child 1"));
        assert!(output.contains("Child 2 - Child desc"));
    }

    #[test]
    fn test_parse_index() {
        let fs = InMemoryFileSystem::new();
        fs.write_file(
            Path::new("test.md"),
            "---\ntitle: Test\ncontents: []\n---\n\nBody content",
        )
        .unwrap();

        let async_fs = SyncToAsyncFs::new(fs);
        let ws = Workspace::new(async_fs);

        let result = block_on_test(ws.parse_index(Path::new("test.md")));
        assert!(result.is_ok());

        let index = result.unwrap();
        assert_eq!(index.frontmatter.title, Some("Test".to_string()));
        assert!(index.frontmatter.is_index());
        assert!(index.body.contains("Body content"));
    }

    #[test]
    fn test_get_workspace_config_reads_daily_entry_folder() {
        let fs = InMemoryFileSystem::new();
        fs.write_file(
            Path::new("README.md"),
            "---\ntitle: Root\ncontents: []\ndaily_entry_folder: Journal/Daily\n---\n",
        )
        .unwrap();

        let async_fs = SyncToAsyncFs::new(fs);
        let ws = Workspace::new(async_fs);

        let config = block_on_test(ws.get_workspace_config(Path::new("README.md"))).unwrap();
        assert_eq!(config.daily_entry_folder.as_deref(), Some("Journal/Daily"));
    }

    #[test]
    fn test_get_workspace_config_reads_theme_selection_fields() {
        let fs = InMemoryFileSystem::new();
        fs.write_file(
            Path::new("README.md"),
            "---\ntitle: Root\ncontents: []\nworkspace_config:\n  theme_mode: dark\n  theme_preset: nord\n  theme_accent_hue: 210\n---\n",
        )
        .unwrap();

        let async_fs = SyncToAsyncFs::new(fs);
        let ws = Workspace::new(async_fs);

        let config = block_on_test(ws.get_workspace_config(Path::new("README.md"))).unwrap();
        assert_eq!(config.theme_mode.as_deref(), Some("dark"));
        assert_eq!(config.theme_preset.as_deref(), Some("nord"));
        assert_eq!(config.theme_accent_hue, Some(210.0));
    }

    #[test]
    fn test_build_tree_deduplicates_duplicate_contents_refs() {
        let fs = InMemoryFileSystem::new();
        fs.write_file(
            Path::new("README.md"),
            "---\ntitle: Root\ncontents:\n  - child.md\n  - child.md\n---\n",
        )
        .unwrap();
        fs.write_file(Path::new("child.md"), "---\ntitle: Child\n---\n")
            .unwrap();

        let async_fs = SyncToAsyncFs::new(fs);
        let ws = Workspace::new(async_fs);

        let tree = block_on_test(ws.build_tree(Path::new("README.md"))).unwrap();
        assert_eq!(tree.children.len(), 1);
        assert_eq!(tree.children[0].path, PathBuf::from("child.md"));
    }

    #[test]
    fn test_is_index_file() {
        let fs = InMemoryFileSystem::new();
        fs.write_file(
            Path::new("index.md"),
            "---\ntitle: Index\ncontents: []\n---\n",
        )
        .unwrap();
        fs.write_file(Path::new("leaf.md"), "---\ntitle: Leaf\n---\n")
            .unwrap();

        let async_fs = SyncToAsyncFs::new(fs);
        let ws = Workspace::new(async_fs);

        assert!(block_on_test(ws.is_index_file(Path::new("index.md"))));
        assert!(!block_on_test(ws.is_index_file(Path::new("leaf.md"))));
        assert!(!block_on_test(
            ws.is_index_file(Path::new("nonexistent.md"))
        ));
    }

    #[test]
    fn test_is_root_index() {
        let fs = InMemoryFileSystem::new();
        fs.write_file(
            Path::new("root.md"),
            "---\ntitle: Root\ncontents: []\n---\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("child.md"),
            "---\ntitle: Child\ncontents: []\npart_of: root.md\n---\n",
        )
        .unwrap();

        let async_fs = SyncToAsyncFs::new(fs);
        let ws = Workspace::new(async_fs);

        assert!(block_on_test(ws.is_root_index(Path::new("root.md"))));
        assert!(!block_on_test(ws.is_root_index(Path::new("child.md"))));
    }

    #[test]
    fn test_find_root_index_in_dir_sync() {
        let fs = InMemoryFileSystem::new();
        fs.write_file(
            Path::new("root.md"),
            "---\ntitle: Root\ncontents: []\n---\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("child.md"),
            "---\ntitle: Child\ncontents: []\npart_of: root.md\n---\n",
        )
        .unwrap();
        fs.write_file(Path::new("plain.md"), "No frontmatter here")
            .unwrap();

        let result = find_root_index_in_dir_sync(&fs, Path::new(".")).unwrap();
        assert_eq!(result, Some(PathBuf::from("root.md")));
    }

    #[test]
    fn test_find_root_index_in_dir_sync_returns_none_when_no_root() {
        let fs = InMemoryFileSystem::new();
        fs.write_file(
            Path::new("child.md"),
            "---\ntitle: Child\ncontents: []\npart_of: root.md\n---\n",
        )
        .unwrap();

        let result = find_root_index_in_dir_sync(&fs, Path::new(".")).unwrap();
        assert_eq!(result, None);
    }

    #[test]
    fn test_rename_entry_updates_parent_contents_without_dropping_child() {
        let fs = InMemoryFileSystem::new();
        fs.write_file(
            Path::new("README.md"),
            "---\ntitle: Root\ncontents:\n  - new-entry.md\n---\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("new-entry.md"),
            "---\ntitle: New Entry\npart_of: README.md\n---\n\n# New Entry\n",
        )
        .unwrap();

        let async_fs = SyncToAsyncFs::new(fs);
        let ws = Workspace::new(async_fs);

        let renamed = block_on_test(ws.rename_entry(Path::new("new-entry.md"), "test.md")).unwrap();
        assert_eq!(renamed, PathBuf::from("test.md"));

        let contents =
            block_on_test(ws.get_frontmatter_property(Path::new("README.md"), "contents")).unwrap();
        let entries = match contents {
            Some(YamlValue::Sequence(items)) => items
                .into_iter()
                .filter_map(|item| item.as_str().map(ToString::to_string))
                .collect::<Vec<_>>(),
            other => panic!("expected contents sequence, got {:?}", other),
        };

        assert!(entries.iter().any(|entry| entry.contains("test.md")));
        assert!(!entries.iter().any(|entry| entry.contains("new-entry.md")));

        let tree = block_on_test(ws.build_tree(Path::new("README.md"))).unwrap();
        assert_eq!(tree.children.len(), 1);
        assert_eq!(tree.children[0].path, PathBuf::from("test.md"));
    }

    #[test]
    fn test_rename_entry_removes_old_from_parent_contents_with_root_path() {
        // Regression: when root_path is set and files are in subdirectories,
        // the old canonical path (e.g. "journal/old.md") was parsed as
        // Ambiguous and double-resolved relative to the index's directory,
        // producing "journal/journal/old.md" which never matched the stored
        // workspace-root link "[Old](/journal/old.md)".
        let fs = InMemoryFileSystem::new();
        let root = PathBuf::from("/ws");
        fs.create_dir_all(Path::new("/ws/journal")).unwrap();
        fs.write_file(
            Path::new("/ws/journal/journal.md"),
            "---\ntitle: Journal\ncontents:\n  - \"[Old Entry](/journal/old-entry.md)\"\n---\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("/ws/journal/old-entry.md"),
            "---\ntitle: Old Entry\npart_of: \"[Journal](/journal/journal.md)\"\n---\n\n# Old Entry\n",
        )
        .unwrap();

        let async_fs = SyncToAsyncFs::new(fs);
        let ws = Workspace::with_link_format(async_fs, root, LinkFormat::MarkdownRoot);

        let renamed =
            block_on_test(ws.rename_entry(Path::new("/ws/journal/old-entry.md"), "new-entry.md"))
                .unwrap();
        assert_eq!(renamed, PathBuf::from("/ws/journal/new-entry.md"));

        let contents = block_on_test(
            ws.get_frontmatter_property(Path::new("/ws/journal/journal.md"), "contents"),
        )
        .unwrap();
        let entries = match contents {
            Some(YamlValue::Sequence(items)) => items
                .into_iter()
                .filter_map(|item| item.as_str().map(ToString::to_string))
                .collect::<Vec<_>>(),
            other => panic!("expected contents sequence, got {:?}", other),
        };

        assert!(
            entries.iter().any(|e| e.contains("new-entry.md")),
            "new entry should be in contents: {:?}",
            entries
        );
        assert!(
            !entries.iter().any(|e| e.contains("old-entry.md")),
            "old entry should NOT be in contents: {:?}",
            entries
        );
        assert_eq!(
            entries.len(),
            1,
            "should have exactly one entry: {:?}",
            entries
        );
    }

    #[test]
    fn test_rename_root_index() {
        let fs = InMemoryFileSystem::new();
        fs.write_file(
            Path::new("README.md"),
            "---\ntitle: My Site\ncontents:\n  - child.md\n---\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("child.md"),
            "---\ntitle: Child\npart_of: README.md\n---\n",
        )
        .unwrap();

        let async_fs = SyncToAsyncFs::new(fs.clone());
        let ws = Workspace::new(async_fs);

        let renamed = block_on_test(ws.rename_entry(Path::new("README.md"), "My Site.md")).unwrap();
        assert_eq!(renamed, PathBuf::from("My Site.md"));

        // File should exist at new path
        assert!(fs.exists(Path::new("My Site.md")));
        assert!(!fs.exists(Path::new("README.md")));

        // Child's part_of should be updated to point to the new filename
        let part_of =
            block_on_test(ws.get_frontmatter_property(Path::new("child.md"), "part_of")).unwrap();
        let part_of_str = part_of.unwrap();
        let part_of_str = part_of_str.as_str().unwrap();
        assert!(
            part_of_str.contains("My Site.md"),
            "Expected part_of to contain 'My Site.md', got '{}'",
            part_of_str
        );
    }

    #[test]
    fn test_rename_root_index_updates_nested_child_part_of() {
        let fs = InMemoryFileSystem::new();
        let root = PathBuf::from("/ws");
        fs.create_dir_all(Path::new("/ws/Section")).unwrap();
        fs.write_file(
            Path::new("/ws/README.md"),
            "---\ntitle: Root\ncontents:\n  - \"[Section](/Section/section.md)\"\n---\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("/ws/Section/section.md"),
            "---\ntitle: Section\npart_of: \"[Root](/README.md)\"\n---\n",
        )
        .unwrap();

        let async_fs = SyncToAsyncFs::new(fs.clone());
        let ws = Workspace::with_link_format(async_fs, root, LinkFormat::MarkdownRoot);

        let renamed =
            block_on_test(ws.rename_entry(Path::new("/ws/README.md"), "Home.md")).unwrap();
        assert_eq!(renamed, PathBuf::from("/ws/Home.md"));

        let part_of = block_on_test(
            ws.get_frontmatter_property(Path::new("/ws/Section/section.md"), "part_of"),
        )
        .unwrap();
        let part_of_str = part_of.unwrap();
        let part_of_str = part_of_str.as_str().unwrap();
        assert!(
            part_of_str.contains("/Home.md"),
            "Expected part_of to contain '/Home.md', got '{}'",
            part_of_str
        );
        assert!(
            !part_of_str.contains("/README.md"),
            "Expected part_of to no longer reference README.md, got '{}'",
            part_of_str
        );
    }

    #[test]
    fn test_rename_index_updates_nested_child_part_of() {
        let fs = InMemoryFileSystem::new();
        let root = PathBuf::from("/ws");
        fs.create_dir_all(Path::new("/ws/Section/Sub")).unwrap();
        fs.write_file(
            Path::new("/ws/README.md"),
            "---\ntitle: Root\ncontents:\n  - \"[Section](/Section/Section.md)\"\n---\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("/ws/Section/Section.md"),
            "---\ntitle: Section\npart_of: \"[Root](/README.md)\"\ncontents:\n  - \"[Sub](/Section/Sub/sub.md)\"\n---\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("/ws/Section/Sub/sub.md"),
            "---\ntitle: Sub\npart_of: \"[Section](/Section/Section.md)\"\n---\n",
        )
        .unwrap();

        let async_fs = SyncToAsyncFs::new(fs.clone());
        let ws = Workspace::with_link_format(async_fs, root, LinkFormat::MarkdownRoot);

        let renamed =
            block_on_test(ws.rename_entry(Path::new("/ws/Section/Section.md"), "Renamed.md"))
                .unwrap();
        assert_eq!(renamed, PathBuf::from("/ws/Renamed/Renamed.md"));

        let part_of = block_on_test(
            ws.get_frontmatter_property(Path::new("/ws/Renamed/Sub/sub.md"), "part_of"),
        )
        .unwrap();
        let part_of_str = part_of.unwrap();
        let part_of_str = part_of_str.as_str().unwrap();
        assert!(
            part_of_str.contains("/Renamed/Renamed.md"),
            "Expected part_of to contain '/Renamed/Renamed.md', got '{}'",
            part_of_str
        );
        assert!(
            !part_of_str.contains("/Section/Section.md"),
            "Expected part_of to no longer reference '/Section/Section.md', got '{}'",
            part_of_str
        );
    }

    #[test]
    fn test_sync_create_metadata_uses_nearest_ancestor_index() {
        let fs = InMemoryFileSystem::new();
        fs.create_dir_all(Path::new("notes/deep")).unwrap();
        fs.write_file(
            Path::new("README.md"),
            "---\ntitle: Root\ncontents: []\n---\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("notes/deep/new.md"),
            "---\ntitle: New Note\n---\n\n# New Note\n",
        )
        .unwrap();

        let async_fs = SyncToAsyncFs::new(fs);
        let ws = Workspace::new(async_fs);

        block_on_test(ws.sync_create_metadata(Path::new("notes/deep/new.md"))).unwrap();

        let contents =
            block_on_test(ws.get_frontmatter_property(Path::new("README.md"), "contents")).unwrap();
        let contents = match contents {
            Some(YamlValue::Sequence(items)) => items
                .into_iter()
                .filter_map(|item| item.as_str().map(ToString::to_string))
                .collect::<Vec<_>>(),
            other => panic!("expected contents sequence, got {:?}", other),
        };
        assert!(
            contents
                .iter()
                .any(|entry| entry.contains("notes/deep/new.md")),
            "expected README contents to include moved file, got {:?}",
            contents
        );

        let part_of =
            block_on_test(ws.get_frontmatter_property(Path::new("notes/deep/new.md"), "part_of"))
                .unwrap();
        let part_of = part_of.and_then(|v| v.as_str().map(ToString::to_string));
        assert_eq!(part_of.as_deref(), Some("../../README.md"));
    }

    #[test]
    fn test_sync_move_metadata_updates_hierarchy_with_nearest_ancestor_index() {
        let fs = InMemoryFileSystem::new();
        fs.create_dir_all(Path::new("nested/deep")).unwrap();
        fs.write_file(
            Path::new("README.md"),
            "---\ntitle: Root\ncontents:\n  - old.md\n---\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("old.md"),
            "---\ntitle: Old\npart_of: README.md\n---\n\n# Old\n",
        )
        .unwrap();

        // Simulate external move (Obsidian already moved the file).
        fs.move_file(Path::new("old.md"), Path::new("nested/deep/new.md"))
            .unwrap();

        let async_fs = SyncToAsyncFs::new(fs);
        let ws = Workspace::new(async_fs);

        block_on_test(ws.sync_move_metadata(Path::new("old.md"), Path::new("nested/deep/new.md")))
            .unwrap();

        let contents =
            block_on_test(ws.get_frontmatter_property(Path::new("README.md"), "contents")).unwrap();
        let contents = match contents {
            Some(YamlValue::Sequence(items)) => items
                .into_iter()
                .filter_map(|item| item.as_str().map(ToString::to_string))
                .collect::<Vec<_>>(),
            other => panic!("expected contents sequence, got {:?}", other),
        };

        assert!(
            contents
                .iter()
                .any(|entry| entry.contains("nested/deep/new.md")),
            "expected README contents to include new path, got {:?}",
            contents
        );
        assert!(
            !contents.iter().any(|entry| entry.contains("old.md")),
            "expected README contents to remove old path, got {:?}",
            contents
        );

        let part_of =
            block_on_test(ws.get_frontmatter_property(Path::new("nested/deep/new.md"), "part_of"))
                .unwrap();
        let part_of = part_of.and_then(|v| v.as_str().map(ToString::to_string));
        assert_eq!(part_of.as_deref(), Some("../../README.md"));
    }

    #[test]
    fn test_sync_move_metadata_clears_part_of_when_destination_has_no_parent_index() {
        let fs = InMemoryFileSystem::new();
        fs.create_dir_all(Path::new("section")).unwrap();
        fs.create_dir_all(Path::new("outside")).unwrap();
        fs.write_file(
            Path::new("section/index.md"),
            "---\ntitle: Section\ncontents:\n  - child.md\n---\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("section/child.md"),
            "---\ntitle: Child\npart_of: index.md\n---\n\n# Child\n",
        )
        .unwrap();

        // Simulate external move into a location with no ancestor index.
        fs.move_file(Path::new("section/child.md"), Path::new("outside/new.md"))
            .unwrap();

        let async_fs = SyncToAsyncFs::new(fs);
        let ws = Workspace::new(async_fs);

        block_on_test(
            ws.sync_move_metadata(Path::new("section/child.md"), Path::new("outside/new.md")),
        )
        .unwrap();

        let contents =
            block_on_test(ws.get_frontmatter_property(Path::new("section/index.md"), "contents"))
                .unwrap();
        let contents = match contents {
            Some(YamlValue::Sequence(items)) => items
                .into_iter()
                .filter_map(|item| item.as_str().map(ToString::to_string))
                .collect::<Vec<_>>(),
            other => panic!("expected contents sequence, got {:?}", other),
        };
        assert!(
            !contents.iter().any(|entry| entry.contains("child.md")),
            "expected section index to drop old child reference, got {:?}",
            contents
        );

        let part_of =
            block_on_test(ws.get_frontmatter_property(Path::new("outside/new.md"), "part_of"))
                .unwrap();
        assert!(
            part_of.is_none(),
            "expected part_of to be removed when destination has no parent index"
        );
    }

    #[test]
    fn test_sync_delete_metadata_uses_nearest_ancestor_index() {
        let fs = InMemoryFileSystem::new();
        fs.create_dir_all(Path::new("nested/deep")).unwrap();
        fs.write_file(
            Path::new("README.md"),
            "---\ntitle: Root\ncontents:\n  - nested/deep/victim.md\n---\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("nested/deep/victim.md"),
            "---\ntitle: Victim\npart_of: ../../README.md\n---\n\n# Victim\n",
        )
        .unwrap();

        // Simulate external delete (Obsidian already deleted the file).
        fs.delete_file(Path::new("nested/deep/victim.md")).unwrap();

        let async_fs = SyncToAsyncFs::new(fs);
        let ws = Workspace::new(async_fs);

        block_on_test(ws.sync_delete_metadata(Path::new("nested/deep/victim.md"))).unwrap();

        let contents =
            block_on_test(ws.get_frontmatter_property(Path::new("README.md"), "contents")).unwrap();
        let contents = match contents {
            Some(YamlValue::Sequence(items)) => items
                .into_iter()
                .filter_map(|item| item.as_str().map(ToString::to_string))
                .collect::<Vec<_>>(),
            other => panic!("expected contents sequence, got {:?}", other),
        };
        assert!(
            !contents
                .iter()
                .any(|entry| entry.contains("nested/deep/victim.md")),
            "expected README contents to remove deleted file, got {:?}",
            contents
        );
    }

    // -------------------------------------------------------------------------
    // attach_entry_to_parent
    // -------------------------------------------------------------------------

    fn get_contents_strings(
        ws: &Workspace<SyncToAsyncFs<InMemoryFileSystem>>,
        index: &str,
    ) -> Vec<String> {
        let val = block_on_test(ws.get_frontmatter_property(Path::new(index), "contents")).unwrap();
        match val {
            Some(YamlValue::Sequence(items)) => items
                .into_iter()
                .filter_map(|v| v.as_str().map(ToString::to_string))
                .collect(),
            _ => vec![],
        }
    }

    #[test]
    fn test_attach_entry_to_parent_adds_to_new_parent_contents() {
        let fs = InMemoryFileSystem::new();
        fs.create_dir_all(Path::new("section")).unwrap();
        fs.write_file(
            Path::new("README.md"),
            "---\ntitle: Root\ncontents: []\n---\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("section/index.md"),
            "---\ntitle: Section\ncontents: []\npart_of: ../README.md\n---\n",
        )
        .unwrap();
        fs.write_file(Path::new("section/note.md"), "---\ntitle: Note\n---\n")
            .unwrap();

        let async_fs = SyncToAsyncFs::new(fs);
        let ws = Workspace::new(async_fs);

        block_on_test(
            ws.attach_entry_to_parent(Path::new("section/note.md"), Path::new("section/index.md")),
        )
        .unwrap();

        let contents = get_contents_strings(&ws, "section/index.md");
        assert!(
            contents.iter().any(|e| e.contains("note.md")),
            "expected section/index.md contents to include note.md, got {:?}",
            contents
        );

        let part_of =
            block_on_test(ws.get_frontmatter_property(Path::new("section/note.md"), "part_of"))
                .unwrap();
        assert!(part_of.is_some(), "expected part_of to be set on note.md");
    }

    #[test]
    fn test_attach_entry_to_parent_removes_from_old_parent_contents() {
        // note.md starts as a child of README.md (root). We re-attach it to
        // section/index.md (same directory as note.md). The root's contents
        // should no longer reference note.md after the call.
        let fs = InMemoryFileSystem::new();
        fs.create_dir_all(Path::new("section")).unwrap();
        fs.write_file(
            Path::new("section/README.md"),
            "---\ntitle: Root\ncontents:\n  - note.md\n---\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("section/index.md"),
            "---\ntitle: Section\ncontents: []\npart_of: README.md\n---\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("section/note.md"),
            "---\ntitle: Note\npart_of: README.md\n---\n",
        )
        .unwrap();

        let async_fs = SyncToAsyncFs::new(fs);
        let ws = Workspace::new(async_fs);

        block_on_test(
            ws.attach_entry_to_parent(Path::new("section/note.md"), Path::new("section/index.md")),
        )
        .unwrap();

        // note.md should now be in section/index.md's contents
        let section_contents = get_contents_strings(&ws, "section/index.md");
        assert!(
            section_contents.iter().any(|e| e.contains("note.md")),
            "expected section/index.md contents to include note.md, got {:?}",
            section_contents
        );

        // note.md should no longer appear in old parent's contents
        let root_contents = get_contents_strings(&ws, "section/README.md");
        assert!(
            !root_contents.iter().any(|e| e.contains("note.md")),
            "expected README.md contents to no longer include note.md, got {:?}",
            root_contents
        );
    }

    // -------------------------------------------------------------------------
    // attach_and_move_entry_to_parent
    // -------------------------------------------------------------------------

    #[test]
    fn test_attach_and_move_entry_to_parent_moves_file_and_updates_hierarchy() {
        // entry.md lives under root and should be moved into section/.
        let fs = InMemoryFileSystem::new();
        fs.create_dir_all(Path::new("section")).unwrap();
        fs.write_file(
            Path::new("README.md"),
            "---\ntitle: Root\ncontents:\n  - entry.md\n---\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("section/index.md"),
            "---\ntitle: Section\ncontents: []\npart_of: ../README.md\n---\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("entry.md"),
            "---\ntitle: Entry\npart_of: README.md\n---\n",
        )
        .unwrap();

        let async_fs = SyncToAsyncFs::new(fs);
        let ws = Workspace::new(async_fs);

        let new_path =
            block_on_test(ws.attach_and_move_entry_to_parent(
                Path::new("entry.md"),
                Path::new("section/index.md"),
            ))
            .unwrap();

        assert_eq!(new_path, PathBuf::from("section/entry.md"));

        // File should exist at new location
        assert!(block_on_test(ws.fs.exists(Path::new("section/entry.md"))));
        assert!(!block_on_test(ws.fs.exists(Path::new("entry.md"))));

        // New parent should contain the entry
        let section_contents = get_contents_strings(&ws, "section/index.md");
        assert!(
            section_contents.iter().any(|e| e.contains("entry.md")),
            "expected section/index.md to contain entry.md, got {:?}",
            section_contents
        );

        // Old parent should no longer reference it
        let root_contents = get_contents_strings(&ws, "README.md");
        assert!(
            !root_contents.iter().any(|e| e.contains("entry.md")),
            "expected README.md to no longer reference entry.md, got {:?}",
            root_contents
        );
    }

    #[test]
    fn test_attach_and_move_entry_to_parent_converts_leaf_target_to_index() {
        // Moving entry.md into leaf.md (a non-index) should convert leaf.md into
        // section/leaf/leaf.md (index) and move entry.md to section/leaf/entry.md.
        let fs = InMemoryFileSystem::new();
        fs.create_dir_all(Path::new("section")).unwrap();
        fs.write_file(
            Path::new("README.md"),
            "---\ntitle: Root\ncontents:\n  - entry.md\n  - section/leaf.md\n---\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("entry.md"),
            "---\ntitle: Entry\npart_of: README.md\n---\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("section/leaf.md"),
            "---\ntitle: Leaf\npart_of: ../README.md\n---\n",
        )
        .unwrap();

        let async_fs = SyncToAsyncFs::new(fs);
        let ws = Workspace::new(async_fs);

        let new_path = block_on_test(
            ws.attach_and_move_entry_to_parent(Path::new("entry.md"), Path::new("section/leaf.md")),
        )
        .unwrap();

        // convert_to_index moves section/leaf.md → section/leaf/leaf.md
        // and entry.md → section/leaf/entry.md
        assert_eq!(new_path, PathBuf::from("section/leaf/entry.md"));

        assert!(block_on_test(
            ws.is_index_file(Path::new("section/leaf/leaf.md"))
        ));
        assert!(block_on_test(
            ws.fs.exists(Path::new("section/leaf/entry.md"))
        ));
        assert!(!block_on_test(ws.fs.exists(Path::new("entry.md"))));

        // Old parent should no longer reference entry.md at the root level
        let root_contents = get_contents_strings(&ws, "README.md");
        assert!(
            !root_contents.iter().any(|e| e == "entry.md"),
            "expected README.md to no longer reference entry.md, got {:?}",
            root_contents
        );
    }

    #[test]
    fn test_attach_and_move_entry_to_parent_moves_folder_and_rewrites_nested_part_of() {
        // Projects/ is a folder (represented by Projects/projects.md) with a
        // nested sub-index (Projects/sub/sub.md) and a grandchild leaf
        // (Projects/sub/task.md). Every file uses markdown_root-format
        // part_of values, so absolute paths get stale after the move unless
        // we rewrite them. We drag Projects into Archive/ and expect the
        // whole tree to move AND every part_of to point at the new location.
        let fs = InMemoryFileSystem::new();
        fs.create_dir_all(Path::new("Projects/sub")).unwrap();
        fs.create_dir_all(Path::new("Archive")).unwrap();
        fs.write_file(
            Path::new("README.md"),
            "---\ntitle: Root\ncontents:\n  - \"[Projects](/Projects/projects.md)\"\n  - \"[Archive](/Archive/archive.md)\"\n---\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("Archive/archive.md"),
            "---\ntitle: Archive\ncontents: []\npart_of: \"[Root](/README.md)\"\n---\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("Projects/projects.md"),
            "---\ntitle: Projects\ncontents:\n  - \"[Sub](/Projects/sub/sub.md)\"\npart_of: \"[Root](/README.md)\"\n---\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("Projects/sub/sub.md"),
            "---\ntitle: Sub\ncontents:\n  - \"[Task](/Projects/sub/task.md)\"\npart_of: \"[Projects](/Projects/projects.md)\"\n---\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("Projects/sub/task.md"),
            "---\ntitle: Task\npart_of: \"[Sub](/Projects/sub/sub.md)\"\n---\n",
        )
        .unwrap();

        let async_fs = SyncToAsyncFs::new(fs);
        let ws = Workspace::with_link_format(async_fs, PathBuf::from(""), LinkFormat::MarkdownRoot);

        let new_path = block_on_test(ws.attach_and_move_entry_to_parent(
            Path::new("Projects/projects.md"),
            Path::new("Archive/archive.md"),
        ))
        .unwrap();

        assert_eq!(new_path, PathBuf::from("Archive/Projects/projects.md"));

        // Folder contents moved.
        assert!(block_on_test(
            ws.fs.exists(Path::new("Archive/Projects/projects.md"))
        ));
        assert!(block_on_test(
            ws.fs.exists(Path::new("Archive/Projects/sub/sub.md"))
        ));
        assert!(block_on_test(
            ws.fs.exists(Path::new("Archive/Projects/sub/task.md"))
        ));
        assert!(!block_on_test(
            ws.fs.exists(Path::new("Projects/projects.md"))
        ));
        assert!(!block_on_test(
            ws.fs.exists(Path::new("Projects/sub/sub.md"))
        ));

        // Moved index's own part_of now points to the new parent.
        let projects_part_of = block_on_test(
            ws.get_frontmatter_property(Path::new("Archive/Projects/projects.md"), "part_of"),
        )
        .unwrap();
        let projects_part_of = match projects_part_of {
            Some(YamlValue::String(s)) => s,
            other => panic!("expected projects.md part_of string, got {:?}", other),
        };
        assert!(
            projects_part_of.contains("/Archive/archive.md"),
            "projects.md part_of should point at new parent, got: {projects_part_of}"
        );

        // Nested sub-index's part_of should now reference the moved projects.md.
        let sub_part_of = block_on_test(
            ws.get_frontmatter_property(Path::new("Archive/Projects/sub/sub.md"), "part_of"),
        )
        .unwrap();
        let sub_part_of = match sub_part_of {
            Some(YamlValue::String(s)) => s,
            other => panic!("expected sub.md part_of string, got {:?}", other),
        };
        assert!(
            sub_part_of.contains("/Archive/Projects/projects.md"),
            "sub.md part_of should point at new projects.md, got: {sub_part_of}"
        );
        assert!(
            !sub_part_of.contains("/Projects/projects.md")
                || sub_part_of.contains("/Archive/Projects/projects.md"),
            "sub.md part_of should not point at old path, got: {sub_part_of}"
        );

        // Grandchild task.md's part_of should now reference the moved sub.md
        // — this is the recursion case the bug was about.
        let task_part_of = block_on_test(
            ws.get_frontmatter_property(Path::new("Archive/Projects/sub/task.md"), "part_of"),
        )
        .unwrap();
        let task_part_of = match task_part_of {
            Some(YamlValue::String(s)) => s,
            other => panic!("expected task.md part_of string, got {:?}", other),
        };
        assert!(
            task_part_of.contains("/Archive/Projects/sub/sub.md"),
            "task.md part_of should point at new sub.md, got: {task_part_of}"
        );
    }

    #[test]
    fn test_collect_workspace_file_set_includes_reachable_markdown_and_attachments() {
        let fs = InMemoryFileSystem::new();
        fs.write_file(
            Path::new("workspace/index.md"),
            "---\ntitle: Root\ncontents:\n  - Notes/day.md\nattachments:\n  - assets/root.png\n---\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("workspace/Notes/day.md"),
            "---\ntitle: Day\npart_of: /index.md\nattachments:\n  - ./_attachments/day.jpg\n  - /shared/manual.pdf\n---\n",
        )
        .unwrap();
        fs.write_file(Path::new("workspace/assets/root.png"), "root")
            .unwrap();
        fs.write_file(Path::new("workspace/Notes/_attachments/day.jpg"), "day")
            .unwrap();
        fs.write_file(Path::new("workspace/shared/manual.pdf"), "manual")
            .unwrap();
        fs.write_file(Path::new("workspace/node_modules/nope.js"), "ignored")
            .unwrap();

        let async_fs = SyncToAsyncFs::new(fs);
        let ws = Workspace::new(async_fs);

        let file_set =
            block_on_test(ws.collect_workspace_file_set(Path::new("workspace/index.md"))).unwrap();

        assert_eq!(
            file_set,
            vec![
                "Notes/_attachments/day.jpg".to_string(),
                "Notes/day.md".to_string(),
                "assets/root.png".to_string(),
                "index.md".to_string(),
                "shared/manual.pdf".to_string(),
            ]
        );
    }

    #[test]
    fn test_build_filesystem_tree_inherits_nested_index_excludes() {
        let fs = InMemoryFileSystem::new();
        fs.create_dir_all(Path::new("workspace/scripts")).unwrap();
        fs.write_file(
            Path::new("workspace/Diaryx.md"),
            "---\ntitle: Root\ncontents: []\nexclude:\n  - \"**/target\"\n---\n",
        )
        .unwrap();
        fs.write_file(
            Path::new("workspace/scripts/scripts.md"),
            "---\ntitle: Scripts\ncontents: []\nexclude:\n  - \"*.sh\"\n---\n",
        )
        .unwrap();
        fs.write_file(Path::new("workspace/scripts/keep.txt"), "keep")
            .unwrap();
        fs.write_file(Path::new("workspace/scripts/run.sh"), "echo hi")
            .unwrap();

        let async_fs = SyncToAsyncFs::new(fs);
        let ws = Workspace::new(async_fs);

        let tree =
            block_on_test(ws.build_filesystem_tree_with_depth(Path::new("workspace"), false, None))
                .unwrap();

        let scripts = tree
            .children
            .iter()
            .find(|child| child.path == PathBuf::from("workspace/scripts/scripts.md"))
            .expect("scripts directory should be present");

        let child_names: Vec<_> = scripts
            .children
            .iter()
            .map(|child| child.name.as_str())
            .collect();
        assert!(
            child_names.contains(&"keep.txt"),
            "expected keep.txt to remain visible, got {:?}",
            child_names
        );
        assert!(
            !child_names.contains(&"run.sh"),
            "expected nested index exclude to hide run.sh, got {:?}",
            child_names
        );
    }

    #[test]
    fn test_build_filesystem_tree_prunes_builtin_skip_directories() {
        let fs = InMemoryFileSystem::new();
        fs.write_file(
            Path::new("workspace/Diaryx.md"),
            "---\ntitle: Root\ncontents: []\n---\n",
        )
        .unwrap();
        fs.write_file(Path::new("workspace/visible.txt"), "ok")
            .unwrap();
        fs.write_file(Path::new("workspace/target/debug/app.bin"), "bin")
            .unwrap();
        fs.write_file(Path::new("workspace/node_modules/pkg/index.js"), "js")
            .unwrap();

        let async_fs = SyncToAsyncFs::new(fs);
        let ws = Workspace::new(async_fs);

        let tree =
            block_on_test(ws.build_filesystem_tree_with_depth(Path::new("workspace"), false, None))
                .unwrap();

        let child_paths: Vec<_> = tree
            .children
            .iter()
            .map(|child| child.path.to_string_lossy().to_string())
            .collect();
        assert!(
            child_paths.contains(&"workspace/visible.txt".to_string()),
            "expected visible file in tree, got {:?}",
            child_paths
        );
        assert!(
            !child_paths.iter().any(|path| path.contains("target")),
            "expected target to be pruned, got {:?}",
            child_paths
        );
        assert!(
            !child_paths.iter().any(|path| path.contains("node_modules")),
            "expected node_modules to be pruned, got {:?}",
            child_paths
        );
    }
}